sqlite3.c 5.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092123093123094123095123096123097123098123099123100123101123102123103123104123105123106123107123108123109123110123111123112123113123114123115123116123117123118123119123120123121123122123123123124123125123126123127123128123129123130123131123132123133123134123135123136123137123138123139123140123141123142123143123144123145123146123147123148123149123150123151123152123153123154123155123156123157123158123159123160123161123162123163123164123165123166123167123168123169123170123171123172123173123174123175123176123177123178123179123180123181123182123183123184123185123186123187123188123189123190123191123192123193123194123195123196123197123198123199123200123201123202123203123204123205123206123207123208123209123210123211123212123213123214123215123216123217123218123219123220123221123222123223123224123225123226123227123228123229123230123231123232123233123234123235123236123237123238123239123240123241123242123243123244123245123246123247123248123249123250123251123252123253123254123255123256123257123258123259123260123261123262123263123264123265123266123267123268123269123270123271123272123273123274123275123276123277123278123279123280123281123282123283123284123285123286123287123288123289123290123291123292123293123294123295123296123297123298123299123300123301123302123303123304123305123306123307123308123309123310123311123312123313123314123315123316123317123318123319123320123321123322123323123324123325123326123327123328123329123330123331123332123333123334123335123336123337123338123339123340123341123342123343123344123345123346123347123348123349123350123351123352123353123354123355123356123357123358123359123360123361123362123363123364123365123366123367123368123369123370123371123372123373123374123375123376123377123378123379123380123381123382123383123384123385123386123387123388123389123390123391123392123393123394123395123396123397123398123399123400123401123402123403123404123405123406123407123408123409123410123411123412123413123414123415123416123417123418123419123420123421123422123423123424123425123426123427123428123429123430123431123432123433123434123435123436123437123438123439123440123441123442123443123444123445123446123447123448123449123450123451123452123453123454123455123456123457123458123459123460123461123462123463123464123465123466123467123468123469123470123471123472123473123474123475123476123477123478123479123480123481123482123483123484123485123486123487123488123489123490123491123492123493123494123495123496123497123498123499123500123501123502123503123504123505123506123507123508123509123510123511123512123513123514123515123516123517123518123519123520123521123522123523123524123525123526123527123528123529123530123531123532123533123534123535123536123537123538123539123540123541123542123543123544123545123546123547123548123549123550123551123552123553123554123555123556123557123558123559123560123561123562123563123564123565123566123567123568123569123570123571123572123573123574123575123576123577123578123579123580123581123582123583123584123585123586123587123588123589123590123591123592123593123594123595123596123597123598123599123600123601123602123603123604123605123606123607123608123609123610123611123612123613123614123615123616123617123618123619123620123621123622123623123624123625123626123627123628123629123630123631123632123633123634123635123636123637123638123639123640123641123642123643123644123645123646123647123648123649123650123651123652123653123654123655123656123657123658123659123660123661123662123663123664123665123666123667123668123669123670123671123672123673123674123675123676123677123678123679123680123681123682123683123684123685123686123687123688123689123690123691123692123693123694123695123696123697123698123699123700123701123702123703123704123705123706123707123708123709123710123711123712123713123714123715123716123717123718123719123720123721123722123723123724123725123726123727123728123729123730123731123732123733123734123735123736123737123738123739123740123741123742123743123744123745123746123747123748123749123750123751123752123753123754123755123756123757123758123759123760123761123762123763123764123765123766123767123768123769123770123771123772123773123774123775123776123777123778123779123780123781123782123783123784123785123786123787123788123789123790123791123792123793123794123795123796123797123798123799123800123801123802123803123804123805123806123807123808123809123810123811123812123813123814123815123816123817123818123819123820123821123822123823123824123825123826123827123828123829123830123831123832123833123834123835123836123837123838123839123840123841123842123843123844123845123846123847123848123849123850123851123852123853123854123855123856123857123858123859123860123861123862123863123864123865123866123867123868123869123870123871123872123873123874123875123876123877123878123879123880123881123882123883123884123885123886123887123888123889123890123891123892123893123894123895123896123897123898123899123900123901123902123903123904123905123906123907123908123909123910123911123912123913123914123915123916123917123918123919123920123921123922123923123924123925123926123927123928123929123930123931123932123933123934123935123936123937123938123939123940123941123942123943123944123945123946123947123948123949123950123951123952123953123954123955123956123957123958123959123960123961123962123963123964123965123966123967123968123969123970123971123972123973123974123975123976123977123978123979123980123981123982123983123984123985123986123987123988123989123990123991123992123993123994123995123996123997123998123999124000124001124002124003124004124005124006124007124008124009124010124011124012124013124014124015124016124017124018124019124020124021124022124023124024124025124026124027124028124029124030124031124032124033124034124035124036124037124038124039124040124041124042124043124044124045124046124047124048124049124050124051124052124053124054124055124056124057124058124059124060124061124062124063124064124065124066124067124068124069124070124071124072124073124074124075124076124077124078124079124080124081124082124083124084124085124086124087124088124089124090124091124092124093124094124095124096124097124098124099124100124101124102124103124104124105124106124107124108124109124110124111124112124113124114124115124116124117124118124119124120124121124122124123124124124125124126124127124128124129124130124131124132124133124134124135124136124137124138124139124140124141124142124143124144124145124146124147124148124149124150124151124152124153124154124155124156124157124158124159124160124161124162124163124164124165124166124167124168124169124170124171124172124173124174124175124176124177124178124179124180124181124182124183124184124185124186124187124188124189124190124191124192124193124194124195124196124197124198124199124200124201124202124203124204124205124206124207124208124209124210124211124212124213124214124215124216124217124218124219124220124221124222124223124224124225124226124227124228124229124230124231124232124233124234124235124236124237124238124239124240124241124242124243124244124245124246124247124248124249124250124251124252124253124254124255124256124257124258124259124260124261124262124263124264124265124266124267124268124269124270124271124272124273124274124275124276124277124278124279124280124281124282124283124284124285124286124287124288124289124290124291124292124293124294124295124296124297124298124299124300124301124302124303124304124305124306124307124308124309124310124311124312124313124314124315124316124317124318124319124320124321124322124323124324124325124326124327124328124329124330124331124332124333124334124335124336124337124338124339124340124341124342124343124344124345124346124347124348124349124350124351124352124353124354124355124356124357124358124359124360124361124362124363124364124365124366124367124368124369124370124371124372124373124374124375124376124377124378124379124380124381124382124383124384124385124386124387124388124389124390124391124392124393124394124395124396124397124398124399124400124401124402124403124404124405124406124407124408124409124410124411124412124413124414124415124416124417124418124419124420124421124422124423124424124425124426124427124428124429124430124431124432124433124434124435124436124437124438124439124440124441124442124443124444124445124446124447124448124449124450124451124452124453124454124455124456124457124458124459124460124461124462124463124464124465124466124467124468124469124470124471124472124473124474124475124476124477124478124479124480124481124482124483124484124485124486124487124488124489124490124491124492124493124494124495124496124497124498124499124500124501124502124503124504124505124506124507124508124509124510124511124512124513124514124515124516124517124518124519124520124521124522124523124524124525124526124527124528124529124530124531124532124533124534124535124536124537124538124539124540124541124542124543124544124545124546124547124548124549124550124551124552124553124554124555124556124557124558124559124560124561124562124563124564124565124566124567124568124569124570124571124572124573124574124575124576124577124578124579124580124581124582124583124584124585124586124587124588124589124590124591124592124593124594124595124596124597124598124599124600124601124602124603124604124605124606124607124608124609124610124611124612124613124614124615124616124617124618124619124620124621124622124623124624124625124626124627124628124629124630124631124632124633124634124635124636124637124638124639124640124641124642124643124644124645124646124647124648124649124650124651124652124653124654124655124656124657124658124659124660124661124662124663124664124665124666124667124668124669124670124671124672124673124674124675124676124677124678124679124680124681124682124683124684124685124686124687124688124689124690124691124692124693124694124695124696124697124698124699124700124701124702124703124704124705124706124707124708124709124710124711124712124713124714124715124716124717124718124719124720124721124722124723124724124725124726124727124728124729124730124731124732124733124734124735124736124737124738124739124740124741124742124743124744124745124746124747124748124749124750124751124752124753124754124755124756124757124758124759124760124761124762124763124764124765124766124767124768124769124770124771124772124773124774124775124776124777124778124779124780124781124782124783124784124785124786124787124788124789124790124791124792124793124794124795124796124797124798124799124800124801124802124803124804124805124806124807124808124809124810124811124812124813124814124815124816124817124818124819124820124821124822124823124824124825124826124827124828124829124830124831124832124833124834124835124836124837124838124839124840124841124842124843124844124845124846124847124848124849124850124851124852124853124854124855124856124857124858124859124860124861124862124863124864124865124866124867124868124869124870124871124872124873124874124875124876124877124878124879124880124881124882124883124884124885124886124887124888124889124890124891124892124893124894124895124896124897124898124899124900124901124902124903124904124905124906124907124908124909124910124911124912124913124914124915124916124917124918124919124920124921124922124923124924124925124926124927124928124929124930124931124932124933124934124935124936124937124938124939124940124941124942124943124944124945124946124947124948124949124950124951124952124953124954124955124956124957124958124959124960124961124962124963124964124965124966124967124968124969124970124971124972124973124974124975124976124977124978124979124980124981124982124983124984124985124986124987124988124989124990124991124992124993124994124995124996124997124998124999125000125001125002125003125004125005125006125007125008125009125010125011125012125013125014125015125016125017125018125019125020125021125022125023125024125025125026125027125028125029125030125031125032125033125034125035125036125037125038125039125040125041125042125043125044125045125046125047125048125049125050125051125052125053125054125055125056125057125058125059125060125061125062125063125064125065125066125067125068125069125070125071125072125073125074125075125076125077125078125079125080125081125082125083125084125085125086125087125088125089125090125091125092125093125094125095125096125097125098125099125100125101125102125103125104125105125106125107125108125109125110125111125112125113125114125115125116125117125118125119125120125121125122125123125124125125125126125127125128125129125130125131125132125133125134125135125136125137125138125139125140125141125142125143125144125145125146125147125148125149125150125151125152125153125154125155125156125157125158125159125160125161125162125163125164125165125166125167125168125169125170125171125172125173125174125175125176125177125178125179125180125181125182125183125184125185125186125187125188125189125190125191125192125193125194125195125196125197125198125199125200125201125202125203125204125205125206125207125208125209125210125211125212125213125214125215125216125217125218125219125220125221125222125223125224125225125226125227125228125229125230125231125232125233125234125235125236125237125238125239125240125241125242125243125244125245125246125247125248125249125250125251125252125253125254125255125256125257125258125259125260125261125262125263125264125265125266125267125268125269125270125271125272125273125274125275125276125277125278125279125280125281125282125283125284125285125286125287125288125289125290125291125292125293125294125295125296125297125298125299125300125301125302125303125304125305125306125307125308125309125310125311125312125313125314125315125316125317125318125319125320125321125322125323125324125325125326125327125328125329125330125331125332125333125334125335125336125337125338125339125340125341125342125343125344125345125346125347125348125349125350125351125352125353125354125355125356125357125358125359125360125361125362125363125364125365125366125367125368125369125370125371125372125373125374125375125376125377125378125379125380125381125382125383125384125385125386125387125388125389125390125391125392125393125394125395125396125397125398125399125400125401125402125403125404125405125406125407125408125409125410125411125412125413125414125415125416125417125418125419125420125421125422125423125424125425125426125427125428125429125430125431125432125433125434125435125436125437125438125439125440125441125442125443125444125445125446125447125448125449125450125451125452125453125454125455125456125457125458125459125460125461125462125463125464125465125466125467125468125469125470125471125472125473125474125475125476125477125478125479125480125481125482125483125484125485125486125487125488125489125490125491125492125493125494125495125496125497125498125499125500125501125502125503125504125505125506125507125508125509125510125511125512125513125514125515125516125517125518125519125520125521125522125523125524125525125526125527125528125529125530125531125532125533125534125535125536125537125538125539125540125541125542125543125544125545125546125547125548125549125550125551125552125553125554125555125556125557125558125559125560125561125562125563125564125565125566125567125568125569125570125571125572125573125574125575125576125577125578125579125580125581125582125583125584125585125586125587125588125589125590125591125592125593125594125595125596125597125598125599125600125601125602125603125604125605125606125607125608125609125610125611125612125613125614125615125616125617125618125619125620125621125622125623125624125625125626125627125628125629125630125631125632125633125634125635125636125637125638125639125640125641125642125643125644125645125646125647125648125649125650125651125652125653125654125655125656125657125658125659125660125661125662125663125664125665125666125667125668125669125670125671125672125673125674125675125676125677125678125679125680125681125682125683125684125685125686125687125688125689125690125691125692125693125694125695125696125697125698125699125700125701125702125703125704125705125706125707125708125709125710125711125712125713125714125715125716125717125718125719125720125721125722125723125724125725125726125727125728125729125730125731125732125733125734125735125736125737125738125739125740125741125742125743125744125745125746125747125748125749125750125751125752125753125754125755125756125757125758125759125760125761125762125763125764125765125766125767125768125769125770125771125772125773125774125775125776125777125778125779125780125781125782125783125784125785125786125787125788125789125790125791125792125793125794125795125796125797125798125799125800125801125802125803125804125805125806125807125808125809125810125811125812125813125814125815125816125817125818125819125820125821125822125823125824125825125826125827125828125829125830125831125832125833125834125835125836125837125838125839125840125841125842125843125844125845125846125847125848125849125850125851125852125853125854125855125856125857125858125859125860125861125862125863125864125865125866125867125868125869125870125871125872125873125874125875125876125877125878125879125880125881125882125883125884125885125886125887125888125889125890125891125892125893125894125895125896125897125898125899125900125901125902125903125904125905125906125907125908125909125910125911125912125913125914125915125916125917125918125919125920125921125922125923125924125925125926125927125928125929125930125931125932125933125934125935125936125937125938125939125940125941125942125943125944125945125946125947125948125949125950125951125952125953125954125955125956125957125958125959125960125961125962125963125964125965125966125967125968125969125970125971125972125973125974125975125976125977125978125979125980125981125982125983125984125985125986125987125988125989125990125991125992125993125994125995125996125997125998125999126000126001126002126003126004126005126006126007126008126009126010126011126012126013126014126015126016126017126018126019126020126021126022126023126024126025126026126027126028126029126030126031126032126033126034126035126036126037126038126039126040126041126042126043126044126045126046126047126048126049126050126051126052126053126054126055126056126057126058126059126060126061126062126063126064126065126066126067126068126069126070126071126072126073126074126075126076126077126078126079126080126081126082126083126084126085126086126087126088126089126090126091126092126093126094126095126096126097126098126099126100126101126102126103126104126105126106126107126108126109126110126111126112126113126114126115126116126117126118126119126120126121126122126123126124126125126126126127126128126129126130126131126132126133126134126135126136126137126138126139126140126141126142126143126144126145126146126147126148126149126150126151126152126153126154126155126156126157126158126159126160126161126162126163126164126165126166126167126168126169126170126171126172126173126174126175126176126177126178126179126180126181126182126183126184126185126186126187126188126189126190126191126192126193126194126195126196126197126198126199126200126201126202126203126204126205126206126207126208126209126210126211126212126213126214126215126216126217126218126219126220126221126222126223126224126225126226126227126228126229126230126231126232126233126234126235126236126237126238126239126240126241126242126243126244126245126246126247126248126249126250126251126252126253126254126255126256126257126258126259126260126261126262126263126264126265126266126267126268126269126270126271126272126273126274126275126276126277126278126279126280126281126282126283126284126285126286126287126288126289126290126291126292126293126294126295126296126297126298126299126300126301126302126303126304126305126306126307126308126309126310126311126312126313126314126315126316126317126318126319126320126321126322126323126324126325126326126327126328126329126330126331126332126333126334126335126336126337126338126339126340126341126342126343126344126345126346126347126348126349126350126351126352126353126354126355126356126357126358126359126360126361126362126363126364126365126366126367126368126369126370126371126372126373126374126375126376126377126378126379126380126381126382126383126384126385126386126387126388126389126390126391126392126393126394126395126396126397126398126399126400126401126402126403126404126405126406126407126408126409126410126411126412126413126414126415126416126417126418126419126420126421126422126423126424126425126426126427126428126429126430126431126432126433126434126435126436126437126438126439126440126441126442126443126444126445126446126447126448126449126450126451126452126453126454126455126456126457126458126459126460126461126462126463126464126465126466126467126468126469126470126471126472126473126474126475126476126477126478126479126480126481126482126483126484126485126486126487126488126489126490126491126492126493126494126495126496126497126498126499126500126501126502126503126504126505126506126507126508126509126510126511126512126513126514126515126516126517126518126519126520126521126522126523126524126525126526126527126528126529126530126531126532126533126534126535126536126537126538126539126540126541126542126543126544126545126546126547126548126549126550126551126552126553126554126555126556126557126558126559126560126561126562126563126564126565126566126567126568126569126570126571126572126573126574126575126576126577126578126579126580126581126582126583126584126585126586126587126588126589126590126591126592126593126594126595126596126597126598126599126600126601126602126603126604126605126606126607126608126609126610126611126612126613126614126615126616126617126618126619126620126621126622126623126624126625126626126627126628126629126630126631126632126633126634126635126636126637126638126639126640126641126642126643126644126645126646126647126648126649126650126651126652126653126654126655126656126657126658126659126660126661126662126663126664126665126666126667126668126669126670126671126672126673126674126675126676126677126678126679126680126681126682126683126684126685126686126687126688126689126690126691126692126693126694126695126696126697126698126699126700126701126702126703126704126705126706126707126708126709126710126711126712126713126714126715126716126717126718126719126720126721126722126723126724126725126726126727126728126729126730126731126732126733126734126735126736126737126738126739126740126741126742126743126744126745126746126747126748126749126750126751126752126753126754126755126756126757126758126759126760126761126762126763126764126765126766126767126768126769126770126771126772126773126774126775126776126777126778126779126780126781126782126783126784126785126786126787126788126789126790126791126792126793126794126795126796126797126798126799126800126801126802126803126804126805126806126807126808126809126810126811126812126813126814126815126816126817126818126819126820126821126822126823126824126825126826126827126828126829126830126831126832126833126834126835126836126837126838126839126840126841126842126843126844126845126846126847126848126849126850126851126852126853126854126855126856126857126858126859126860126861126862126863126864126865126866126867126868126869126870126871126872126873126874126875126876126877126878126879126880126881126882126883126884126885126886126887126888126889126890126891126892126893126894126895126896126897126898126899126900126901126902126903126904126905126906126907126908126909126910126911126912126913126914126915126916126917126918126919126920126921126922126923126924126925126926126927126928126929126930126931126932126933126934126935126936126937126938126939126940126941126942126943126944126945126946126947126948126949126950126951126952126953126954126955126956126957126958126959126960126961126962126963126964126965126966126967126968126969126970126971126972126973126974126975126976126977126978126979126980126981126982126983126984126985126986126987126988126989126990126991126992126993126994126995126996126997126998126999127000127001127002127003127004127005127006127007127008127009127010127011127012127013127014127015127016127017127018127019127020127021127022127023127024127025127026127027127028127029127030127031127032127033127034127035127036127037127038127039127040127041127042127043127044127045127046127047127048127049127050127051127052127053127054127055127056127057127058127059127060127061127062127063127064127065127066127067127068127069127070127071127072127073127074127075127076127077127078127079127080127081127082127083127084127085127086127087127088127089127090127091127092127093127094127095127096127097127098127099127100127101127102127103127104127105127106127107127108127109127110127111127112127113127114127115127116127117127118127119127120127121127122127123127124127125127126127127127128127129127130127131127132127133127134127135127136127137127138127139127140127141127142127143127144127145127146127147127148127149127150127151127152127153127154127155127156127157127158127159127160127161127162127163127164127165127166127167127168127169127170127171127172127173127174127175127176127177127178127179127180127181127182127183127184127185127186127187127188127189127190127191127192127193127194127195127196127197127198127199127200127201127202127203127204127205127206127207127208127209127210127211127212127213127214127215127216127217127218127219127220127221127222127223127224127225127226127227127228127229127230127231127232127233127234127235127236127237127238127239127240127241127242127243127244127245127246127247127248127249127250127251127252127253127254127255127256127257127258127259127260127261127262127263127264127265127266127267127268127269127270127271127272127273127274127275127276127277127278127279127280127281127282127283127284127285127286127287127288127289127290127291127292127293127294127295127296127297127298127299127300127301127302127303127304127305127306127307127308127309127310127311127312127313127314127315127316127317127318127319127320127321127322127323127324127325127326127327127328127329127330127331127332127333127334127335127336127337127338127339127340127341127342127343127344127345127346127347127348127349127350127351127352127353127354127355127356127357127358127359127360127361127362127363127364127365127366127367127368127369127370127371127372127373127374127375127376127377127378127379127380127381127382127383127384127385127386127387127388127389127390127391127392127393127394127395127396127397127398127399127400127401127402127403127404127405127406127407127408127409127410127411127412127413127414127415127416127417127418127419127420127421127422127423127424127425127426127427127428127429127430127431127432127433127434127435127436127437127438127439127440127441127442127443127444127445127446127447127448127449127450127451127452127453127454127455127456127457127458127459127460127461127462127463127464127465127466127467127468127469127470127471127472127473127474127475127476127477127478127479127480127481127482127483127484127485127486127487127488127489127490127491127492127493127494127495127496127497127498127499127500127501127502127503127504127505127506127507127508127509127510127511127512127513127514127515127516127517127518127519127520127521127522127523127524127525127526127527127528127529127530127531127532127533127534127535127536127537127538127539127540127541127542127543127544127545127546127547127548127549127550127551127552127553127554127555127556127557127558127559127560127561127562127563127564127565127566127567127568127569127570127571127572127573127574127575127576127577127578127579127580127581127582127583127584127585127586127587127588127589127590127591127592127593127594127595127596127597127598127599127600127601127602127603127604127605127606127607127608127609127610127611127612127613127614127615127616127617127618127619127620127621127622127623127624127625127626127627127628127629127630127631127632127633127634127635127636127637127638127639127640127641127642127643127644127645127646127647127648127649127650127651127652127653127654127655127656127657127658127659127660127661127662127663127664127665127666127667127668127669127670127671127672127673127674127675127676127677127678127679127680127681127682127683127684127685127686127687127688127689127690127691127692127693127694127695127696127697127698127699127700127701127702127703127704127705127706127707127708127709127710127711127712127713127714127715127716127717127718127719127720127721127722127723127724127725127726127727127728127729127730127731127732127733127734127735127736127737127738127739127740127741127742127743127744127745127746127747127748127749127750127751127752127753127754127755127756127757127758127759127760127761127762127763127764127765127766127767127768127769127770127771127772127773127774127775127776127777127778127779127780127781127782127783127784127785127786127787127788127789127790127791127792127793127794127795127796127797127798127799127800127801127802127803127804127805127806127807127808127809127810127811127812127813127814127815127816127817127818127819127820127821127822127823127824127825127826127827127828127829127830127831127832127833127834127835127836127837127838127839127840127841127842127843127844127845127846127847127848127849127850127851127852127853127854127855127856127857127858127859127860127861127862127863127864127865127866127867127868127869127870127871127872127873127874127875127876127877127878127879127880127881127882127883127884127885127886127887127888127889127890127891127892127893127894127895127896127897127898127899127900127901127902127903127904127905127906127907127908127909127910127911127912127913127914127915127916127917127918127919127920127921127922127923127924127925127926127927127928127929127930127931127932127933127934127935127936127937127938127939127940127941127942127943127944127945127946127947127948127949127950127951127952127953127954127955127956127957127958127959127960127961127962127963127964127965127966127967127968127969127970127971127972127973127974127975127976127977127978127979127980127981127982127983127984127985127986127987127988127989127990127991127992127993127994127995127996127997127998127999128000128001128002128003128004128005128006128007128008128009128010128011128012128013128014128015128016128017128018128019128020128021128022128023128024128025128026128027128028128029128030128031128032128033128034128035128036128037128038128039128040128041128042128043128044128045128046128047128048128049128050128051128052128053128054128055128056128057128058128059128060128061128062128063128064128065128066128067128068128069128070128071128072128073128074128075128076128077128078128079128080128081128082128083128084128085128086128087128088128089128090128091128092128093128094128095128096128097128098128099128100128101128102128103128104128105128106128107128108128109128110128111128112128113128114128115128116128117128118128119128120128121128122128123128124128125128126128127128128128129128130128131128132128133128134128135128136128137128138128139128140128141128142128143128144128145128146128147128148128149128150128151128152128153128154128155128156128157128158128159128160128161128162128163128164128165128166128167128168128169128170128171128172128173128174128175128176128177128178128179128180128181128182128183128184128185128186128187128188128189128190128191128192128193128194128195128196128197128198128199128200128201128202128203128204128205128206128207128208128209128210128211128212128213128214128215128216128217128218128219128220128221128222128223128224128225128226128227128228128229128230128231128232128233128234128235128236128237128238128239128240128241128242128243128244128245128246128247128248128249128250128251128252128253128254128255128256128257128258128259128260128261128262128263128264128265128266128267128268128269128270128271128272128273128274128275128276128277128278128279128280128281128282128283128284128285128286128287128288128289128290128291128292128293128294128295128296128297128298128299128300128301128302128303128304128305128306128307128308128309128310128311128312128313128314128315128316128317128318128319128320128321128322128323128324128325128326128327128328128329128330128331128332128333128334128335128336128337128338128339128340128341128342128343128344128345128346128347128348128349128350128351128352128353128354128355128356128357128358128359128360128361128362128363128364128365128366128367128368128369128370128371128372128373128374128375128376128377128378128379128380128381128382128383128384128385128386128387128388128389128390128391128392128393128394128395128396128397128398128399128400128401128402128403128404128405128406128407128408128409128410128411128412128413128414128415128416128417128418128419128420128421128422128423128424128425128426128427128428128429128430128431128432128433128434128435128436128437128438128439128440128441128442128443128444128445128446128447128448128449128450128451128452128453128454128455128456128457128458128459128460128461128462128463128464128465128466128467128468128469128470128471128472128473128474128475128476128477128478128479128480128481128482128483128484128485128486128487128488128489128490128491128492128493128494128495128496128497128498128499128500128501128502128503128504128505128506128507128508128509128510128511128512128513128514128515128516128517128518128519128520128521128522128523128524128525128526128527128528128529128530128531128532128533128534128535128536128537128538128539128540128541128542128543128544128545128546128547128548128549128550128551128552128553128554128555128556128557128558128559128560128561128562128563128564128565128566128567128568128569128570128571128572128573128574128575128576128577128578128579128580128581128582128583128584128585128586128587128588128589128590128591128592128593128594128595128596128597128598128599128600128601128602128603128604128605128606128607128608128609128610128611128612128613128614128615128616128617128618128619128620128621128622128623128624128625128626128627128628128629128630128631128632128633128634128635128636128637128638128639128640128641128642128643128644128645128646128647128648128649128650128651128652128653128654128655128656128657128658128659128660128661128662128663128664128665128666128667128668128669128670128671128672128673128674128675128676128677128678128679128680128681128682128683128684128685128686128687128688128689128690128691128692128693128694128695128696128697128698128699128700128701128702128703128704128705128706128707128708128709128710128711128712128713128714128715128716128717128718128719128720128721128722128723128724128725128726128727128728128729128730128731128732128733128734128735128736128737128738128739128740128741128742128743128744128745128746128747128748128749128750128751128752128753128754128755128756128757128758128759128760128761128762128763128764128765128766128767128768128769128770128771128772128773128774128775128776128777128778128779128780128781128782128783128784128785128786128787128788128789128790128791128792128793128794128795128796128797128798128799128800128801128802128803128804128805128806128807128808128809128810128811128812128813128814128815128816128817128818128819128820128821128822128823128824128825128826128827128828128829128830128831128832128833128834128835128836128837128838128839128840128841128842128843128844128845128846128847128848128849128850128851128852128853128854128855128856128857128858128859128860128861128862128863128864128865128866128867128868128869128870128871128872128873128874128875128876128877128878128879128880128881128882128883128884128885128886128887128888128889128890128891128892128893128894128895128896128897128898128899128900128901128902128903128904128905128906128907128908128909128910128911128912128913128914128915128916128917128918128919128920128921128922128923128924128925128926128927128928128929128930128931128932128933128934128935128936128937128938128939128940128941128942128943128944128945128946128947128948128949128950128951128952128953128954128955128956128957128958128959128960128961128962128963128964128965128966128967128968128969128970128971128972128973128974128975128976128977128978128979128980128981128982128983128984128985128986128987128988128989128990128991128992128993128994128995128996128997128998128999129000129001129002129003129004129005129006129007129008129009129010129011129012129013129014129015129016129017129018129019129020129021129022129023129024129025129026129027129028129029129030129031129032129033129034129035129036129037129038129039129040129041129042129043129044129045129046129047129048129049129050129051129052129053129054129055129056129057129058129059129060129061129062129063129064129065129066129067129068129069129070129071129072129073129074129075129076129077129078129079129080129081129082129083129084129085129086129087129088129089129090129091129092129093129094129095129096129097129098129099129100129101129102129103129104129105129106129107129108129109129110129111129112129113129114129115129116129117129118129119129120129121129122129123129124129125129126129127129128129129129130129131129132129133129134129135129136129137129138129139129140129141129142129143129144129145129146129147129148129149129150129151129152129153129154129155129156129157129158129159129160129161129162129163129164129165129166129167129168129169129170129171129172129173129174129175129176129177129178129179129180129181129182129183129184129185129186129187129188129189129190129191129192129193129194129195129196129197129198129199129200129201129202129203129204129205129206129207129208129209129210129211129212129213129214129215129216129217129218129219129220129221129222129223129224129225129226129227129228129229129230129231129232129233129234129235129236129237129238129239129240129241129242129243129244129245129246129247129248129249129250129251129252129253129254129255129256129257129258129259129260129261129262129263129264129265129266129267129268129269129270129271129272129273129274129275129276129277129278129279129280129281129282129283129284129285129286129287129288129289129290129291129292129293129294129295129296129297129298129299129300129301129302129303129304129305129306129307129308129309129310129311129312129313129314129315129316129317129318129319129320129321129322129323129324129325129326129327129328129329129330129331129332129333129334129335129336129337129338129339129340129341129342129343129344129345129346129347129348129349129350129351129352129353129354129355129356129357129358129359129360129361129362129363129364129365129366129367129368129369129370129371129372129373129374129375129376129377129378129379129380129381129382129383129384129385129386129387129388129389129390129391129392129393129394129395129396129397129398129399129400129401129402129403129404129405129406129407129408129409129410129411129412129413129414129415129416129417129418129419129420129421129422129423129424129425129426129427129428129429129430129431129432129433129434129435129436129437129438129439129440129441129442129443129444129445129446129447129448129449129450129451129452129453129454129455129456129457129458129459129460129461129462129463129464129465129466129467129468129469129470129471129472129473129474129475129476129477129478129479129480129481129482129483129484129485129486129487129488129489129490129491129492129493129494129495129496129497129498129499129500129501129502129503129504129505129506129507129508129509129510129511129512129513129514129515129516129517129518129519129520129521129522129523129524129525129526129527129528129529129530129531129532129533129534129535129536129537129538129539129540129541129542129543129544129545129546129547129548129549129550129551129552129553129554129555129556129557129558129559129560129561129562129563129564129565129566129567129568129569129570129571129572129573129574129575129576129577129578129579129580129581129582129583129584129585129586129587129588129589129590129591129592129593129594129595129596129597129598129599129600129601129602129603129604129605129606129607129608129609129610129611129612129613129614129615129616129617129618129619129620129621129622129623129624129625129626129627129628129629129630129631129632129633129634129635129636129637129638129639129640129641129642129643129644129645129646129647129648129649129650129651129652129653129654129655129656129657129658129659129660129661129662129663129664129665129666129667129668129669129670129671129672129673129674129675129676129677129678129679129680129681129682129683129684129685129686129687129688129689129690129691129692129693129694129695129696129697129698129699129700129701129702129703129704129705129706129707129708129709129710129711129712129713129714129715129716129717129718129719129720129721129722129723129724129725129726129727129728129729129730129731129732129733129734129735129736129737129738129739129740129741129742129743129744129745129746129747129748129749129750129751129752129753129754129755129756129757129758129759129760129761129762129763129764129765129766129767129768129769129770129771129772129773129774129775129776129777129778129779129780129781129782129783129784129785129786129787129788129789129790129791129792129793129794129795129796129797129798129799129800129801129802129803129804129805129806129807129808129809129810129811129812129813129814129815129816129817129818129819129820129821129822129823129824129825129826129827129828129829129830129831129832129833129834129835129836129837129838129839129840129841129842129843129844129845129846129847129848129849129850129851129852129853129854129855129856129857129858129859129860129861129862129863129864129865129866129867129868129869129870129871129872129873129874129875129876129877129878129879129880129881129882129883129884129885129886129887129888129889129890129891129892129893129894129895129896129897129898129899129900129901129902129903129904129905129906129907129908129909129910129911129912129913129914129915129916129917129918129919129920129921129922129923129924129925129926129927129928129929129930129931129932129933129934129935129936129937129938129939129940129941129942129943129944129945129946129947129948129949129950129951129952129953129954129955129956129957129958129959129960129961129962129963129964129965129966129967129968129969129970129971129972129973129974129975129976129977129978129979129980129981129982129983129984129985129986129987129988129989129990129991129992129993129994129995129996129997129998129999130000130001130002130003130004130005130006130007130008130009130010130011130012130013130014130015130016130017130018130019130020130021130022130023130024130025130026130027130028130029130030130031130032130033130034130035130036130037130038130039130040130041130042130043130044130045130046130047130048130049130050130051130052130053130054130055130056130057130058130059130060130061130062130063130064130065130066130067130068130069130070130071130072130073130074130075130076130077130078130079130080130081130082130083130084130085130086130087130088130089130090130091130092130093130094130095130096130097130098130099130100130101130102130103130104130105130106130107130108130109130110130111130112130113130114130115130116130117130118130119130120130121130122130123130124130125130126130127130128130129130130130131130132130133130134130135130136130137130138130139130140130141130142130143130144130145130146130147130148130149130150130151130152130153130154130155130156130157130158130159130160130161130162130163130164130165130166130167130168130169130170130171130172130173130174130175130176130177130178130179130180130181130182130183130184130185130186130187130188130189130190130191130192130193130194130195130196130197130198130199130200130201130202130203130204130205130206130207130208130209130210130211130212130213130214130215130216130217130218130219130220130221130222130223130224130225130226130227130228130229130230130231130232130233130234130235130236130237130238130239130240130241130242130243130244130245130246130247130248130249130250130251130252130253130254130255130256130257130258130259130260130261130262130263130264130265130266130267130268130269130270130271130272130273130274130275130276130277130278130279130280130281130282130283130284130285130286130287130288130289130290130291130292130293130294130295130296130297130298130299130300130301130302130303130304130305130306130307130308130309130310130311130312130313130314130315130316130317130318130319130320130321130322130323130324130325130326130327130328130329130330130331130332130333130334130335130336130337130338130339130340130341130342130343130344130345130346130347130348130349130350130351130352130353130354130355130356130357130358130359130360130361130362130363130364130365130366130367130368130369130370130371130372130373130374130375130376130377130378130379130380130381130382130383130384130385130386130387130388130389130390130391130392130393130394130395130396130397130398130399130400130401130402130403130404130405130406130407130408130409130410130411130412130413130414130415130416130417130418130419130420130421130422130423130424130425130426130427130428130429130430130431130432130433130434130435130436130437130438130439130440130441130442130443130444130445130446130447130448130449130450130451130452130453130454130455130456130457130458130459130460130461130462130463130464130465130466130467130468130469130470130471130472130473130474130475130476130477130478130479130480130481130482130483130484130485130486130487130488130489130490130491130492130493130494130495130496130497130498130499130500130501130502130503130504130505130506130507130508130509130510130511130512130513130514130515130516130517130518130519130520130521130522130523130524130525130526130527130528130529130530130531130532130533130534130535130536130537130538130539130540130541130542130543130544130545130546130547130548130549130550130551130552130553130554130555130556130557130558130559130560130561130562130563130564130565130566130567130568130569130570130571130572130573130574130575130576130577130578130579130580130581130582130583130584130585130586130587130588130589130590130591130592130593130594130595130596130597130598130599130600130601130602130603130604130605130606130607130608130609130610130611130612130613130614130615130616130617130618130619130620130621130622130623130624130625130626130627130628130629130630130631130632130633130634130635130636130637130638130639130640130641130642130643130644130645130646130647130648130649130650130651130652130653130654130655130656130657130658130659130660130661130662130663130664130665130666130667130668130669130670130671130672130673130674130675130676130677130678130679130680130681130682130683130684130685130686130687130688130689130690130691130692130693130694130695130696130697130698130699130700130701130702130703130704130705130706130707130708130709130710130711130712130713130714130715130716130717130718130719130720130721130722130723130724130725130726130727130728130729130730130731130732130733130734130735130736130737130738130739130740130741130742130743130744130745130746130747130748130749130750130751130752130753130754130755130756130757130758130759130760130761130762130763130764130765130766130767130768130769130770130771130772130773130774130775130776130777130778130779130780130781130782130783130784130785130786130787130788130789130790130791130792130793130794130795130796130797130798130799130800130801130802130803130804130805130806130807130808130809130810130811130812130813130814130815130816130817130818130819130820130821130822130823130824130825130826130827130828130829130830130831130832130833130834130835130836130837130838130839130840130841130842130843130844130845130846130847130848130849130850130851130852130853130854130855130856130857130858130859130860130861130862130863130864130865130866130867130868130869130870130871130872130873130874130875130876130877130878130879130880130881130882130883130884130885130886130887130888130889130890130891130892130893130894130895130896130897130898130899130900130901130902130903130904130905130906130907130908130909130910130911130912130913130914130915130916130917130918130919130920130921130922130923130924130925130926130927130928130929130930130931130932130933130934130935130936130937130938130939130940130941130942130943130944130945130946130947130948130949130950130951130952130953130954130955130956130957130958130959130960130961130962130963130964130965130966130967130968130969130970130971130972130973130974130975130976130977130978130979130980130981130982130983130984130985130986130987130988130989130990130991130992130993130994130995130996130997130998130999131000131001131002131003131004131005131006131007131008131009131010131011131012131013131014131015131016131017131018131019131020131021131022131023131024131025131026131027131028131029131030131031131032131033131034131035131036131037131038131039131040131041131042131043131044131045131046131047131048131049131050131051131052131053131054131055131056131057131058131059131060131061131062131063131064131065131066131067131068131069131070131071131072131073131074131075131076131077131078131079131080131081131082131083131084131085131086131087131088131089131090131091131092131093131094131095131096131097131098131099131100131101131102131103131104131105131106131107131108131109131110131111131112131113131114131115131116131117131118131119131120131121131122131123131124131125131126131127131128131129131130131131131132131133131134131135131136131137131138131139131140131141131142131143131144131145131146131147131148131149131150131151131152131153131154131155131156131157131158131159131160131161131162131163131164131165131166131167131168131169131170131171131172131173131174131175131176131177131178131179131180131181131182131183131184131185131186131187131188131189131190131191131192131193131194131195131196131197131198131199131200131201131202131203131204131205131206131207131208131209131210131211131212131213131214131215131216131217131218131219131220131221131222131223131224131225131226131227131228131229131230131231131232131233131234131235131236131237131238131239131240131241131242131243131244131245131246131247131248131249131250131251131252131253131254131255131256131257131258131259131260131261131262131263131264131265131266131267131268131269131270131271131272131273131274131275131276131277131278131279131280131281131282131283131284131285131286131287131288131289131290131291131292131293131294131295131296131297131298131299131300131301131302131303131304131305131306131307131308131309131310131311131312131313131314131315131316131317131318131319131320131321131322131323131324131325131326131327131328131329131330131331131332131333131334131335131336131337131338131339131340131341131342131343131344131345131346131347131348131349131350131351131352131353131354131355131356131357131358131359131360131361131362131363131364131365131366131367131368131369131370131371131372131373131374131375131376131377131378131379131380131381131382131383131384131385131386131387131388131389131390131391131392131393131394131395131396131397131398131399131400131401131402131403131404131405131406131407131408131409131410131411131412131413131414131415131416131417131418131419131420131421131422131423131424131425131426131427131428131429131430131431131432131433131434131435131436131437131438131439131440131441131442131443131444131445131446131447131448131449131450131451131452131453131454131455131456131457131458131459131460131461131462131463131464131465131466131467131468131469131470131471131472131473131474131475131476131477131478131479131480131481131482131483131484131485131486131487131488131489131490131491131492131493131494131495131496131497131498131499131500131501131502131503131504131505131506131507131508131509131510131511131512131513131514131515131516131517131518131519131520131521131522131523131524131525131526131527131528131529131530131531131532131533131534131535131536131537131538131539131540131541131542131543131544131545131546131547131548131549131550131551131552131553131554131555131556131557131558131559131560131561131562131563131564131565131566131567131568131569131570131571131572131573131574131575131576131577131578131579131580131581131582131583131584131585131586131587131588131589131590131591131592131593131594131595131596131597131598131599131600131601131602131603131604131605131606131607131608131609131610131611131612131613131614131615131616131617131618131619131620131621131622131623131624131625131626131627131628131629131630131631131632131633131634131635131636131637131638131639131640131641131642131643131644131645131646131647131648131649131650131651131652131653131654131655131656131657131658131659131660131661131662131663131664131665131666131667131668131669131670131671131672131673131674131675131676131677131678131679131680131681131682131683131684131685131686131687131688131689131690131691131692131693131694131695131696131697131698131699131700131701131702131703131704131705131706131707131708131709131710131711131712131713131714131715131716131717131718131719131720131721131722131723131724131725131726131727131728131729131730131731131732131733131734131735131736131737131738131739131740131741131742131743131744131745131746131747131748131749131750131751131752131753131754131755131756131757131758131759131760131761131762131763131764131765131766131767131768131769131770131771131772131773131774131775131776131777131778131779131780131781131782131783131784131785131786131787131788131789131790131791131792131793131794131795131796131797131798131799131800131801131802131803131804131805131806131807131808131809131810131811131812131813131814131815131816131817131818131819131820131821131822131823131824131825131826131827131828131829131830131831131832131833131834131835131836131837131838131839131840131841131842131843131844131845131846131847131848131849131850131851131852131853131854131855131856131857131858131859131860131861131862131863131864131865131866131867131868131869131870131871131872131873131874131875131876131877131878131879131880131881131882131883131884131885131886131887131888131889131890131891131892131893131894131895131896131897131898131899131900131901131902131903131904131905131906131907131908131909131910131911131912131913131914131915131916131917131918131919131920131921131922131923131924131925131926131927131928131929131930131931131932131933131934131935131936131937131938131939131940131941131942131943131944131945131946131947131948131949131950131951131952131953131954131955131956131957131958131959131960131961131962131963131964131965131966131967131968131969131970131971131972131973131974131975131976131977131978131979131980131981131982131983131984131985131986131987131988131989131990131991131992131993131994131995131996131997131998131999132000132001132002132003132004132005132006132007132008132009132010132011132012132013132014132015132016132017132018132019132020132021132022132023132024132025132026132027132028132029132030132031132032132033132034132035132036132037132038132039132040132041132042132043132044132045132046132047132048132049132050132051132052132053132054132055132056132057132058132059132060132061132062132063132064132065132066132067132068132069132070132071132072132073132074132075132076132077132078132079132080132081132082132083132084132085132086132087132088132089132090132091132092132093132094132095132096132097132098132099132100132101132102132103132104132105132106132107132108132109132110132111132112132113132114132115132116132117132118132119132120132121132122132123132124132125132126132127132128132129132130132131132132132133132134132135132136132137132138132139132140132141132142132143132144132145132146132147132148132149132150132151132152132153132154132155132156132157132158132159132160132161132162132163132164132165132166132167132168132169132170132171132172132173132174132175132176132177132178132179132180132181132182132183132184132185132186132187132188132189132190132191132192132193132194132195132196132197132198132199132200132201132202132203132204132205132206132207132208132209132210132211132212132213132214132215132216132217132218132219132220132221132222132223132224132225132226132227132228132229132230132231132232132233132234132235132236132237132238132239132240132241132242132243132244132245132246132247132248132249132250132251132252132253132254132255132256132257132258132259132260132261132262132263132264132265132266132267132268132269132270132271132272132273132274132275132276132277132278132279132280132281132282132283132284132285132286132287132288132289132290132291132292132293132294132295132296132297132298132299132300132301132302132303132304132305132306132307132308132309132310132311132312132313132314132315132316132317132318132319132320132321132322132323132324132325132326132327132328132329132330132331132332132333132334132335132336132337132338132339132340132341132342132343132344132345132346132347132348132349132350132351132352132353132354132355132356132357132358132359132360132361132362132363132364132365132366132367132368132369132370132371132372132373132374132375132376132377132378132379132380132381132382132383132384132385132386132387132388132389132390132391132392132393132394132395132396132397132398132399132400132401132402132403132404132405132406132407132408132409132410132411132412132413132414132415132416132417132418132419132420132421132422132423132424132425132426132427132428132429132430132431132432132433132434132435132436132437132438132439132440132441132442132443132444132445132446132447132448132449132450132451132452132453132454132455132456132457132458132459132460132461132462132463132464132465132466132467132468132469132470132471132472132473132474132475132476132477132478132479132480132481132482132483132484132485132486132487132488132489132490132491132492132493132494132495132496132497132498132499132500132501132502132503132504132505132506132507132508132509132510132511132512132513132514132515132516132517132518132519132520132521132522132523132524132525132526132527132528132529132530132531132532132533132534132535132536132537132538132539132540132541132542132543132544132545132546132547132548132549132550132551132552132553132554132555132556132557132558132559132560132561132562132563132564132565132566132567132568132569132570132571132572132573132574132575132576132577132578132579132580132581132582132583132584132585132586132587132588132589132590132591132592132593132594132595132596132597132598132599132600132601132602132603132604132605132606132607132608132609132610132611132612132613132614132615132616132617132618132619132620132621132622132623132624132625132626132627132628132629132630132631132632132633132634132635132636132637132638132639132640132641132642132643132644132645132646132647132648132649132650132651132652132653132654132655132656132657132658132659132660132661132662132663132664132665132666132667132668132669132670132671132672132673132674132675132676132677132678132679132680132681132682132683132684132685132686132687132688132689132690132691132692132693132694132695132696132697132698132699132700132701132702132703132704132705132706132707132708132709132710132711132712132713132714132715132716132717132718132719132720132721132722132723132724132725132726132727132728132729132730132731132732132733132734132735132736132737132738132739132740132741132742132743132744132745132746132747132748132749132750132751132752132753132754132755132756132757132758132759132760132761132762132763132764132765132766132767132768132769132770132771132772132773132774132775132776132777132778132779132780132781132782132783132784132785132786132787132788132789132790132791132792132793132794132795132796132797132798132799132800132801132802132803132804132805132806132807132808132809132810132811132812132813132814132815132816132817132818132819132820132821132822132823132824132825132826132827132828132829132830132831132832132833132834132835132836132837132838132839132840132841132842132843132844132845132846132847132848132849132850132851132852132853132854132855132856132857132858132859132860132861132862132863132864132865132866132867132868132869132870132871132872132873132874132875132876132877132878132879132880132881132882132883132884132885132886132887132888132889132890132891132892132893132894132895132896132897132898132899132900132901132902132903132904132905132906132907132908132909132910132911132912132913132914132915132916132917132918132919132920132921132922132923132924132925132926132927132928132929132930132931132932132933132934132935132936132937132938132939132940132941132942132943132944132945132946132947132948132949132950132951132952132953132954132955132956132957132958132959132960132961132962132963132964132965132966132967132968132969132970132971132972132973132974132975132976132977132978132979132980132981132982132983132984132985132986132987132988132989132990132991132992132993132994132995132996132997132998132999133000133001133002133003133004133005133006133007133008133009133010133011133012133013133014133015133016133017133018133019133020133021133022133023133024133025133026133027133028133029133030133031133032133033133034133035133036133037133038133039133040133041133042133043133044133045133046133047133048133049133050133051133052133053133054133055133056133057133058133059133060133061133062133063133064133065133066133067133068133069133070133071133072133073133074133075133076133077133078133079133080133081133082133083133084133085133086133087133088133089133090133091133092133093133094133095133096133097133098133099133100133101133102133103133104133105133106133107133108133109133110133111133112133113133114133115133116133117133118133119133120133121133122133123133124133125133126133127133128133129133130133131133132133133133134133135133136133137133138133139133140133141133142133143133144133145133146133147133148133149133150133151133152133153133154133155133156133157133158133159133160133161133162133163133164133165133166133167133168133169133170133171133172133173133174133175133176133177133178133179133180133181133182133183133184133185133186133187133188133189133190133191133192133193133194133195133196133197133198133199133200133201133202133203133204133205133206133207133208133209133210133211133212133213133214133215133216133217133218133219133220133221133222133223133224133225133226133227133228133229133230133231133232133233133234133235133236133237133238133239133240133241133242133243133244133245133246133247133248133249133250133251133252133253133254133255133256133257133258133259133260133261133262133263133264133265133266133267133268133269133270133271133272133273133274133275133276133277133278133279133280133281133282133283133284133285133286133287133288133289133290133291133292133293133294133295133296133297133298133299133300133301133302133303133304133305133306133307133308133309133310133311133312133313133314133315133316133317133318133319133320133321133322133323133324133325133326133327133328133329133330133331133332133333133334133335133336133337133338133339133340133341133342133343133344133345133346133347133348133349133350133351133352133353133354133355133356133357133358133359133360133361133362133363133364133365133366133367133368133369133370133371133372133373133374133375133376133377133378133379133380133381133382133383133384133385133386133387133388133389133390133391133392133393133394133395133396133397133398133399133400133401133402133403133404133405133406133407133408133409133410133411133412133413133414133415133416133417133418133419133420133421133422133423133424133425133426133427133428133429133430133431133432133433133434133435133436133437133438133439133440133441133442133443133444133445133446133447133448133449133450133451133452133453133454133455133456133457133458133459133460133461133462133463133464133465133466133467133468133469133470133471133472133473133474133475133476133477133478133479133480133481133482133483133484133485133486133487133488133489133490133491133492133493133494133495133496133497133498133499133500133501133502133503133504133505133506133507133508133509133510133511133512133513133514133515133516133517133518133519133520133521133522133523133524133525133526133527133528133529133530133531133532133533133534133535133536133537133538133539133540133541133542133543133544133545133546133547133548133549133550133551133552133553133554133555133556133557133558133559133560133561133562133563133564133565133566133567133568133569133570133571133572133573133574133575133576133577133578133579133580133581133582133583133584133585133586133587133588133589133590133591133592133593133594133595133596133597133598133599133600133601133602133603133604133605133606133607133608133609133610133611133612133613133614133615133616133617133618133619133620133621133622133623133624133625133626133627133628133629133630133631133632133633133634133635133636133637133638133639133640133641133642133643133644133645133646133647133648133649133650133651133652133653133654133655133656133657133658133659133660133661133662133663133664133665133666133667133668133669133670133671133672133673133674133675133676133677133678133679133680133681133682133683133684133685133686133687133688133689133690133691133692133693133694133695133696133697133698133699133700133701133702133703133704133705133706133707133708133709133710133711133712133713133714133715133716133717133718133719133720133721133722133723133724133725133726133727133728133729133730133731133732133733133734133735133736133737133738133739133740133741133742133743133744133745133746133747133748133749133750133751133752133753133754133755133756133757133758133759133760133761133762133763133764133765133766133767133768133769133770133771133772133773133774133775133776133777133778133779133780133781133782133783133784133785133786133787133788133789133790133791133792133793133794133795133796133797133798133799133800133801133802133803133804133805133806133807133808133809133810133811133812133813133814133815133816133817133818133819133820133821133822133823133824133825133826133827133828133829133830133831133832133833133834133835133836133837133838133839133840133841133842133843133844133845133846133847133848133849133850133851133852133853133854133855133856133857133858133859133860133861133862133863133864133865133866133867133868133869133870133871133872133873133874133875133876133877133878133879133880133881133882133883133884133885133886133887133888133889133890133891133892133893133894133895133896133897133898133899133900133901133902133903133904133905133906133907133908133909133910133911133912133913133914133915133916133917133918133919133920133921133922133923133924133925133926133927133928133929133930133931133932133933133934133935133936133937133938133939133940133941133942133943133944133945133946133947133948133949133950133951133952133953133954133955133956133957133958133959133960133961133962133963133964133965133966133967133968133969133970133971133972133973133974133975133976133977133978133979133980133981133982133983133984133985133986133987133988133989133990133991133992133993133994133995133996133997133998133999134000134001134002134003134004134005134006134007134008134009134010134011134012134013134014134015134016134017134018134019134020134021134022134023134024134025134026134027134028134029134030134031134032134033134034134035134036134037134038134039134040134041134042134043134044134045134046134047134048134049134050134051134052134053134054134055134056134057134058134059134060134061134062134063134064134065134066134067134068134069134070134071134072134073134074134075134076134077134078134079134080134081134082134083134084134085134086134087134088134089134090134091134092134093134094134095134096134097134098134099134100134101134102134103134104134105134106134107134108134109134110134111134112134113134114134115134116134117134118134119134120134121134122134123134124134125134126134127134128134129134130134131134132134133134134134135134136134137134138134139134140134141134142134143134144134145134146134147134148134149134150134151134152134153134154134155134156134157134158134159134160134161134162134163134164134165134166134167134168134169134170134171134172134173134174134175134176134177134178134179134180134181134182134183134184134185134186134187134188134189134190134191134192134193134194134195134196134197134198134199134200134201134202134203134204134205134206134207134208134209134210134211134212134213134214134215134216134217134218134219134220134221134222134223134224134225134226134227134228134229134230134231134232134233134234134235134236134237134238134239134240134241134242134243134244134245134246134247134248134249134250134251134252134253134254134255134256134257134258134259134260134261134262134263134264134265134266134267134268134269134270134271134272134273134274134275134276134277134278134279134280134281134282134283134284134285134286134287134288134289134290134291134292134293134294134295134296134297134298134299134300134301134302134303134304134305134306134307134308134309134310134311134312134313134314134315134316134317134318134319134320134321134322134323134324134325134326134327134328134329134330134331134332134333134334134335134336134337134338134339134340134341134342134343134344134345134346134347134348134349134350134351134352134353134354134355134356134357134358134359134360134361134362134363134364134365134366134367134368134369134370134371134372134373134374134375134376134377134378134379134380134381134382134383134384134385134386134387134388134389134390134391134392134393134394134395134396134397134398134399134400134401134402134403134404134405134406134407134408134409134410134411134412134413134414134415134416134417134418134419134420134421134422134423134424134425134426134427134428134429134430134431134432134433134434134435134436134437134438134439134440134441134442134443134444134445134446134447134448134449134450134451134452134453134454134455134456134457134458134459134460134461134462134463134464134465134466134467134468134469134470134471134472134473134474134475134476134477134478134479134480134481134482134483134484134485134486134487134488134489134490134491134492134493134494134495134496134497134498134499134500134501134502134503134504134505134506134507134508134509134510134511134512134513134514134515134516134517134518134519134520134521134522134523134524134525134526134527134528134529134530134531134532134533134534134535134536134537134538134539134540134541134542134543134544134545134546134547134548134549134550134551134552134553134554134555134556134557134558134559134560134561134562134563134564134565134566134567134568134569134570134571134572134573134574134575134576134577134578134579134580134581134582134583134584134585134586134587134588134589134590134591134592134593134594134595134596134597134598134599134600134601134602134603134604134605134606134607134608134609134610134611134612134613134614134615134616134617134618134619134620134621134622134623134624134625134626134627134628134629134630134631134632134633134634134635134636134637134638134639134640134641134642134643134644134645134646134647134648134649134650134651134652134653134654134655134656134657134658134659134660134661134662134663134664134665134666134667134668134669134670134671134672134673134674134675134676134677134678134679134680134681134682134683134684134685134686134687134688134689134690134691134692134693134694134695134696134697134698134699134700134701134702134703134704134705134706134707134708134709134710134711134712134713134714134715134716134717134718134719134720134721134722134723134724134725134726134727134728134729134730134731134732134733134734134735134736134737134738134739134740134741134742134743134744134745134746134747134748134749134750134751134752134753134754134755134756134757134758134759134760134761134762134763134764134765134766134767134768134769134770134771134772134773134774134775134776134777134778134779134780134781134782134783134784134785134786134787134788134789134790134791134792134793134794134795134796134797134798134799134800134801134802134803134804134805134806134807134808134809134810134811134812134813134814134815134816134817134818134819134820134821134822134823134824134825134826134827134828134829134830134831134832134833134834134835134836134837134838134839134840134841134842134843134844134845134846134847134848134849134850134851134852134853134854134855134856134857134858134859134860134861134862134863134864134865134866134867134868134869134870134871134872134873134874134875134876134877134878134879134880134881134882134883134884134885134886134887134888134889134890134891134892134893134894134895134896134897134898134899134900134901134902134903134904134905134906134907134908134909134910134911134912134913134914134915134916134917134918134919134920134921134922134923134924134925134926134927134928134929134930134931134932134933134934134935134936134937134938134939134940134941134942134943134944134945134946134947134948134949134950134951134952134953134954134955134956134957134958134959134960134961134962134963134964134965134966134967134968134969134970134971134972134973134974134975134976134977134978134979134980134981134982134983134984134985134986134987134988134989134990134991134992134993134994134995134996134997134998134999135000135001135002135003135004135005135006135007135008135009135010135011135012135013135014135015135016135017135018135019135020135021135022135023135024135025135026135027135028135029135030135031135032135033135034135035135036135037135038135039135040135041135042135043135044135045135046135047135048135049135050135051135052135053135054135055135056135057135058135059135060135061135062135063135064135065135066135067135068135069135070135071135072135073135074135075135076135077135078135079135080135081135082135083135084135085135086135087135088135089135090135091135092135093135094135095135096135097135098135099135100135101135102135103135104135105135106135107135108135109135110135111135112135113135114135115135116135117135118135119135120135121135122135123135124135125135126135127135128135129135130135131135132135133135134135135135136135137135138135139135140135141135142135143135144135145135146135147135148135149135150135151135152135153135154135155135156135157135158135159135160135161135162135163135164135165135166135167135168135169135170135171135172135173135174135175135176135177135178135179135180135181135182135183135184135185135186135187135188135189135190135191135192135193135194135195135196135197135198135199135200135201135202135203135204135205135206135207135208135209135210135211135212135213135214135215135216135217135218135219135220135221135222135223135224135225135226135227135228135229135230135231135232135233135234135235135236135237135238135239135240135241135242135243135244135245135246135247135248135249135250135251135252135253135254135255135256135257135258135259135260135261135262135263135264135265135266135267135268135269135270135271135272135273135274135275135276135277135278135279135280135281135282135283135284135285135286135287135288135289135290135291135292135293135294135295135296135297135298135299135300135301135302135303135304135305135306135307135308135309135310135311135312135313135314135315135316135317135318135319135320135321135322135323135324135325135326135327135328135329135330135331135332135333135334135335135336135337135338135339135340135341135342135343135344135345135346135347135348135349135350135351135352135353135354135355135356135357135358135359135360135361135362135363135364135365135366135367135368135369135370135371135372135373135374135375135376135377135378135379135380135381135382135383135384135385135386135387135388135389135390135391135392135393135394135395135396135397135398135399135400135401135402135403135404135405135406135407135408135409135410135411135412135413135414135415135416135417135418135419135420135421135422135423135424135425135426135427135428135429135430135431135432135433135434135435135436135437135438135439135440135441135442135443135444135445135446135447135448135449135450135451135452135453135454135455135456135457135458135459135460135461135462135463135464135465135466135467135468135469135470135471135472135473135474135475135476135477135478135479135480135481135482135483135484135485135486135487135488135489135490135491135492135493135494135495135496135497135498135499135500135501135502135503135504135505135506135507135508135509135510135511135512135513135514135515135516135517135518135519135520135521135522135523135524135525135526135527135528135529135530135531135532135533135534135535135536135537135538135539135540135541135542135543135544135545135546135547135548135549135550135551135552135553135554135555135556135557135558135559135560135561135562135563135564135565135566135567135568135569135570135571135572135573135574135575135576135577135578135579135580135581135582135583135584135585135586135587135588135589135590135591135592135593135594135595135596135597135598135599135600135601135602135603135604135605135606135607135608135609135610135611135612135613135614135615135616135617135618135619135620135621135622135623135624135625135626135627135628135629135630135631135632135633135634135635135636135637135638135639135640135641135642135643135644135645135646135647135648135649135650135651135652135653135654135655135656135657135658135659135660135661135662135663135664135665135666135667135668135669135670135671135672135673135674135675135676135677135678135679135680135681135682135683135684135685135686135687135688135689135690135691135692135693135694135695135696135697135698135699135700135701135702135703135704135705135706135707135708135709135710135711135712135713135714135715135716135717135718135719135720135721135722135723135724135725135726135727135728135729135730135731135732135733135734135735135736135737135738135739135740135741135742135743135744135745135746135747135748135749135750135751135752135753135754135755135756135757135758135759135760135761135762135763135764135765135766135767135768135769135770135771135772135773135774135775135776135777135778135779135780135781135782135783135784135785135786135787135788135789135790135791135792135793135794135795135796135797135798135799135800135801135802135803135804135805135806135807135808135809135810135811135812135813135814135815135816135817135818135819135820135821135822135823135824135825135826135827135828135829135830135831135832135833135834135835135836135837135838135839135840135841135842135843135844135845135846135847135848135849135850135851135852135853135854135855135856135857135858135859135860135861135862135863135864135865135866135867135868135869135870135871135872135873135874135875135876135877135878135879135880135881135882135883135884135885135886135887135888135889135890135891135892135893135894135895135896135897135898135899135900135901135902135903135904135905135906135907135908135909135910135911135912135913135914135915135916135917135918135919135920135921135922135923135924135925135926135927135928135929135930135931135932135933135934135935135936135937135938135939135940135941135942135943135944135945135946135947135948135949135950135951135952135953135954135955135956135957135958135959135960135961135962135963135964135965135966135967135968135969135970135971135972135973135974135975135976135977135978135979135980135981135982135983135984135985135986135987135988135989135990135991135992135993135994135995135996135997135998135999136000136001136002136003136004136005136006136007136008136009136010136011136012136013136014136015136016136017136018136019136020136021136022136023136024136025136026136027136028136029136030136031136032136033136034136035136036136037136038136039136040136041136042136043136044136045136046136047136048136049136050136051136052136053136054136055136056136057136058136059136060136061136062136063136064136065136066136067136068136069136070136071136072136073136074136075136076136077136078136079136080136081136082136083136084136085136086136087136088136089136090136091136092136093136094136095136096136097136098136099136100136101136102136103136104136105136106136107136108136109136110136111136112136113136114136115136116136117136118136119136120136121136122136123136124136125136126136127136128136129136130136131136132136133136134136135136136136137136138136139136140136141136142136143136144136145136146136147136148136149136150136151136152136153136154136155136156136157136158136159136160136161136162136163136164136165136166136167136168136169136170136171136172136173136174136175136176136177136178136179136180136181136182136183136184136185136186136187136188136189136190136191136192136193136194136195136196136197136198136199136200136201136202136203136204136205136206136207136208136209136210136211136212136213136214136215136216136217136218136219136220136221136222136223136224136225136226136227136228136229136230136231136232136233136234136235136236136237136238136239136240136241136242136243136244136245136246136247136248136249136250136251136252136253136254136255136256136257136258136259136260136261136262136263136264136265136266136267136268136269136270136271136272136273136274136275136276136277136278136279136280136281136282136283136284136285136286136287136288136289136290136291136292136293136294136295136296136297136298136299136300136301136302136303136304136305136306136307136308136309136310136311136312136313136314136315136316136317136318136319136320136321136322136323136324136325136326136327136328136329136330136331136332136333136334136335136336136337136338136339136340136341136342136343136344136345136346136347136348136349136350136351136352136353136354136355136356136357136358136359136360136361136362136363136364136365136366136367136368136369136370136371136372136373136374136375136376136377136378136379136380136381136382136383136384136385136386136387136388136389136390136391136392136393136394136395136396136397136398136399136400136401136402136403136404136405136406136407136408136409136410136411136412136413136414136415136416136417136418136419136420136421136422136423136424136425136426136427136428136429136430136431136432136433136434136435136436136437136438136439136440136441136442136443136444136445136446136447136448136449136450136451136452136453136454136455136456136457136458136459136460136461136462136463136464136465136466136467136468136469136470136471136472136473136474136475136476136477136478136479136480136481136482136483136484136485136486136487136488136489136490136491136492136493136494136495136496136497136498136499136500136501136502136503136504136505136506136507136508136509136510136511136512136513136514136515136516136517136518136519136520136521136522136523136524136525136526136527136528136529136530136531136532136533136534136535136536136537136538136539136540136541136542136543136544136545136546136547136548136549136550136551136552136553136554136555136556136557136558136559136560136561136562136563136564136565136566136567136568136569136570136571136572136573136574136575136576136577136578136579136580136581136582136583136584136585136586136587136588136589136590136591136592136593136594136595136596136597136598136599136600136601136602136603136604136605136606136607136608136609136610136611136612136613136614136615136616136617136618136619136620136621136622136623136624136625136626136627136628136629136630136631136632136633136634136635136636136637136638136639136640136641136642136643136644136645136646136647136648136649136650136651136652136653136654136655136656136657136658136659136660136661136662136663136664136665136666136667136668136669136670136671136672136673136674136675136676136677136678136679136680136681136682136683136684136685136686136687136688136689136690136691136692136693136694136695136696136697136698136699136700136701136702136703136704136705136706136707136708136709136710136711136712136713136714136715136716136717136718136719136720136721136722136723136724136725136726136727136728136729136730136731136732136733136734136735136736136737136738136739136740136741136742136743136744136745136746136747136748136749136750136751136752136753136754136755136756136757136758136759136760136761136762136763136764136765136766136767136768136769136770136771136772136773136774136775136776136777136778136779136780136781136782136783136784136785136786136787136788136789136790136791136792136793136794136795136796136797136798136799136800136801136802136803136804136805136806136807136808136809136810136811136812136813136814136815136816136817136818136819136820136821136822136823136824136825136826136827136828136829136830136831136832136833136834136835136836136837136838136839136840136841136842136843136844136845136846136847136848136849136850136851136852136853136854136855136856136857136858136859136860136861136862136863136864136865136866136867136868136869136870136871136872136873136874136875136876136877136878136879136880136881136882136883136884136885136886136887136888136889136890136891136892136893136894136895136896136897136898136899136900136901136902136903136904136905136906136907136908136909136910136911136912136913136914136915136916136917136918136919136920136921136922136923136924136925136926136927136928136929136930136931136932136933136934136935136936136937136938136939136940136941136942136943136944136945136946136947136948136949136950136951136952136953136954136955136956136957136958136959136960136961136962136963136964136965136966136967136968136969136970136971136972136973136974136975136976136977136978136979136980136981136982136983136984136985136986136987136988136989136990136991136992136993136994136995136996136997136998136999137000137001137002137003137004137005137006137007137008137009137010137011137012137013137014137015137016137017137018137019137020137021137022137023137024137025137026137027137028137029137030137031137032137033137034137035137036137037137038137039137040137041137042137043137044137045137046137047137048137049137050137051137052137053137054137055137056137057137058137059137060137061137062137063137064137065137066137067137068137069137070137071137072137073137074137075137076137077137078137079137080137081137082137083137084137085137086137087137088137089137090137091137092137093137094137095137096137097137098137099137100137101137102137103137104137105137106137107137108137109137110137111137112137113137114137115137116137117137118137119137120137121137122137123137124137125137126137127137128137129137130137131137132137133137134137135137136137137137138137139137140137141137142137143137144137145137146137147137148137149137150137151137152137153137154137155137156137157137158137159137160137161137162137163137164137165137166137167137168137169137170137171137172137173137174137175137176137177137178137179137180137181137182137183137184137185137186137187137188137189137190137191137192137193137194137195137196137197137198137199137200137201137202137203137204137205137206137207137208137209137210137211137212137213137214137215137216137217137218137219137220137221137222137223137224137225137226137227137228137229137230137231137232137233137234137235137236137237137238137239137240137241137242137243137244137245137246137247137248137249137250137251137252137253137254137255137256137257137258137259137260137261137262137263137264137265137266137267137268137269137270137271137272137273137274137275137276137277137278137279137280137281137282137283137284137285137286137287137288137289137290137291137292137293137294137295137296137297137298137299137300137301137302137303137304137305137306137307137308137309137310137311137312137313137314137315137316137317137318137319137320137321137322137323137324137325137326137327137328137329137330137331137332137333137334137335137336137337137338137339137340137341137342137343137344137345137346137347137348137349137350137351137352137353137354137355137356137357137358137359137360137361137362137363137364137365137366137367137368137369137370137371137372137373137374137375137376137377137378137379137380137381137382137383137384137385137386137387137388137389137390137391137392137393137394137395137396137397137398137399137400137401137402137403137404137405137406137407137408137409137410137411137412137413137414137415137416137417137418137419137420137421137422137423137424137425137426137427137428137429137430137431137432137433137434137435137436137437137438137439137440137441137442137443137444137445137446137447137448137449137450137451137452137453137454137455137456137457137458137459137460137461137462137463137464137465137466137467137468137469137470137471137472137473137474137475137476137477137478137479137480137481137482137483137484137485137486137487137488137489137490137491137492137493137494137495137496137497137498137499137500137501137502137503137504137505137506137507137508137509137510137511137512137513137514137515137516137517137518137519137520137521137522137523137524137525137526137527137528137529137530137531137532137533137534137535137536137537137538137539137540137541137542137543137544137545137546137547137548137549137550137551137552137553137554137555137556137557137558137559137560137561137562137563137564137565137566137567137568137569137570137571137572137573137574137575137576137577137578137579137580137581137582137583137584137585137586137587137588137589137590137591137592137593137594137595137596137597137598137599137600137601137602137603137604137605137606137607137608137609137610137611137612137613137614137615137616137617137618137619137620137621137622137623137624137625137626137627137628137629137630137631137632137633137634137635137636137637137638137639137640137641137642137643137644137645137646137647137648137649137650137651137652137653137654137655137656137657137658137659137660137661137662137663137664137665137666137667137668137669137670137671137672137673137674137675137676137677137678137679137680137681137682137683137684137685137686137687137688137689137690137691137692137693137694137695137696137697137698137699137700137701137702137703137704137705137706137707137708137709137710137711137712137713137714137715137716137717137718137719137720137721137722137723137724137725137726137727137728137729137730137731137732137733137734137735137736137737137738137739137740137741137742137743137744137745137746137747137748137749137750137751137752137753137754137755137756137757137758137759137760137761137762137763137764137765137766137767137768137769137770137771137772137773137774137775137776137777137778137779137780137781137782137783137784137785137786137787137788137789137790137791137792137793137794137795137796137797137798137799137800137801137802137803137804137805137806137807137808137809137810137811137812137813137814137815137816137817137818137819137820137821137822137823137824137825137826137827137828137829137830137831137832137833137834137835137836137837137838137839137840137841137842137843137844137845137846137847137848137849137850137851137852137853137854137855137856137857137858137859137860137861137862137863137864137865137866137867137868137869137870137871137872137873137874137875137876137877137878137879137880137881137882137883137884137885137886137887137888137889137890137891137892137893137894137895137896137897137898137899137900137901137902137903137904137905137906137907137908137909137910137911137912137913137914137915137916137917137918137919137920137921137922137923137924137925137926137927137928137929137930137931137932137933137934137935137936137937137938137939137940137941137942137943137944137945137946137947137948137949137950137951137952137953137954137955137956137957137958137959137960137961137962137963137964137965137966137967137968137969137970137971137972137973137974137975137976137977137978137979137980137981137982137983137984137985137986137987137988137989137990137991137992137993137994137995137996137997137998137999138000138001138002138003138004138005138006138007138008138009138010138011138012138013138014138015138016138017138018138019138020138021138022138023138024138025138026138027138028138029138030138031138032138033138034138035138036138037138038138039138040138041138042138043138044138045138046138047138048138049138050138051138052138053138054138055138056138057138058138059138060138061138062138063138064138065138066138067138068138069138070138071138072138073138074138075138076138077138078138079138080138081138082138083138084138085138086138087138088138089138090138091138092138093138094138095138096138097138098138099138100138101138102138103138104138105138106138107138108138109138110138111138112138113138114138115138116138117138118138119138120138121138122138123138124138125138126138127138128138129138130138131138132138133138134138135138136138137138138138139138140138141138142138143138144138145138146138147138148138149138150138151138152138153138154138155138156138157138158138159138160138161138162138163138164138165138166138167138168138169138170138171138172138173138174138175138176138177138178138179138180138181138182138183138184138185138186138187138188138189138190138191138192138193138194138195138196138197138198138199138200138201138202138203138204138205138206138207138208138209138210138211138212138213138214138215138216138217138218138219138220138221138222138223138224138225138226138227138228138229138230138231138232138233138234138235138236138237138238138239138240138241138242138243138244138245138246138247138248138249138250138251138252138253138254138255138256138257138258138259138260138261138262138263138264138265138266138267138268138269138270138271138272138273138274138275138276138277138278138279138280138281138282138283138284138285138286138287138288138289138290138291138292138293138294138295138296138297138298138299138300138301138302138303138304138305138306138307138308138309138310138311138312138313138314138315138316138317138318138319138320138321138322138323138324138325138326138327138328138329138330138331138332138333138334138335138336138337138338138339138340138341138342138343138344138345138346138347138348138349138350138351138352138353138354138355138356138357138358138359138360138361138362138363138364138365138366138367138368138369138370138371138372138373138374138375138376138377138378138379138380138381138382138383138384138385138386138387138388138389138390138391138392138393138394138395138396138397138398138399138400138401138402138403138404138405138406138407138408138409138410138411138412138413138414138415138416138417138418138419138420138421138422138423138424138425138426138427138428138429138430138431138432138433138434138435138436138437138438138439138440138441138442138443138444138445138446138447138448138449138450138451138452138453138454138455138456138457138458138459138460138461138462138463138464138465138466138467138468138469138470138471138472138473138474138475138476138477138478138479138480138481138482138483138484138485138486138487138488138489138490138491138492138493138494138495138496138497138498138499138500138501138502138503138504138505138506138507138508138509138510138511138512138513138514138515138516138517138518138519138520138521138522138523138524138525138526138527138528138529138530138531138532138533138534138535138536138537138538138539138540138541138542138543138544138545138546138547138548138549138550138551138552138553138554138555138556138557138558138559138560138561138562138563138564138565138566138567138568138569138570138571138572138573138574138575138576138577138578138579138580138581138582138583138584138585138586138587138588138589138590138591138592138593138594138595138596138597138598138599138600138601138602138603138604138605138606138607138608138609138610138611138612138613138614138615138616138617138618138619138620138621138622138623138624138625138626138627138628138629138630138631138632138633138634138635138636138637138638138639138640138641138642138643138644138645138646138647138648138649138650138651138652138653138654138655138656138657138658138659138660138661138662138663138664138665138666138667138668138669138670138671138672138673138674138675138676138677138678138679138680138681138682138683138684138685138686138687138688138689138690138691138692138693138694138695138696138697138698138699138700138701138702138703138704138705138706138707138708138709138710138711138712138713138714138715138716138717138718138719138720138721138722138723138724138725138726138727138728138729138730138731138732138733138734138735138736138737138738138739138740138741138742138743138744138745138746138747138748138749138750138751138752138753138754138755138756138757138758138759138760138761138762138763138764138765138766138767138768138769138770138771138772138773138774138775138776138777138778138779138780138781138782138783138784138785138786138787138788138789138790138791138792138793138794138795138796138797138798138799138800138801138802138803138804138805138806138807138808138809138810138811138812138813138814138815138816138817138818138819138820138821138822138823138824138825138826138827138828138829138830138831138832138833138834138835138836138837138838138839138840138841138842138843138844138845138846138847138848138849138850138851138852138853138854138855138856138857138858138859138860138861138862138863138864138865138866138867138868138869138870138871138872138873138874138875138876138877138878138879138880138881138882138883138884138885138886138887138888138889138890138891138892138893138894138895138896138897138898138899138900138901138902138903138904138905138906138907138908138909138910138911138912138913138914138915138916138917138918138919138920138921138922138923138924138925138926138927138928138929138930138931138932138933138934138935138936138937138938138939138940138941138942138943138944138945138946138947138948138949138950138951138952138953138954138955138956138957138958138959138960138961138962138963138964138965138966138967138968138969138970138971138972138973138974138975138976138977138978138979138980138981138982138983138984138985138986138987138988138989138990138991138992138993138994138995138996138997138998138999139000139001139002139003139004139005139006139007139008139009139010139011139012139013139014139015139016139017139018139019139020139021139022139023139024139025139026139027139028139029139030139031139032139033139034139035139036139037139038139039139040139041139042139043139044139045139046139047139048139049139050139051139052139053139054139055139056139057139058139059139060139061139062139063139064139065139066139067139068139069139070139071139072139073139074139075139076139077139078139079139080139081139082139083139084139085139086139087139088139089139090139091139092139093139094139095139096139097139098139099139100139101139102139103139104139105139106139107139108139109139110139111139112139113139114139115139116139117139118139119139120139121139122139123139124139125139126139127139128139129139130139131139132139133139134139135139136139137139138139139139140139141139142139143139144139145139146139147139148139149139150139151139152139153139154139155139156139157139158139159139160139161139162139163139164139165139166139167139168139169139170139171139172139173139174139175139176139177139178139179139180139181139182139183139184139185139186139187139188139189139190139191139192139193139194139195139196139197139198139199139200139201139202139203139204139205139206139207139208139209139210139211139212139213139214139215139216139217139218139219139220139221139222139223139224139225139226139227139228139229139230139231139232139233139234139235139236139237139238139239139240139241139242139243139244139245139246139247139248139249139250139251139252139253139254139255139256139257139258139259139260139261139262139263139264139265139266139267139268139269139270139271139272139273139274139275139276139277139278139279139280139281139282139283139284139285139286139287139288139289139290139291139292139293139294139295139296139297139298139299139300139301139302139303139304139305139306139307139308139309139310139311139312139313139314139315139316139317139318139319139320139321139322139323139324139325139326139327139328139329139330139331139332139333139334139335139336139337139338139339139340139341139342139343139344139345139346139347139348139349139350139351139352139353139354139355139356139357139358139359139360139361139362139363139364139365139366139367139368139369139370139371139372139373139374139375139376139377139378139379139380139381139382139383139384139385139386139387139388139389139390139391139392139393139394139395139396139397139398139399139400139401139402139403139404139405139406139407139408139409139410139411139412139413139414139415139416139417139418139419139420139421139422139423139424139425139426139427139428139429139430139431139432139433139434139435139436139437139438139439139440139441139442139443139444139445139446139447139448139449139450139451139452139453139454139455139456139457139458139459139460139461139462139463139464139465139466139467139468139469139470139471139472139473139474139475139476139477139478139479139480139481139482139483139484139485139486139487139488139489139490139491139492139493139494139495139496139497139498139499139500139501139502139503139504139505139506139507139508139509139510139511139512139513139514139515139516139517139518139519139520139521139522139523139524139525139526139527139528139529139530139531139532139533139534139535139536139537139538139539139540139541139542139543139544139545139546139547139548139549139550139551139552139553139554139555139556139557139558139559139560139561139562139563139564139565139566139567139568139569139570139571139572139573139574139575139576139577139578139579139580139581139582139583139584139585139586139587139588139589139590139591139592139593139594139595139596139597139598139599139600139601139602139603139604139605139606139607139608139609139610139611139612139613139614139615139616139617139618139619139620139621139622139623139624139625139626139627139628139629139630139631139632139633139634139635139636139637139638139639139640139641139642139643139644139645139646139647139648139649139650139651139652139653139654139655139656139657139658139659139660139661139662139663139664139665139666139667139668139669139670139671139672139673139674139675139676139677139678139679139680139681139682139683139684139685139686139687139688139689139690139691139692139693139694139695139696139697139698139699139700139701139702139703139704139705139706139707139708139709139710139711139712139713139714139715139716139717139718139719139720139721139722139723139724139725139726139727139728139729139730139731139732139733139734139735139736139737139738139739139740139741139742139743139744139745139746139747139748139749139750139751139752139753139754139755139756139757139758139759139760139761139762139763139764139765139766139767139768139769139770139771139772139773139774139775139776139777139778139779139780139781139782139783139784139785139786139787139788139789139790139791139792139793139794139795139796139797139798139799139800139801139802139803139804139805139806139807139808139809139810139811139812139813139814139815139816139817139818139819139820139821139822139823139824139825139826139827139828139829139830139831139832139833139834139835139836139837139838139839139840139841139842139843139844139845139846139847139848139849139850139851139852139853139854139855139856139857139858139859139860139861139862139863139864139865139866139867139868139869139870139871139872139873139874139875139876139877139878139879139880139881139882139883139884139885139886139887139888139889139890139891139892139893139894139895139896139897139898139899139900139901139902139903139904139905139906139907139908139909139910139911139912139913139914139915139916139917139918139919139920139921139922139923139924139925139926139927139928139929139930139931139932139933139934139935139936139937139938139939139940139941139942139943139944139945139946139947139948139949139950139951139952139953139954139955139956139957139958139959139960139961139962139963139964139965139966139967139968139969139970139971139972139973139974139975139976139977139978139979139980139981139982139983139984139985139986139987139988139989139990139991139992139993139994139995139996139997139998139999140000140001140002140003140004140005140006140007140008140009140010140011140012140013140014140015140016140017140018140019140020140021140022140023140024140025140026140027140028140029140030140031140032140033140034140035140036140037140038140039140040140041140042140043140044140045140046140047140048140049140050140051140052140053140054140055140056140057140058140059140060140061140062140063140064140065140066140067140068140069140070140071140072140073140074140075140076140077140078140079140080140081140082140083140084140085140086140087140088140089140090140091140092140093140094140095140096140097140098140099140100140101140102140103140104140105140106140107140108140109140110140111140112140113140114140115140116140117140118140119140120140121140122140123140124140125140126140127140128140129140130140131140132140133140134140135140136140137140138140139140140140141140142140143140144140145140146140147140148140149140150140151140152140153140154140155140156140157140158140159140160140161140162140163140164140165140166140167140168140169140170140171140172140173140174140175140176140177140178140179140180140181140182140183140184140185140186140187140188140189140190140191140192140193140194140195140196140197140198140199140200140201140202140203140204140205140206140207140208140209140210140211140212140213140214140215140216140217140218140219140220140221140222140223140224140225140226140227140228140229140230140231140232140233140234140235140236140237140238140239140240140241140242140243140244140245140246140247140248140249140250140251140252140253140254140255140256140257140258140259140260140261140262140263140264140265140266140267140268140269140270140271140272140273140274140275140276140277140278140279140280140281140282140283140284140285140286140287140288140289140290140291140292140293140294140295140296140297140298140299140300140301140302140303140304140305140306140307140308140309140310140311140312140313140314140315140316140317140318140319140320140321140322140323140324140325140326140327140328140329140330140331140332140333140334140335140336140337140338140339140340140341140342140343140344140345140346140347140348140349140350140351140352140353140354140355140356140357140358140359140360140361140362140363140364140365140366140367140368140369140370140371140372140373140374140375140376140377140378140379140380140381140382140383140384140385140386140387140388140389140390140391140392140393140394140395140396140397140398140399140400140401140402140403140404140405140406140407140408140409140410140411140412140413140414140415140416140417140418140419140420140421140422140423140424140425140426140427140428140429140430140431140432140433140434140435140436140437140438140439140440140441140442140443140444140445140446140447140448140449140450140451140452140453140454140455140456140457140458140459140460140461140462140463140464140465140466140467140468140469140470140471140472140473140474140475140476140477140478140479140480140481140482140483140484140485140486140487140488140489140490140491140492140493140494140495140496140497140498140499140500140501140502140503140504140505140506140507140508140509140510140511140512140513140514140515140516140517140518140519140520140521140522140523140524140525140526140527140528140529140530140531140532140533140534140535140536140537140538140539140540140541140542140543140544140545140546140547140548140549140550140551140552140553140554140555140556140557140558140559140560140561140562140563140564140565140566140567140568140569140570140571140572140573140574140575140576140577140578140579140580140581140582140583140584140585140586140587140588140589140590140591140592140593140594140595140596140597140598140599140600140601140602140603140604140605140606140607140608140609140610140611140612140613140614140615140616140617140618140619140620140621140622140623140624140625140626140627140628140629140630140631140632140633140634140635140636140637140638140639140640140641140642140643140644140645140646140647140648140649140650140651140652140653140654140655140656140657140658140659140660140661140662140663140664140665140666140667140668140669140670140671140672140673140674140675140676140677140678140679140680140681140682140683140684140685140686140687140688140689140690140691140692140693140694140695140696140697140698140699140700140701140702140703140704140705140706140707140708140709140710140711140712140713140714140715140716140717140718140719140720140721140722140723140724140725140726140727140728140729140730140731140732140733140734140735140736140737140738140739140740140741140742140743140744140745140746140747140748140749140750140751140752140753140754140755140756140757140758140759140760140761140762140763140764140765140766140767140768140769140770140771140772140773140774140775140776140777140778140779140780140781140782140783140784140785140786140787140788140789140790140791140792140793140794140795140796140797140798140799140800140801140802140803140804140805140806140807140808140809140810140811140812140813140814140815140816140817140818140819140820140821140822140823140824140825140826140827140828140829140830140831140832140833140834140835140836140837140838140839140840140841140842140843140844140845140846140847140848140849140850140851140852140853140854140855140856140857140858140859140860140861140862140863140864140865140866140867140868140869140870140871140872140873140874140875140876140877140878140879140880140881140882140883140884140885140886140887140888140889140890140891140892140893140894140895140896140897140898140899140900140901140902140903140904140905140906140907140908140909140910140911140912140913140914140915140916140917140918140919140920140921140922140923140924140925140926140927140928140929140930140931140932140933140934140935140936140937140938140939140940140941140942140943140944140945140946140947140948140949140950140951140952140953140954140955140956140957140958140959140960140961140962140963140964140965140966140967140968140969140970140971140972140973140974140975140976140977140978140979140980140981140982140983140984140985140986140987140988140989140990140991140992140993140994140995140996140997140998140999141000141001141002141003141004141005141006141007141008141009141010141011141012141013141014141015141016141017141018141019141020141021141022141023141024141025141026141027141028141029141030141031141032141033141034141035141036141037141038141039141040141041141042141043141044141045141046141047141048141049141050141051141052141053141054141055141056141057141058141059141060141061141062141063141064141065141066141067141068141069141070141071141072141073141074141075141076141077141078141079141080141081141082141083141084141085141086141087141088141089141090141091141092141093141094141095141096141097141098141099141100141101141102141103141104141105141106141107141108141109141110141111141112141113141114141115141116141117141118141119141120141121141122141123141124141125141126141127141128141129141130141131141132141133141134141135141136141137141138141139141140141141141142141143141144141145141146141147141148141149141150141151141152141153141154141155141156141157141158141159141160141161141162141163141164141165141166141167141168141169141170141171141172141173141174141175141176141177141178141179141180141181141182141183141184141185141186141187141188141189141190141191141192141193141194141195141196141197141198141199141200141201141202141203141204141205141206141207141208141209141210141211141212141213141214141215141216141217141218141219141220141221141222141223141224141225141226141227141228141229141230141231141232141233141234141235141236141237141238141239141240141241141242141243141244141245141246141247141248141249141250141251141252141253141254141255141256141257141258141259141260141261141262141263141264141265141266141267141268141269141270141271141272141273141274141275141276141277141278141279141280141281141282141283141284141285141286141287141288141289141290141291141292141293141294141295141296141297141298141299141300141301141302141303141304141305141306141307141308141309141310141311141312141313141314141315141316141317141318141319141320141321141322141323141324141325141326141327141328141329141330141331141332141333141334141335141336141337141338141339141340141341141342141343141344141345141346141347141348141349141350141351141352141353141354141355141356141357141358141359141360141361141362141363141364141365141366141367141368141369141370141371141372141373141374141375141376141377141378141379141380141381141382141383141384141385141386141387141388141389141390141391141392141393141394141395141396141397141398141399141400141401141402141403141404141405141406141407141408141409141410141411141412141413141414141415141416141417141418141419141420141421141422141423141424141425141426141427141428141429141430141431141432141433141434141435141436141437141438141439141440141441141442141443141444141445141446141447141448141449141450141451141452141453141454141455141456141457141458141459141460141461141462141463141464141465141466141467141468141469141470141471141472141473141474141475141476141477141478141479141480141481141482141483141484141485141486141487141488141489141490141491141492141493141494141495141496141497141498141499141500141501141502141503141504141505141506141507141508141509141510141511141512141513141514141515141516141517141518141519141520141521141522141523141524141525141526141527141528141529141530141531141532141533141534141535141536141537141538141539141540141541141542141543141544141545141546141547141548141549141550141551141552141553141554141555141556141557141558141559141560141561141562141563141564141565141566141567141568141569141570141571141572141573141574141575141576141577141578141579141580141581141582141583141584141585141586141587141588141589141590141591141592141593141594141595141596141597141598141599141600141601141602141603141604141605141606141607141608141609141610141611141612141613141614141615141616141617141618141619141620141621141622141623141624141625141626141627141628141629141630141631141632141633141634141635141636141637141638141639141640141641141642141643141644141645141646141647141648141649141650141651141652141653141654141655141656141657141658141659141660141661141662141663141664141665141666141667141668141669141670141671141672141673141674141675141676141677141678141679141680141681141682141683141684141685141686141687141688141689141690141691141692141693141694141695141696141697141698141699141700141701141702141703141704141705141706141707141708141709141710141711141712141713141714141715141716141717141718141719141720141721141722141723141724141725141726141727141728141729141730141731141732141733141734141735141736141737141738141739141740141741141742141743141744141745141746141747141748141749141750141751141752141753141754141755141756141757141758141759141760141761141762141763141764141765141766141767141768141769141770141771141772141773141774141775141776141777141778141779141780141781141782141783141784141785141786141787141788141789141790141791141792141793141794141795141796141797141798141799141800141801141802141803141804141805141806141807141808141809141810141811141812141813141814141815141816141817141818141819141820141821141822141823141824141825141826141827141828141829141830141831141832141833141834141835141836141837141838141839141840141841141842141843141844141845141846141847141848141849141850141851141852141853141854141855141856141857141858141859141860141861141862141863141864141865141866141867141868141869141870141871141872141873141874141875141876141877141878141879141880141881141882141883141884141885141886141887141888141889141890141891141892141893141894141895141896141897141898141899141900141901141902141903141904141905141906141907141908141909141910141911141912141913141914141915141916141917141918141919141920141921141922141923141924141925141926141927141928141929141930141931141932141933141934141935141936141937141938141939141940141941141942141943141944141945141946141947141948141949141950141951141952141953141954141955141956141957141958141959141960141961141962141963141964141965141966141967141968141969141970141971141972141973141974141975141976141977141978141979141980141981141982141983141984141985141986141987141988141989141990141991141992141993141994141995141996141997141998141999142000142001142002142003142004142005142006142007142008142009142010142011142012142013142014142015142016142017142018142019142020142021142022142023142024142025142026142027142028142029142030142031142032142033142034142035142036142037142038142039142040142041142042142043142044142045142046142047142048142049142050142051142052142053142054142055142056142057142058142059142060142061142062142063142064142065142066142067142068142069142070142071142072142073142074142075142076142077142078142079142080142081142082142083142084142085142086142087142088142089142090142091142092142093142094142095142096142097142098142099142100142101142102142103142104142105142106142107142108142109142110142111142112142113142114142115142116142117142118142119142120142121142122142123142124142125142126142127142128142129142130142131142132142133142134142135142136142137142138142139142140142141142142142143142144142145142146142147142148142149142150142151142152142153142154142155142156142157142158142159142160142161142162142163142164142165142166142167142168142169142170142171142172142173142174142175142176142177142178142179142180142181142182142183142184142185142186142187142188142189142190142191142192142193142194142195142196142197142198142199142200142201142202142203142204142205142206142207142208142209142210142211142212142213142214142215142216142217142218142219142220142221142222142223142224142225142226142227142228142229142230142231142232142233142234142235142236142237142238142239142240142241142242142243142244142245142246142247142248142249142250142251142252142253142254142255142256142257142258142259142260142261142262142263142264142265142266142267142268142269142270142271142272142273142274142275142276142277142278142279142280142281142282142283142284142285142286142287142288142289142290142291142292142293142294142295142296142297142298142299142300142301142302142303142304142305142306142307142308142309142310142311142312142313142314142315142316142317142318142319142320142321142322142323142324142325142326142327142328142329142330142331142332142333142334142335142336142337142338142339142340142341142342142343142344142345142346142347142348142349142350142351142352142353142354142355142356142357142358142359142360142361142362142363142364142365142366142367142368142369142370142371142372142373142374142375142376142377142378142379142380142381142382142383142384142385142386142387142388142389142390142391142392142393142394142395142396142397142398142399142400142401142402142403142404142405142406142407142408142409142410142411142412142413142414142415142416142417142418142419142420142421142422142423142424142425142426142427142428142429142430142431142432142433142434142435142436142437142438142439142440142441142442142443142444142445142446142447142448142449142450142451142452142453142454142455142456142457142458142459142460142461142462142463142464142465142466142467142468142469142470142471142472142473142474142475142476142477142478142479142480142481142482142483142484142485142486142487142488142489142490142491142492142493142494142495142496142497142498142499142500142501142502142503142504142505142506142507142508142509142510142511142512142513142514142515142516142517142518142519142520142521142522142523142524142525142526142527142528142529142530142531142532142533142534142535142536142537142538142539142540142541142542142543142544142545142546142547142548142549142550142551142552142553142554142555142556142557142558142559142560142561142562142563142564142565142566142567142568142569142570142571142572142573142574142575142576142577142578142579142580142581142582142583142584142585142586142587142588142589142590142591142592142593142594142595142596142597142598142599142600142601142602142603142604142605142606142607142608142609142610142611142612142613142614142615142616142617142618142619142620142621142622142623142624142625142626142627142628142629142630142631142632142633142634142635142636142637142638142639142640142641142642142643142644142645142646142647142648142649142650142651142652142653142654142655142656142657142658142659142660142661142662142663142664142665142666142667142668142669142670142671142672142673142674142675142676142677142678142679142680142681142682142683142684142685142686142687142688142689142690142691142692142693142694142695142696142697142698142699142700142701142702142703142704142705142706142707142708142709142710142711142712142713142714142715142716142717142718142719142720142721142722142723142724142725142726142727142728142729142730142731142732142733142734142735142736142737142738142739142740142741142742142743142744142745142746142747142748142749142750142751142752142753142754142755142756142757142758142759142760142761142762142763142764142765142766142767142768142769142770142771142772142773142774142775142776142777142778142779142780142781142782142783142784142785142786142787142788142789142790142791142792142793142794142795142796142797142798142799142800142801142802142803142804142805142806142807142808142809142810142811142812142813142814142815142816142817142818142819142820142821142822142823142824142825142826142827142828142829142830142831142832142833142834142835142836142837142838142839142840142841142842142843142844142845142846142847142848142849142850142851142852142853142854142855142856142857142858142859142860142861142862142863142864142865142866142867142868142869142870142871142872142873142874142875142876142877142878142879142880142881142882142883142884142885142886142887142888142889142890142891142892142893142894142895142896142897142898142899142900142901142902142903142904142905142906142907142908142909142910142911142912142913142914142915142916142917142918142919142920142921142922142923142924142925142926142927142928142929142930142931142932142933142934142935142936142937142938142939142940142941142942142943142944142945142946142947142948142949142950142951142952142953142954142955142956142957142958142959142960142961142962142963142964142965142966142967142968142969142970142971142972142973142974142975142976142977142978142979142980142981142982142983142984142985142986142987142988142989142990142991142992142993142994142995142996142997142998142999143000143001143002143003143004143005143006143007143008143009143010143011143012143013143014143015143016143017143018143019143020143021143022143023143024143025143026143027143028143029143030143031143032143033143034143035143036143037143038143039143040143041143042143043143044143045143046143047143048143049143050143051143052143053143054143055143056143057143058143059143060143061143062143063143064143065143066143067143068143069143070143071143072143073143074143075143076143077143078143079143080143081143082143083143084143085143086143087143088143089143090143091143092143093143094143095143096143097143098143099143100143101143102143103143104143105143106143107143108143109143110143111143112143113143114143115143116143117143118143119143120143121143122143123143124143125143126143127143128143129143130143131143132143133143134143135143136143137143138143139143140143141143142143143143144143145143146143147143148143149143150143151143152143153143154143155143156143157143158143159143160143161143162143163143164143165143166143167143168143169143170143171143172143173143174143175143176143177143178143179143180143181143182143183143184143185143186143187143188143189143190143191143192143193143194143195143196143197143198143199143200143201143202143203143204143205143206143207143208143209143210143211143212143213143214143215143216143217143218143219143220143221143222143223143224143225143226143227143228143229143230143231143232143233143234143235143236143237143238143239143240143241143242143243143244143245143246143247143248143249143250143251143252143253143254143255143256143257143258143259143260143261143262143263143264143265143266143267143268143269143270143271143272143273143274143275143276143277143278143279143280143281143282143283143284143285143286143287143288143289143290143291143292143293143294143295143296143297143298143299143300143301143302143303143304143305143306143307143308143309143310143311143312143313143314143315143316143317143318143319143320143321143322143323143324143325143326143327143328143329143330143331143332143333143334143335143336143337143338143339143340143341143342143343143344143345143346143347143348143349143350143351143352143353143354143355143356143357143358143359143360143361143362143363143364143365143366143367143368143369143370143371143372143373143374143375143376143377143378143379143380143381143382143383143384143385143386143387143388143389143390143391143392143393143394143395143396143397143398143399143400143401143402143403143404143405143406143407143408143409143410143411143412143413143414143415143416143417143418143419143420143421143422143423143424143425143426143427143428143429143430143431143432143433143434143435143436143437143438143439143440143441143442143443143444143445143446143447143448143449143450143451143452143453143454143455143456143457143458143459143460143461143462143463143464143465143466143467143468143469143470143471143472143473143474143475143476143477143478143479143480143481143482143483143484143485143486143487143488143489143490143491143492143493143494143495143496143497143498143499143500143501143502143503143504143505143506143507143508143509143510143511143512143513143514143515143516143517143518143519143520143521143522143523143524143525143526143527143528143529143530143531143532143533143534143535143536143537143538143539143540143541143542143543143544143545143546143547143548143549143550143551143552143553143554143555143556143557143558143559143560143561143562143563143564143565143566143567143568143569143570143571143572143573143574143575143576143577143578143579143580143581143582143583143584143585143586143587143588143589143590143591143592143593143594143595143596143597143598143599143600143601143602143603143604143605143606143607143608143609143610143611143612143613143614143615143616143617143618143619143620143621143622143623143624143625143626143627143628143629143630143631143632143633143634143635143636143637143638143639143640143641143642143643143644143645143646143647143648143649143650143651143652143653143654143655143656143657143658143659143660143661143662143663143664143665143666143667143668143669143670143671143672143673143674143675143676143677143678143679143680143681143682143683143684143685143686143687143688143689143690143691143692143693143694143695143696143697143698143699143700143701143702143703143704143705143706143707143708143709143710143711143712143713143714143715143716143717143718143719143720143721143722143723143724143725143726143727143728143729143730143731143732143733143734143735143736143737143738143739143740143741143742143743143744143745143746143747143748143749143750143751143752143753143754143755143756143757143758143759143760143761143762143763143764143765143766143767143768143769143770143771143772143773143774143775143776143777143778143779143780143781143782143783143784143785143786143787143788143789143790143791143792143793143794143795143796143797143798143799143800143801143802143803143804143805143806143807143808143809143810143811143812143813143814143815143816143817143818143819143820143821143822143823143824143825143826143827143828143829143830143831143832143833143834143835143836143837143838143839143840143841143842143843143844143845143846143847143848143849143850143851143852143853143854143855143856143857143858143859143860143861143862143863143864143865143866143867143868143869143870143871143872143873143874143875143876143877143878143879143880143881143882143883143884143885143886143887143888143889143890143891143892143893143894143895143896143897143898143899143900143901143902143903143904143905143906143907143908143909143910143911143912143913143914143915143916143917143918143919143920143921143922143923143924143925143926143927143928143929143930143931143932143933143934143935143936143937143938143939143940143941143942143943143944143945143946143947143948143949143950143951143952143953143954143955143956143957143958143959143960143961143962143963143964143965143966143967143968143969143970143971143972143973143974143975143976143977143978143979143980143981143982143983143984143985143986143987143988143989143990143991143992143993143994143995143996143997143998143999144000144001144002144003144004144005144006144007144008144009144010144011144012144013144014144015144016144017144018144019144020144021144022144023144024144025144026144027144028144029144030144031144032144033144034144035144036144037144038144039144040144041144042144043144044144045144046144047144048144049144050144051144052144053144054144055144056144057144058144059144060144061144062144063144064144065144066144067144068144069144070144071144072144073144074144075144076144077144078144079144080144081144082144083144084144085144086144087144088144089144090144091144092144093144094144095144096144097144098144099144100144101144102144103144104144105144106144107144108144109144110144111144112144113144114144115144116144117144118144119144120144121144122144123144124144125144126144127144128144129144130144131144132144133144134144135144136144137144138144139144140144141144142144143144144144145144146144147144148144149144150144151144152144153144154144155144156144157144158144159144160144161144162144163144164144165144166144167144168144169144170144171144172144173144174144175144176144177144178144179144180144181144182144183144184144185144186144187144188144189144190144191144192144193144194144195144196144197144198144199144200144201144202144203144204144205144206144207144208144209144210144211144212144213144214144215144216144217144218144219144220144221144222144223144224144225144226144227144228144229144230144231144232144233144234144235144236144237144238144239144240144241144242144243144244144245144246144247144248144249144250144251144252144253144254144255144256144257144258144259144260144261144262144263144264144265144266144267144268144269144270144271144272144273144274144275144276144277144278144279144280144281144282144283144284144285144286144287144288144289144290144291144292144293144294144295144296144297144298144299144300144301144302144303144304144305144306144307144308144309144310144311144312144313144314144315144316144317144318144319144320144321144322144323144324144325144326144327144328144329144330144331144332144333144334144335144336144337144338144339144340144341144342144343144344144345144346144347144348144349144350144351144352144353144354144355144356144357144358144359144360144361144362144363144364144365144366144367144368144369144370144371144372144373144374144375144376144377144378144379144380144381144382144383144384144385144386144387144388144389144390144391144392144393144394144395144396144397144398144399144400144401144402144403144404144405144406144407144408144409144410144411144412144413144414144415144416144417144418144419144420144421144422144423144424144425144426144427144428144429144430144431144432144433144434144435144436144437144438144439144440144441144442144443144444144445144446144447144448144449144450144451144452144453144454144455144456144457144458144459144460144461144462144463144464144465144466144467144468144469144470144471144472144473144474144475144476144477144478144479144480144481144482144483144484144485144486144487144488144489144490144491144492144493144494144495144496144497144498144499144500144501144502144503144504144505144506144507144508144509144510144511144512144513144514144515144516144517144518144519144520144521144522144523144524144525144526144527144528144529144530144531144532144533144534144535144536144537144538144539144540144541144542144543144544144545144546144547144548144549144550144551144552144553144554144555144556144557144558144559144560144561144562144563144564144565144566144567144568144569144570144571144572144573144574144575144576144577144578144579144580144581144582144583144584144585144586144587144588144589144590144591144592144593144594144595144596144597144598144599144600144601144602144603144604144605144606144607144608144609144610144611144612144613144614144615144616144617144618144619144620144621144622144623144624144625144626144627144628144629144630144631144632144633144634144635144636144637144638144639144640144641144642144643144644144645144646144647144648144649144650144651144652144653144654144655144656144657144658144659144660144661144662144663144664144665144666144667144668144669144670144671144672144673144674144675144676144677144678144679144680144681144682144683144684144685144686144687144688144689144690144691144692144693144694144695144696144697144698144699144700144701144702144703144704144705144706144707144708144709144710144711144712144713144714144715144716144717144718144719144720144721144722144723144724144725144726144727144728144729144730144731144732144733144734144735144736144737144738144739144740144741144742144743144744144745144746144747144748144749144750144751144752144753144754144755144756144757144758144759144760144761144762144763144764144765144766144767144768144769144770144771144772144773144774144775144776144777144778144779144780144781144782144783144784144785144786144787144788144789144790144791144792144793144794144795144796144797144798144799144800144801144802144803144804144805144806144807144808144809144810144811144812144813144814144815144816144817144818144819144820144821144822144823144824144825144826144827144828144829144830144831144832144833144834144835144836144837144838144839144840144841144842144843144844144845144846144847144848144849144850144851144852144853144854144855144856144857144858144859144860144861144862144863144864144865144866144867144868144869144870144871144872144873144874144875144876144877144878144879144880144881144882144883144884144885144886144887144888144889144890144891144892144893144894144895144896144897144898144899144900144901144902144903144904144905144906144907144908144909144910144911144912144913144914144915144916144917144918144919144920144921144922144923144924144925144926144927144928144929144930144931144932144933144934144935144936144937144938144939144940144941144942144943144944144945144946144947144948144949144950144951144952144953144954144955144956144957144958144959144960144961144962144963144964144965144966144967144968144969144970144971144972144973144974144975144976144977144978144979144980144981144982144983144984144985144986144987144988144989144990144991144992144993144994144995144996144997144998144999145000145001145002145003145004145005145006145007145008145009145010145011145012145013145014145015145016145017145018145019145020145021145022145023145024145025145026145027145028145029145030145031145032145033145034145035145036145037145038145039145040145041145042145043145044145045145046145047145048145049145050145051145052145053145054145055145056145057145058145059145060145061145062145063145064145065145066145067145068145069145070145071145072145073145074145075145076145077145078145079145080145081145082145083145084145085145086145087145088145089145090145091145092145093145094145095145096145097145098145099145100145101145102145103145104145105145106145107145108145109145110145111145112145113145114145115145116145117145118145119145120145121145122145123145124145125145126145127145128145129145130145131145132145133145134145135145136145137145138145139145140145141145142145143145144145145145146145147145148145149145150145151145152145153145154145155145156145157145158145159145160145161145162145163145164145165145166145167145168145169145170145171145172145173145174145175145176145177145178145179145180145181145182145183145184145185145186145187145188145189145190145191145192145193145194145195145196145197145198145199145200145201145202145203145204145205145206145207145208145209145210145211145212145213145214145215145216145217145218145219145220145221145222145223145224145225145226145227145228145229145230145231145232145233145234145235145236145237145238145239145240145241145242145243145244145245145246145247145248145249145250145251145252145253145254145255145256145257145258145259145260145261145262145263145264145265145266145267145268145269145270145271145272145273145274145275145276145277145278145279145280145281145282145283145284145285145286145287145288145289145290145291145292145293145294145295145296145297145298145299145300145301145302145303145304145305145306145307145308145309145310145311145312145313145314145315145316145317145318145319145320145321145322145323145324145325145326145327145328145329145330145331145332145333145334145335145336145337145338145339145340145341145342145343145344145345145346145347145348145349145350145351145352145353145354145355145356145357145358145359145360145361145362145363145364145365145366145367145368145369145370145371145372145373145374145375145376145377145378145379145380145381145382145383145384145385145386145387145388145389145390145391145392145393145394145395145396145397145398145399145400145401145402145403145404145405145406145407145408145409145410145411145412145413145414145415145416145417145418145419145420145421145422145423145424145425145426145427145428145429145430145431145432145433145434145435145436145437145438145439145440145441145442145443145444145445145446145447145448145449145450145451145452145453145454145455145456145457145458145459145460145461145462145463145464145465145466145467145468145469145470145471145472145473145474145475145476145477145478145479145480145481145482145483145484145485145486145487145488145489145490145491145492145493145494145495145496145497145498145499145500145501145502145503145504145505145506145507145508145509145510145511145512145513145514145515145516145517145518145519145520145521145522145523145524145525145526145527145528145529145530145531145532145533145534145535145536145537145538145539145540145541145542145543145544145545145546145547145548145549145550145551145552145553145554145555145556145557145558145559145560145561145562145563145564145565145566145567145568145569145570145571145572145573145574145575145576145577145578145579145580145581145582145583145584145585145586145587145588145589145590145591145592145593145594145595145596145597145598145599145600145601145602145603145604145605145606145607145608145609145610145611145612145613145614145615145616145617145618145619145620145621145622145623145624145625145626145627145628145629145630145631145632145633145634145635145636145637145638145639145640145641145642145643145644145645145646145647145648145649145650145651145652145653145654145655145656145657145658145659145660145661145662145663145664145665145666145667145668145669145670145671145672145673145674145675145676145677145678145679145680145681145682145683145684145685145686145687145688145689145690145691145692145693145694145695145696145697145698145699145700145701145702145703145704145705145706145707145708145709145710145711145712145713145714145715145716145717145718145719145720145721145722145723145724145725145726145727145728145729145730145731145732145733145734145735145736145737145738145739145740145741145742145743145744145745145746145747145748145749145750145751145752145753145754145755145756145757145758145759145760145761145762145763145764145765145766145767145768145769145770145771145772145773145774145775145776145777145778145779145780145781145782145783145784145785145786145787145788145789145790145791145792145793145794145795145796145797145798145799145800145801145802145803145804145805145806145807145808145809145810145811145812145813145814145815145816145817145818145819145820145821145822145823145824145825145826145827145828145829145830145831145832145833145834145835145836145837145838145839145840145841145842145843145844145845145846145847145848145849145850145851145852145853145854145855145856145857145858145859145860145861145862145863145864145865145866145867145868145869145870145871145872145873145874145875145876145877145878145879145880145881145882145883145884145885145886145887145888145889145890145891145892145893145894145895145896145897145898145899145900145901145902145903145904145905145906145907145908145909145910145911145912145913145914145915145916145917145918145919145920145921145922145923145924145925145926145927145928145929145930145931145932145933145934145935145936145937145938145939145940145941145942145943145944145945145946145947145948145949145950145951145952145953145954145955145956145957145958145959145960145961145962145963145964145965145966145967145968145969145970145971145972145973145974145975145976145977145978145979145980145981145982145983145984145985145986145987145988145989145990145991145992145993145994145995145996145997145998145999146000146001146002146003146004146005146006146007146008146009146010146011146012146013146014146015146016146017146018146019146020146021146022146023146024146025146026146027146028146029146030146031146032146033146034146035146036146037146038146039146040146041146042146043146044146045146046146047146048146049146050146051146052146053146054146055146056146057146058146059146060146061146062146063146064146065146066146067146068146069146070146071146072146073146074146075146076146077146078146079146080146081146082146083146084146085146086146087146088146089146090146091146092146093146094146095146096146097146098146099146100146101146102146103146104146105146106146107146108146109146110146111146112146113146114146115146116146117146118146119146120146121146122146123146124146125146126146127146128146129146130146131146132146133146134146135146136146137146138146139146140146141146142146143146144146145146146146147146148146149146150146151146152146153146154146155146156146157146158146159146160146161146162146163146164146165146166146167146168146169146170146171146172146173146174146175146176146177146178146179146180146181146182146183146184146185146186146187146188146189146190146191146192146193146194146195146196146197146198146199146200146201146202146203146204146205146206146207146208146209146210146211146212146213146214146215146216146217146218146219146220146221146222146223146224146225146226146227146228146229146230146231146232146233146234146235146236146237146238146239146240146241146242146243146244146245146246146247146248146249146250146251146252146253146254146255146256146257146258146259146260146261146262146263146264146265146266146267146268146269146270146271146272146273146274146275146276146277146278146279146280146281146282146283146284146285146286146287146288146289146290146291146292146293146294146295146296146297146298146299146300146301146302146303146304146305146306146307146308146309146310146311146312146313146314146315146316146317146318146319146320146321146322146323146324146325146326146327146328146329146330146331146332146333146334146335146336146337146338146339146340146341146342146343146344146345146346146347146348146349146350146351146352146353146354146355146356146357146358146359146360146361146362146363146364146365146366146367146368146369146370146371146372146373146374146375146376146377146378146379146380146381146382146383146384146385146386146387146388146389146390146391146392146393146394146395146396146397146398146399146400146401146402146403146404146405146406146407146408146409146410146411146412146413146414146415146416146417146418146419146420146421146422146423146424146425146426146427146428146429146430146431146432146433146434146435146436146437146438146439146440146441146442146443146444146445146446146447146448146449146450146451146452146453146454146455146456146457146458146459146460146461146462146463146464146465146466146467146468146469146470146471146472146473146474146475146476146477146478146479146480146481146482146483146484146485146486146487146488146489146490146491146492146493146494146495146496146497146498146499146500146501146502146503146504146505146506146507146508146509146510146511146512146513146514146515146516146517146518146519146520146521146522146523146524146525146526146527146528146529146530146531146532146533146534146535146536146537146538146539146540146541146542146543146544146545146546146547146548146549146550146551146552146553146554146555146556146557146558146559146560146561146562146563146564146565146566146567146568146569146570146571146572146573146574146575146576146577146578146579146580146581146582146583146584146585146586146587146588146589146590146591146592146593146594146595146596146597146598146599146600146601146602146603146604146605146606146607146608146609146610146611146612146613146614146615146616146617146618146619146620146621146622146623146624146625146626146627146628146629146630146631146632146633146634146635146636146637146638146639146640146641146642146643146644146645146646146647146648146649146650146651146652146653146654146655146656146657146658146659146660146661146662146663146664146665146666146667146668146669146670146671146672146673146674146675146676146677146678146679146680146681146682146683146684146685146686146687146688146689146690146691146692146693146694146695146696146697146698146699146700146701146702146703146704146705146706146707146708146709146710146711146712146713146714146715146716146717146718146719146720146721146722146723146724146725146726146727146728146729146730146731146732146733146734146735146736146737146738146739146740146741146742146743146744146745146746146747146748146749146750146751146752146753146754146755146756146757146758146759146760146761146762146763146764146765146766146767146768146769146770146771146772146773146774146775146776146777146778146779146780146781146782146783146784146785146786146787146788146789146790146791146792146793146794146795146796146797146798146799146800146801146802146803146804146805146806146807146808146809146810146811146812146813146814146815146816146817146818146819146820146821146822146823146824146825146826146827146828146829146830146831146832146833146834146835146836146837146838146839146840146841146842146843146844146845146846146847146848146849146850146851146852146853146854146855146856146857146858146859146860146861146862146863146864146865146866146867146868146869146870146871146872146873146874146875146876146877146878146879146880146881146882146883146884146885146886146887146888146889146890146891146892146893146894146895146896146897146898146899146900146901146902146903146904146905146906146907146908146909146910146911146912146913146914146915146916146917146918146919146920146921146922146923146924146925146926146927146928146929146930146931146932146933146934146935146936146937146938146939146940146941146942146943146944146945146946146947146948146949146950146951146952146953146954146955146956146957146958146959146960146961146962146963146964146965146966146967146968146969146970146971146972146973146974146975146976146977146978146979146980146981146982146983146984146985146986146987146988146989146990146991146992146993146994146995146996146997146998146999147000147001147002147003147004147005147006147007147008147009147010147011147012147013147014147015147016147017147018147019147020147021147022147023147024147025147026147027147028147029147030147031147032147033147034147035147036147037147038147039147040147041147042147043147044147045147046147047147048147049147050147051147052147053147054147055147056147057147058147059147060147061147062147063147064147065147066147067147068147069147070147071147072147073147074147075147076147077147078147079147080147081147082147083147084147085147086147087147088147089147090147091147092147093147094147095147096147097147098147099147100147101147102147103147104147105147106147107147108147109147110147111147112147113147114147115147116147117147118147119147120147121147122147123147124147125147126147127147128147129147130147131147132147133147134147135147136147137147138147139147140147141147142147143147144147145147146147147147148147149147150147151147152147153147154147155147156147157147158147159147160147161147162147163147164147165147166147167147168147169147170147171147172147173147174147175147176147177147178147179147180147181147182147183147184147185147186147187147188147189147190147191147192147193147194147195147196147197147198147199147200147201147202147203147204147205147206147207147208147209147210147211147212147213147214147215147216147217147218147219147220147221147222147223147224147225147226147227147228147229147230147231147232147233147234147235147236147237147238147239147240147241147242147243147244147245147246147247147248147249147250147251147252147253147254147255147256147257147258147259147260147261147262147263147264147265147266147267147268147269147270147271147272147273147274147275147276147277147278147279147280147281147282147283147284147285147286147287147288147289147290147291147292147293147294147295147296147297147298147299147300147301147302147303147304147305147306147307147308147309147310147311147312147313147314147315147316147317147318147319147320147321147322147323147324147325147326147327147328147329147330147331147332147333147334147335147336147337147338147339147340147341147342147343147344147345147346147347147348147349147350147351147352147353147354147355147356147357147358147359147360147361147362147363147364147365147366147367147368147369147370147371147372147373147374147375147376147377147378147379147380147381147382147383147384147385147386147387147388147389147390147391147392147393147394147395147396147397147398147399147400147401147402147403147404147405147406147407147408147409147410147411147412147413147414147415147416147417147418147419147420147421147422147423147424147425147426147427147428147429147430147431147432147433147434147435147436147437147438147439147440147441147442147443147444147445147446147447147448147449147450147451147452147453147454147455147456147457147458147459147460147461147462147463147464147465147466147467147468147469147470147471147472147473147474147475147476147477147478147479147480147481147482147483147484147485147486147487147488147489147490147491147492147493147494147495147496147497147498147499147500147501147502147503147504147505147506147507147508147509147510147511147512147513147514147515147516147517147518147519147520147521147522147523147524147525147526147527147528147529147530147531147532147533147534147535147536147537147538147539147540147541147542147543147544147545147546147547147548147549147550147551147552147553147554147555147556147557147558147559147560147561147562147563147564147565147566147567147568147569147570147571147572147573147574147575147576147577147578147579147580147581147582147583147584147585147586147587147588147589147590147591147592147593147594147595147596147597147598147599147600147601147602147603147604147605147606147607147608147609147610147611147612147613147614147615147616147617147618147619147620147621147622147623147624147625147626147627147628147629147630147631147632147633147634147635147636147637147638147639147640147641147642147643147644147645147646147647147648147649147650147651147652147653147654147655147656147657147658147659147660147661147662147663147664147665147666147667147668147669147670147671147672147673147674147675147676147677147678147679147680147681147682147683147684147685147686147687147688147689147690147691147692147693147694147695147696147697147698147699147700147701147702147703147704147705147706147707147708147709147710147711147712147713147714147715147716147717147718147719147720147721147722147723147724147725147726147727147728147729147730147731147732147733147734147735147736147737147738147739147740147741147742147743147744147745147746147747147748147749147750147751147752147753147754147755147756147757147758147759147760147761147762147763147764147765147766147767147768147769147770147771147772147773147774147775147776147777147778147779147780147781147782147783147784147785147786147787147788147789147790147791147792147793147794147795147796147797147798147799147800147801147802147803147804147805147806147807147808147809147810147811147812147813147814147815147816147817147818147819147820147821147822147823147824147825147826147827147828147829147830147831147832147833147834147835147836147837147838147839147840147841147842147843147844147845147846147847147848147849147850147851147852147853147854147855147856147857147858147859147860147861147862147863147864147865147866147867147868147869147870147871147872147873147874147875147876147877147878147879147880147881147882147883147884147885147886147887147888147889147890147891147892147893147894147895147896147897147898147899147900147901147902147903147904147905147906147907147908147909147910147911147912147913147914147915147916147917147918147919147920147921147922147923147924147925147926147927147928147929147930147931147932147933147934147935147936147937147938147939147940147941147942147943147944147945147946147947147948147949147950147951147952147953147954147955147956147957147958147959147960147961147962147963147964147965147966147967147968147969147970147971147972147973147974147975147976147977147978147979147980147981147982147983147984147985147986147987147988147989147990147991147992147993147994147995147996147997147998147999148000148001148002148003148004148005148006148007148008148009148010148011148012148013148014148015148016148017148018148019148020148021148022148023148024148025148026148027148028148029148030148031148032148033148034148035148036148037148038148039148040148041148042148043148044148045148046148047148048148049148050148051148052148053148054148055148056148057148058148059148060148061148062148063148064148065148066148067148068148069148070148071148072148073148074148075148076148077148078148079148080148081148082148083148084148085148086148087148088148089148090148091148092148093148094148095148096148097148098148099148100148101148102148103148104148105148106148107148108148109148110148111148112148113148114148115148116148117148118148119148120148121148122148123148124148125148126148127148128148129148130148131148132148133148134148135148136148137148138148139148140148141148142148143148144148145148146148147148148148149148150148151148152148153148154148155148156148157148158148159148160148161148162148163148164148165148166148167148168148169148170148171148172148173148174148175148176148177148178148179148180148181148182148183148184148185148186148187148188148189148190148191148192148193148194148195148196148197148198148199148200148201148202148203148204148205148206148207148208148209148210148211148212148213148214148215148216148217148218148219148220148221148222148223148224148225148226148227148228148229148230148231148232148233148234148235148236148237148238148239148240148241148242148243148244148245148246148247148248148249148250148251148252148253148254148255148256148257148258148259148260148261148262148263148264148265148266148267148268148269148270148271148272148273148274148275148276148277148278148279148280148281148282148283148284148285148286148287148288148289148290148291148292148293148294148295148296148297148298148299148300148301148302148303148304148305148306148307148308148309148310148311148312148313148314148315148316148317148318148319148320148321148322148323148324148325148326148327148328148329148330148331148332148333148334148335148336148337148338148339148340148341148342148343148344148345148346148347148348148349148350148351148352148353148354148355148356148357148358148359148360148361148362148363148364148365148366148367148368148369148370148371148372148373148374148375148376148377148378148379148380148381148382148383148384148385148386148387148388148389148390148391148392148393148394148395148396148397148398148399148400148401148402148403148404148405148406148407148408148409148410148411148412148413148414148415148416148417148418148419148420148421148422148423148424148425148426148427148428148429148430148431148432148433148434148435148436148437148438148439148440148441148442148443148444148445148446148447148448148449148450148451148452148453148454148455148456148457148458148459148460148461148462148463148464148465148466148467148468148469148470148471148472148473148474148475148476148477148478148479148480148481148482148483148484148485148486148487148488148489148490148491148492148493148494148495148496148497148498148499148500148501148502148503148504148505148506148507148508148509148510148511148512148513148514148515148516148517148518148519148520148521148522148523148524148525148526148527148528148529148530148531148532148533148534148535148536148537148538148539148540148541148542148543148544148545148546148547148548148549148550148551148552148553148554148555148556148557148558148559148560148561148562148563148564148565148566148567148568148569148570148571148572148573148574148575148576148577148578148579148580148581148582148583148584148585148586148587148588148589148590148591148592148593148594148595148596148597148598148599148600148601148602148603148604148605148606148607148608148609148610148611148612148613148614148615148616148617148618148619148620148621148622148623148624148625148626148627148628148629148630148631148632148633148634148635148636148637148638148639148640148641148642148643148644148645148646148647148648148649148650148651148652148653148654148655148656148657148658148659148660148661148662148663148664148665148666148667148668148669148670148671148672148673148674148675148676148677148678148679148680148681148682148683148684148685148686148687148688148689148690148691148692148693148694148695148696148697148698148699148700148701148702148703148704148705148706148707148708148709148710148711148712148713148714148715148716148717148718148719148720148721148722148723148724148725148726148727148728148729148730148731148732148733148734148735148736148737148738148739148740148741148742148743148744148745148746148747148748148749148750148751148752148753148754148755148756148757148758148759148760148761148762148763148764148765148766148767148768148769148770148771148772148773148774148775148776148777148778148779148780148781148782148783148784148785148786148787148788148789148790148791148792148793148794148795148796148797148798148799148800148801148802148803148804148805148806148807148808148809148810148811148812148813148814148815148816148817148818148819148820148821148822148823148824148825148826148827148828148829148830148831148832148833148834148835148836148837148838148839148840148841148842148843148844148845148846148847148848148849148850148851148852148853148854148855148856148857148858148859148860148861148862148863148864148865148866148867148868148869148870148871148872148873148874148875148876148877148878148879148880148881148882148883148884148885148886148887148888148889148890148891148892148893148894148895148896148897148898148899148900148901148902148903148904148905148906148907148908148909148910148911148912148913148914148915148916148917148918148919148920148921148922148923148924148925148926148927148928148929148930148931148932148933148934148935148936148937148938148939148940148941148942148943148944148945148946148947148948148949148950148951148952148953148954148955148956148957148958148959148960148961148962148963148964148965148966148967148968148969148970148971148972148973148974148975148976148977148978148979148980148981148982148983148984148985148986148987148988148989148990148991148992148993148994148995148996148997148998148999149000149001149002149003149004149005149006149007149008149009149010149011149012149013149014149015149016149017149018149019149020149021149022149023149024149025149026149027149028149029149030149031149032149033149034149035149036149037149038149039149040149041149042149043149044149045149046149047149048149049149050149051149052149053149054149055149056149057149058149059149060149061149062149063149064149065149066149067149068149069149070149071149072149073149074149075149076149077149078149079149080149081149082149083149084149085149086149087149088149089149090149091149092149093149094149095149096149097149098149099149100149101149102149103149104149105149106149107149108149109149110149111149112149113149114149115149116149117149118149119149120149121149122149123149124149125149126149127149128149129149130149131149132149133149134149135149136149137149138149139149140149141149142149143149144149145149146149147149148149149149150149151149152149153149154149155149156149157149158149159149160149161149162149163149164149165149166149167149168149169149170149171149172149173149174149175149176149177149178149179149180149181149182149183149184149185149186149187149188149189149190149191149192149193149194149195149196149197149198149199149200149201149202149203149204149205149206149207149208149209149210149211149212149213149214149215149216149217149218149219149220149221149222149223149224149225149226149227149228149229149230149231149232149233149234149235149236149237149238149239149240149241149242149243149244149245149246149247149248149249149250149251149252149253149254149255149256149257149258149259149260149261149262149263149264149265149266149267149268149269149270149271149272149273149274149275149276149277149278149279149280149281149282149283149284149285149286149287149288149289149290149291149292149293149294149295149296149297149298149299149300149301149302149303149304149305149306149307149308149309149310149311149312149313149314149315149316149317149318149319149320149321149322149323149324149325149326149327149328149329149330149331149332149333149334149335149336149337149338149339149340149341149342149343149344149345149346149347149348149349149350149351149352149353149354149355149356149357149358149359149360149361149362149363149364149365149366149367149368149369149370149371149372149373149374149375149376149377149378149379149380149381149382149383149384149385149386149387149388149389149390149391149392149393149394149395149396149397149398149399149400149401149402149403149404149405149406149407149408149409149410149411149412149413149414149415149416149417149418149419149420149421149422149423149424149425149426149427149428149429149430149431149432149433149434149435149436149437149438149439149440149441149442149443149444149445149446149447149448149449149450149451149452149453149454149455149456149457149458149459149460149461149462149463149464149465149466149467149468149469149470149471149472149473149474149475149476149477149478149479149480149481149482149483149484149485149486149487149488149489149490149491149492149493149494149495149496149497149498149499149500149501149502149503149504149505149506149507149508149509149510149511149512149513149514149515149516149517149518149519149520149521149522149523149524149525149526149527149528149529149530149531149532149533149534149535149536149537149538149539149540149541149542149543149544149545149546149547149548149549149550149551149552149553149554149555149556149557149558149559149560149561149562149563149564149565149566149567149568149569149570149571149572149573149574149575149576149577149578149579149580149581149582149583149584149585149586149587149588149589149590149591149592149593149594149595149596149597149598149599149600149601149602149603149604149605149606149607149608149609149610149611149612149613149614149615149616149617149618149619149620149621149622149623149624149625149626149627149628149629149630149631149632149633149634149635149636149637149638149639149640149641149642149643149644149645149646149647149648149649149650149651149652149653149654149655149656149657149658149659149660149661149662149663149664149665149666149667149668149669149670149671149672149673149674149675149676149677149678149679149680149681149682149683149684149685149686149687149688149689149690149691149692149693149694149695149696149697149698149699149700149701149702149703149704149705149706149707149708149709149710149711149712149713149714149715149716149717149718149719149720149721149722149723149724149725149726149727149728149729149730149731149732149733149734149735149736149737149738149739149740149741149742149743149744149745149746149747149748149749149750149751149752149753149754149755149756149757149758149759149760149761149762149763149764149765149766149767149768149769149770149771149772149773149774149775149776149777149778149779149780149781149782149783149784149785149786149787149788149789149790149791149792149793149794149795149796149797149798149799149800149801149802149803149804149805149806149807149808149809149810149811149812149813149814149815149816149817149818149819149820149821149822149823149824149825149826149827149828149829149830149831149832149833149834149835149836149837149838149839149840149841149842149843149844149845149846149847149848149849149850149851149852149853149854149855149856149857149858149859149860149861149862149863149864149865149866149867149868149869149870149871149872149873149874149875149876149877149878149879149880149881149882149883149884149885149886149887149888149889149890149891149892149893149894149895149896149897149898149899149900149901149902149903149904149905149906149907149908149909149910149911149912149913149914149915149916149917149918149919149920149921149922149923149924149925149926149927149928149929149930149931149932149933149934149935149936149937149938149939149940149941149942149943149944149945149946149947149948149949149950149951149952149953149954149955149956149957149958149959149960149961149962149963149964149965149966149967149968149969149970149971149972149973149974149975149976149977149978149979149980149981149982149983149984149985149986149987149988149989149990149991149992149993149994149995149996149997149998149999150000150001150002150003150004150005150006150007150008150009150010150011150012150013150014150015150016150017150018150019150020150021150022150023150024150025150026150027150028150029150030150031150032150033150034150035150036150037150038150039150040150041150042150043150044150045150046150047150048150049150050150051150052150053150054150055150056150057150058150059150060150061150062150063150064150065150066150067150068150069150070150071150072150073150074150075150076150077150078150079150080150081150082150083150084150085150086150087150088150089150090150091150092150093150094150095150096150097150098150099150100150101150102150103150104150105150106150107150108150109150110150111150112150113150114150115150116150117150118150119150120150121150122150123150124150125150126150127150128150129150130150131150132150133150134150135150136150137150138150139150140150141150142150143150144150145150146150147150148150149150150150151150152150153150154150155150156150157150158150159150160150161150162150163150164150165150166150167150168150169150170150171150172150173150174150175150176150177150178150179150180150181150182150183150184150185150186150187150188150189150190150191150192150193150194150195150196150197150198150199150200150201150202150203150204150205150206150207150208150209150210150211150212150213150214150215150216150217150218150219150220150221150222150223150224150225150226150227150228150229150230150231150232150233150234150235150236150237150238150239150240150241150242150243150244150245150246150247150248150249150250150251150252150253150254150255150256150257150258150259150260150261150262150263150264150265150266150267150268150269150270150271150272150273150274150275150276150277150278150279150280150281150282150283150284150285150286150287150288150289150290150291150292150293150294150295150296150297150298150299150300150301150302150303150304150305150306150307150308150309150310150311150312150313150314150315150316150317150318150319150320150321150322150323150324150325150326150327150328150329150330150331150332150333150334150335150336150337150338150339150340150341150342150343150344150345150346150347150348150349150350150351150352150353150354150355150356150357150358150359150360150361150362150363150364150365150366150367150368150369150370150371150372150373150374150375150376150377150378150379150380150381150382150383150384150385150386150387150388150389150390150391150392150393150394150395150396150397150398150399150400150401150402150403150404150405150406150407150408150409150410150411150412150413150414150415150416150417150418150419150420150421150422150423150424150425150426150427150428150429150430150431150432150433150434150435150436150437150438150439150440150441150442150443150444150445150446150447150448150449150450150451150452150453150454150455150456150457150458150459150460150461150462150463150464150465150466150467150468150469150470150471150472150473150474150475150476150477150478150479150480150481150482150483150484150485150486150487150488150489150490150491150492150493150494150495150496150497150498150499150500150501150502150503150504150505150506150507150508150509150510150511150512150513150514150515150516150517150518150519150520150521150522150523150524150525150526150527150528150529150530150531150532150533150534150535150536150537150538150539150540150541150542150543150544150545150546150547150548150549150550150551150552150553150554150555150556150557150558150559150560150561150562150563150564150565150566150567150568150569150570150571150572150573150574150575150576150577150578150579150580150581150582150583150584150585150586150587150588150589150590150591150592150593150594150595150596150597150598150599150600150601150602150603150604150605150606150607150608150609150610150611150612150613150614150615150616150617150618150619150620150621150622150623150624150625150626150627150628150629150630150631150632150633150634150635150636150637150638150639150640150641150642150643150644150645150646150647150648150649150650150651150652150653150654150655150656150657150658150659150660150661150662150663150664150665150666150667150668150669150670150671150672150673150674150675150676150677150678150679150680150681150682150683150684150685150686150687150688150689150690150691150692150693150694150695150696150697150698150699150700150701150702150703150704150705150706150707150708150709150710150711150712150713150714150715150716150717150718150719150720150721150722150723150724150725150726150727150728150729150730150731150732150733150734150735150736150737150738150739150740150741150742150743150744150745150746150747150748150749150750150751150752150753150754150755150756150757150758150759150760150761150762150763150764150765150766150767150768150769150770150771150772150773150774150775150776150777150778150779150780150781150782150783150784150785150786150787150788150789150790150791150792150793150794150795150796150797150798150799150800150801150802150803150804150805150806150807150808150809150810150811150812150813150814150815150816150817150818150819150820150821150822150823150824150825150826150827150828150829150830150831150832150833150834150835150836150837150838150839150840150841150842150843150844150845150846150847150848150849150850150851150852150853150854150855150856150857150858150859150860150861150862150863150864150865150866150867150868150869150870150871150872150873150874150875150876150877150878150879150880150881150882150883150884150885150886150887150888150889150890150891150892150893150894150895150896150897150898150899150900150901150902150903150904150905150906150907150908150909150910150911150912150913150914150915150916150917150918150919150920150921150922150923150924150925150926150927150928150929150930150931150932150933150934150935150936150937150938150939150940150941150942150943150944150945150946150947150948150949150950150951150952150953150954150955150956150957150958150959150960150961150962150963150964150965150966150967150968150969150970150971150972150973150974150975150976150977150978150979150980150981150982150983150984150985150986150987150988150989150990150991150992150993150994150995150996150997150998150999151000151001151002151003151004151005151006151007151008151009151010151011151012151013151014151015151016151017151018151019151020151021151022151023151024151025151026151027151028151029151030151031151032151033151034151035151036151037151038151039151040151041151042151043151044151045151046151047151048151049151050151051151052151053151054151055151056151057151058151059151060151061151062151063151064151065151066151067151068151069151070151071151072151073151074151075151076151077151078151079151080151081151082151083151084151085151086151087151088151089151090151091151092151093151094151095151096151097151098151099151100151101151102151103151104151105151106151107151108151109151110151111151112151113151114151115151116151117151118151119151120151121151122151123151124151125151126151127151128151129151130151131151132151133151134151135151136151137151138151139151140151141151142151143151144151145151146151147151148151149151150151151151152151153151154151155151156151157151158151159151160151161151162151163151164151165151166151167151168151169151170151171151172151173151174151175151176151177151178151179151180151181151182151183151184151185151186151187151188151189151190151191151192151193151194151195151196151197151198151199151200151201151202151203151204151205151206151207151208151209151210151211151212151213151214151215151216151217151218151219151220151221151222151223151224151225151226151227151228151229151230151231151232151233151234151235151236151237151238151239151240151241151242151243151244151245151246151247151248151249151250151251151252151253151254151255151256151257151258151259151260151261151262151263151264151265151266151267151268151269151270151271151272151273151274151275151276151277151278151279151280151281151282151283151284151285151286151287151288151289151290151291151292151293151294151295151296151297151298151299151300151301151302151303151304151305151306151307151308151309151310151311151312151313151314151315151316151317151318151319151320151321151322151323151324151325151326151327151328151329151330151331151332151333151334151335151336151337151338151339151340151341151342151343151344151345151346151347151348151349151350151351151352151353151354151355151356151357151358151359151360151361151362151363151364151365151366151367151368151369151370151371151372151373151374151375151376151377151378151379151380151381151382151383151384151385151386151387151388151389151390151391151392151393151394151395151396151397151398151399151400151401151402151403151404151405151406151407151408151409151410151411151412151413151414151415151416151417151418151419151420151421151422151423151424151425151426151427151428151429151430151431151432151433151434151435151436151437151438151439151440151441151442151443151444151445151446151447151448151449151450151451151452151453151454151455151456151457151458151459151460151461151462151463151464151465151466151467151468151469151470151471151472151473151474151475151476151477151478151479151480151481151482151483151484151485151486151487151488151489151490151491151492151493151494151495151496151497151498151499151500151501151502151503151504151505151506151507151508151509151510151511151512151513151514151515151516151517151518151519151520151521151522151523151524151525151526151527151528151529151530151531151532151533151534151535151536151537151538151539151540151541151542151543151544151545151546151547151548151549151550151551151552151553151554151555151556151557151558151559151560151561151562151563151564151565151566151567151568151569151570151571151572151573151574151575151576151577151578151579151580151581151582151583151584151585151586151587151588151589151590151591151592151593151594151595151596151597151598151599151600151601151602151603151604151605151606151607151608151609151610151611151612151613151614151615151616151617151618151619151620151621151622151623151624151625151626151627151628151629151630151631151632151633151634151635151636151637151638151639151640151641151642151643151644151645151646151647151648151649151650151651151652151653151654151655151656151657151658151659151660151661151662151663151664151665151666151667151668151669151670151671151672151673151674151675151676151677151678151679151680151681151682151683151684151685151686151687151688151689151690151691151692151693151694151695151696151697151698151699151700151701151702151703151704151705151706
  1. /******************************************************************************
  2. ** This file is an amalgamation of many separate C source files from SQLite
  3. ** version 3.8.7.4. By combining all the individual C code files into this
  4. ** single large file, the entire code can be compiled as a single translation
  5. ** unit. This allows many compilers to do optimizations that would not be
  6. ** possible if the files were compiled separately. Performance improvements
  7. ** of 5% or more are commonly seen when SQLite is compiled as a single
  8. ** translation unit.
  9. **
  10. ** This file is all you need to compile SQLite. To use SQLite in other
  11. ** programs, you need this file and the "sqlite3.h" header file that defines
  12. ** the programming interface to the SQLite library. (If you do not have
  13. ** the "sqlite3.h" header file at hand, you will find a copy embedded within
  14. ** the text of this file. Search for "Begin file sqlite3.h" to find the start
  15. ** of the embedded sqlite3.h header file.) Additional code files may be needed
  16. ** if you want a wrapper to interface SQLite with your choice of programming
  17. ** language. The code for the "sqlite3" command-line shell is also in a
  18. ** separate file. This file contains only code for the core SQLite library.
  19. */
  20. #define SQLITE_CORE 1
  21. #define SQLITE_AMALGAMATION 1
  22. #ifndef SQLITE_PRIVATE
  23. # define SQLITE_PRIVATE static
  24. #endif
  25. #ifndef SQLITE_API
  26. # define SQLITE_API
  27. #endif
  28. /************** Begin file sqliteInt.h ***************************************/
  29. /*
  30. ** 2001 September 15
  31. **
  32. ** The author disclaims copyright to this source code. In place of
  33. ** a legal notice, here is a blessing:
  34. **
  35. ** May you do good and not evil.
  36. ** May you find forgiveness for yourself and forgive others.
  37. ** May you share freely, never taking more than you give.
  38. **
  39. *************************************************************************
  40. ** Internal interface definitions for SQLite.
  41. **
  42. */
  43. #ifndef _SQLITEINT_H_
  44. #define _SQLITEINT_H_
  45. /*
  46. ** These #defines should enable >2GB file support on POSIX if the
  47. ** underlying operating system supports it. If the OS lacks
  48. ** large file support, or if the OS is windows, these should be no-ops.
  49. **
  50. ** Ticket #2739: The _LARGEFILE_SOURCE macro must appear before any
  51. ** system #includes. Hence, this block of code must be the very first
  52. ** code in all source files.
  53. **
  54. ** Large file support can be disabled using the -DSQLITE_DISABLE_LFS switch
  55. ** on the compiler command line. This is necessary if you are compiling
  56. ** on a recent machine (ex: Red Hat 7.2) but you want your code to work
  57. ** on an older machine (ex: Red Hat 6.0). If you compile on Red Hat 7.2
  58. ** without this option, LFS is enable. But LFS does not exist in the kernel
  59. ** in Red Hat 6.0, so the code won't work. Hence, for maximum binary
  60. ** portability you should omit LFS.
  61. **
  62. ** The previous paragraph was written in 2005. (This paragraph is written
  63. ** on 2008-11-28.) These days, all Linux kernels support large files, so
  64. ** you should probably leave LFS enabled. But some embedded platforms might
  65. ** lack LFS in which case the SQLITE_DISABLE_LFS macro might still be useful.
  66. **
  67. ** Similar is true for Mac OS X. LFS is only supported on Mac OS X 9 and later.
  68. */
  69. #ifndef SQLITE_DISABLE_LFS
  70. # define _LARGE_FILE 1
  71. # ifndef _FILE_OFFSET_BITS
  72. # define _FILE_OFFSET_BITS 64
  73. # endif
  74. # define _LARGEFILE_SOURCE 1
  75. #endif
  76. /* Needed for various definitions... */
  77. #if defined(__GNUC__) && !defined(_GNU_SOURCE)
  78. # define _GNU_SOURCE
  79. #endif
  80. #if defined(__OpenBSD__) && !defined(_BSD_SOURCE)
  81. # define _BSD_SOURCE
  82. #endif
  83. /*
  84. ** For MinGW, check to see if we can include the header file containing its
  85. ** version information, among other things. Normally, this internal MinGW
  86. ** header file would [only] be included automatically by other MinGW header
  87. ** files; however, the contained version information is now required by this
  88. ** header file to work around binary compatibility issues (see below) and
  89. ** this is the only known way to reliably obtain it. This entire #if block
  90. ** would be completely unnecessary if there was any other way of detecting
  91. ** MinGW via their preprocessor (e.g. if they customized their GCC to define
  92. ** some MinGW-specific macros). When compiling for MinGW, either the
  93. ** _HAVE_MINGW_H or _HAVE__MINGW_H (note the extra underscore) macro must be
  94. ** defined; otherwise, detection of conditions specific to MinGW will be
  95. ** disabled.
  96. */
  97. #if defined(_HAVE_MINGW_H)
  98. # include "mingw.h"
  99. #elif defined(_HAVE__MINGW_H)
  100. # include "_mingw.h"
  101. #endif
  102. /*
  103. ** For MinGW version 4.x (and higher), check to see if the _USE_32BIT_TIME_T
  104. ** define is required to maintain binary compatibility with the MSVC runtime
  105. ** library in use (e.g. for Windows XP).
  106. */
  107. #if !defined(_USE_32BIT_TIME_T) && !defined(_USE_64BIT_TIME_T) && \
  108. defined(_WIN32) && !defined(_WIN64) && \
  109. defined(__MINGW_MAJOR_VERSION) && __MINGW_MAJOR_VERSION >= 4 && \
  110. defined(__MSVCRT__)
  111. # define _USE_32BIT_TIME_T
  112. #endif
  113. /* The public SQLite interface. The _FILE_OFFSET_BITS macro must appear
  114. ** first in QNX. Also, the _USE_32BIT_TIME_T macro must appear first for
  115. ** MinGW.
  116. */
  117. /************** Include sqlite3.h in the middle of sqliteInt.h ***************/
  118. /************** Begin file sqlite3.h *****************************************/
  119. /*
  120. ** 2001 September 15
  121. **
  122. ** The author disclaims copyright to this source code. In place of
  123. ** a legal notice, here is a blessing:
  124. **
  125. ** May you do good and not evil.
  126. ** May you find forgiveness for yourself and forgive others.
  127. ** May you share freely, never taking more than you give.
  128. **
  129. *************************************************************************
  130. ** This header file defines the interface that the SQLite library
  131. ** presents to client programs. If a C-function, structure, datatype,
  132. ** or constant definition does not appear in this file, then it is
  133. ** not a published API of SQLite, is subject to change without
  134. ** notice, and should not be referenced by programs that use SQLite.
  135. **
  136. ** Some of the definitions that are in this file are marked as
  137. ** "experimental". Experimental interfaces are normally new
  138. ** features recently added to SQLite. We do not anticipate changes
  139. ** to experimental interfaces but reserve the right to make minor changes
  140. ** if experience from use "in the wild" suggest such changes are prudent.
  141. **
  142. ** The official C-language API documentation for SQLite is derived
  143. ** from comments in this file. This file is the authoritative source
  144. ** on how SQLite interfaces are suppose to operate.
  145. **
  146. ** The name of this file under configuration management is "sqlite.h.in".
  147. ** The makefile makes some minor changes to this file (such as inserting
  148. ** the version number) and changes its name to "sqlite3.h" as
  149. ** part of the build process.
  150. */
  151. #ifndef _SQLITE3_H_
  152. #define _SQLITE3_H_
  153. #include <stdarg.h> /* Needed for the definition of va_list */
  154. /*
  155. ** Make sure we can call this stuff from C++.
  156. */
  157. #if 0
  158. extern "C" {
  159. #endif
  160. /*
  161. ** Add the ability to override 'extern'
  162. */
  163. #ifndef SQLITE_EXTERN
  164. # define SQLITE_EXTERN extern
  165. #endif
  166. #ifndef SQLITE_API
  167. # define SQLITE_API
  168. #endif
  169. /*
  170. ** These no-op macros are used in front of interfaces to mark those
  171. ** interfaces as either deprecated or experimental. New applications
  172. ** should not use deprecated interfaces - they are support for backwards
  173. ** compatibility only. Application writers should be aware that
  174. ** experimental interfaces are subject to change in point releases.
  175. **
  176. ** These macros used to resolve to various kinds of compiler magic that
  177. ** would generate warning messages when they were used. But that
  178. ** compiler magic ended up generating such a flurry of bug reports
  179. ** that we have taken it all out and gone back to using simple
  180. ** noop macros.
  181. */
  182. #define SQLITE_DEPRECATED
  183. #define SQLITE_EXPERIMENTAL
  184. /*
  185. ** Ensure these symbols were not defined by some previous header file.
  186. */
  187. #ifdef SQLITE_VERSION
  188. # undef SQLITE_VERSION
  189. #endif
  190. #ifdef SQLITE_VERSION_NUMBER
  191. # undef SQLITE_VERSION_NUMBER
  192. #endif
  193. /*
  194. ** CAPI3REF: Compile-Time Library Version Numbers
  195. **
  196. ** ^(The [SQLITE_VERSION] C preprocessor macro in the sqlite3.h header
  197. ** evaluates to a string literal that is the SQLite version in the
  198. ** format "X.Y.Z" where X is the major version number (always 3 for
  199. ** SQLite3) and Y is the minor version number and Z is the release number.)^
  200. ** ^(The [SQLITE_VERSION_NUMBER] C preprocessor macro resolves to an integer
  201. ** with the value (X*1000000 + Y*1000 + Z) where X, Y, and Z are the same
  202. ** numbers used in [SQLITE_VERSION].)^
  203. ** The SQLITE_VERSION_NUMBER for any given release of SQLite will also
  204. ** be larger than the release from which it is derived. Either Y will
  205. ** be held constant and Z will be incremented or else Y will be incremented
  206. ** and Z will be reset to zero.
  207. **
  208. ** Since version 3.6.18, SQLite source code has been stored in the
  209. ** <a href="http://www.fossil-scm.org/">Fossil configuration management
  210. ** system</a>. ^The SQLITE_SOURCE_ID macro evaluates to
  211. ** a string which identifies a particular check-in of SQLite
  212. ** within its configuration management system. ^The SQLITE_SOURCE_ID
  213. ** string contains the date and time of the check-in (UTC) and an SHA1
  214. ** hash of the entire source tree.
  215. **
  216. ** See also: [sqlite3_libversion()],
  217. ** [sqlite3_libversion_number()], [sqlite3_sourceid()],
  218. ** [sqlite_version()] and [sqlite_source_id()].
  219. */
  220. #define SQLITE_VERSION "3.8.7.4"
  221. #define SQLITE_VERSION_NUMBER 3008007
  222. #define SQLITE_SOURCE_ID "2014-12-09 01:34:36 f66f7a17b78ba617acde90fc810107f34f1a1f2e"
  223. /*
  224. ** CAPI3REF: Run-Time Library Version Numbers
  225. ** KEYWORDS: sqlite3_version, sqlite3_sourceid
  226. **
  227. ** These interfaces provide the same information as the [SQLITE_VERSION],
  228. ** [SQLITE_VERSION_NUMBER], and [SQLITE_SOURCE_ID] C preprocessor macros
  229. ** but are associated with the library instead of the header file. ^(Cautious
  230. ** programmers might include assert() statements in their application to
  231. ** verify that values returned by these interfaces match the macros in
  232. ** the header, and thus insure that the application is
  233. ** compiled with matching library and header files.
  234. **
  235. ** <blockquote><pre>
  236. ** assert( sqlite3_libversion_number()==SQLITE_VERSION_NUMBER );
  237. ** assert( strcmp(sqlite3_sourceid(),SQLITE_SOURCE_ID)==0 );
  238. ** assert( strcmp(sqlite3_libversion(),SQLITE_VERSION)==0 );
  239. ** </pre></blockquote>)^
  240. **
  241. ** ^The sqlite3_version[] string constant contains the text of [SQLITE_VERSION]
  242. ** macro. ^The sqlite3_libversion() function returns a pointer to the
  243. ** to the sqlite3_version[] string constant. The sqlite3_libversion()
  244. ** function is provided for use in DLLs since DLL users usually do not have
  245. ** direct access to string constants within the DLL. ^The
  246. ** sqlite3_libversion_number() function returns an integer equal to
  247. ** [SQLITE_VERSION_NUMBER]. ^The sqlite3_sourceid() function returns
  248. ** a pointer to a string constant whose value is the same as the
  249. ** [SQLITE_SOURCE_ID] C preprocessor macro.
  250. **
  251. ** See also: [sqlite_version()] and [sqlite_source_id()].
  252. */
  253. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  254. SQLITE_API const char *sqlite3_libversion(void);
  255. SQLITE_API const char *sqlite3_sourceid(void);
  256. SQLITE_API int sqlite3_libversion_number(void);
  257. /*
  258. ** CAPI3REF: Run-Time Library Compilation Options Diagnostics
  259. **
  260. ** ^The sqlite3_compileoption_used() function returns 0 or 1
  261. ** indicating whether the specified option was defined at
  262. ** compile time. ^The SQLITE_ prefix may be omitted from the
  263. ** option name passed to sqlite3_compileoption_used().
  264. **
  265. ** ^The sqlite3_compileoption_get() function allows iterating
  266. ** over the list of options that were defined at compile time by
  267. ** returning the N-th compile time option string. ^If N is out of range,
  268. ** sqlite3_compileoption_get() returns a NULL pointer. ^The SQLITE_
  269. ** prefix is omitted from any strings returned by
  270. ** sqlite3_compileoption_get().
  271. **
  272. ** ^Support for the diagnostic functions sqlite3_compileoption_used()
  273. ** and sqlite3_compileoption_get() may be omitted by specifying the
  274. ** [SQLITE_OMIT_COMPILEOPTION_DIAGS] option at compile time.
  275. **
  276. ** See also: SQL functions [sqlite_compileoption_used()] and
  277. ** [sqlite_compileoption_get()] and the [compile_options pragma].
  278. */
  279. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  280. SQLITE_API int sqlite3_compileoption_used(const char *zOptName);
  281. SQLITE_API const char *sqlite3_compileoption_get(int N);
  282. #endif
  283. /*
  284. ** CAPI3REF: Test To See If The Library Is Threadsafe
  285. **
  286. ** ^The sqlite3_threadsafe() function returns zero if and only if
  287. ** SQLite was compiled with mutexing code omitted due to the
  288. ** [SQLITE_THREADSAFE] compile-time option being set to 0.
  289. **
  290. ** SQLite can be compiled with or without mutexes. When
  291. ** the [SQLITE_THREADSAFE] C preprocessor macro is 1 or 2, mutexes
  292. ** are enabled and SQLite is threadsafe. When the
  293. ** [SQLITE_THREADSAFE] macro is 0,
  294. ** the mutexes are omitted. Without the mutexes, it is not safe
  295. ** to use SQLite concurrently from more than one thread.
  296. **
  297. ** Enabling mutexes incurs a measurable performance penalty.
  298. ** So if speed is of utmost importance, it makes sense to disable
  299. ** the mutexes. But for maximum safety, mutexes should be enabled.
  300. ** ^The default behavior is for mutexes to be enabled.
  301. **
  302. ** This interface can be used by an application to make sure that the
  303. ** version of SQLite that it is linking against was compiled with
  304. ** the desired setting of the [SQLITE_THREADSAFE] macro.
  305. **
  306. ** This interface only reports on the compile-time mutex setting
  307. ** of the [SQLITE_THREADSAFE] flag. If SQLite is compiled with
  308. ** SQLITE_THREADSAFE=1 or =2 then mutexes are enabled by default but
  309. ** can be fully or partially disabled using a call to [sqlite3_config()]
  310. ** with the verbs [SQLITE_CONFIG_SINGLETHREAD], [SQLITE_CONFIG_MULTITHREAD],
  311. ** or [SQLITE_CONFIG_MUTEX]. ^(The return value of the
  312. ** sqlite3_threadsafe() function shows only the compile-time setting of
  313. ** thread safety, not any run-time changes to that setting made by
  314. ** sqlite3_config(). In other words, the return value from sqlite3_threadsafe()
  315. ** is unchanged by calls to sqlite3_config().)^
  316. **
  317. ** See the [threading mode] documentation for additional information.
  318. */
  319. SQLITE_API int sqlite3_threadsafe(void);
  320. /*
  321. ** CAPI3REF: Database Connection Handle
  322. ** KEYWORDS: {database connection} {database connections}
  323. **
  324. ** Each open SQLite database is represented by a pointer to an instance of
  325. ** the opaque structure named "sqlite3". It is useful to think of an sqlite3
  326. ** pointer as an object. The [sqlite3_open()], [sqlite3_open16()], and
  327. ** [sqlite3_open_v2()] interfaces are its constructors, and [sqlite3_close()]
  328. ** and [sqlite3_close_v2()] are its destructors. There are many other
  329. ** interfaces (such as
  330. ** [sqlite3_prepare_v2()], [sqlite3_create_function()], and
  331. ** [sqlite3_busy_timeout()] to name but three) that are methods on an
  332. ** sqlite3 object.
  333. */
  334. typedef struct sqlite3 sqlite3;
  335. /*
  336. ** CAPI3REF: 64-Bit Integer Types
  337. ** KEYWORDS: sqlite_int64 sqlite_uint64
  338. **
  339. ** Because there is no cross-platform way to specify 64-bit integer types
  340. ** SQLite includes typedefs for 64-bit signed and unsigned integers.
  341. **
  342. ** The sqlite3_int64 and sqlite3_uint64 are the preferred type definitions.
  343. ** The sqlite_int64 and sqlite_uint64 types are supported for backwards
  344. ** compatibility only.
  345. **
  346. ** ^The sqlite3_int64 and sqlite_int64 types can store integer values
  347. ** between -9223372036854775808 and +9223372036854775807 inclusive. ^The
  348. ** sqlite3_uint64 and sqlite_uint64 types can store integer values
  349. ** between 0 and +18446744073709551615 inclusive.
  350. */
  351. #ifdef SQLITE_INT64_TYPE
  352. typedef SQLITE_INT64_TYPE sqlite_int64;
  353. typedef unsigned SQLITE_INT64_TYPE sqlite_uint64;
  354. #elif defined(_MSC_VER) || defined(__BORLANDC__)
  355. typedef __int64 sqlite_int64;
  356. typedef unsigned __int64 sqlite_uint64;
  357. #else
  358. typedef long long int sqlite_int64;
  359. typedef unsigned long long int sqlite_uint64;
  360. #endif
  361. typedef sqlite_int64 sqlite3_int64;
  362. typedef sqlite_uint64 sqlite3_uint64;
  363. /*
  364. ** If compiling for a processor that lacks floating point support,
  365. ** substitute integer for floating-point.
  366. */
  367. #ifdef SQLITE_OMIT_FLOATING_POINT
  368. # define double sqlite3_int64
  369. #endif
  370. /*
  371. ** CAPI3REF: Closing A Database Connection
  372. **
  373. ** ^The sqlite3_close() and sqlite3_close_v2() routines are destructors
  374. ** for the [sqlite3] object.
  375. ** ^Calls to sqlite3_close() and sqlite3_close_v2() return [SQLITE_OK] if
  376. ** the [sqlite3] object is successfully destroyed and all associated
  377. ** resources are deallocated.
  378. **
  379. ** ^If the database connection is associated with unfinalized prepared
  380. ** statements or unfinished sqlite3_backup objects then sqlite3_close()
  381. ** will leave the database connection open and return [SQLITE_BUSY].
  382. ** ^If sqlite3_close_v2() is called with unfinalized prepared statements
  383. ** and/or unfinished sqlite3_backups, then the database connection becomes
  384. ** an unusable "zombie" which will automatically be deallocated when the
  385. ** last prepared statement is finalized or the last sqlite3_backup is
  386. ** finished. The sqlite3_close_v2() interface is intended for use with
  387. ** host languages that are garbage collected, and where the order in which
  388. ** destructors are called is arbitrary.
  389. **
  390. ** Applications should [sqlite3_finalize | finalize] all [prepared statements],
  391. ** [sqlite3_blob_close | close] all [BLOB handles], and
  392. ** [sqlite3_backup_finish | finish] all [sqlite3_backup] objects associated
  393. ** with the [sqlite3] object prior to attempting to close the object. ^If
  394. ** sqlite3_close_v2() is called on a [database connection] that still has
  395. ** outstanding [prepared statements], [BLOB handles], and/or
  396. ** [sqlite3_backup] objects then it returns [SQLITE_OK] and the deallocation
  397. ** of resources is deferred until all [prepared statements], [BLOB handles],
  398. ** and [sqlite3_backup] objects are also destroyed.
  399. **
  400. ** ^If an [sqlite3] object is destroyed while a transaction is open,
  401. ** the transaction is automatically rolled back.
  402. **
  403. ** The C parameter to [sqlite3_close(C)] and [sqlite3_close_v2(C)]
  404. ** must be either a NULL
  405. ** pointer or an [sqlite3] object pointer obtained
  406. ** from [sqlite3_open()], [sqlite3_open16()], or
  407. ** [sqlite3_open_v2()], and not previously closed.
  408. ** ^Calling sqlite3_close() or sqlite3_close_v2() with a NULL pointer
  409. ** argument is a harmless no-op.
  410. */
  411. SQLITE_API int sqlite3_close(sqlite3*);
  412. SQLITE_API int sqlite3_close_v2(sqlite3*);
  413. /*
  414. ** The type for a callback function.
  415. ** This is legacy and deprecated. It is included for historical
  416. ** compatibility and is not documented.
  417. */
  418. typedef int (*sqlite3_callback)(void*,int,char**, char**);
  419. /*
  420. ** CAPI3REF: One-Step Query Execution Interface
  421. **
  422. ** The sqlite3_exec() interface is a convenience wrapper around
  423. ** [sqlite3_prepare_v2()], [sqlite3_step()], and [sqlite3_finalize()],
  424. ** that allows an application to run multiple statements of SQL
  425. ** without having to use a lot of C code.
  426. **
  427. ** ^The sqlite3_exec() interface runs zero or more UTF-8 encoded,
  428. ** semicolon-separate SQL statements passed into its 2nd argument,
  429. ** in the context of the [database connection] passed in as its 1st
  430. ** argument. ^If the callback function of the 3rd argument to
  431. ** sqlite3_exec() is not NULL, then it is invoked for each result row
  432. ** coming out of the evaluated SQL statements. ^The 4th argument to
  433. ** sqlite3_exec() is relayed through to the 1st argument of each
  434. ** callback invocation. ^If the callback pointer to sqlite3_exec()
  435. ** is NULL, then no callback is ever invoked and result rows are
  436. ** ignored.
  437. **
  438. ** ^If an error occurs while evaluating the SQL statements passed into
  439. ** sqlite3_exec(), then execution of the current statement stops and
  440. ** subsequent statements are skipped. ^If the 5th parameter to sqlite3_exec()
  441. ** is not NULL then any error message is written into memory obtained
  442. ** from [sqlite3_malloc()] and passed back through the 5th parameter.
  443. ** To avoid memory leaks, the application should invoke [sqlite3_free()]
  444. ** on error message strings returned through the 5th parameter of
  445. ** of sqlite3_exec() after the error message string is no longer needed.
  446. ** ^If the 5th parameter to sqlite3_exec() is not NULL and no errors
  447. ** occur, then sqlite3_exec() sets the pointer in its 5th parameter to
  448. ** NULL before returning.
  449. **
  450. ** ^If an sqlite3_exec() callback returns non-zero, the sqlite3_exec()
  451. ** routine returns SQLITE_ABORT without invoking the callback again and
  452. ** without running any subsequent SQL statements.
  453. **
  454. ** ^The 2nd argument to the sqlite3_exec() callback function is the
  455. ** number of columns in the result. ^The 3rd argument to the sqlite3_exec()
  456. ** callback is an array of pointers to strings obtained as if from
  457. ** [sqlite3_column_text()], one for each column. ^If an element of a
  458. ** result row is NULL then the corresponding string pointer for the
  459. ** sqlite3_exec() callback is a NULL pointer. ^The 4th argument to the
  460. ** sqlite3_exec() callback is an array of pointers to strings where each
  461. ** entry represents the name of corresponding result column as obtained
  462. ** from [sqlite3_column_name()].
  463. **
  464. ** ^If the 2nd parameter to sqlite3_exec() is a NULL pointer, a pointer
  465. ** to an empty string, or a pointer that contains only whitespace and/or
  466. ** SQL comments, then no SQL statements are evaluated and the database
  467. ** is not changed.
  468. **
  469. ** Restrictions:
  470. **
  471. ** <ul>
  472. ** <li> The application must insure that the 1st parameter to sqlite3_exec()
  473. ** is a valid and open [database connection].
  474. ** <li> The application must not close the [database connection] specified by
  475. ** the 1st parameter to sqlite3_exec() while sqlite3_exec() is running.
  476. ** <li> The application must not modify the SQL statement text passed into
  477. ** the 2nd parameter of sqlite3_exec() while sqlite3_exec() is running.
  478. ** </ul>
  479. */
  480. SQLITE_API int sqlite3_exec(
  481. sqlite3*, /* An open database */
  482. const char *sql, /* SQL to be evaluated */
  483. int (*callback)(void*,int,char**,char**), /* Callback function */
  484. void *, /* 1st argument to callback */
  485. char **errmsg /* Error msg written here */
  486. );
  487. /*
  488. ** CAPI3REF: Result Codes
  489. ** KEYWORDS: {result code definitions}
  490. **
  491. ** Many SQLite functions return an integer result code from the set shown
  492. ** here in order to indicate success or failure.
  493. **
  494. ** New error codes may be added in future versions of SQLite.
  495. **
  496. ** See also: [extended result code definitions]
  497. */
  498. #define SQLITE_OK 0 /* Successful result */
  499. /* beginning-of-error-codes */
  500. #define SQLITE_ERROR 1 /* SQL error or missing database */
  501. #define SQLITE_INTERNAL 2 /* Internal logic error in SQLite */
  502. #define SQLITE_PERM 3 /* Access permission denied */
  503. #define SQLITE_ABORT 4 /* Callback routine requested an abort */
  504. #define SQLITE_BUSY 5 /* The database file is locked */
  505. #define SQLITE_LOCKED 6 /* A table in the database is locked */
  506. #define SQLITE_NOMEM 7 /* A malloc() failed */
  507. #define SQLITE_READONLY 8 /* Attempt to write a readonly database */
  508. #define SQLITE_INTERRUPT 9 /* Operation terminated by sqlite3_interrupt()*/
  509. #define SQLITE_IOERR 10 /* Some kind of disk I/O error occurred */
  510. #define SQLITE_CORRUPT 11 /* The database disk image is malformed */
  511. #define SQLITE_NOTFOUND 12 /* Unknown opcode in sqlite3_file_control() */
  512. #define SQLITE_FULL 13 /* Insertion failed because database is full */
  513. #define SQLITE_CANTOPEN 14 /* Unable to open the database file */
  514. #define SQLITE_PROTOCOL 15 /* Database lock protocol error */
  515. #define SQLITE_EMPTY 16 /* Database is empty */
  516. #define SQLITE_SCHEMA 17 /* The database schema changed */
  517. #define SQLITE_TOOBIG 18 /* String or BLOB exceeds size limit */
  518. #define SQLITE_CONSTRAINT 19 /* Abort due to constraint violation */
  519. #define SQLITE_MISMATCH 20 /* Data type mismatch */
  520. #define SQLITE_MISUSE 21 /* Library used incorrectly */
  521. #define SQLITE_NOLFS 22 /* Uses OS features not supported on host */
  522. #define SQLITE_AUTH 23 /* Authorization denied */
  523. #define SQLITE_FORMAT 24 /* Auxiliary database format error */
  524. #define SQLITE_RANGE 25 /* 2nd parameter to sqlite3_bind out of range */
  525. #define SQLITE_NOTADB 26 /* File opened that is not a database file */
  526. #define SQLITE_NOTICE 27 /* Notifications from sqlite3_log() */
  527. #define SQLITE_WARNING 28 /* Warnings from sqlite3_log() */
  528. #define SQLITE_ROW 100 /* sqlite3_step() has another row ready */
  529. #define SQLITE_DONE 101 /* sqlite3_step() has finished executing */
  530. /* end-of-error-codes */
  531. /*
  532. ** CAPI3REF: Extended Result Codes
  533. ** KEYWORDS: {extended result code definitions}
  534. **
  535. ** In its default configuration, SQLite API routines return one of 30 integer
  536. ** [result codes]. However, experience has shown that many of
  537. ** these result codes are too coarse-grained. They do not provide as
  538. ** much information about problems as programmers might like. In an effort to
  539. ** address this, newer versions of SQLite (version 3.3.8 and later) include
  540. ** support for additional result codes that provide more detailed information
  541. ** about errors. These [extended result codes] are enabled or disabled
  542. ** on a per database connection basis using the
  543. ** [sqlite3_extended_result_codes()] API. Or, the extended code for
  544. ** the most recent error can be obtained using
  545. ** [sqlite3_extended_errcode()].
  546. */
  547. #define SQLITE_IOERR_READ (SQLITE_IOERR | (1<<8))
  548. #define SQLITE_IOERR_SHORT_READ (SQLITE_IOERR | (2<<8))
  549. #define SQLITE_IOERR_WRITE (SQLITE_IOERR | (3<<8))
  550. #define SQLITE_IOERR_FSYNC (SQLITE_IOERR | (4<<8))
  551. #define SQLITE_IOERR_DIR_FSYNC (SQLITE_IOERR | (5<<8))
  552. #define SQLITE_IOERR_TRUNCATE (SQLITE_IOERR | (6<<8))
  553. #define SQLITE_IOERR_FSTAT (SQLITE_IOERR | (7<<8))
  554. #define SQLITE_IOERR_UNLOCK (SQLITE_IOERR | (8<<8))
  555. #define SQLITE_IOERR_RDLOCK (SQLITE_IOERR | (9<<8))
  556. #define SQLITE_IOERR_DELETE (SQLITE_IOERR | (10<<8))
  557. #define SQLITE_IOERR_BLOCKED (SQLITE_IOERR | (11<<8))
  558. #define SQLITE_IOERR_NOMEM (SQLITE_IOERR | (12<<8))
  559. #define SQLITE_IOERR_ACCESS (SQLITE_IOERR | (13<<8))
  560. #define SQLITE_IOERR_CHECKRESERVEDLOCK (SQLITE_IOERR | (14<<8))
  561. #define SQLITE_IOERR_LOCK (SQLITE_IOERR | (15<<8))
  562. #define SQLITE_IOERR_CLOSE (SQLITE_IOERR | (16<<8))
  563. #define SQLITE_IOERR_DIR_CLOSE (SQLITE_IOERR | (17<<8))
  564. #define SQLITE_IOERR_SHMOPEN (SQLITE_IOERR | (18<<8))
  565. #define SQLITE_IOERR_SHMSIZE (SQLITE_IOERR | (19<<8))
  566. #define SQLITE_IOERR_SHMLOCK (SQLITE_IOERR | (20<<8))
  567. #define SQLITE_IOERR_SHMMAP (SQLITE_IOERR | (21<<8))
  568. #define SQLITE_IOERR_SEEK (SQLITE_IOERR | (22<<8))
  569. #define SQLITE_IOERR_DELETE_NOENT (SQLITE_IOERR | (23<<8))
  570. #define SQLITE_IOERR_MMAP (SQLITE_IOERR | (24<<8))
  571. #define SQLITE_IOERR_GETTEMPPATH (SQLITE_IOERR | (25<<8))
  572. #define SQLITE_IOERR_CONVPATH (SQLITE_IOERR | (26<<8))
  573. #define SQLITE_LOCKED_SHAREDCACHE (SQLITE_LOCKED | (1<<8))
  574. #define SQLITE_BUSY_RECOVERY (SQLITE_BUSY | (1<<8))
  575. #define SQLITE_BUSY_SNAPSHOT (SQLITE_BUSY | (2<<8))
  576. #define SQLITE_CANTOPEN_NOTEMPDIR (SQLITE_CANTOPEN | (1<<8))
  577. #define SQLITE_CANTOPEN_ISDIR (SQLITE_CANTOPEN | (2<<8))
  578. #define SQLITE_CANTOPEN_FULLPATH (SQLITE_CANTOPEN | (3<<8))
  579. #define SQLITE_CANTOPEN_CONVPATH (SQLITE_CANTOPEN | (4<<8))
  580. #define SQLITE_CORRUPT_VTAB (SQLITE_CORRUPT | (1<<8))
  581. #define SQLITE_READONLY_RECOVERY (SQLITE_READONLY | (1<<8))
  582. #define SQLITE_READONLY_CANTLOCK (SQLITE_READONLY | (2<<8))
  583. #define SQLITE_READONLY_ROLLBACK (SQLITE_READONLY | (3<<8))
  584. #define SQLITE_READONLY_DBMOVED (SQLITE_READONLY | (4<<8))
  585. #define SQLITE_ABORT_ROLLBACK (SQLITE_ABORT | (2<<8))
  586. #define SQLITE_CONSTRAINT_CHECK (SQLITE_CONSTRAINT | (1<<8))
  587. #define SQLITE_CONSTRAINT_COMMITHOOK (SQLITE_CONSTRAINT | (2<<8))
  588. #define SQLITE_CONSTRAINT_FOREIGNKEY (SQLITE_CONSTRAINT | (3<<8))
  589. #define SQLITE_CONSTRAINT_FUNCTION (SQLITE_CONSTRAINT | (4<<8))
  590. #define SQLITE_CONSTRAINT_NOTNULL (SQLITE_CONSTRAINT | (5<<8))
  591. #define SQLITE_CONSTRAINT_PRIMARYKEY (SQLITE_CONSTRAINT | (6<<8))
  592. #define SQLITE_CONSTRAINT_TRIGGER (SQLITE_CONSTRAINT | (7<<8))
  593. #define SQLITE_CONSTRAINT_UNIQUE (SQLITE_CONSTRAINT | (8<<8))
  594. #define SQLITE_CONSTRAINT_VTAB (SQLITE_CONSTRAINT | (9<<8))
  595. #define SQLITE_CONSTRAINT_ROWID (SQLITE_CONSTRAINT |(10<<8))
  596. #define SQLITE_NOTICE_RECOVER_WAL (SQLITE_NOTICE | (1<<8))
  597. #define SQLITE_NOTICE_RECOVER_ROLLBACK (SQLITE_NOTICE | (2<<8))
  598. #define SQLITE_WARNING_AUTOINDEX (SQLITE_WARNING | (1<<8))
  599. #define SQLITE_AUTH_USER (SQLITE_AUTH | (1<<8))
  600. /*
  601. ** CAPI3REF: Flags For File Open Operations
  602. **
  603. ** These bit values are intended for use in the
  604. ** 3rd parameter to the [sqlite3_open_v2()] interface and
  605. ** in the 4th parameter to the [sqlite3_vfs.xOpen] method.
  606. */
  607. #define SQLITE_OPEN_READONLY 0x00000001 /* Ok for sqlite3_open_v2() */
  608. #define SQLITE_OPEN_READWRITE 0x00000002 /* Ok for sqlite3_open_v2() */
  609. #define SQLITE_OPEN_CREATE 0x00000004 /* Ok for sqlite3_open_v2() */
  610. #define SQLITE_OPEN_DELETEONCLOSE 0x00000008 /* VFS only */
  611. #define SQLITE_OPEN_EXCLUSIVE 0x00000010 /* VFS only */
  612. #define SQLITE_OPEN_AUTOPROXY 0x00000020 /* VFS only */
  613. #define SQLITE_OPEN_URI 0x00000040 /* Ok for sqlite3_open_v2() */
  614. #define SQLITE_OPEN_MEMORY 0x00000080 /* Ok for sqlite3_open_v2() */
  615. #define SQLITE_OPEN_MAIN_DB 0x00000100 /* VFS only */
  616. #define SQLITE_OPEN_TEMP_DB 0x00000200 /* VFS only */
  617. #define SQLITE_OPEN_TRANSIENT_DB 0x00000400 /* VFS only */
  618. #define SQLITE_OPEN_MAIN_JOURNAL 0x00000800 /* VFS only */
  619. #define SQLITE_OPEN_TEMP_JOURNAL 0x00001000 /* VFS only */
  620. #define SQLITE_OPEN_SUBJOURNAL 0x00002000 /* VFS only */
  621. #define SQLITE_OPEN_MASTER_JOURNAL 0x00004000 /* VFS only */
  622. #define SQLITE_OPEN_NOMUTEX 0x00008000 /* Ok for sqlite3_open_v2() */
  623. #define SQLITE_OPEN_FULLMUTEX 0x00010000 /* Ok for sqlite3_open_v2() */
  624. #define SQLITE_OPEN_SHAREDCACHE 0x00020000 /* Ok for sqlite3_open_v2() */
  625. #define SQLITE_OPEN_PRIVATECACHE 0x00040000 /* Ok for sqlite3_open_v2() */
  626. #define SQLITE_OPEN_WAL 0x00080000 /* VFS only */
  627. /* Reserved: 0x00F00000 */
  628. /*
  629. ** CAPI3REF: Device Characteristics
  630. **
  631. ** The xDeviceCharacteristics method of the [sqlite3_io_methods]
  632. ** object returns an integer which is a vector of these
  633. ** bit values expressing I/O characteristics of the mass storage
  634. ** device that holds the file that the [sqlite3_io_methods]
  635. ** refers to.
  636. **
  637. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  638. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  639. ** mean that writes of blocks that are nnn bytes in size and
  640. ** are aligned to an address which is an integer multiple of
  641. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  642. ** that when data is appended to a file, the data is appended
  643. ** first then the size of the file is extended, never the other
  644. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  645. ** information is written to disk in the same order as calls
  646. ** to xWrite(). The SQLITE_IOCAP_POWERSAFE_OVERWRITE property means that
  647. ** after reboot following a crash or power loss, the only bytes in a
  648. ** file that were written at the application level might have changed
  649. ** and that adjacent bytes, even bytes within the same sector are
  650. ** guaranteed to be unchanged. The SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  651. ** flag indicate that a file cannot be deleted when open. The
  652. ** SQLITE_IOCAP_IMMUTABLE flag indicates that the file is on
  653. ** read-only media and cannot be changed even by processes with
  654. ** elevated privileges.
  655. */
  656. #define SQLITE_IOCAP_ATOMIC 0x00000001
  657. #define SQLITE_IOCAP_ATOMIC512 0x00000002
  658. #define SQLITE_IOCAP_ATOMIC1K 0x00000004
  659. #define SQLITE_IOCAP_ATOMIC2K 0x00000008
  660. #define SQLITE_IOCAP_ATOMIC4K 0x00000010
  661. #define SQLITE_IOCAP_ATOMIC8K 0x00000020
  662. #define SQLITE_IOCAP_ATOMIC16K 0x00000040
  663. #define SQLITE_IOCAP_ATOMIC32K 0x00000080
  664. #define SQLITE_IOCAP_ATOMIC64K 0x00000100
  665. #define SQLITE_IOCAP_SAFE_APPEND 0x00000200
  666. #define SQLITE_IOCAP_SEQUENTIAL 0x00000400
  667. #define SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN 0x00000800
  668. #define SQLITE_IOCAP_POWERSAFE_OVERWRITE 0x00001000
  669. #define SQLITE_IOCAP_IMMUTABLE 0x00002000
  670. /*
  671. ** CAPI3REF: File Locking Levels
  672. **
  673. ** SQLite uses one of these integer values as the second
  674. ** argument to calls it makes to the xLock() and xUnlock() methods
  675. ** of an [sqlite3_io_methods] object.
  676. */
  677. #define SQLITE_LOCK_NONE 0
  678. #define SQLITE_LOCK_SHARED 1
  679. #define SQLITE_LOCK_RESERVED 2
  680. #define SQLITE_LOCK_PENDING 3
  681. #define SQLITE_LOCK_EXCLUSIVE 4
  682. /*
  683. ** CAPI3REF: Synchronization Type Flags
  684. **
  685. ** When SQLite invokes the xSync() method of an
  686. ** [sqlite3_io_methods] object it uses a combination of
  687. ** these integer values as the second argument.
  688. **
  689. ** When the SQLITE_SYNC_DATAONLY flag is used, it means that the
  690. ** sync operation only needs to flush data to mass storage. Inode
  691. ** information need not be flushed. If the lower four bits of the flag
  692. ** equal SQLITE_SYNC_NORMAL, that means to use normal fsync() semantics.
  693. ** If the lower four bits equal SQLITE_SYNC_FULL, that means
  694. ** to use Mac OS X style fullsync instead of fsync().
  695. **
  696. ** Do not confuse the SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags
  697. ** with the [PRAGMA synchronous]=NORMAL and [PRAGMA synchronous]=FULL
  698. ** settings. The [synchronous pragma] determines when calls to the
  699. ** xSync VFS method occur and applies uniformly across all platforms.
  700. ** The SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL flags determine how
  701. ** energetic or rigorous or forceful the sync operations are and
  702. ** only make a difference on Mac OSX for the default SQLite code.
  703. ** (Third-party VFS implementations might also make the distinction
  704. ** between SQLITE_SYNC_NORMAL and SQLITE_SYNC_FULL, but among the
  705. ** operating systems natively supported by SQLite, only Mac OSX
  706. ** cares about the difference.)
  707. */
  708. #define SQLITE_SYNC_NORMAL 0x00002
  709. #define SQLITE_SYNC_FULL 0x00003
  710. #define SQLITE_SYNC_DATAONLY 0x00010
  711. /*
  712. ** CAPI3REF: OS Interface Open File Handle
  713. **
  714. ** An [sqlite3_file] object represents an open file in the
  715. ** [sqlite3_vfs | OS interface layer]. Individual OS interface
  716. ** implementations will
  717. ** want to subclass this object by appending additional fields
  718. ** for their own use. The pMethods entry is a pointer to an
  719. ** [sqlite3_io_methods] object that defines methods for performing
  720. ** I/O operations on the open file.
  721. */
  722. typedef struct sqlite3_file sqlite3_file;
  723. struct sqlite3_file {
  724. const struct sqlite3_io_methods *pMethods; /* Methods for an open file */
  725. };
  726. /*
  727. ** CAPI3REF: OS Interface File Virtual Methods Object
  728. **
  729. ** Every file opened by the [sqlite3_vfs.xOpen] method populates an
  730. ** [sqlite3_file] object (or, more commonly, a subclass of the
  731. ** [sqlite3_file] object) with a pointer to an instance of this object.
  732. ** This object defines the methods used to perform various operations
  733. ** against the open file represented by the [sqlite3_file] object.
  734. **
  735. ** If the [sqlite3_vfs.xOpen] method sets the sqlite3_file.pMethods element
  736. ** to a non-NULL pointer, then the sqlite3_io_methods.xClose method
  737. ** may be invoked even if the [sqlite3_vfs.xOpen] reported that it failed. The
  738. ** only way to prevent a call to xClose following a failed [sqlite3_vfs.xOpen]
  739. ** is for the [sqlite3_vfs.xOpen] to set the sqlite3_file.pMethods element
  740. ** to NULL.
  741. **
  742. ** The flags argument to xSync may be one of [SQLITE_SYNC_NORMAL] or
  743. ** [SQLITE_SYNC_FULL]. The first choice is the normal fsync().
  744. ** The second choice is a Mac OS X style fullsync. The [SQLITE_SYNC_DATAONLY]
  745. ** flag may be ORed in to indicate that only the data of the file
  746. ** and not its inode needs to be synced.
  747. **
  748. ** The integer values to xLock() and xUnlock() are one of
  749. ** <ul>
  750. ** <li> [SQLITE_LOCK_NONE],
  751. ** <li> [SQLITE_LOCK_SHARED],
  752. ** <li> [SQLITE_LOCK_RESERVED],
  753. ** <li> [SQLITE_LOCK_PENDING], or
  754. ** <li> [SQLITE_LOCK_EXCLUSIVE].
  755. ** </ul>
  756. ** xLock() increases the lock. xUnlock() decreases the lock.
  757. ** The xCheckReservedLock() method checks whether any database connection,
  758. ** either in this process or in some other process, is holding a RESERVED,
  759. ** PENDING, or EXCLUSIVE lock on the file. It returns true
  760. ** if such a lock exists and false otherwise.
  761. **
  762. ** The xFileControl() method is a generic interface that allows custom
  763. ** VFS implementations to directly control an open file using the
  764. ** [sqlite3_file_control()] interface. The second "op" argument is an
  765. ** integer opcode. The third argument is a generic pointer intended to
  766. ** point to a structure that may contain arguments or space in which to
  767. ** write return values. Potential uses for xFileControl() might be
  768. ** functions to enable blocking locks with timeouts, to change the
  769. ** locking strategy (for example to use dot-file locks), to inquire
  770. ** about the status of a lock, or to break stale locks. The SQLite
  771. ** core reserves all opcodes less than 100 for its own use.
  772. ** A [file control opcodes | list of opcodes] less than 100 is available.
  773. ** Applications that define a custom xFileControl method should use opcodes
  774. ** greater than 100 to avoid conflicts. VFS implementations should
  775. ** return [SQLITE_NOTFOUND] for file control opcodes that they do not
  776. ** recognize.
  777. **
  778. ** The xSectorSize() method returns the sector size of the
  779. ** device that underlies the file. The sector size is the
  780. ** minimum write that can be performed without disturbing
  781. ** other bytes in the file. The xDeviceCharacteristics()
  782. ** method returns a bit vector describing behaviors of the
  783. ** underlying device:
  784. **
  785. ** <ul>
  786. ** <li> [SQLITE_IOCAP_ATOMIC]
  787. ** <li> [SQLITE_IOCAP_ATOMIC512]
  788. ** <li> [SQLITE_IOCAP_ATOMIC1K]
  789. ** <li> [SQLITE_IOCAP_ATOMIC2K]
  790. ** <li> [SQLITE_IOCAP_ATOMIC4K]
  791. ** <li> [SQLITE_IOCAP_ATOMIC8K]
  792. ** <li> [SQLITE_IOCAP_ATOMIC16K]
  793. ** <li> [SQLITE_IOCAP_ATOMIC32K]
  794. ** <li> [SQLITE_IOCAP_ATOMIC64K]
  795. ** <li> [SQLITE_IOCAP_SAFE_APPEND]
  796. ** <li> [SQLITE_IOCAP_SEQUENTIAL]
  797. ** </ul>
  798. **
  799. ** The SQLITE_IOCAP_ATOMIC property means that all writes of
  800. ** any size are atomic. The SQLITE_IOCAP_ATOMICnnn values
  801. ** mean that writes of blocks that are nnn bytes in size and
  802. ** are aligned to an address which is an integer multiple of
  803. ** nnn are atomic. The SQLITE_IOCAP_SAFE_APPEND value means
  804. ** that when data is appended to a file, the data is appended
  805. ** first then the size of the file is extended, never the other
  806. ** way around. The SQLITE_IOCAP_SEQUENTIAL property means that
  807. ** information is written to disk in the same order as calls
  808. ** to xWrite().
  809. **
  810. ** If xRead() returns SQLITE_IOERR_SHORT_READ it must also fill
  811. ** in the unread portions of the buffer with zeros. A VFS that
  812. ** fails to zero-fill short reads might seem to work. However,
  813. ** failure to zero-fill short reads will eventually lead to
  814. ** database corruption.
  815. */
  816. typedef struct sqlite3_io_methods sqlite3_io_methods;
  817. struct sqlite3_io_methods {
  818. int iVersion;
  819. int (*xClose)(sqlite3_file*);
  820. int (*xRead)(sqlite3_file*, void*, int iAmt, sqlite3_int64 iOfst);
  821. int (*xWrite)(sqlite3_file*, const void*, int iAmt, sqlite3_int64 iOfst);
  822. int (*xTruncate)(sqlite3_file*, sqlite3_int64 size);
  823. int (*xSync)(sqlite3_file*, int flags);
  824. int (*xFileSize)(sqlite3_file*, sqlite3_int64 *pSize);
  825. int (*xLock)(sqlite3_file*, int);
  826. int (*xUnlock)(sqlite3_file*, int);
  827. int (*xCheckReservedLock)(sqlite3_file*, int *pResOut);
  828. int (*xFileControl)(sqlite3_file*, int op, void *pArg);
  829. int (*xSectorSize)(sqlite3_file*);
  830. int (*xDeviceCharacteristics)(sqlite3_file*);
  831. /* Methods above are valid for version 1 */
  832. int (*xShmMap)(sqlite3_file*, int iPg, int pgsz, int, void volatile**);
  833. int (*xShmLock)(sqlite3_file*, int offset, int n, int flags);
  834. void (*xShmBarrier)(sqlite3_file*);
  835. int (*xShmUnmap)(sqlite3_file*, int deleteFlag);
  836. /* Methods above are valid for version 2 */
  837. int (*xFetch)(sqlite3_file*, sqlite3_int64 iOfst, int iAmt, void **pp);
  838. int (*xUnfetch)(sqlite3_file*, sqlite3_int64 iOfst, void *p);
  839. /* Methods above are valid for version 3 */
  840. /* Additional methods may be added in future releases */
  841. };
  842. /*
  843. ** CAPI3REF: Standard File Control Opcodes
  844. ** KEYWORDS: {file control opcodes} {file control opcode}
  845. **
  846. ** These integer constants are opcodes for the xFileControl method
  847. ** of the [sqlite3_io_methods] object and for the [sqlite3_file_control()]
  848. ** interface.
  849. **
  850. ** The [SQLITE_FCNTL_LOCKSTATE] opcode is used for debugging. This
  851. ** opcode causes the xFileControl method to write the current state of
  852. ** the lock (one of [SQLITE_LOCK_NONE], [SQLITE_LOCK_SHARED],
  853. ** [SQLITE_LOCK_RESERVED], [SQLITE_LOCK_PENDING], or [SQLITE_LOCK_EXCLUSIVE])
  854. ** into an integer that the pArg argument points to. This capability
  855. ** is used during testing and only needs to be supported when SQLITE_TEST
  856. ** is defined.
  857. ** <ul>
  858. ** <li>[[SQLITE_FCNTL_SIZE_HINT]]
  859. ** The [SQLITE_FCNTL_SIZE_HINT] opcode is used by SQLite to give the VFS
  860. ** layer a hint of how large the database file will grow to be during the
  861. ** current transaction. This hint is not guaranteed to be accurate but it
  862. ** is often close. The underlying VFS might choose to preallocate database
  863. ** file space based on this hint in order to help writes to the database
  864. ** file run faster.
  865. **
  866. ** <li>[[SQLITE_FCNTL_CHUNK_SIZE]]
  867. ** The [SQLITE_FCNTL_CHUNK_SIZE] opcode is used to request that the VFS
  868. ** extends and truncates the database file in chunks of a size specified
  869. ** by the user. The fourth argument to [sqlite3_file_control()] should
  870. ** point to an integer (type int) containing the new chunk-size to use
  871. ** for the nominated database. Allocating database file space in large
  872. ** chunks (say 1MB at a time), may reduce file-system fragmentation and
  873. ** improve performance on some systems.
  874. **
  875. ** <li>[[SQLITE_FCNTL_FILE_POINTER]]
  876. ** The [SQLITE_FCNTL_FILE_POINTER] opcode is used to obtain a pointer
  877. ** to the [sqlite3_file] object associated with a particular database
  878. ** connection. See the [sqlite3_file_control()] documentation for
  879. ** additional information.
  880. **
  881. ** <li>[[SQLITE_FCNTL_SYNC_OMITTED]]
  882. ** No longer in use.
  883. **
  884. ** <li>[[SQLITE_FCNTL_SYNC]]
  885. ** The [SQLITE_FCNTL_SYNC] opcode is generated internally by SQLite and
  886. ** sent to the VFS immediately before the xSync method is invoked on a
  887. ** database file descriptor. Or, if the xSync method is not invoked
  888. ** because the user has configured SQLite with
  889. ** [PRAGMA synchronous | PRAGMA synchronous=OFF] it is invoked in place
  890. ** of the xSync method. In most cases, the pointer argument passed with
  891. ** this file-control is NULL. However, if the database file is being synced
  892. ** as part of a multi-database commit, the argument points to a nul-terminated
  893. ** string containing the transactions master-journal file name. VFSes that
  894. ** do not need this signal should silently ignore this opcode. Applications
  895. ** should not call [sqlite3_file_control()] with this opcode as doing so may
  896. ** disrupt the operation of the specialized VFSes that do require it.
  897. **
  898. ** <li>[[SQLITE_FCNTL_COMMIT_PHASETWO]]
  899. ** The [SQLITE_FCNTL_COMMIT_PHASETWO] opcode is generated internally by SQLite
  900. ** and sent to the VFS after a transaction has been committed immediately
  901. ** but before the database is unlocked. VFSes that do not need this signal
  902. ** should silently ignore this opcode. Applications should not call
  903. ** [sqlite3_file_control()] with this opcode as doing so may disrupt the
  904. ** operation of the specialized VFSes that do require it.
  905. **
  906. ** <li>[[SQLITE_FCNTL_WIN32_AV_RETRY]]
  907. ** ^The [SQLITE_FCNTL_WIN32_AV_RETRY] opcode is used to configure automatic
  908. ** retry counts and intervals for certain disk I/O operations for the
  909. ** windows [VFS] in order to provide robustness in the presence of
  910. ** anti-virus programs. By default, the windows VFS will retry file read,
  911. ** file write, and file delete operations up to 10 times, with a delay
  912. ** of 25 milliseconds before the first retry and with the delay increasing
  913. ** by an additional 25 milliseconds with each subsequent retry. This
  914. ** opcode allows these two values (10 retries and 25 milliseconds of delay)
  915. ** to be adjusted. The values are changed for all database connections
  916. ** within the same process. The argument is a pointer to an array of two
  917. ** integers where the first integer i the new retry count and the second
  918. ** integer is the delay. If either integer is negative, then the setting
  919. ** is not changed but instead the prior value of that setting is written
  920. ** into the array entry, allowing the current retry settings to be
  921. ** interrogated. The zDbName parameter is ignored.
  922. **
  923. ** <li>[[SQLITE_FCNTL_PERSIST_WAL]]
  924. ** ^The [SQLITE_FCNTL_PERSIST_WAL] opcode is used to set or query the
  925. ** persistent [WAL | Write Ahead Log] setting. By default, the auxiliary
  926. ** write ahead log and shared memory files used for transaction control
  927. ** are automatically deleted when the latest connection to the database
  928. ** closes. Setting persistent WAL mode causes those files to persist after
  929. ** close. Persisting the files is useful when other processes that do not
  930. ** have write permission on the directory containing the database file want
  931. ** to read the database file, as the WAL and shared memory files must exist
  932. ** in order for the database to be readable. The fourth parameter to
  933. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  934. ** That integer is 0 to disable persistent WAL mode or 1 to enable persistent
  935. ** WAL mode. If the integer is -1, then it is overwritten with the current
  936. ** WAL persistence setting.
  937. **
  938. ** <li>[[SQLITE_FCNTL_POWERSAFE_OVERWRITE]]
  939. ** ^The [SQLITE_FCNTL_POWERSAFE_OVERWRITE] opcode is used to set or query the
  940. ** persistent "powersafe-overwrite" or "PSOW" setting. The PSOW setting
  941. ** determines the [SQLITE_IOCAP_POWERSAFE_OVERWRITE] bit of the
  942. ** xDeviceCharacteristics methods. The fourth parameter to
  943. ** [sqlite3_file_control()] for this opcode should be a pointer to an integer.
  944. ** That integer is 0 to disable zero-damage mode or 1 to enable zero-damage
  945. ** mode. If the integer is -1, then it is overwritten with the current
  946. ** zero-damage mode setting.
  947. **
  948. ** <li>[[SQLITE_FCNTL_OVERWRITE]]
  949. ** ^The [SQLITE_FCNTL_OVERWRITE] opcode is invoked by SQLite after opening
  950. ** a write transaction to indicate that, unless it is rolled back for some
  951. ** reason, the entire database file will be overwritten by the current
  952. ** transaction. This is used by VACUUM operations.
  953. **
  954. ** <li>[[SQLITE_FCNTL_VFSNAME]]
  955. ** ^The [SQLITE_FCNTL_VFSNAME] opcode can be used to obtain the names of
  956. ** all [VFSes] in the VFS stack. The names are of all VFS shims and the
  957. ** final bottom-level VFS are written into memory obtained from
  958. ** [sqlite3_malloc()] and the result is stored in the char* variable
  959. ** that the fourth parameter of [sqlite3_file_control()] points to.
  960. ** The caller is responsible for freeing the memory when done. As with
  961. ** all file-control actions, there is no guarantee that this will actually
  962. ** do anything. Callers should initialize the char* variable to a NULL
  963. ** pointer in case this file-control is not implemented. This file-control
  964. ** is intended for diagnostic use only.
  965. **
  966. ** <li>[[SQLITE_FCNTL_PRAGMA]]
  967. ** ^Whenever a [PRAGMA] statement is parsed, an [SQLITE_FCNTL_PRAGMA]
  968. ** file control is sent to the open [sqlite3_file] object corresponding
  969. ** to the database file to which the pragma statement refers. ^The argument
  970. ** to the [SQLITE_FCNTL_PRAGMA] file control is an array of
  971. ** pointers to strings (char**) in which the second element of the array
  972. ** is the name of the pragma and the third element is the argument to the
  973. ** pragma or NULL if the pragma has no argument. ^The handler for an
  974. ** [SQLITE_FCNTL_PRAGMA] file control can optionally make the first element
  975. ** of the char** argument point to a string obtained from [sqlite3_mprintf()]
  976. ** or the equivalent and that string will become the result of the pragma or
  977. ** the error message if the pragma fails. ^If the
  978. ** [SQLITE_FCNTL_PRAGMA] file control returns [SQLITE_NOTFOUND], then normal
  979. ** [PRAGMA] processing continues. ^If the [SQLITE_FCNTL_PRAGMA]
  980. ** file control returns [SQLITE_OK], then the parser assumes that the
  981. ** VFS has handled the PRAGMA itself and the parser generates a no-op
  982. ** prepared statement. ^If the [SQLITE_FCNTL_PRAGMA] file control returns
  983. ** any result code other than [SQLITE_OK] or [SQLITE_NOTFOUND], that means
  984. ** that the VFS encountered an error while handling the [PRAGMA] and the
  985. ** compilation of the PRAGMA fails with an error. ^The [SQLITE_FCNTL_PRAGMA]
  986. ** file control occurs at the beginning of pragma statement analysis and so
  987. ** it is able to override built-in [PRAGMA] statements.
  988. **
  989. ** <li>[[SQLITE_FCNTL_BUSYHANDLER]]
  990. ** ^The [SQLITE_FCNTL_BUSYHANDLER]
  991. ** file-control may be invoked by SQLite on the database file handle
  992. ** shortly after it is opened in order to provide a custom VFS with access
  993. ** to the connections busy-handler callback. The argument is of type (void **)
  994. ** - an array of two (void *) values. The first (void *) actually points
  995. ** to a function of type (int (*)(void *)). In order to invoke the connections
  996. ** busy-handler, this function should be invoked with the second (void *) in
  997. ** the array as the only argument. If it returns non-zero, then the operation
  998. ** should be retried. If it returns zero, the custom VFS should abandon the
  999. ** current operation.
  1000. **
  1001. ** <li>[[SQLITE_FCNTL_TEMPFILENAME]]
  1002. ** ^Application can invoke the [SQLITE_FCNTL_TEMPFILENAME] file-control
  1003. ** to have SQLite generate a
  1004. ** temporary filename using the same algorithm that is followed to generate
  1005. ** temporary filenames for TEMP tables and other internal uses. The
  1006. ** argument should be a char** which will be filled with the filename
  1007. ** written into memory obtained from [sqlite3_malloc()]. The caller should
  1008. ** invoke [sqlite3_free()] on the result to avoid a memory leak.
  1009. **
  1010. ** <li>[[SQLITE_FCNTL_MMAP_SIZE]]
  1011. ** The [SQLITE_FCNTL_MMAP_SIZE] file control is used to query or set the
  1012. ** maximum number of bytes that will be used for memory-mapped I/O.
  1013. ** The argument is a pointer to a value of type sqlite3_int64 that
  1014. ** is an advisory maximum number of bytes in the file to memory map. The
  1015. ** pointer is overwritten with the old value. The limit is not changed if
  1016. ** the value originally pointed to is negative, and so the current limit
  1017. ** can be queried by passing in a pointer to a negative number. This
  1018. ** file-control is used internally to implement [PRAGMA mmap_size].
  1019. **
  1020. ** <li>[[SQLITE_FCNTL_TRACE]]
  1021. ** The [SQLITE_FCNTL_TRACE] file control provides advisory information
  1022. ** to the VFS about what the higher layers of the SQLite stack are doing.
  1023. ** This file control is used by some VFS activity tracing [shims].
  1024. ** The argument is a zero-terminated string. Higher layers in the
  1025. ** SQLite stack may generate instances of this file control if
  1026. ** the [SQLITE_USE_FCNTL_TRACE] compile-time option is enabled.
  1027. **
  1028. ** <li>[[SQLITE_FCNTL_HAS_MOVED]]
  1029. ** The [SQLITE_FCNTL_HAS_MOVED] file control interprets its argument as a
  1030. ** pointer to an integer and it writes a boolean into that integer depending
  1031. ** on whether or not the file has been renamed, moved, or deleted since it
  1032. ** was first opened.
  1033. **
  1034. ** <li>[[SQLITE_FCNTL_WIN32_SET_HANDLE]]
  1035. ** The [SQLITE_FCNTL_WIN32_SET_HANDLE] opcode is used for debugging. This
  1036. ** opcode causes the xFileControl method to swap the file handle with the one
  1037. ** pointed to by the pArg argument. This capability is used during testing
  1038. ** and only needs to be supported when SQLITE_TEST is defined.
  1039. **
  1040. ** </ul>
  1041. */
  1042. #define SQLITE_FCNTL_LOCKSTATE 1
  1043. #define SQLITE_GET_LOCKPROXYFILE 2
  1044. #define SQLITE_SET_LOCKPROXYFILE 3
  1045. #define SQLITE_LAST_ERRNO 4
  1046. #define SQLITE_FCNTL_SIZE_HINT 5
  1047. #define SQLITE_FCNTL_CHUNK_SIZE 6
  1048. #define SQLITE_FCNTL_FILE_POINTER 7
  1049. #define SQLITE_FCNTL_SYNC_OMITTED 8
  1050. #define SQLITE_FCNTL_WIN32_AV_RETRY 9
  1051. #define SQLITE_FCNTL_PERSIST_WAL 10
  1052. #define SQLITE_FCNTL_OVERWRITE 11
  1053. #define SQLITE_FCNTL_VFSNAME 12
  1054. #define SQLITE_FCNTL_POWERSAFE_OVERWRITE 13
  1055. #define SQLITE_FCNTL_PRAGMA 14
  1056. #define SQLITE_FCNTL_BUSYHANDLER 15
  1057. #define SQLITE_FCNTL_TEMPFILENAME 16
  1058. #define SQLITE_FCNTL_MMAP_SIZE 18
  1059. #define SQLITE_FCNTL_TRACE 19
  1060. #define SQLITE_FCNTL_HAS_MOVED 20
  1061. #define SQLITE_FCNTL_SYNC 21
  1062. #define SQLITE_FCNTL_COMMIT_PHASETWO 22
  1063. #define SQLITE_FCNTL_WIN32_SET_HANDLE 23
  1064. /*
  1065. ** CAPI3REF: Mutex Handle
  1066. **
  1067. ** The mutex module within SQLite defines [sqlite3_mutex] to be an
  1068. ** abstract type for a mutex object. The SQLite core never looks
  1069. ** at the internal representation of an [sqlite3_mutex]. It only
  1070. ** deals with pointers to the [sqlite3_mutex] object.
  1071. **
  1072. ** Mutexes are created using [sqlite3_mutex_alloc()].
  1073. */
  1074. typedef struct sqlite3_mutex sqlite3_mutex;
  1075. /*
  1076. ** CAPI3REF: OS Interface Object
  1077. **
  1078. ** An instance of the sqlite3_vfs object defines the interface between
  1079. ** the SQLite core and the underlying operating system. The "vfs"
  1080. ** in the name of the object stands for "virtual file system". See
  1081. ** the [VFS | VFS documentation] for further information.
  1082. **
  1083. ** The value of the iVersion field is initially 1 but may be larger in
  1084. ** future versions of SQLite. Additional fields may be appended to this
  1085. ** object when the iVersion value is increased. Note that the structure
  1086. ** of the sqlite3_vfs object changes in the transaction between
  1087. ** SQLite version 3.5.9 and 3.6.0 and yet the iVersion field was not
  1088. ** modified.
  1089. **
  1090. ** The szOsFile field is the size of the subclassed [sqlite3_file]
  1091. ** structure used by this VFS. mxPathname is the maximum length of
  1092. ** a pathname in this VFS.
  1093. **
  1094. ** Registered sqlite3_vfs objects are kept on a linked list formed by
  1095. ** the pNext pointer. The [sqlite3_vfs_register()]
  1096. ** and [sqlite3_vfs_unregister()] interfaces manage this list
  1097. ** in a thread-safe way. The [sqlite3_vfs_find()] interface
  1098. ** searches the list. Neither the application code nor the VFS
  1099. ** implementation should use the pNext pointer.
  1100. **
  1101. ** The pNext field is the only field in the sqlite3_vfs
  1102. ** structure that SQLite will ever modify. SQLite will only access
  1103. ** or modify this field while holding a particular static mutex.
  1104. ** The application should never modify anything within the sqlite3_vfs
  1105. ** object once the object has been registered.
  1106. **
  1107. ** The zName field holds the name of the VFS module. The name must
  1108. ** be unique across all VFS modules.
  1109. **
  1110. ** [[sqlite3_vfs.xOpen]]
  1111. ** ^SQLite guarantees that the zFilename parameter to xOpen
  1112. ** is either a NULL pointer or string obtained
  1113. ** from xFullPathname() with an optional suffix added.
  1114. ** ^If a suffix is added to the zFilename parameter, it will
  1115. ** consist of a single "-" character followed by no more than
  1116. ** 11 alphanumeric and/or "-" characters.
  1117. ** ^SQLite further guarantees that
  1118. ** the string will be valid and unchanged until xClose() is
  1119. ** called. Because of the previous sentence,
  1120. ** the [sqlite3_file] can safely store a pointer to the
  1121. ** filename if it needs to remember the filename for some reason.
  1122. ** If the zFilename parameter to xOpen is a NULL pointer then xOpen
  1123. ** must invent its own temporary name for the file. ^Whenever the
  1124. ** xFilename parameter is NULL it will also be the case that the
  1125. ** flags parameter will include [SQLITE_OPEN_DELETEONCLOSE].
  1126. **
  1127. ** The flags argument to xOpen() includes all bits set in
  1128. ** the flags argument to [sqlite3_open_v2()]. Or if [sqlite3_open()]
  1129. ** or [sqlite3_open16()] is used, then flags includes at least
  1130. ** [SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE].
  1131. ** If xOpen() opens a file read-only then it sets *pOutFlags to
  1132. ** include [SQLITE_OPEN_READONLY]. Other bits in *pOutFlags may be set.
  1133. **
  1134. ** ^(SQLite will also add one of the following flags to the xOpen()
  1135. ** call, depending on the object being opened:
  1136. **
  1137. ** <ul>
  1138. ** <li> [SQLITE_OPEN_MAIN_DB]
  1139. ** <li> [SQLITE_OPEN_MAIN_JOURNAL]
  1140. ** <li> [SQLITE_OPEN_TEMP_DB]
  1141. ** <li> [SQLITE_OPEN_TEMP_JOURNAL]
  1142. ** <li> [SQLITE_OPEN_TRANSIENT_DB]
  1143. ** <li> [SQLITE_OPEN_SUBJOURNAL]
  1144. ** <li> [SQLITE_OPEN_MASTER_JOURNAL]
  1145. ** <li> [SQLITE_OPEN_WAL]
  1146. ** </ul>)^
  1147. **
  1148. ** The file I/O implementation can use the object type flags to
  1149. ** change the way it deals with files. For example, an application
  1150. ** that does not care about crash recovery or rollback might make
  1151. ** the open of a journal file a no-op. Writes to this journal would
  1152. ** also be no-ops, and any attempt to read the journal would return
  1153. ** SQLITE_IOERR. Or the implementation might recognize that a database
  1154. ** file will be doing page-aligned sector reads and writes in a random
  1155. ** order and set up its I/O subsystem accordingly.
  1156. **
  1157. ** SQLite might also add one of the following flags to the xOpen method:
  1158. **
  1159. ** <ul>
  1160. ** <li> [SQLITE_OPEN_DELETEONCLOSE]
  1161. ** <li> [SQLITE_OPEN_EXCLUSIVE]
  1162. ** </ul>
  1163. **
  1164. ** The [SQLITE_OPEN_DELETEONCLOSE] flag means the file should be
  1165. ** deleted when it is closed. ^The [SQLITE_OPEN_DELETEONCLOSE]
  1166. ** will be set for TEMP databases and their journals, transient
  1167. ** databases, and subjournals.
  1168. **
  1169. ** ^The [SQLITE_OPEN_EXCLUSIVE] flag is always used in conjunction
  1170. ** with the [SQLITE_OPEN_CREATE] flag, which are both directly
  1171. ** analogous to the O_EXCL and O_CREAT flags of the POSIX open()
  1172. ** API. The SQLITE_OPEN_EXCLUSIVE flag, when paired with the
  1173. ** SQLITE_OPEN_CREATE, is used to indicate that file should always
  1174. ** be created, and that it is an error if it already exists.
  1175. ** It is <i>not</i> used to indicate the file should be opened
  1176. ** for exclusive access.
  1177. **
  1178. ** ^At least szOsFile bytes of memory are allocated by SQLite
  1179. ** to hold the [sqlite3_file] structure passed as the third
  1180. ** argument to xOpen. The xOpen method does not have to
  1181. ** allocate the structure; it should just fill it in. Note that
  1182. ** the xOpen method must set the sqlite3_file.pMethods to either
  1183. ** a valid [sqlite3_io_methods] object or to NULL. xOpen must do
  1184. ** this even if the open fails. SQLite expects that the sqlite3_file.pMethods
  1185. ** element will be valid after xOpen returns regardless of the success
  1186. ** or failure of the xOpen call.
  1187. **
  1188. ** [[sqlite3_vfs.xAccess]]
  1189. ** ^The flags argument to xAccess() may be [SQLITE_ACCESS_EXISTS]
  1190. ** to test for the existence of a file, or [SQLITE_ACCESS_READWRITE] to
  1191. ** test whether a file is readable and writable, or [SQLITE_ACCESS_READ]
  1192. ** to test whether a file is at least readable. The file can be a
  1193. ** directory.
  1194. **
  1195. ** ^SQLite will always allocate at least mxPathname+1 bytes for the
  1196. ** output buffer xFullPathname. The exact size of the output buffer
  1197. ** is also passed as a parameter to both methods. If the output buffer
  1198. ** is not large enough, [SQLITE_CANTOPEN] should be returned. Since this is
  1199. ** handled as a fatal error by SQLite, vfs implementations should endeavor
  1200. ** to prevent this by setting mxPathname to a sufficiently large value.
  1201. **
  1202. ** The xRandomness(), xSleep(), xCurrentTime(), and xCurrentTimeInt64()
  1203. ** interfaces are not strictly a part of the filesystem, but they are
  1204. ** included in the VFS structure for completeness.
  1205. ** The xRandomness() function attempts to return nBytes bytes
  1206. ** of good-quality randomness into zOut. The return value is
  1207. ** the actual number of bytes of randomness obtained.
  1208. ** The xSleep() method causes the calling thread to sleep for at
  1209. ** least the number of microseconds given. ^The xCurrentTime()
  1210. ** method returns a Julian Day Number for the current date and time as
  1211. ** a floating point value.
  1212. ** ^The xCurrentTimeInt64() method returns, as an integer, the Julian
  1213. ** Day Number multiplied by 86400000 (the number of milliseconds in
  1214. ** a 24-hour day).
  1215. ** ^SQLite will use the xCurrentTimeInt64() method to get the current
  1216. ** date and time if that method is available (if iVersion is 2 or
  1217. ** greater and the function pointer is not NULL) and will fall back
  1218. ** to xCurrentTime() if xCurrentTimeInt64() is unavailable.
  1219. **
  1220. ** ^The xSetSystemCall(), xGetSystemCall(), and xNestSystemCall() interfaces
  1221. ** are not used by the SQLite core. These optional interfaces are provided
  1222. ** by some VFSes to facilitate testing of the VFS code. By overriding
  1223. ** system calls with functions under its control, a test program can
  1224. ** simulate faults and error conditions that would otherwise be difficult
  1225. ** or impossible to induce. The set of system calls that can be overridden
  1226. ** varies from one VFS to another, and from one version of the same VFS to the
  1227. ** next. Applications that use these interfaces must be prepared for any
  1228. ** or all of these interfaces to be NULL or for their behavior to change
  1229. ** from one release to the next. Applications must not attempt to access
  1230. ** any of these methods if the iVersion of the VFS is less than 3.
  1231. */
  1232. typedef struct sqlite3_vfs sqlite3_vfs;
  1233. typedef void (*sqlite3_syscall_ptr)(void);
  1234. struct sqlite3_vfs {
  1235. int iVersion; /* Structure version number (currently 3) */
  1236. int szOsFile; /* Size of subclassed sqlite3_file */
  1237. int mxPathname; /* Maximum file pathname length */
  1238. sqlite3_vfs *pNext; /* Next registered VFS */
  1239. const char *zName; /* Name of this virtual file system */
  1240. void *pAppData; /* Pointer to application-specific data */
  1241. int (*xOpen)(sqlite3_vfs*, const char *zName, sqlite3_file*,
  1242. int flags, int *pOutFlags);
  1243. int (*xDelete)(sqlite3_vfs*, const char *zName, int syncDir);
  1244. int (*xAccess)(sqlite3_vfs*, const char *zName, int flags, int *pResOut);
  1245. int (*xFullPathname)(sqlite3_vfs*, const char *zName, int nOut, char *zOut);
  1246. void *(*xDlOpen)(sqlite3_vfs*, const char *zFilename);
  1247. void (*xDlError)(sqlite3_vfs*, int nByte, char *zErrMsg);
  1248. void (*(*xDlSym)(sqlite3_vfs*,void*, const char *zSymbol))(void);
  1249. void (*xDlClose)(sqlite3_vfs*, void*);
  1250. int (*xRandomness)(sqlite3_vfs*, int nByte, char *zOut);
  1251. int (*xSleep)(sqlite3_vfs*, int microseconds);
  1252. int (*xCurrentTime)(sqlite3_vfs*, double*);
  1253. int (*xGetLastError)(sqlite3_vfs*, int, char *);
  1254. /*
  1255. ** The methods above are in version 1 of the sqlite_vfs object
  1256. ** definition. Those that follow are added in version 2 or later
  1257. */
  1258. int (*xCurrentTimeInt64)(sqlite3_vfs*, sqlite3_int64*);
  1259. /*
  1260. ** The methods above are in versions 1 and 2 of the sqlite_vfs object.
  1261. ** Those below are for version 3 and greater.
  1262. */
  1263. int (*xSetSystemCall)(sqlite3_vfs*, const char *zName, sqlite3_syscall_ptr);
  1264. sqlite3_syscall_ptr (*xGetSystemCall)(sqlite3_vfs*, const char *zName);
  1265. const char *(*xNextSystemCall)(sqlite3_vfs*, const char *zName);
  1266. /*
  1267. ** The methods above are in versions 1 through 3 of the sqlite_vfs object.
  1268. ** New fields may be appended in figure versions. The iVersion
  1269. ** value will increment whenever this happens.
  1270. */
  1271. };
  1272. /*
  1273. ** CAPI3REF: Flags for the xAccess VFS method
  1274. **
  1275. ** These integer constants can be used as the third parameter to
  1276. ** the xAccess method of an [sqlite3_vfs] object. They determine
  1277. ** what kind of permissions the xAccess method is looking for.
  1278. ** With SQLITE_ACCESS_EXISTS, the xAccess method
  1279. ** simply checks whether the file exists.
  1280. ** With SQLITE_ACCESS_READWRITE, the xAccess method
  1281. ** checks whether the named directory is both readable and writable
  1282. ** (in other words, if files can be added, removed, and renamed within
  1283. ** the directory).
  1284. ** The SQLITE_ACCESS_READWRITE constant is currently used only by the
  1285. ** [temp_store_directory pragma], though this could change in a future
  1286. ** release of SQLite.
  1287. ** With SQLITE_ACCESS_READ, the xAccess method
  1288. ** checks whether the file is readable. The SQLITE_ACCESS_READ constant is
  1289. ** currently unused, though it might be used in a future release of
  1290. ** SQLite.
  1291. */
  1292. #define SQLITE_ACCESS_EXISTS 0
  1293. #define SQLITE_ACCESS_READWRITE 1 /* Used by PRAGMA temp_store_directory */
  1294. #define SQLITE_ACCESS_READ 2 /* Unused */
  1295. /*
  1296. ** CAPI3REF: Flags for the xShmLock VFS method
  1297. **
  1298. ** These integer constants define the various locking operations
  1299. ** allowed by the xShmLock method of [sqlite3_io_methods]. The
  1300. ** following are the only legal combinations of flags to the
  1301. ** xShmLock method:
  1302. **
  1303. ** <ul>
  1304. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_SHARED
  1305. ** <li> SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE
  1306. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED
  1307. ** <li> SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE
  1308. ** </ul>
  1309. **
  1310. ** When unlocking, the same SHARED or EXCLUSIVE flag must be supplied as
  1311. ** was given no the corresponding lock.
  1312. **
  1313. ** The xShmLock method can transition between unlocked and SHARED or
  1314. ** between unlocked and EXCLUSIVE. It cannot transition between SHARED
  1315. ** and EXCLUSIVE.
  1316. */
  1317. #define SQLITE_SHM_UNLOCK 1
  1318. #define SQLITE_SHM_LOCK 2
  1319. #define SQLITE_SHM_SHARED 4
  1320. #define SQLITE_SHM_EXCLUSIVE 8
  1321. /*
  1322. ** CAPI3REF: Maximum xShmLock index
  1323. **
  1324. ** The xShmLock method on [sqlite3_io_methods] may use values
  1325. ** between 0 and this upper bound as its "offset" argument.
  1326. ** The SQLite core will never attempt to acquire or release a
  1327. ** lock outside of this range
  1328. */
  1329. #define SQLITE_SHM_NLOCK 8
  1330. /*
  1331. ** CAPI3REF: Initialize The SQLite Library
  1332. **
  1333. ** ^The sqlite3_initialize() routine initializes the
  1334. ** SQLite library. ^The sqlite3_shutdown() routine
  1335. ** deallocates any resources that were allocated by sqlite3_initialize().
  1336. ** These routines are designed to aid in process initialization and
  1337. ** shutdown on embedded systems. Workstation applications using
  1338. ** SQLite normally do not need to invoke either of these routines.
  1339. **
  1340. ** A call to sqlite3_initialize() is an "effective" call if it is
  1341. ** the first time sqlite3_initialize() is invoked during the lifetime of
  1342. ** the process, or if it is the first time sqlite3_initialize() is invoked
  1343. ** following a call to sqlite3_shutdown(). ^(Only an effective call
  1344. ** of sqlite3_initialize() does any initialization. All other calls
  1345. ** are harmless no-ops.)^
  1346. **
  1347. ** A call to sqlite3_shutdown() is an "effective" call if it is the first
  1348. ** call to sqlite3_shutdown() since the last sqlite3_initialize(). ^(Only
  1349. ** an effective call to sqlite3_shutdown() does any deinitialization.
  1350. ** All other valid calls to sqlite3_shutdown() are harmless no-ops.)^
  1351. **
  1352. ** The sqlite3_initialize() interface is threadsafe, but sqlite3_shutdown()
  1353. ** is not. The sqlite3_shutdown() interface must only be called from a
  1354. ** single thread. All open [database connections] must be closed and all
  1355. ** other SQLite resources must be deallocated prior to invoking
  1356. ** sqlite3_shutdown().
  1357. **
  1358. ** Among other things, ^sqlite3_initialize() will invoke
  1359. ** sqlite3_os_init(). Similarly, ^sqlite3_shutdown()
  1360. ** will invoke sqlite3_os_end().
  1361. **
  1362. ** ^The sqlite3_initialize() routine returns [SQLITE_OK] on success.
  1363. ** ^If for some reason, sqlite3_initialize() is unable to initialize
  1364. ** the library (perhaps it is unable to allocate a needed resource such
  1365. ** as a mutex) it returns an [error code] other than [SQLITE_OK].
  1366. **
  1367. ** ^The sqlite3_initialize() routine is called internally by many other
  1368. ** SQLite interfaces so that an application usually does not need to
  1369. ** invoke sqlite3_initialize() directly. For example, [sqlite3_open()]
  1370. ** calls sqlite3_initialize() so the SQLite library will be automatically
  1371. ** initialized when [sqlite3_open()] is called if it has not be initialized
  1372. ** already. ^However, if SQLite is compiled with the [SQLITE_OMIT_AUTOINIT]
  1373. ** compile-time option, then the automatic calls to sqlite3_initialize()
  1374. ** are omitted and the application must call sqlite3_initialize() directly
  1375. ** prior to using any other SQLite interface. For maximum portability,
  1376. ** it is recommended that applications always invoke sqlite3_initialize()
  1377. ** directly prior to using any other SQLite interface. Future releases
  1378. ** of SQLite may require this. In other words, the behavior exhibited
  1379. ** when SQLite is compiled with [SQLITE_OMIT_AUTOINIT] might become the
  1380. ** default behavior in some future release of SQLite.
  1381. **
  1382. ** The sqlite3_os_init() routine does operating-system specific
  1383. ** initialization of the SQLite library. The sqlite3_os_end()
  1384. ** routine undoes the effect of sqlite3_os_init(). Typical tasks
  1385. ** performed by these routines include allocation or deallocation
  1386. ** of static resources, initialization of global variables,
  1387. ** setting up a default [sqlite3_vfs] module, or setting up
  1388. ** a default configuration using [sqlite3_config()].
  1389. **
  1390. ** The application should never invoke either sqlite3_os_init()
  1391. ** or sqlite3_os_end() directly. The application should only invoke
  1392. ** sqlite3_initialize() and sqlite3_shutdown(). The sqlite3_os_init()
  1393. ** interface is called automatically by sqlite3_initialize() and
  1394. ** sqlite3_os_end() is called by sqlite3_shutdown(). Appropriate
  1395. ** implementations for sqlite3_os_init() and sqlite3_os_end()
  1396. ** are built into SQLite when it is compiled for Unix, Windows, or OS/2.
  1397. ** When [custom builds | built for other platforms]
  1398. ** (using the [SQLITE_OS_OTHER=1] compile-time
  1399. ** option) the application must supply a suitable implementation for
  1400. ** sqlite3_os_init() and sqlite3_os_end(). An application-supplied
  1401. ** implementation of sqlite3_os_init() or sqlite3_os_end()
  1402. ** must return [SQLITE_OK] on success and some other [error code] upon
  1403. ** failure.
  1404. */
  1405. SQLITE_API int sqlite3_initialize(void);
  1406. SQLITE_API int sqlite3_shutdown(void);
  1407. SQLITE_API int sqlite3_os_init(void);
  1408. SQLITE_API int sqlite3_os_end(void);
  1409. /*
  1410. ** CAPI3REF: Configuring The SQLite Library
  1411. **
  1412. ** The sqlite3_config() interface is used to make global configuration
  1413. ** changes to SQLite in order to tune SQLite to the specific needs of
  1414. ** the application. The default configuration is recommended for most
  1415. ** applications and so this routine is usually not necessary. It is
  1416. ** provided to support rare applications with unusual needs.
  1417. **
  1418. ** The sqlite3_config() interface is not threadsafe. The application
  1419. ** must insure that no other SQLite interfaces are invoked by other
  1420. ** threads while sqlite3_config() is running. Furthermore, sqlite3_config()
  1421. ** may only be invoked prior to library initialization using
  1422. ** [sqlite3_initialize()] or after shutdown by [sqlite3_shutdown()].
  1423. ** ^If sqlite3_config() is called after [sqlite3_initialize()] and before
  1424. ** [sqlite3_shutdown()] then it will return SQLITE_MISUSE.
  1425. ** Note, however, that ^sqlite3_config() can be called as part of the
  1426. ** implementation of an application-defined [sqlite3_os_init()].
  1427. **
  1428. ** The first argument to sqlite3_config() is an integer
  1429. ** [configuration option] that determines
  1430. ** what property of SQLite is to be configured. Subsequent arguments
  1431. ** vary depending on the [configuration option]
  1432. ** in the first argument.
  1433. **
  1434. ** ^When a configuration option is set, sqlite3_config() returns [SQLITE_OK].
  1435. ** ^If the option is unknown or SQLite is unable to set the option
  1436. ** then this routine returns a non-zero [error code].
  1437. */
  1438. SQLITE_API int sqlite3_config(int, ...);
  1439. /*
  1440. ** CAPI3REF: Configure database connections
  1441. **
  1442. ** The sqlite3_db_config() interface is used to make configuration
  1443. ** changes to a [database connection]. The interface is similar to
  1444. ** [sqlite3_config()] except that the changes apply to a single
  1445. ** [database connection] (specified in the first argument).
  1446. **
  1447. ** The second argument to sqlite3_db_config(D,V,...) is the
  1448. ** [SQLITE_DBCONFIG_LOOKASIDE | configuration verb] - an integer code
  1449. ** that indicates what aspect of the [database connection] is being configured.
  1450. ** Subsequent arguments vary depending on the configuration verb.
  1451. **
  1452. ** ^Calls to sqlite3_db_config() return SQLITE_OK if and only if
  1453. ** the call is considered successful.
  1454. */
  1455. SQLITE_API int sqlite3_db_config(sqlite3*, int op, ...);
  1456. /*
  1457. ** CAPI3REF: Memory Allocation Routines
  1458. **
  1459. ** An instance of this object defines the interface between SQLite
  1460. ** and low-level memory allocation routines.
  1461. **
  1462. ** This object is used in only one place in the SQLite interface.
  1463. ** A pointer to an instance of this object is the argument to
  1464. ** [sqlite3_config()] when the configuration option is
  1465. ** [SQLITE_CONFIG_MALLOC] or [SQLITE_CONFIG_GETMALLOC].
  1466. ** By creating an instance of this object
  1467. ** and passing it to [sqlite3_config]([SQLITE_CONFIG_MALLOC])
  1468. ** during configuration, an application can specify an alternative
  1469. ** memory allocation subsystem for SQLite to use for all of its
  1470. ** dynamic memory needs.
  1471. **
  1472. ** Note that SQLite comes with several [built-in memory allocators]
  1473. ** that are perfectly adequate for the overwhelming majority of applications
  1474. ** and that this object is only useful to a tiny minority of applications
  1475. ** with specialized memory allocation requirements. This object is
  1476. ** also used during testing of SQLite in order to specify an alternative
  1477. ** memory allocator that simulates memory out-of-memory conditions in
  1478. ** order to verify that SQLite recovers gracefully from such
  1479. ** conditions.
  1480. **
  1481. ** The xMalloc, xRealloc, and xFree methods must work like the
  1482. ** malloc(), realloc() and free() functions from the standard C library.
  1483. ** ^SQLite guarantees that the second argument to
  1484. ** xRealloc is always a value returned by a prior call to xRoundup.
  1485. **
  1486. ** xSize should return the allocated size of a memory allocation
  1487. ** previously obtained from xMalloc or xRealloc. The allocated size
  1488. ** is always at least as big as the requested size but may be larger.
  1489. **
  1490. ** The xRoundup method returns what would be the allocated size of
  1491. ** a memory allocation given a particular requested size. Most memory
  1492. ** allocators round up memory allocations at least to the next multiple
  1493. ** of 8. Some allocators round up to a larger multiple or to a power of 2.
  1494. ** Every memory allocation request coming in through [sqlite3_malloc()]
  1495. ** or [sqlite3_realloc()] first calls xRoundup. If xRoundup returns 0,
  1496. ** that causes the corresponding memory allocation to fail.
  1497. **
  1498. ** The xInit method initializes the memory allocator. For example,
  1499. ** it might allocate any require mutexes or initialize internal data
  1500. ** structures. The xShutdown method is invoked (indirectly) by
  1501. ** [sqlite3_shutdown()] and should deallocate any resources acquired
  1502. ** by xInit. The pAppData pointer is used as the only parameter to
  1503. ** xInit and xShutdown.
  1504. **
  1505. ** SQLite holds the [SQLITE_MUTEX_STATIC_MASTER] mutex when it invokes
  1506. ** the xInit method, so the xInit method need not be threadsafe. The
  1507. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  1508. ** not need to be threadsafe either. For all other methods, SQLite
  1509. ** holds the [SQLITE_MUTEX_STATIC_MEM] mutex as long as the
  1510. ** [SQLITE_CONFIG_MEMSTATUS] configuration option is turned on (which
  1511. ** it is by default) and so the methods are automatically serialized.
  1512. ** However, if [SQLITE_CONFIG_MEMSTATUS] is disabled, then the other
  1513. ** methods must be threadsafe or else make their own arrangements for
  1514. ** serialization.
  1515. **
  1516. ** SQLite will never invoke xInit() more than once without an intervening
  1517. ** call to xShutdown().
  1518. */
  1519. typedef struct sqlite3_mem_methods sqlite3_mem_methods;
  1520. struct sqlite3_mem_methods {
  1521. void *(*xMalloc)(int); /* Memory allocation function */
  1522. void (*xFree)(void*); /* Free a prior allocation */
  1523. void *(*xRealloc)(void*,int); /* Resize an allocation */
  1524. int (*xSize)(void*); /* Return the size of an allocation */
  1525. int (*xRoundup)(int); /* Round up request size to allocation size */
  1526. int (*xInit)(void*); /* Initialize the memory allocator */
  1527. void (*xShutdown)(void*); /* Deinitialize the memory allocator */
  1528. void *pAppData; /* Argument to xInit() and xShutdown() */
  1529. };
  1530. /*
  1531. ** CAPI3REF: Configuration Options
  1532. ** KEYWORDS: {configuration option}
  1533. **
  1534. ** These constants are the available integer configuration options that
  1535. ** can be passed as the first argument to the [sqlite3_config()] interface.
  1536. **
  1537. ** New configuration options may be added in future releases of SQLite.
  1538. ** Existing configuration options might be discontinued. Applications
  1539. ** should check the return code from [sqlite3_config()] to make sure that
  1540. ** the call worked. The [sqlite3_config()] interface will return a
  1541. ** non-zero [error code] if a discontinued or unsupported configuration option
  1542. ** is invoked.
  1543. **
  1544. ** <dl>
  1545. ** [[SQLITE_CONFIG_SINGLETHREAD]] <dt>SQLITE_CONFIG_SINGLETHREAD</dt>
  1546. ** <dd>There are no arguments to this option. ^This option sets the
  1547. ** [threading mode] to Single-thread. In other words, it disables
  1548. ** all mutexing and puts SQLite into a mode where it can only be used
  1549. ** by a single thread. ^If SQLite is compiled with
  1550. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1551. ** it is not possible to change the [threading mode] from its default
  1552. ** value of Single-thread and so [sqlite3_config()] will return
  1553. ** [SQLITE_ERROR] if called with the SQLITE_CONFIG_SINGLETHREAD
  1554. ** configuration option.</dd>
  1555. **
  1556. ** [[SQLITE_CONFIG_MULTITHREAD]] <dt>SQLITE_CONFIG_MULTITHREAD</dt>
  1557. ** <dd>There are no arguments to this option. ^This option sets the
  1558. ** [threading mode] to Multi-thread. In other words, it disables
  1559. ** mutexing on [database connection] and [prepared statement] objects.
  1560. ** The application is responsible for serializing access to
  1561. ** [database connections] and [prepared statements]. But other mutexes
  1562. ** are enabled so that SQLite will be safe to use in a multi-threaded
  1563. ** environment as long as no two threads attempt to use the same
  1564. ** [database connection] at the same time. ^If SQLite is compiled with
  1565. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1566. ** it is not possible to set the Multi-thread [threading mode] and
  1567. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1568. ** SQLITE_CONFIG_MULTITHREAD configuration option.</dd>
  1569. **
  1570. ** [[SQLITE_CONFIG_SERIALIZED]] <dt>SQLITE_CONFIG_SERIALIZED</dt>
  1571. ** <dd>There are no arguments to this option. ^This option sets the
  1572. ** [threading mode] to Serialized. In other words, this option enables
  1573. ** all mutexes including the recursive
  1574. ** mutexes on [database connection] and [prepared statement] objects.
  1575. ** In this mode (which is the default when SQLite is compiled with
  1576. ** [SQLITE_THREADSAFE=1]) the SQLite library will itself serialize access
  1577. ** to [database connections] and [prepared statements] so that the
  1578. ** application is free to use the same [database connection] or the
  1579. ** same [prepared statement] in different threads at the same time.
  1580. ** ^If SQLite is compiled with
  1581. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1582. ** it is not possible to set the Serialized [threading mode] and
  1583. ** [sqlite3_config()] will return [SQLITE_ERROR] if called with the
  1584. ** SQLITE_CONFIG_SERIALIZED configuration option.</dd>
  1585. **
  1586. ** [[SQLITE_CONFIG_MALLOC]] <dt>SQLITE_CONFIG_MALLOC</dt>
  1587. ** <dd> ^(This option takes a single argument which is a pointer to an
  1588. ** instance of the [sqlite3_mem_methods] structure. The argument specifies
  1589. ** alternative low-level memory allocation routines to be used in place of
  1590. ** the memory allocation routines built into SQLite.)^ ^SQLite makes
  1591. ** its own private copy of the content of the [sqlite3_mem_methods] structure
  1592. ** before the [sqlite3_config()] call returns.</dd>
  1593. **
  1594. ** [[SQLITE_CONFIG_GETMALLOC]] <dt>SQLITE_CONFIG_GETMALLOC</dt>
  1595. ** <dd> ^(This option takes a single argument which is a pointer to an
  1596. ** instance of the [sqlite3_mem_methods] structure. The [sqlite3_mem_methods]
  1597. ** structure is filled with the currently defined memory allocation routines.)^
  1598. ** This option can be used to overload the default memory allocation
  1599. ** routines with a wrapper that simulations memory allocation failure or
  1600. ** tracks memory usage, for example. </dd>
  1601. **
  1602. ** [[SQLITE_CONFIG_MEMSTATUS]] <dt>SQLITE_CONFIG_MEMSTATUS</dt>
  1603. ** <dd> ^This option takes single argument of type int, interpreted as a
  1604. ** boolean, which enables or disables the collection of memory allocation
  1605. ** statistics. ^(When memory allocation statistics are disabled, the
  1606. ** following SQLite interfaces become non-operational:
  1607. ** <ul>
  1608. ** <li> [sqlite3_memory_used()]
  1609. ** <li> [sqlite3_memory_highwater()]
  1610. ** <li> [sqlite3_soft_heap_limit64()]
  1611. ** <li> [sqlite3_status()]
  1612. ** </ul>)^
  1613. ** ^Memory allocation statistics are enabled by default unless SQLite is
  1614. ** compiled with [SQLITE_DEFAULT_MEMSTATUS]=0 in which case memory
  1615. ** allocation statistics are disabled by default.
  1616. ** </dd>
  1617. **
  1618. ** [[SQLITE_CONFIG_SCRATCH]] <dt>SQLITE_CONFIG_SCRATCH</dt>
  1619. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1620. ** scratch memory. There are three arguments: A pointer an 8-byte
  1621. ** aligned memory buffer from which the scratch allocations will be
  1622. ** drawn, the size of each scratch allocation (sz),
  1623. ** and the maximum number of scratch allocations (N). The sz
  1624. ** argument must be a multiple of 16.
  1625. ** The first argument must be a pointer to an 8-byte aligned buffer
  1626. ** of at least sz*N bytes of memory.
  1627. ** ^SQLite will use no more than two scratch buffers per thread. So
  1628. ** N should be set to twice the expected maximum number of threads.
  1629. ** ^SQLite will never require a scratch buffer that is more than 6
  1630. ** times the database page size. ^If SQLite needs needs additional
  1631. ** scratch memory beyond what is provided by this configuration option, then
  1632. ** [sqlite3_malloc()] will be used to obtain the memory needed.</dd>
  1633. **
  1634. ** [[SQLITE_CONFIG_PAGECACHE]] <dt>SQLITE_CONFIG_PAGECACHE</dt>
  1635. ** <dd> ^This option specifies a static memory buffer that SQLite can use for
  1636. ** the database page cache with the default page cache implementation.
  1637. ** This configuration should not be used if an application-define page
  1638. ** cache implementation is loaded using the SQLITE_CONFIG_PCACHE2 option.
  1639. ** There are three arguments to this option: A pointer to 8-byte aligned
  1640. ** memory, the size of each page buffer (sz), and the number of pages (N).
  1641. ** The sz argument should be the size of the largest database page
  1642. ** (a power of two between 512 and 32768) plus a little extra for each
  1643. ** page header. ^The page header size is 20 to 40 bytes depending on
  1644. ** the host architecture. ^It is harmless, apart from the wasted memory,
  1645. ** to make sz a little too large. The first
  1646. ** argument should point to an allocation of at least sz*N bytes of memory.
  1647. ** ^SQLite will use the memory provided by the first argument to satisfy its
  1648. ** memory needs for the first N pages that it adds to cache. ^If additional
  1649. ** page cache memory is needed beyond what is provided by this option, then
  1650. ** SQLite goes to [sqlite3_malloc()] for the additional storage space.
  1651. ** The pointer in the first argument must
  1652. ** be aligned to an 8-byte boundary or subsequent behavior of SQLite
  1653. ** will be undefined.</dd>
  1654. **
  1655. ** [[SQLITE_CONFIG_HEAP]] <dt>SQLITE_CONFIG_HEAP</dt>
  1656. ** <dd> ^This option specifies a static memory buffer that SQLite will use
  1657. ** for all of its dynamic memory allocation needs beyond those provided
  1658. ** for by [SQLITE_CONFIG_SCRATCH] and [SQLITE_CONFIG_PAGECACHE].
  1659. ** There are three arguments: An 8-byte aligned pointer to the memory,
  1660. ** the number of bytes in the memory buffer, and the minimum allocation size.
  1661. ** ^If the first pointer (the memory pointer) is NULL, then SQLite reverts
  1662. ** to using its default memory allocator (the system malloc() implementation),
  1663. ** undoing any prior invocation of [SQLITE_CONFIG_MALLOC]. ^If the
  1664. ** memory pointer is not NULL and either [SQLITE_ENABLE_MEMSYS3] or
  1665. ** [SQLITE_ENABLE_MEMSYS5] are defined, then the alternative memory
  1666. ** allocator is engaged to handle all of SQLites memory allocation needs.
  1667. ** The first pointer (the memory pointer) must be aligned to an 8-byte
  1668. ** boundary or subsequent behavior of SQLite will be undefined.
  1669. ** The minimum allocation size is capped at 2**12. Reasonable values
  1670. ** for the minimum allocation size are 2**5 through 2**8.</dd>
  1671. **
  1672. ** [[SQLITE_CONFIG_MUTEX]] <dt>SQLITE_CONFIG_MUTEX</dt>
  1673. ** <dd> ^(This option takes a single argument which is a pointer to an
  1674. ** instance of the [sqlite3_mutex_methods] structure. The argument specifies
  1675. ** alternative low-level mutex routines to be used in place
  1676. ** the mutex routines built into SQLite.)^ ^SQLite makes a copy of the
  1677. ** content of the [sqlite3_mutex_methods] structure before the call to
  1678. ** [sqlite3_config()] returns. ^If SQLite is compiled with
  1679. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1680. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1681. ** [sqlite3_config()] with the SQLITE_CONFIG_MUTEX configuration option will
  1682. ** return [SQLITE_ERROR].</dd>
  1683. **
  1684. ** [[SQLITE_CONFIG_GETMUTEX]] <dt>SQLITE_CONFIG_GETMUTEX</dt>
  1685. ** <dd> ^(This option takes a single argument which is a pointer to an
  1686. ** instance of the [sqlite3_mutex_methods] structure. The
  1687. ** [sqlite3_mutex_methods]
  1688. ** structure is filled with the currently defined mutex routines.)^
  1689. ** This option can be used to overload the default mutex allocation
  1690. ** routines with a wrapper used to track mutex usage for performance
  1691. ** profiling or testing, for example. ^If SQLite is compiled with
  1692. ** the [SQLITE_THREADSAFE | SQLITE_THREADSAFE=0] compile-time option then
  1693. ** the entire mutexing subsystem is omitted from the build and hence calls to
  1694. ** [sqlite3_config()] with the SQLITE_CONFIG_GETMUTEX configuration option will
  1695. ** return [SQLITE_ERROR].</dd>
  1696. **
  1697. ** [[SQLITE_CONFIG_LOOKASIDE]] <dt>SQLITE_CONFIG_LOOKASIDE</dt>
  1698. ** <dd> ^(This option takes two arguments that determine the default
  1699. ** memory allocation for the lookaside memory allocator on each
  1700. ** [database connection]. The first argument is the
  1701. ** size of each lookaside buffer slot and the second is the number of
  1702. ** slots allocated to each database connection.)^ ^(This option sets the
  1703. ** <i>default</i> lookaside size. The [SQLITE_DBCONFIG_LOOKASIDE]
  1704. ** verb to [sqlite3_db_config()] can be used to change the lookaside
  1705. ** configuration on individual connections.)^ </dd>
  1706. **
  1707. ** [[SQLITE_CONFIG_PCACHE2]] <dt>SQLITE_CONFIG_PCACHE2</dt>
  1708. ** <dd> ^(This option takes a single argument which is a pointer to
  1709. ** an [sqlite3_pcache_methods2] object. This object specifies the interface
  1710. ** to a custom page cache implementation.)^ ^SQLite makes a copy of the
  1711. ** object and uses it for page cache memory allocations.</dd>
  1712. **
  1713. ** [[SQLITE_CONFIG_GETPCACHE2]] <dt>SQLITE_CONFIG_GETPCACHE2</dt>
  1714. ** <dd> ^(This option takes a single argument which is a pointer to an
  1715. ** [sqlite3_pcache_methods2] object. SQLite copies of the current
  1716. ** page cache implementation into that object.)^ </dd>
  1717. **
  1718. ** [[SQLITE_CONFIG_LOG]] <dt>SQLITE_CONFIG_LOG</dt>
  1719. ** <dd> The SQLITE_CONFIG_LOG option is used to configure the SQLite
  1720. ** global [error log].
  1721. ** (^The SQLITE_CONFIG_LOG option takes two arguments: a pointer to a
  1722. ** function with a call signature of void(*)(void*,int,const char*),
  1723. ** and a pointer to void. ^If the function pointer is not NULL, it is
  1724. ** invoked by [sqlite3_log()] to process each logging event. ^If the
  1725. ** function pointer is NULL, the [sqlite3_log()] interface becomes a no-op.
  1726. ** ^The void pointer that is the second argument to SQLITE_CONFIG_LOG is
  1727. ** passed through as the first parameter to the application-defined logger
  1728. ** function whenever that function is invoked. ^The second parameter to
  1729. ** the logger function is a copy of the first parameter to the corresponding
  1730. ** [sqlite3_log()] call and is intended to be a [result code] or an
  1731. ** [extended result code]. ^The third parameter passed to the logger is
  1732. ** log message after formatting via [sqlite3_snprintf()].
  1733. ** The SQLite logging interface is not reentrant; the logger function
  1734. ** supplied by the application must not invoke any SQLite interface.
  1735. ** In a multi-threaded application, the application-defined logger
  1736. ** function must be threadsafe. </dd>
  1737. **
  1738. ** [[SQLITE_CONFIG_URI]] <dt>SQLITE_CONFIG_URI
  1739. ** <dd>^(This option takes a single argument of type int. If non-zero, then
  1740. ** URI handling is globally enabled. If the parameter is zero, then URI handling
  1741. ** is globally disabled.)^ ^If URI handling is globally enabled, all filenames
  1742. ** passed to [sqlite3_open()], [sqlite3_open_v2()], [sqlite3_open16()] or
  1743. ** specified as part of [ATTACH] commands are interpreted as URIs, regardless
  1744. ** of whether or not the [SQLITE_OPEN_URI] flag is set when the database
  1745. ** connection is opened. ^If it is globally disabled, filenames are
  1746. ** only interpreted as URIs if the SQLITE_OPEN_URI flag is set when the
  1747. ** database connection is opened. ^(By default, URI handling is globally
  1748. ** disabled. The default value may be changed by compiling with the
  1749. ** [SQLITE_USE_URI] symbol defined.)^
  1750. **
  1751. ** [[SQLITE_CONFIG_COVERING_INDEX_SCAN]] <dt>SQLITE_CONFIG_COVERING_INDEX_SCAN
  1752. ** <dd>^This option takes a single integer argument which is interpreted as
  1753. ** a boolean in order to enable or disable the use of covering indices for
  1754. ** full table scans in the query optimizer. ^The default setting is determined
  1755. ** by the [SQLITE_ALLOW_COVERING_INDEX_SCAN] compile-time option, or is "on"
  1756. ** if that compile-time option is omitted.
  1757. ** The ability to disable the use of covering indices for full table scans
  1758. ** is because some incorrectly coded legacy applications might malfunction
  1759. ** when the optimization is enabled. Providing the ability to
  1760. ** disable the optimization allows the older, buggy application code to work
  1761. ** without change even with newer versions of SQLite.
  1762. **
  1763. ** [[SQLITE_CONFIG_PCACHE]] [[SQLITE_CONFIG_GETPCACHE]]
  1764. ** <dt>SQLITE_CONFIG_PCACHE and SQLITE_CONFIG_GETPCACHE
  1765. ** <dd> These options are obsolete and should not be used by new code.
  1766. ** They are retained for backwards compatibility but are now no-ops.
  1767. ** </dd>
  1768. **
  1769. ** [[SQLITE_CONFIG_SQLLOG]]
  1770. ** <dt>SQLITE_CONFIG_SQLLOG
  1771. ** <dd>This option is only available if sqlite is compiled with the
  1772. ** [SQLITE_ENABLE_SQLLOG] pre-processor macro defined. The first argument should
  1773. ** be a pointer to a function of type void(*)(void*,sqlite3*,const char*, int).
  1774. ** The second should be of type (void*). The callback is invoked by the library
  1775. ** in three separate circumstances, identified by the value passed as the
  1776. ** fourth parameter. If the fourth parameter is 0, then the database connection
  1777. ** passed as the second argument has just been opened. The third argument
  1778. ** points to a buffer containing the name of the main database file. If the
  1779. ** fourth parameter is 1, then the SQL statement that the third parameter
  1780. ** points to has just been executed. Or, if the fourth parameter is 2, then
  1781. ** the connection being passed as the second parameter is being closed. The
  1782. ** third parameter is passed NULL In this case. An example of using this
  1783. ** configuration option can be seen in the "test_sqllog.c" source file in
  1784. ** the canonical SQLite source tree.</dd>
  1785. **
  1786. ** [[SQLITE_CONFIG_MMAP_SIZE]]
  1787. ** <dt>SQLITE_CONFIG_MMAP_SIZE
  1788. ** <dd>^SQLITE_CONFIG_MMAP_SIZE takes two 64-bit integer (sqlite3_int64) values
  1789. ** that are the default mmap size limit (the default setting for
  1790. ** [PRAGMA mmap_size]) and the maximum allowed mmap size limit.
  1791. ** ^The default setting can be overridden by each database connection using
  1792. ** either the [PRAGMA mmap_size] command, or by using the
  1793. ** [SQLITE_FCNTL_MMAP_SIZE] file control. ^(The maximum allowed mmap size
  1794. ** cannot be changed at run-time. Nor may the maximum allowed mmap size
  1795. ** exceed the compile-time maximum mmap size set by the
  1796. ** [SQLITE_MAX_MMAP_SIZE] compile-time option.)^
  1797. ** ^If either argument to this option is negative, then that argument is
  1798. ** changed to its compile-time default.
  1799. **
  1800. ** [[SQLITE_CONFIG_WIN32_HEAPSIZE]]
  1801. ** <dt>SQLITE_CONFIG_WIN32_HEAPSIZE
  1802. ** <dd>^This option is only available if SQLite is compiled for Windows
  1803. ** with the [SQLITE_WIN32_MALLOC] pre-processor macro defined.
  1804. ** SQLITE_CONFIG_WIN32_HEAPSIZE takes a 32-bit unsigned integer value
  1805. ** that specifies the maximum size of the created heap.
  1806. ** </dl>
  1807. */
  1808. #define SQLITE_CONFIG_SINGLETHREAD 1 /* nil */
  1809. #define SQLITE_CONFIG_MULTITHREAD 2 /* nil */
  1810. #define SQLITE_CONFIG_SERIALIZED 3 /* nil */
  1811. #define SQLITE_CONFIG_MALLOC 4 /* sqlite3_mem_methods* */
  1812. #define SQLITE_CONFIG_GETMALLOC 5 /* sqlite3_mem_methods* */
  1813. #define SQLITE_CONFIG_SCRATCH 6 /* void*, int sz, int N */
  1814. #define SQLITE_CONFIG_PAGECACHE 7 /* void*, int sz, int N */
  1815. #define SQLITE_CONFIG_HEAP 8 /* void*, int nByte, int min */
  1816. #define SQLITE_CONFIG_MEMSTATUS 9 /* boolean */
  1817. #define SQLITE_CONFIG_MUTEX 10 /* sqlite3_mutex_methods* */
  1818. #define SQLITE_CONFIG_GETMUTEX 11 /* sqlite3_mutex_methods* */
  1819. /* previously SQLITE_CONFIG_CHUNKALLOC 12 which is now unused. */
  1820. #define SQLITE_CONFIG_LOOKASIDE 13 /* int int */
  1821. #define SQLITE_CONFIG_PCACHE 14 /* no-op */
  1822. #define SQLITE_CONFIG_GETPCACHE 15 /* no-op */
  1823. #define SQLITE_CONFIG_LOG 16 /* xFunc, void* */
  1824. #define SQLITE_CONFIG_URI 17 /* int */
  1825. #define SQLITE_CONFIG_PCACHE2 18 /* sqlite3_pcache_methods2* */
  1826. #define SQLITE_CONFIG_GETPCACHE2 19 /* sqlite3_pcache_methods2* */
  1827. #define SQLITE_CONFIG_COVERING_INDEX_SCAN 20 /* int */
  1828. #define SQLITE_CONFIG_SQLLOG 21 /* xSqllog, void* */
  1829. #define SQLITE_CONFIG_MMAP_SIZE 22 /* sqlite3_int64, sqlite3_int64 */
  1830. #define SQLITE_CONFIG_WIN32_HEAPSIZE 23 /* int nByte */
  1831. /*
  1832. ** CAPI3REF: Database Connection Configuration Options
  1833. **
  1834. ** These constants are the available integer configuration options that
  1835. ** can be passed as the second argument to the [sqlite3_db_config()] interface.
  1836. **
  1837. ** New configuration options may be added in future releases of SQLite.
  1838. ** Existing configuration options might be discontinued. Applications
  1839. ** should check the return code from [sqlite3_db_config()] to make sure that
  1840. ** the call worked. ^The [sqlite3_db_config()] interface will return a
  1841. ** non-zero [error code] if a discontinued or unsupported configuration option
  1842. ** is invoked.
  1843. **
  1844. ** <dl>
  1845. ** <dt>SQLITE_DBCONFIG_LOOKASIDE</dt>
  1846. ** <dd> ^This option takes three additional arguments that determine the
  1847. ** [lookaside memory allocator] configuration for the [database connection].
  1848. ** ^The first argument (the third parameter to [sqlite3_db_config()] is a
  1849. ** pointer to a memory buffer to use for lookaside memory.
  1850. ** ^The first argument after the SQLITE_DBCONFIG_LOOKASIDE verb
  1851. ** may be NULL in which case SQLite will allocate the
  1852. ** lookaside buffer itself using [sqlite3_malloc()]. ^The second argument is the
  1853. ** size of each lookaside buffer slot. ^The third argument is the number of
  1854. ** slots. The size of the buffer in the first argument must be greater than
  1855. ** or equal to the product of the second and third arguments. The buffer
  1856. ** must be aligned to an 8-byte boundary. ^If the second argument to
  1857. ** SQLITE_DBCONFIG_LOOKASIDE is not a multiple of 8, it is internally
  1858. ** rounded down to the next smaller multiple of 8. ^(The lookaside memory
  1859. ** configuration for a database connection can only be changed when that
  1860. ** connection is not currently using lookaside memory, or in other words
  1861. ** when the "current value" returned by
  1862. ** [sqlite3_db_status](D,[SQLITE_CONFIG_LOOKASIDE],...) is zero.
  1863. ** Any attempt to change the lookaside memory configuration when lookaside
  1864. ** memory is in use leaves the configuration unchanged and returns
  1865. ** [SQLITE_BUSY].)^</dd>
  1866. **
  1867. ** <dt>SQLITE_DBCONFIG_ENABLE_FKEY</dt>
  1868. ** <dd> ^This option is used to enable or disable the enforcement of
  1869. ** [foreign key constraints]. There should be two additional arguments.
  1870. ** The first argument is an integer which is 0 to disable FK enforcement,
  1871. ** positive to enable FK enforcement or negative to leave FK enforcement
  1872. ** unchanged. The second parameter is a pointer to an integer into which
  1873. ** is written 0 or 1 to indicate whether FK enforcement is off or on
  1874. ** following this call. The second parameter may be a NULL pointer, in
  1875. ** which case the FK enforcement setting is not reported back. </dd>
  1876. **
  1877. ** <dt>SQLITE_DBCONFIG_ENABLE_TRIGGER</dt>
  1878. ** <dd> ^This option is used to enable or disable [CREATE TRIGGER | triggers].
  1879. ** There should be two additional arguments.
  1880. ** The first argument is an integer which is 0 to disable triggers,
  1881. ** positive to enable triggers or negative to leave the setting unchanged.
  1882. ** The second parameter is a pointer to an integer into which
  1883. ** is written 0 or 1 to indicate whether triggers are disabled or enabled
  1884. ** following this call. The second parameter may be a NULL pointer, in
  1885. ** which case the trigger setting is not reported back. </dd>
  1886. **
  1887. ** </dl>
  1888. */
  1889. #define SQLITE_DBCONFIG_LOOKASIDE 1001 /* void* int int */
  1890. #define SQLITE_DBCONFIG_ENABLE_FKEY 1002 /* int int* */
  1891. #define SQLITE_DBCONFIG_ENABLE_TRIGGER 1003 /* int int* */
  1892. /*
  1893. ** CAPI3REF: Enable Or Disable Extended Result Codes
  1894. **
  1895. ** ^The sqlite3_extended_result_codes() routine enables or disables the
  1896. ** [extended result codes] feature of SQLite. ^The extended result
  1897. ** codes are disabled by default for historical compatibility.
  1898. */
  1899. SQLITE_API int sqlite3_extended_result_codes(sqlite3*, int onoff);
  1900. /*
  1901. ** CAPI3REF: Last Insert Rowid
  1902. **
  1903. ** ^Each entry in most SQLite tables (except for [WITHOUT ROWID] tables)
  1904. ** has a unique 64-bit signed
  1905. ** integer key called the [ROWID | "rowid"]. ^The rowid is always available
  1906. ** as an undeclared column named ROWID, OID, or _ROWID_ as long as those
  1907. ** names are not also used by explicitly declared columns. ^If
  1908. ** the table has a column of type [INTEGER PRIMARY KEY] then that column
  1909. ** is another alias for the rowid.
  1910. **
  1911. ** ^The sqlite3_last_insert_rowid(D) interface returns the [rowid] of the
  1912. ** most recent successful [INSERT] into a rowid table or [virtual table]
  1913. ** on database connection D.
  1914. ** ^Inserts into [WITHOUT ROWID] tables are not recorded.
  1915. ** ^If no successful [INSERT]s into rowid tables
  1916. ** have ever occurred on the database connection D,
  1917. ** then sqlite3_last_insert_rowid(D) returns zero.
  1918. **
  1919. ** ^(If an [INSERT] occurs within a trigger or within a [virtual table]
  1920. ** method, then this routine will return the [rowid] of the inserted
  1921. ** row as long as the trigger or virtual table method is running.
  1922. ** But once the trigger or virtual table method ends, the value returned
  1923. ** by this routine reverts to what it was before the trigger or virtual
  1924. ** table method began.)^
  1925. **
  1926. ** ^An [INSERT] that fails due to a constraint violation is not a
  1927. ** successful [INSERT] and does not change the value returned by this
  1928. ** routine. ^Thus INSERT OR FAIL, INSERT OR IGNORE, INSERT OR ROLLBACK,
  1929. ** and INSERT OR ABORT make no changes to the return value of this
  1930. ** routine when their insertion fails. ^(When INSERT OR REPLACE
  1931. ** encounters a constraint violation, it does not fail. The
  1932. ** INSERT continues to completion after deleting rows that caused
  1933. ** the constraint problem so INSERT OR REPLACE will always change
  1934. ** the return value of this interface.)^
  1935. **
  1936. ** ^For the purposes of this routine, an [INSERT] is considered to
  1937. ** be successful even if it is subsequently rolled back.
  1938. **
  1939. ** This function is accessible to SQL statements via the
  1940. ** [last_insert_rowid() SQL function].
  1941. **
  1942. ** If a separate thread performs a new [INSERT] on the same
  1943. ** database connection while the [sqlite3_last_insert_rowid()]
  1944. ** function is running and thus changes the last insert [rowid],
  1945. ** then the value returned by [sqlite3_last_insert_rowid()] is
  1946. ** unpredictable and might not equal either the old or the new
  1947. ** last insert [rowid].
  1948. */
  1949. SQLITE_API sqlite3_int64 sqlite3_last_insert_rowid(sqlite3*);
  1950. /*
  1951. ** CAPI3REF: Count The Number Of Rows Modified
  1952. **
  1953. ** ^This function returns the number of database rows that were changed
  1954. ** or inserted or deleted by the most recently completed SQL statement
  1955. ** on the [database connection] specified by the first parameter.
  1956. ** ^(Only changes that are directly specified by the [INSERT], [UPDATE],
  1957. ** or [DELETE] statement are counted. Auxiliary changes caused by
  1958. ** triggers or [foreign key actions] are not counted.)^ Use the
  1959. ** [sqlite3_total_changes()] function to find the total number of changes
  1960. ** including changes caused by triggers and foreign key actions.
  1961. **
  1962. ** ^Changes to a view that are simulated by an [INSTEAD OF trigger]
  1963. ** are not counted. Only real table changes are counted.
  1964. **
  1965. ** ^(A "row change" is a change to a single row of a single table
  1966. ** caused by an INSERT, DELETE, or UPDATE statement. Rows that
  1967. ** are changed as side effects of [REPLACE] constraint resolution,
  1968. ** rollback, ABORT processing, [DROP TABLE], or by any other
  1969. ** mechanisms do not count as direct row changes.)^
  1970. **
  1971. ** A "trigger context" is a scope of execution that begins and
  1972. ** ends with the script of a [CREATE TRIGGER | trigger].
  1973. ** Most SQL statements are
  1974. ** evaluated outside of any trigger. This is the "top level"
  1975. ** trigger context. If a trigger fires from the top level, a
  1976. ** new trigger context is entered for the duration of that one
  1977. ** trigger. Subtriggers create subcontexts for their duration.
  1978. **
  1979. ** ^Calling [sqlite3_exec()] or [sqlite3_step()] recursively does
  1980. ** not create a new trigger context.
  1981. **
  1982. ** ^This function returns the number of direct row changes in the
  1983. ** most recent INSERT, UPDATE, or DELETE statement within the same
  1984. ** trigger context.
  1985. **
  1986. ** ^Thus, when called from the top level, this function returns the
  1987. ** number of changes in the most recent INSERT, UPDATE, or DELETE
  1988. ** that also occurred at the top level. ^(Within the body of a trigger,
  1989. ** the sqlite3_changes() interface can be called to find the number of
  1990. ** changes in the most recently completed INSERT, UPDATE, or DELETE
  1991. ** statement within the body of the same trigger.
  1992. ** However, the number returned does not include changes
  1993. ** caused by subtriggers since those have their own context.)^
  1994. **
  1995. ** See also the [sqlite3_total_changes()] interface, the
  1996. ** [count_changes pragma], and the [changes() SQL function].
  1997. **
  1998. ** If a separate thread makes changes on the same database connection
  1999. ** while [sqlite3_changes()] is running then the value returned
  2000. ** is unpredictable and not meaningful.
  2001. */
  2002. SQLITE_API int sqlite3_changes(sqlite3*);
  2003. /*
  2004. ** CAPI3REF: Total Number Of Rows Modified
  2005. **
  2006. ** ^This function returns the number of row changes caused by [INSERT],
  2007. ** [UPDATE] or [DELETE] statements since the [database connection] was opened.
  2008. ** ^(The count returned by sqlite3_total_changes() includes all changes
  2009. ** from all [CREATE TRIGGER | trigger] contexts and changes made by
  2010. ** [foreign key actions]. However,
  2011. ** the count does not include changes used to implement [REPLACE] constraints,
  2012. ** do rollbacks or ABORT processing, or [DROP TABLE] processing. The
  2013. ** count does not include rows of views that fire an [INSTEAD OF trigger],
  2014. ** though if the INSTEAD OF trigger makes changes of its own, those changes
  2015. ** are counted.)^
  2016. ** ^The sqlite3_total_changes() function counts the changes as soon as
  2017. ** the statement that makes them is completed (when the statement handle
  2018. ** is passed to [sqlite3_reset()] or [sqlite3_finalize()]).
  2019. **
  2020. ** See also the [sqlite3_changes()] interface, the
  2021. ** [count_changes pragma], and the [total_changes() SQL function].
  2022. **
  2023. ** If a separate thread makes changes on the same database connection
  2024. ** while [sqlite3_total_changes()] is running then the value
  2025. ** returned is unpredictable and not meaningful.
  2026. */
  2027. SQLITE_API int sqlite3_total_changes(sqlite3*);
  2028. /*
  2029. ** CAPI3REF: Interrupt A Long-Running Query
  2030. **
  2031. ** ^This function causes any pending database operation to abort and
  2032. ** return at its earliest opportunity. This routine is typically
  2033. ** called in response to a user action such as pressing "Cancel"
  2034. ** or Ctrl-C where the user wants a long query operation to halt
  2035. ** immediately.
  2036. **
  2037. ** ^It is safe to call this routine from a thread different from the
  2038. ** thread that is currently running the database operation. But it
  2039. ** is not safe to call this routine with a [database connection] that
  2040. ** is closed or might close before sqlite3_interrupt() returns.
  2041. **
  2042. ** ^If an SQL operation is very nearly finished at the time when
  2043. ** sqlite3_interrupt() is called, then it might not have an opportunity
  2044. ** to be interrupted and might continue to completion.
  2045. **
  2046. ** ^An SQL operation that is interrupted will return [SQLITE_INTERRUPT].
  2047. ** ^If the interrupted SQL operation is an INSERT, UPDATE, or DELETE
  2048. ** that is inside an explicit transaction, then the entire transaction
  2049. ** will be rolled back automatically.
  2050. **
  2051. ** ^The sqlite3_interrupt(D) call is in effect until all currently running
  2052. ** SQL statements on [database connection] D complete. ^Any new SQL statements
  2053. ** that are started after the sqlite3_interrupt() call and before the
  2054. ** running statements reaches zero are interrupted as if they had been
  2055. ** running prior to the sqlite3_interrupt() call. ^New SQL statements
  2056. ** that are started after the running statement count reaches zero are
  2057. ** not effected by the sqlite3_interrupt().
  2058. ** ^A call to sqlite3_interrupt(D) that occurs when there are no running
  2059. ** SQL statements is a no-op and has no effect on SQL statements
  2060. ** that are started after the sqlite3_interrupt() call returns.
  2061. **
  2062. ** If the database connection closes while [sqlite3_interrupt()]
  2063. ** is running then bad things will likely happen.
  2064. */
  2065. SQLITE_API void sqlite3_interrupt(sqlite3*);
  2066. /*
  2067. ** CAPI3REF: Determine If An SQL Statement Is Complete
  2068. **
  2069. ** These routines are useful during command-line input to determine if the
  2070. ** currently entered text seems to form a complete SQL statement or
  2071. ** if additional input is needed before sending the text into
  2072. ** SQLite for parsing. ^These routines return 1 if the input string
  2073. ** appears to be a complete SQL statement. ^A statement is judged to be
  2074. ** complete if it ends with a semicolon token and is not a prefix of a
  2075. ** well-formed CREATE TRIGGER statement. ^Semicolons that are embedded within
  2076. ** string literals or quoted identifier names or comments are not
  2077. ** independent tokens (they are part of the token in which they are
  2078. ** embedded) and thus do not count as a statement terminator. ^Whitespace
  2079. ** and comments that follow the final semicolon are ignored.
  2080. **
  2081. ** ^These routines return 0 if the statement is incomplete. ^If a
  2082. ** memory allocation fails, then SQLITE_NOMEM is returned.
  2083. **
  2084. ** ^These routines do not parse the SQL statements thus
  2085. ** will not detect syntactically incorrect SQL.
  2086. **
  2087. ** ^(If SQLite has not been initialized using [sqlite3_initialize()] prior
  2088. ** to invoking sqlite3_complete16() then sqlite3_initialize() is invoked
  2089. ** automatically by sqlite3_complete16(). If that initialization fails,
  2090. ** then the return value from sqlite3_complete16() will be non-zero
  2091. ** regardless of whether or not the input SQL is complete.)^
  2092. **
  2093. ** The input to [sqlite3_complete()] must be a zero-terminated
  2094. ** UTF-8 string.
  2095. **
  2096. ** The input to [sqlite3_complete16()] must be a zero-terminated
  2097. ** UTF-16 string in native byte order.
  2098. */
  2099. SQLITE_API int sqlite3_complete(const char *sql);
  2100. SQLITE_API int sqlite3_complete16(const void *sql);
  2101. /*
  2102. ** CAPI3REF: Register A Callback To Handle SQLITE_BUSY Errors
  2103. **
  2104. ** ^The sqlite3_busy_handler(D,X,P) routine sets a callback function X
  2105. ** that might be invoked with argument P whenever
  2106. ** an attempt is made to access a database table associated with
  2107. ** [database connection] D when another thread
  2108. ** or process has the table locked.
  2109. ** The sqlite3_busy_handler() interface is used to implement
  2110. ** [sqlite3_busy_timeout()] and [PRAGMA busy_timeout].
  2111. **
  2112. ** ^If the busy callback is NULL, then [SQLITE_BUSY]
  2113. ** is returned immediately upon encountering the lock. ^If the busy callback
  2114. ** is not NULL, then the callback might be invoked with two arguments.
  2115. **
  2116. ** ^The first argument to the busy handler is a copy of the void* pointer which
  2117. ** is the third argument to sqlite3_busy_handler(). ^The second argument to
  2118. ** the busy handler callback is the number of times that the busy handler has
  2119. ** been invoked for the same locking event. ^If the
  2120. ** busy callback returns 0, then no additional attempts are made to
  2121. ** access the database and [SQLITE_BUSY] is returned
  2122. ** to the application.
  2123. ** ^If the callback returns non-zero, then another attempt
  2124. ** is made to access the database and the cycle repeats.
  2125. **
  2126. ** The presence of a busy handler does not guarantee that it will be invoked
  2127. ** when there is lock contention. ^If SQLite determines that invoking the busy
  2128. ** handler could result in a deadlock, it will go ahead and return [SQLITE_BUSY]
  2129. ** to the application instead of invoking the
  2130. ** busy handler.
  2131. ** Consider a scenario where one process is holding a read lock that
  2132. ** it is trying to promote to a reserved lock and
  2133. ** a second process is holding a reserved lock that it is trying
  2134. ** to promote to an exclusive lock. The first process cannot proceed
  2135. ** because it is blocked by the second and the second process cannot
  2136. ** proceed because it is blocked by the first. If both processes
  2137. ** invoke the busy handlers, neither will make any progress. Therefore,
  2138. ** SQLite returns [SQLITE_BUSY] for the first process, hoping that this
  2139. ** will induce the first process to release its read lock and allow
  2140. ** the second process to proceed.
  2141. **
  2142. ** ^The default busy callback is NULL.
  2143. **
  2144. ** ^(There can only be a single busy handler defined for each
  2145. ** [database connection]. Setting a new busy handler clears any
  2146. ** previously set handler.)^ ^Note that calling [sqlite3_busy_timeout()]
  2147. ** or evaluating [PRAGMA busy_timeout=N] will change the
  2148. ** busy handler and thus clear any previously set busy handler.
  2149. **
  2150. ** The busy callback should not take any actions which modify the
  2151. ** database connection that invoked the busy handler. In other words,
  2152. ** the busy handler is not reentrant. Any such actions
  2153. ** result in undefined behavior.
  2154. **
  2155. ** A busy handler must not close the database connection
  2156. ** or [prepared statement] that invoked the busy handler.
  2157. */
  2158. SQLITE_API int sqlite3_busy_handler(sqlite3*, int(*)(void*,int), void*);
  2159. /*
  2160. ** CAPI3REF: Set A Busy Timeout
  2161. **
  2162. ** ^This routine sets a [sqlite3_busy_handler | busy handler] that sleeps
  2163. ** for a specified amount of time when a table is locked. ^The handler
  2164. ** will sleep multiple times until at least "ms" milliseconds of sleeping
  2165. ** have accumulated. ^After at least "ms" milliseconds of sleeping,
  2166. ** the handler returns 0 which causes [sqlite3_step()] to return
  2167. ** [SQLITE_BUSY].
  2168. **
  2169. ** ^Calling this routine with an argument less than or equal to zero
  2170. ** turns off all busy handlers.
  2171. **
  2172. ** ^(There can only be a single busy handler for a particular
  2173. ** [database connection] at any given moment. If another busy handler
  2174. ** was defined (using [sqlite3_busy_handler()]) prior to calling
  2175. ** this routine, that other busy handler is cleared.)^
  2176. **
  2177. ** See also: [PRAGMA busy_timeout]
  2178. */
  2179. SQLITE_API int sqlite3_busy_timeout(sqlite3*, int ms);
  2180. /*
  2181. ** CAPI3REF: Convenience Routines For Running Queries
  2182. **
  2183. ** This is a legacy interface that is preserved for backwards compatibility.
  2184. ** Use of this interface is not recommended.
  2185. **
  2186. ** Definition: A <b>result table</b> is memory data structure created by the
  2187. ** [sqlite3_get_table()] interface. A result table records the
  2188. ** complete query results from one or more queries.
  2189. **
  2190. ** The table conceptually has a number of rows and columns. But
  2191. ** these numbers are not part of the result table itself. These
  2192. ** numbers are obtained separately. Let N be the number of rows
  2193. ** and M be the number of columns.
  2194. **
  2195. ** A result table is an array of pointers to zero-terminated UTF-8 strings.
  2196. ** There are (N+1)*M elements in the array. The first M pointers point
  2197. ** to zero-terminated strings that contain the names of the columns.
  2198. ** The remaining entries all point to query results. NULL values result
  2199. ** in NULL pointers. All other values are in their UTF-8 zero-terminated
  2200. ** string representation as returned by [sqlite3_column_text()].
  2201. **
  2202. ** A result table might consist of one or more memory allocations.
  2203. ** It is not safe to pass a result table directly to [sqlite3_free()].
  2204. ** A result table should be deallocated using [sqlite3_free_table()].
  2205. **
  2206. ** ^(As an example of the result table format, suppose a query result
  2207. ** is as follows:
  2208. **
  2209. ** <blockquote><pre>
  2210. ** Name | Age
  2211. ** -----------------------
  2212. ** Alice | 43
  2213. ** Bob | 28
  2214. ** Cindy | 21
  2215. ** </pre></blockquote>
  2216. **
  2217. ** There are two column (M==2) and three rows (N==3). Thus the
  2218. ** result table has 8 entries. Suppose the result table is stored
  2219. ** in an array names azResult. Then azResult holds this content:
  2220. **
  2221. ** <blockquote><pre>
  2222. ** azResult&#91;0] = "Name";
  2223. ** azResult&#91;1] = "Age";
  2224. ** azResult&#91;2] = "Alice";
  2225. ** azResult&#91;3] = "43";
  2226. ** azResult&#91;4] = "Bob";
  2227. ** azResult&#91;5] = "28";
  2228. ** azResult&#91;6] = "Cindy";
  2229. ** azResult&#91;7] = "21";
  2230. ** </pre></blockquote>)^
  2231. **
  2232. ** ^The sqlite3_get_table() function evaluates one or more
  2233. ** semicolon-separated SQL statements in the zero-terminated UTF-8
  2234. ** string of its 2nd parameter and returns a result table to the
  2235. ** pointer given in its 3rd parameter.
  2236. **
  2237. ** After the application has finished with the result from sqlite3_get_table(),
  2238. ** it must pass the result table pointer to sqlite3_free_table() in order to
  2239. ** release the memory that was malloced. Because of the way the
  2240. ** [sqlite3_malloc()] happens within sqlite3_get_table(), the calling
  2241. ** function must not try to call [sqlite3_free()] directly. Only
  2242. ** [sqlite3_free_table()] is able to release the memory properly and safely.
  2243. **
  2244. ** The sqlite3_get_table() interface is implemented as a wrapper around
  2245. ** [sqlite3_exec()]. The sqlite3_get_table() routine does not have access
  2246. ** to any internal data structures of SQLite. It uses only the public
  2247. ** interface defined here. As a consequence, errors that occur in the
  2248. ** wrapper layer outside of the internal [sqlite3_exec()] call are not
  2249. ** reflected in subsequent calls to [sqlite3_errcode()] or
  2250. ** [sqlite3_errmsg()].
  2251. */
  2252. SQLITE_API int sqlite3_get_table(
  2253. sqlite3 *db, /* An open database */
  2254. const char *zSql, /* SQL to be evaluated */
  2255. char ***pazResult, /* Results of the query */
  2256. int *pnRow, /* Number of result rows written here */
  2257. int *pnColumn, /* Number of result columns written here */
  2258. char **pzErrmsg /* Error msg written here */
  2259. );
  2260. SQLITE_API void sqlite3_free_table(char **result);
  2261. /*
  2262. ** CAPI3REF: Formatted String Printing Functions
  2263. **
  2264. ** These routines are work-alikes of the "printf()" family of functions
  2265. ** from the standard C library.
  2266. **
  2267. ** ^The sqlite3_mprintf() and sqlite3_vmprintf() routines write their
  2268. ** results into memory obtained from [sqlite3_malloc()].
  2269. ** The strings returned by these two routines should be
  2270. ** released by [sqlite3_free()]. ^Both routines return a
  2271. ** NULL pointer if [sqlite3_malloc()] is unable to allocate enough
  2272. ** memory to hold the resulting string.
  2273. **
  2274. ** ^(The sqlite3_snprintf() routine is similar to "snprintf()" from
  2275. ** the standard C library. The result is written into the
  2276. ** buffer supplied as the second parameter whose size is given by
  2277. ** the first parameter. Note that the order of the
  2278. ** first two parameters is reversed from snprintf().)^ This is an
  2279. ** historical accident that cannot be fixed without breaking
  2280. ** backwards compatibility. ^(Note also that sqlite3_snprintf()
  2281. ** returns a pointer to its buffer instead of the number of
  2282. ** characters actually written into the buffer.)^ We admit that
  2283. ** the number of characters written would be a more useful return
  2284. ** value but we cannot change the implementation of sqlite3_snprintf()
  2285. ** now without breaking compatibility.
  2286. **
  2287. ** ^As long as the buffer size is greater than zero, sqlite3_snprintf()
  2288. ** guarantees that the buffer is always zero-terminated. ^The first
  2289. ** parameter "n" is the total size of the buffer, including space for
  2290. ** the zero terminator. So the longest string that can be completely
  2291. ** written will be n-1 characters.
  2292. **
  2293. ** ^The sqlite3_vsnprintf() routine is a varargs version of sqlite3_snprintf().
  2294. **
  2295. ** These routines all implement some additional formatting
  2296. ** options that are useful for constructing SQL statements.
  2297. ** All of the usual printf() formatting options apply. In addition, there
  2298. ** is are "%q", "%Q", and "%z" options.
  2299. **
  2300. ** ^(The %q option works like %s in that it substitutes a nul-terminated
  2301. ** string from the argument list. But %q also doubles every '\'' character.
  2302. ** %q is designed for use inside a string literal.)^ By doubling each '\''
  2303. ** character it escapes that character and allows it to be inserted into
  2304. ** the string.
  2305. **
  2306. ** For example, assume the string variable zText contains text as follows:
  2307. **
  2308. ** <blockquote><pre>
  2309. ** char *zText = "It's a happy day!";
  2310. ** </pre></blockquote>
  2311. **
  2312. ** One can use this text in an SQL statement as follows:
  2313. **
  2314. ** <blockquote><pre>
  2315. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES('%q')", zText);
  2316. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2317. ** sqlite3_free(zSQL);
  2318. ** </pre></blockquote>
  2319. **
  2320. ** Because the %q format string is used, the '\'' character in zText
  2321. ** is escaped and the SQL generated is as follows:
  2322. **
  2323. ** <blockquote><pre>
  2324. ** INSERT INTO table1 VALUES('It''s a happy day!')
  2325. ** </pre></blockquote>
  2326. **
  2327. ** This is correct. Had we used %s instead of %q, the generated SQL
  2328. ** would have looked like this:
  2329. **
  2330. ** <blockquote><pre>
  2331. ** INSERT INTO table1 VALUES('It's a happy day!');
  2332. ** </pre></blockquote>
  2333. **
  2334. ** This second example is an SQL syntax error. As a general rule you should
  2335. ** always use %q instead of %s when inserting text into a string literal.
  2336. **
  2337. ** ^(The %Q option works like %q except it also adds single quotes around
  2338. ** the outside of the total string. Additionally, if the parameter in the
  2339. ** argument list is a NULL pointer, %Q substitutes the text "NULL" (without
  2340. ** single quotes).)^ So, for example, one could say:
  2341. **
  2342. ** <blockquote><pre>
  2343. ** char *zSQL = sqlite3_mprintf("INSERT INTO table VALUES(%Q)", zText);
  2344. ** sqlite3_exec(db, zSQL, 0, 0, 0);
  2345. ** sqlite3_free(zSQL);
  2346. ** </pre></blockquote>
  2347. **
  2348. ** The code above will render a correct SQL statement in the zSQL
  2349. ** variable even if the zText variable is a NULL pointer.
  2350. **
  2351. ** ^(The "%z" formatting option works like "%s" but with the
  2352. ** addition that after the string has been read and copied into
  2353. ** the result, [sqlite3_free()] is called on the input string.)^
  2354. */
  2355. SQLITE_API char *sqlite3_mprintf(const char*,...);
  2356. SQLITE_API char *sqlite3_vmprintf(const char*, va_list);
  2357. SQLITE_API char *sqlite3_snprintf(int,char*,const char*, ...);
  2358. SQLITE_API char *sqlite3_vsnprintf(int,char*,const char*, va_list);
  2359. /*
  2360. ** CAPI3REF: Memory Allocation Subsystem
  2361. **
  2362. ** The SQLite core uses these three routines for all of its own
  2363. ** internal memory allocation needs. "Core" in the previous sentence
  2364. ** does not include operating-system specific VFS implementation. The
  2365. ** Windows VFS uses native malloc() and free() for some operations.
  2366. **
  2367. ** ^The sqlite3_malloc() routine returns a pointer to a block
  2368. ** of memory at least N bytes in length, where N is the parameter.
  2369. ** ^If sqlite3_malloc() is unable to obtain sufficient free
  2370. ** memory, it returns a NULL pointer. ^If the parameter N to
  2371. ** sqlite3_malloc() is zero or negative then sqlite3_malloc() returns
  2372. ** a NULL pointer.
  2373. **
  2374. ** ^The sqlite3_malloc64(N) routine works just like
  2375. ** sqlite3_malloc(N) except that N is an unsigned 64-bit integer instead
  2376. ** of a signed 32-bit integer.
  2377. **
  2378. ** ^Calling sqlite3_free() with a pointer previously returned
  2379. ** by sqlite3_malloc() or sqlite3_realloc() releases that memory so
  2380. ** that it might be reused. ^The sqlite3_free() routine is
  2381. ** a no-op if is called with a NULL pointer. Passing a NULL pointer
  2382. ** to sqlite3_free() is harmless. After being freed, memory
  2383. ** should neither be read nor written. Even reading previously freed
  2384. ** memory might result in a segmentation fault or other severe error.
  2385. ** Memory corruption, a segmentation fault, or other severe error
  2386. ** might result if sqlite3_free() is called with a non-NULL pointer that
  2387. ** was not obtained from sqlite3_malloc() or sqlite3_realloc().
  2388. **
  2389. ** ^The sqlite3_realloc(X,N) interface attempts to resize a
  2390. ** prior memory allocation X to be at least N bytes.
  2391. ** ^If the X parameter to sqlite3_realloc(X,N)
  2392. ** is a NULL pointer then its behavior is identical to calling
  2393. ** sqlite3_malloc(N).
  2394. ** ^If the N parameter to sqlite3_realloc(X,N) is zero or
  2395. ** negative then the behavior is exactly the same as calling
  2396. ** sqlite3_free(X).
  2397. ** ^sqlite3_realloc(X,N) returns a pointer to a memory allocation
  2398. ** of at least N bytes in size or NULL if insufficient memory is available.
  2399. ** ^If M is the size of the prior allocation, then min(N,M) bytes
  2400. ** of the prior allocation are copied into the beginning of buffer returned
  2401. ** by sqlite3_realloc(X,N) and the prior allocation is freed.
  2402. ** ^If sqlite3_realloc(X,N) returns NULL and N is positive, then the
  2403. ** prior allocation is not freed.
  2404. **
  2405. ** ^The sqlite3_realloc64(X,N) interfaces works the same as
  2406. ** sqlite3_realloc(X,N) except that N is a 64-bit unsigned integer instead
  2407. ** of a 32-bit signed integer.
  2408. **
  2409. ** ^If X is a memory allocation previously obtained from sqlite3_malloc(),
  2410. ** sqlite3_malloc64(), sqlite3_realloc(), or sqlite3_realloc64(), then
  2411. ** sqlite3_msize(X) returns the size of that memory allocation in bytes.
  2412. ** ^The value returned by sqlite3_msize(X) might be larger than the number
  2413. ** of bytes requested when X was allocated. ^If X is a NULL pointer then
  2414. ** sqlite3_msize(X) returns zero. If X points to something that is not
  2415. ** the beginning of memory allocation, or if it points to a formerly
  2416. ** valid memory allocation that has now been freed, then the behavior
  2417. ** of sqlite3_msize(X) is undefined and possibly harmful.
  2418. **
  2419. ** ^The memory returned by sqlite3_malloc(), sqlite3_realloc(),
  2420. ** sqlite3_malloc64(), and sqlite3_realloc64()
  2421. ** is always aligned to at least an 8 byte boundary, or to a
  2422. ** 4 byte boundary if the [SQLITE_4_BYTE_ALIGNED_MALLOC] compile-time
  2423. ** option is used.
  2424. **
  2425. ** In SQLite version 3.5.0 and 3.5.1, it was possible to define
  2426. ** the SQLITE_OMIT_MEMORY_ALLOCATION which would cause the built-in
  2427. ** implementation of these routines to be omitted. That capability
  2428. ** is no longer provided. Only built-in memory allocators can be used.
  2429. **
  2430. ** Prior to SQLite version 3.7.10, the Windows OS interface layer called
  2431. ** the system malloc() and free() directly when converting
  2432. ** filenames between the UTF-8 encoding used by SQLite
  2433. ** and whatever filename encoding is used by the particular Windows
  2434. ** installation. Memory allocation errors were detected, but
  2435. ** they were reported back as [SQLITE_CANTOPEN] or
  2436. ** [SQLITE_IOERR] rather than [SQLITE_NOMEM].
  2437. **
  2438. ** The pointer arguments to [sqlite3_free()] and [sqlite3_realloc()]
  2439. ** must be either NULL or else pointers obtained from a prior
  2440. ** invocation of [sqlite3_malloc()] or [sqlite3_realloc()] that have
  2441. ** not yet been released.
  2442. **
  2443. ** The application must not read or write any part of
  2444. ** a block of memory after it has been released using
  2445. ** [sqlite3_free()] or [sqlite3_realloc()].
  2446. */
  2447. SQLITE_API void *sqlite3_malloc(int);
  2448. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64);
  2449. SQLITE_API void *sqlite3_realloc(void*, int);
  2450. SQLITE_API void *sqlite3_realloc64(void*, sqlite3_uint64);
  2451. SQLITE_API void sqlite3_free(void*);
  2452. SQLITE_API sqlite3_uint64 sqlite3_msize(void*);
  2453. /*
  2454. ** CAPI3REF: Memory Allocator Statistics
  2455. **
  2456. ** SQLite provides these two interfaces for reporting on the status
  2457. ** of the [sqlite3_malloc()], [sqlite3_free()], and [sqlite3_realloc()]
  2458. ** routines, which form the built-in memory allocation subsystem.
  2459. **
  2460. ** ^The [sqlite3_memory_used()] routine returns the number of bytes
  2461. ** of memory currently outstanding (malloced but not freed).
  2462. ** ^The [sqlite3_memory_highwater()] routine returns the maximum
  2463. ** value of [sqlite3_memory_used()] since the high-water mark
  2464. ** was last reset. ^The values returned by [sqlite3_memory_used()] and
  2465. ** [sqlite3_memory_highwater()] include any overhead
  2466. ** added by SQLite in its implementation of [sqlite3_malloc()],
  2467. ** but not overhead added by the any underlying system library
  2468. ** routines that [sqlite3_malloc()] may call.
  2469. **
  2470. ** ^The memory high-water mark is reset to the current value of
  2471. ** [sqlite3_memory_used()] if and only if the parameter to
  2472. ** [sqlite3_memory_highwater()] is true. ^The value returned
  2473. ** by [sqlite3_memory_highwater(1)] is the high-water mark
  2474. ** prior to the reset.
  2475. */
  2476. SQLITE_API sqlite3_int64 sqlite3_memory_used(void);
  2477. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag);
  2478. /*
  2479. ** CAPI3REF: Pseudo-Random Number Generator
  2480. **
  2481. ** SQLite contains a high-quality pseudo-random number generator (PRNG) used to
  2482. ** select random [ROWID | ROWIDs] when inserting new records into a table that
  2483. ** already uses the largest possible [ROWID]. The PRNG is also used for
  2484. ** the build-in random() and randomblob() SQL functions. This interface allows
  2485. ** applications to access the same PRNG for other purposes.
  2486. **
  2487. ** ^A call to this routine stores N bytes of randomness into buffer P.
  2488. ** ^If N is less than one, then P can be a NULL pointer.
  2489. **
  2490. ** ^If this routine has not been previously called or if the previous
  2491. ** call had N less than one, then the PRNG is seeded using randomness
  2492. ** obtained from the xRandomness method of the default [sqlite3_vfs] object.
  2493. ** ^If the previous call to this routine had an N of 1 or more then
  2494. ** the pseudo-randomness is generated
  2495. ** internally and without recourse to the [sqlite3_vfs] xRandomness
  2496. ** method.
  2497. */
  2498. SQLITE_API void sqlite3_randomness(int N, void *P);
  2499. /*
  2500. ** CAPI3REF: Compile-Time Authorization Callbacks
  2501. **
  2502. ** ^This routine registers an authorizer callback with a particular
  2503. ** [database connection], supplied in the first argument.
  2504. ** ^The authorizer callback is invoked as SQL statements are being compiled
  2505. ** by [sqlite3_prepare()] or its variants [sqlite3_prepare_v2()],
  2506. ** [sqlite3_prepare16()] and [sqlite3_prepare16_v2()]. ^At various
  2507. ** points during the compilation process, as logic is being created
  2508. ** to perform various actions, the authorizer callback is invoked to
  2509. ** see if those actions are allowed. ^The authorizer callback should
  2510. ** return [SQLITE_OK] to allow the action, [SQLITE_IGNORE] to disallow the
  2511. ** specific action but allow the SQL statement to continue to be
  2512. ** compiled, or [SQLITE_DENY] to cause the entire SQL statement to be
  2513. ** rejected with an error. ^If the authorizer callback returns
  2514. ** any value other than [SQLITE_IGNORE], [SQLITE_OK], or [SQLITE_DENY]
  2515. ** then the [sqlite3_prepare_v2()] or equivalent call that triggered
  2516. ** the authorizer will fail with an error message.
  2517. **
  2518. ** When the callback returns [SQLITE_OK], that means the operation
  2519. ** requested is ok. ^When the callback returns [SQLITE_DENY], the
  2520. ** [sqlite3_prepare_v2()] or equivalent call that triggered the
  2521. ** authorizer will fail with an error message explaining that
  2522. ** access is denied.
  2523. **
  2524. ** ^The first parameter to the authorizer callback is a copy of the third
  2525. ** parameter to the sqlite3_set_authorizer() interface. ^The second parameter
  2526. ** to the callback is an integer [SQLITE_COPY | action code] that specifies
  2527. ** the particular action to be authorized. ^The third through sixth parameters
  2528. ** to the callback are zero-terminated strings that contain additional
  2529. ** details about the action to be authorized.
  2530. **
  2531. ** ^If the action code is [SQLITE_READ]
  2532. ** and the callback returns [SQLITE_IGNORE] then the
  2533. ** [prepared statement] statement is constructed to substitute
  2534. ** a NULL value in place of the table column that would have
  2535. ** been read if [SQLITE_OK] had been returned. The [SQLITE_IGNORE]
  2536. ** return can be used to deny an untrusted user access to individual
  2537. ** columns of a table.
  2538. ** ^If the action code is [SQLITE_DELETE] and the callback returns
  2539. ** [SQLITE_IGNORE] then the [DELETE] operation proceeds but the
  2540. ** [truncate optimization] is disabled and all rows are deleted individually.
  2541. **
  2542. ** An authorizer is used when [sqlite3_prepare | preparing]
  2543. ** SQL statements from an untrusted source, to ensure that the SQL statements
  2544. ** do not try to access data they are not allowed to see, or that they do not
  2545. ** try to execute malicious statements that damage the database. For
  2546. ** example, an application may allow a user to enter arbitrary
  2547. ** SQL queries for evaluation by a database. But the application does
  2548. ** not want the user to be able to make arbitrary changes to the
  2549. ** database. An authorizer could then be put in place while the
  2550. ** user-entered SQL is being [sqlite3_prepare | prepared] that
  2551. ** disallows everything except [SELECT] statements.
  2552. **
  2553. ** Applications that need to process SQL from untrusted sources
  2554. ** might also consider lowering resource limits using [sqlite3_limit()]
  2555. ** and limiting database size using the [max_page_count] [PRAGMA]
  2556. ** in addition to using an authorizer.
  2557. **
  2558. ** ^(Only a single authorizer can be in place on a database connection
  2559. ** at a time. Each call to sqlite3_set_authorizer overrides the
  2560. ** previous call.)^ ^Disable the authorizer by installing a NULL callback.
  2561. ** The authorizer is disabled by default.
  2562. **
  2563. ** The authorizer callback must not do anything that will modify
  2564. ** the database connection that invoked the authorizer callback.
  2565. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2566. ** database connections for the meaning of "modify" in this paragraph.
  2567. **
  2568. ** ^When [sqlite3_prepare_v2()] is used to prepare a statement, the
  2569. ** statement might be re-prepared during [sqlite3_step()] due to a
  2570. ** schema change. Hence, the application should ensure that the
  2571. ** correct authorizer callback remains in place during the [sqlite3_step()].
  2572. **
  2573. ** ^Note that the authorizer callback is invoked only during
  2574. ** [sqlite3_prepare()] or its variants. Authorization is not
  2575. ** performed during statement evaluation in [sqlite3_step()], unless
  2576. ** as stated in the previous paragraph, sqlite3_step() invokes
  2577. ** sqlite3_prepare_v2() to reprepare a statement after a schema change.
  2578. */
  2579. SQLITE_API int sqlite3_set_authorizer(
  2580. sqlite3*,
  2581. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  2582. void *pUserData
  2583. );
  2584. /*
  2585. ** CAPI3REF: Authorizer Return Codes
  2586. **
  2587. ** The [sqlite3_set_authorizer | authorizer callback function] must
  2588. ** return either [SQLITE_OK] or one of these two constants in order
  2589. ** to signal SQLite whether or not the action is permitted. See the
  2590. ** [sqlite3_set_authorizer | authorizer documentation] for additional
  2591. ** information.
  2592. **
  2593. ** Note that SQLITE_IGNORE is also used as a [conflict resolution mode]
  2594. ** returned from the [sqlite3_vtab_on_conflict()] interface.
  2595. */
  2596. #define SQLITE_DENY 1 /* Abort the SQL statement with an error */
  2597. #define SQLITE_IGNORE 2 /* Don't allow access, but don't generate an error */
  2598. /*
  2599. ** CAPI3REF: Authorizer Action Codes
  2600. **
  2601. ** The [sqlite3_set_authorizer()] interface registers a callback function
  2602. ** that is invoked to authorize certain SQL statement actions. The
  2603. ** second parameter to the callback is an integer code that specifies
  2604. ** what action is being authorized. These are the integer action codes that
  2605. ** the authorizer callback may be passed.
  2606. **
  2607. ** These action code values signify what kind of operation is to be
  2608. ** authorized. The 3rd and 4th parameters to the authorization
  2609. ** callback function will be parameters or NULL depending on which of these
  2610. ** codes is used as the second parameter. ^(The 5th parameter to the
  2611. ** authorizer callback is the name of the database ("main", "temp",
  2612. ** etc.) if applicable.)^ ^The 6th parameter to the authorizer callback
  2613. ** is the name of the inner-most trigger or view that is responsible for
  2614. ** the access attempt or NULL if this access attempt is directly from
  2615. ** top-level SQL code.
  2616. */
  2617. /******************************************* 3rd ************ 4th ***********/
  2618. #define SQLITE_CREATE_INDEX 1 /* Index Name Table Name */
  2619. #define SQLITE_CREATE_TABLE 2 /* Table Name NULL */
  2620. #define SQLITE_CREATE_TEMP_INDEX 3 /* Index Name Table Name */
  2621. #define SQLITE_CREATE_TEMP_TABLE 4 /* Table Name NULL */
  2622. #define SQLITE_CREATE_TEMP_TRIGGER 5 /* Trigger Name Table Name */
  2623. #define SQLITE_CREATE_TEMP_VIEW 6 /* View Name NULL */
  2624. #define SQLITE_CREATE_TRIGGER 7 /* Trigger Name Table Name */
  2625. #define SQLITE_CREATE_VIEW 8 /* View Name NULL */
  2626. #define SQLITE_DELETE 9 /* Table Name NULL */
  2627. #define SQLITE_DROP_INDEX 10 /* Index Name Table Name */
  2628. #define SQLITE_DROP_TABLE 11 /* Table Name NULL */
  2629. #define SQLITE_DROP_TEMP_INDEX 12 /* Index Name Table Name */
  2630. #define SQLITE_DROP_TEMP_TABLE 13 /* Table Name NULL */
  2631. #define SQLITE_DROP_TEMP_TRIGGER 14 /* Trigger Name Table Name */
  2632. #define SQLITE_DROP_TEMP_VIEW 15 /* View Name NULL */
  2633. #define SQLITE_DROP_TRIGGER 16 /* Trigger Name Table Name */
  2634. #define SQLITE_DROP_VIEW 17 /* View Name NULL */
  2635. #define SQLITE_INSERT 18 /* Table Name NULL */
  2636. #define SQLITE_PRAGMA 19 /* Pragma Name 1st arg or NULL */
  2637. #define SQLITE_READ 20 /* Table Name Column Name */
  2638. #define SQLITE_SELECT 21 /* NULL NULL */
  2639. #define SQLITE_TRANSACTION 22 /* Operation NULL */
  2640. #define SQLITE_UPDATE 23 /* Table Name Column Name */
  2641. #define SQLITE_ATTACH 24 /* Filename NULL */
  2642. #define SQLITE_DETACH 25 /* Database Name NULL */
  2643. #define SQLITE_ALTER_TABLE 26 /* Database Name Table Name */
  2644. #define SQLITE_REINDEX 27 /* Index Name NULL */
  2645. #define SQLITE_ANALYZE 28 /* Table Name NULL */
  2646. #define SQLITE_CREATE_VTABLE 29 /* Table Name Module Name */
  2647. #define SQLITE_DROP_VTABLE 30 /* Table Name Module Name */
  2648. #define SQLITE_FUNCTION 31 /* NULL Function Name */
  2649. #define SQLITE_SAVEPOINT 32 /* Operation Savepoint Name */
  2650. #define SQLITE_COPY 0 /* No longer used */
  2651. #define SQLITE_RECURSIVE 33 /* NULL NULL */
  2652. /*
  2653. ** CAPI3REF: Tracing And Profiling Functions
  2654. **
  2655. ** These routines register callback functions that can be used for
  2656. ** tracing and profiling the execution of SQL statements.
  2657. **
  2658. ** ^The callback function registered by sqlite3_trace() is invoked at
  2659. ** various times when an SQL statement is being run by [sqlite3_step()].
  2660. ** ^The sqlite3_trace() callback is invoked with a UTF-8 rendering of the
  2661. ** SQL statement text as the statement first begins executing.
  2662. ** ^(Additional sqlite3_trace() callbacks might occur
  2663. ** as each triggered subprogram is entered. The callbacks for triggers
  2664. ** contain a UTF-8 SQL comment that identifies the trigger.)^
  2665. **
  2666. ** The [SQLITE_TRACE_SIZE_LIMIT] compile-time option can be used to limit
  2667. ** the length of [bound parameter] expansion in the output of sqlite3_trace().
  2668. **
  2669. ** ^The callback function registered by sqlite3_profile() is invoked
  2670. ** as each SQL statement finishes. ^The profile callback contains
  2671. ** the original statement text and an estimate of wall-clock time
  2672. ** of how long that statement took to run. ^The profile callback
  2673. ** time is in units of nanoseconds, however the current implementation
  2674. ** is only capable of millisecond resolution so the six least significant
  2675. ** digits in the time are meaningless. Future versions of SQLite
  2676. ** might provide greater resolution on the profiler callback. The
  2677. ** sqlite3_profile() function is considered experimental and is
  2678. ** subject to change in future versions of SQLite.
  2679. */
  2680. SQLITE_API void *sqlite3_trace(sqlite3*, void(*xTrace)(void*,const char*), void*);
  2681. SQLITE_API SQLITE_EXPERIMENTAL void *sqlite3_profile(sqlite3*,
  2682. void(*xProfile)(void*,const char*,sqlite3_uint64), void*);
  2683. /*
  2684. ** CAPI3REF: Query Progress Callbacks
  2685. **
  2686. ** ^The sqlite3_progress_handler(D,N,X,P) interface causes the callback
  2687. ** function X to be invoked periodically during long running calls to
  2688. ** [sqlite3_exec()], [sqlite3_step()] and [sqlite3_get_table()] for
  2689. ** database connection D. An example use for this
  2690. ** interface is to keep a GUI updated during a large query.
  2691. **
  2692. ** ^The parameter P is passed through as the only parameter to the
  2693. ** callback function X. ^The parameter N is the approximate number of
  2694. ** [virtual machine instructions] that are evaluated between successive
  2695. ** invocations of the callback X. ^If N is less than one then the progress
  2696. ** handler is disabled.
  2697. **
  2698. ** ^Only a single progress handler may be defined at one time per
  2699. ** [database connection]; setting a new progress handler cancels the
  2700. ** old one. ^Setting parameter X to NULL disables the progress handler.
  2701. ** ^The progress handler is also disabled by setting N to a value less
  2702. ** than 1.
  2703. **
  2704. ** ^If the progress callback returns non-zero, the operation is
  2705. ** interrupted. This feature can be used to implement a
  2706. ** "Cancel" button on a GUI progress dialog box.
  2707. **
  2708. ** The progress handler callback must not do anything that will modify
  2709. ** the database connection that invoked the progress handler.
  2710. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  2711. ** database connections for the meaning of "modify" in this paragraph.
  2712. **
  2713. */
  2714. SQLITE_API void sqlite3_progress_handler(sqlite3*, int, int(*)(void*), void*);
  2715. /*
  2716. ** CAPI3REF: Opening A New Database Connection
  2717. **
  2718. ** ^These routines open an SQLite database file as specified by the
  2719. ** filename argument. ^The filename argument is interpreted as UTF-8 for
  2720. ** sqlite3_open() and sqlite3_open_v2() and as UTF-16 in the native byte
  2721. ** order for sqlite3_open16(). ^(A [database connection] handle is usually
  2722. ** returned in *ppDb, even if an error occurs. The only exception is that
  2723. ** if SQLite is unable to allocate memory to hold the [sqlite3] object,
  2724. ** a NULL will be written into *ppDb instead of a pointer to the [sqlite3]
  2725. ** object.)^ ^(If the database is opened (and/or created) successfully, then
  2726. ** [SQLITE_OK] is returned. Otherwise an [error code] is returned.)^ ^The
  2727. ** [sqlite3_errmsg()] or [sqlite3_errmsg16()] routines can be used to obtain
  2728. ** an English language description of the error following a failure of any
  2729. ** of the sqlite3_open() routines.
  2730. **
  2731. ** ^The default encoding will be UTF-8 for databases created using
  2732. ** sqlite3_open() or sqlite3_open_v2(). ^The default encoding for databases
  2733. ** created using sqlite3_open16() will be UTF-16 in the native byte order.
  2734. **
  2735. ** Whether or not an error occurs when it is opened, resources
  2736. ** associated with the [database connection] handle should be released by
  2737. ** passing it to [sqlite3_close()] when it is no longer required.
  2738. **
  2739. ** The sqlite3_open_v2() interface works like sqlite3_open()
  2740. ** except that it accepts two additional parameters for additional control
  2741. ** over the new database connection. ^(The flags parameter to
  2742. ** sqlite3_open_v2() can take one of
  2743. ** the following three values, optionally combined with the
  2744. ** [SQLITE_OPEN_NOMUTEX], [SQLITE_OPEN_FULLMUTEX], [SQLITE_OPEN_SHAREDCACHE],
  2745. ** [SQLITE_OPEN_PRIVATECACHE], and/or [SQLITE_OPEN_URI] flags:)^
  2746. **
  2747. ** <dl>
  2748. ** ^(<dt>[SQLITE_OPEN_READONLY]</dt>
  2749. ** <dd>The database is opened in read-only mode. If the database does not
  2750. ** already exist, an error is returned.</dd>)^
  2751. **
  2752. ** ^(<dt>[SQLITE_OPEN_READWRITE]</dt>
  2753. ** <dd>The database is opened for reading and writing if possible, or reading
  2754. ** only if the file is write protected by the operating system. In either
  2755. ** case the database must already exist, otherwise an error is returned.</dd>)^
  2756. **
  2757. ** ^(<dt>[SQLITE_OPEN_READWRITE] | [SQLITE_OPEN_CREATE]</dt>
  2758. ** <dd>The database is opened for reading and writing, and is created if
  2759. ** it does not already exist. This is the behavior that is always used for
  2760. ** sqlite3_open() and sqlite3_open16().</dd>)^
  2761. ** </dl>
  2762. **
  2763. ** If the 3rd parameter to sqlite3_open_v2() is not one of the
  2764. ** combinations shown above optionally combined with other
  2765. ** [SQLITE_OPEN_READONLY | SQLITE_OPEN_* bits]
  2766. ** then the behavior is undefined.
  2767. **
  2768. ** ^If the [SQLITE_OPEN_NOMUTEX] flag is set, then the database connection
  2769. ** opens in the multi-thread [threading mode] as long as the single-thread
  2770. ** mode has not been set at compile-time or start-time. ^If the
  2771. ** [SQLITE_OPEN_FULLMUTEX] flag is set then the database connection opens
  2772. ** in the serialized [threading mode] unless single-thread was
  2773. ** previously selected at compile-time or start-time.
  2774. ** ^The [SQLITE_OPEN_SHAREDCACHE] flag causes the database connection to be
  2775. ** eligible to use [shared cache mode], regardless of whether or not shared
  2776. ** cache is enabled using [sqlite3_enable_shared_cache()]. ^The
  2777. ** [SQLITE_OPEN_PRIVATECACHE] flag causes the database connection to not
  2778. ** participate in [shared cache mode] even if it is enabled.
  2779. **
  2780. ** ^The fourth parameter to sqlite3_open_v2() is the name of the
  2781. ** [sqlite3_vfs] object that defines the operating system interface that
  2782. ** the new database connection should use. ^If the fourth parameter is
  2783. ** a NULL pointer then the default [sqlite3_vfs] object is used.
  2784. **
  2785. ** ^If the filename is ":memory:", then a private, temporary in-memory database
  2786. ** is created for the connection. ^This in-memory database will vanish when
  2787. ** the database connection is closed. Future versions of SQLite might
  2788. ** make use of additional special filenames that begin with the ":" character.
  2789. ** It is recommended that when a database filename actually does begin with
  2790. ** a ":" character you should prefix the filename with a pathname such as
  2791. ** "./" to avoid ambiguity.
  2792. **
  2793. ** ^If the filename is an empty string, then a private, temporary
  2794. ** on-disk database will be created. ^This private database will be
  2795. ** automatically deleted as soon as the database connection is closed.
  2796. **
  2797. ** [[URI filenames in sqlite3_open()]] <h3>URI Filenames</h3>
  2798. **
  2799. ** ^If [URI filename] interpretation is enabled, and the filename argument
  2800. ** begins with "file:", then the filename is interpreted as a URI. ^URI
  2801. ** filename interpretation is enabled if the [SQLITE_OPEN_URI] flag is
  2802. ** set in the fourth argument to sqlite3_open_v2(), or if it has
  2803. ** been enabled globally using the [SQLITE_CONFIG_URI] option with the
  2804. ** [sqlite3_config()] method or by the [SQLITE_USE_URI] compile-time option.
  2805. ** As of SQLite version 3.7.7, URI filename interpretation is turned off
  2806. ** by default, but future releases of SQLite might enable URI filename
  2807. ** interpretation by default. See "[URI filenames]" for additional
  2808. ** information.
  2809. **
  2810. ** URI filenames are parsed according to RFC 3986. ^If the URI contains an
  2811. ** authority, then it must be either an empty string or the string
  2812. ** "localhost". ^If the authority is not an empty string or "localhost", an
  2813. ** error is returned to the caller. ^The fragment component of a URI, if
  2814. ** present, is ignored.
  2815. **
  2816. ** ^SQLite uses the path component of the URI as the name of the disk file
  2817. ** which contains the database. ^If the path begins with a '/' character,
  2818. ** then it is interpreted as an absolute path. ^If the path does not begin
  2819. ** with a '/' (meaning that the authority section is omitted from the URI)
  2820. ** then the path is interpreted as a relative path.
  2821. ** ^(On windows, the first component of an absolute path
  2822. ** is a drive specification (e.g. "C:").)^
  2823. **
  2824. ** [[core URI query parameters]]
  2825. ** The query component of a URI may contain parameters that are interpreted
  2826. ** either by SQLite itself, or by a [VFS | custom VFS implementation].
  2827. ** SQLite and its built-in [VFSes] interpret the
  2828. ** following query parameters:
  2829. **
  2830. ** <ul>
  2831. ** <li> <b>vfs</b>: ^The "vfs" parameter may be used to specify the name of
  2832. ** a VFS object that provides the operating system interface that should
  2833. ** be used to access the database file on disk. ^If this option is set to
  2834. ** an empty string the default VFS object is used. ^Specifying an unknown
  2835. ** VFS is an error. ^If sqlite3_open_v2() is used and the vfs option is
  2836. ** present, then the VFS specified by the option takes precedence over
  2837. ** the value passed as the fourth parameter to sqlite3_open_v2().
  2838. **
  2839. ** <li> <b>mode</b>: ^(The mode parameter may be set to either "ro", "rw",
  2840. ** "rwc", or "memory". Attempting to set it to any other value is
  2841. ** an error)^.
  2842. ** ^If "ro" is specified, then the database is opened for read-only
  2843. ** access, just as if the [SQLITE_OPEN_READONLY] flag had been set in the
  2844. ** third argument to sqlite3_open_v2(). ^If the mode option is set to
  2845. ** "rw", then the database is opened for read-write (but not create)
  2846. ** access, as if SQLITE_OPEN_READWRITE (but not SQLITE_OPEN_CREATE) had
  2847. ** been set. ^Value "rwc" is equivalent to setting both
  2848. ** SQLITE_OPEN_READWRITE and SQLITE_OPEN_CREATE. ^If the mode option is
  2849. ** set to "memory" then a pure [in-memory database] that never reads
  2850. ** or writes from disk is used. ^It is an error to specify a value for
  2851. ** the mode parameter that is less restrictive than that specified by
  2852. ** the flags passed in the third parameter to sqlite3_open_v2().
  2853. **
  2854. ** <li> <b>cache</b>: ^The cache parameter may be set to either "shared" or
  2855. ** "private". ^Setting it to "shared" is equivalent to setting the
  2856. ** SQLITE_OPEN_SHAREDCACHE bit in the flags argument passed to
  2857. ** sqlite3_open_v2(). ^Setting the cache parameter to "private" is
  2858. ** equivalent to setting the SQLITE_OPEN_PRIVATECACHE bit.
  2859. ** ^If sqlite3_open_v2() is used and the "cache" parameter is present in
  2860. ** a URI filename, its value overrides any behavior requested by setting
  2861. ** SQLITE_OPEN_PRIVATECACHE or SQLITE_OPEN_SHAREDCACHE flag.
  2862. **
  2863. ** <li> <b>psow</b>: ^The psow parameter indicates whether or not the
  2864. ** [powersafe overwrite] property does or does not apply to the
  2865. ** storage media on which the database file resides.
  2866. **
  2867. ** <li> <b>nolock</b>: ^The nolock parameter is a boolean query parameter
  2868. ** which if set disables file locking in rollback journal modes. This
  2869. ** is useful for accessing a database on a filesystem that does not
  2870. ** support locking. Caution: Database corruption might result if two
  2871. ** or more processes write to the same database and any one of those
  2872. ** processes uses nolock=1.
  2873. **
  2874. ** <li> <b>immutable</b>: ^The immutable parameter is a boolean query
  2875. ** parameter that indicates that the database file is stored on
  2876. ** read-only media. ^When immutable is set, SQLite assumes that the
  2877. ** database file cannot be changed, even by a process with higher
  2878. ** privilege, and so the database is opened read-only and all locking
  2879. ** and change detection is disabled. Caution: Setting the immutable
  2880. ** property on a database file that does in fact change can result
  2881. ** in incorrect query results and/or [SQLITE_CORRUPT] errors.
  2882. ** See also: [SQLITE_IOCAP_IMMUTABLE].
  2883. **
  2884. ** </ul>
  2885. **
  2886. ** ^Specifying an unknown parameter in the query component of a URI is not an
  2887. ** error. Future versions of SQLite might understand additional query
  2888. ** parameters. See "[query parameters with special meaning to SQLite]" for
  2889. ** additional information.
  2890. **
  2891. ** [[URI filename examples]] <h3>URI filename examples</h3>
  2892. **
  2893. ** <table border="1" align=center cellpadding=5>
  2894. ** <tr><th> URI filenames <th> Results
  2895. ** <tr><td> file:data.db <td>
  2896. ** Open the file "data.db" in the current directory.
  2897. ** <tr><td> file:/home/fred/data.db<br>
  2898. ** file:///home/fred/data.db <br>
  2899. ** file://localhost/home/fred/data.db <br> <td>
  2900. ** Open the database file "/home/fred/data.db".
  2901. ** <tr><td> file://darkstar/home/fred/data.db <td>
  2902. ** An error. "darkstar" is not a recognized authority.
  2903. ** <tr><td style="white-space:nowrap">
  2904. ** file:///C:/Documents%20and%20Settings/fred/Desktop/data.db
  2905. ** <td> Windows only: Open the file "data.db" on fred's desktop on drive
  2906. ** C:. Note that the %20 escaping in this example is not strictly
  2907. ** necessary - space characters can be used literally
  2908. ** in URI filenames.
  2909. ** <tr><td> file:data.db?mode=ro&cache=private <td>
  2910. ** Open file "data.db" in the current directory for read-only access.
  2911. ** Regardless of whether or not shared-cache mode is enabled by
  2912. ** default, use a private cache.
  2913. ** <tr><td> file:/home/fred/data.db?vfs=unix-dotfile <td>
  2914. ** Open file "/home/fred/data.db". Use the special VFS "unix-dotfile"
  2915. ** that uses dot-files in place of posix advisory locking.
  2916. ** <tr><td> file:data.db?mode=readonly <td>
  2917. ** An error. "readonly" is not a valid option for the "mode" parameter.
  2918. ** </table>
  2919. **
  2920. ** ^URI hexadecimal escape sequences (%HH) are supported within the path and
  2921. ** query components of a URI. A hexadecimal escape sequence consists of a
  2922. ** percent sign - "%" - followed by exactly two hexadecimal digits
  2923. ** specifying an octet value. ^Before the path or query components of a
  2924. ** URI filename are interpreted, they are encoded using UTF-8 and all
  2925. ** hexadecimal escape sequences replaced by a single byte containing the
  2926. ** corresponding octet. If this process generates an invalid UTF-8 encoding,
  2927. ** the results are undefined.
  2928. **
  2929. ** <b>Note to Windows users:</b> The encoding used for the filename argument
  2930. ** of sqlite3_open() and sqlite3_open_v2() must be UTF-8, not whatever
  2931. ** codepage is currently defined. Filenames containing international
  2932. ** characters must be converted to UTF-8 prior to passing them into
  2933. ** sqlite3_open() or sqlite3_open_v2().
  2934. **
  2935. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  2936. ** prior to calling sqlite3_open() or sqlite3_open_v2(). Otherwise, various
  2937. ** features that require the use of temporary files may fail.
  2938. **
  2939. ** See also: [sqlite3_temp_directory]
  2940. */
  2941. SQLITE_API int sqlite3_open(
  2942. const char *filename, /* Database filename (UTF-8) */
  2943. sqlite3 **ppDb /* OUT: SQLite db handle */
  2944. );
  2945. SQLITE_API int sqlite3_open16(
  2946. const void *filename, /* Database filename (UTF-16) */
  2947. sqlite3 **ppDb /* OUT: SQLite db handle */
  2948. );
  2949. SQLITE_API int sqlite3_open_v2(
  2950. const char *filename, /* Database filename (UTF-8) */
  2951. sqlite3 **ppDb, /* OUT: SQLite db handle */
  2952. int flags, /* Flags */
  2953. const char *zVfs /* Name of VFS module to use */
  2954. );
  2955. /*
  2956. ** CAPI3REF: Obtain Values For URI Parameters
  2957. **
  2958. ** These are utility routines, useful to VFS implementations, that check
  2959. ** to see if a database file was a URI that contained a specific query
  2960. ** parameter, and if so obtains the value of that query parameter.
  2961. **
  2962. ** If F is the database filename pointer passed into the xOpen() method of
  2963. ** a VFS implementation when the flags parameter to xOpen() has one or
  2964. ** more of the [SQLITE_OPEN_URI] or [SQLITE_OPEN_MAIN_DB] bits set and
  2965. ** P is the name of the query parameter, then
  2966. ** sqlite3_uri_parameter(F,P) returns the value of the P
  2967. ** parameter if it exists or a NULL pointer if P does not appear as a
  2968. ** query parameter on F. If P is a query parameter of F
  2969. ** has no explicit value, then sqlite3_uri_parameter(F,P) returns
  2970. ** a pointer to an empty string.
  2971. **
  2972. ** The sqlite3_uri_boolean(F,P,B) routine assumes that P is a boolean
  2973. ** parameter and returns true (1) or false (0) according to the value
  2974. ** of P. The sqlite3_uri_boolean(F,P,B) routine returns true (1) if the
  2975. ** value of query parameter P is one of "yes", "true", or "on" in any
  2976. ** case or if the value begins with a non-zero number. The
  2977. ** sqlite3_uri_boolean(F,P,B) routines returns false (0) if the value of
  2978. ** query parameter P is one of "no", "false", or "off" in any case or
  2979. ** if the value begins with a numeric zero. If P is not a query
  2980. ** parameter on F or if the value of P is does not match any of the
  2981. ** above, then sqlite3_uri_boolean(F,P,B) returns (B!=0).
  2982. **
  2983. ** The sqlite3_uri_int64(F,P,D) routine converts the value of P into a
  2984. ** 64-bit signed integer and returns that integer, or D if P does not
  2985. ** exist. If the value of P is something other than an integer, then
  2986. ** zero is returned.
  2987. **
  2988. ** If F is a NULL pointer, then sqlite3_uri_parameter(F,P) returns NULL and
  2989. ** sqlite3_uri_boolean(F,P,B) returns B. If F is not a NULL pointer and
  2990. ** is not a database file pathname pointer that SQLite passed into the xOpen
  2991. ** VFS method, then the behavior of this routine is undefined and probably
  2992. ** undesirable.
  2993. */
  2994. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam);
  2995. SQLITE_API int sqlite3_uri_boolean(const char *zFile, const char *zParam, int bDefault);
  2996. SQLITE_API sqlite3_int64 sqlite3_uri_int64(const char*, const char*, sqlite3_int64);
  2997. /*
  2998. ** CAPI3REF: Error Codes And Messages
  2999. **
  3000. ** ^The sqlite3_errcode() interface returns the numeric [result code] or
  3001. ** [extended result code] for the most recent failed sqlite3_* API call
  3002. ** associated with a [database connection]. If a prior API call failed
  3003. ** but the most recent API call succeeded, the return value from
  3004. ** sqlite3_errcode() is undefined. ^The sqlite3_extended_errcode()
  3005. ** interface is the same except that it always returns the
  3006. ** [extended result code] even when extended result codes are
  3007. ** disabled.
  3008. **
  3009. ** ^The sqlite3_errmsg() and sqlite3_errmsg16() return English-language
  3010. ** text that describes the error, as either UTF-8 or UTF-16 respectively.
  3011. ** ^(Memory to hold the error message string is managed internally.
  3012. ** The application does not need to worry about freeing the result.
  3013. ** However, the error string might be overwritten or deallocated by
  3014. ** subsequent calls to other SQLite interface functions.)^
  3015. **
  3016. ** ^The sqlite3_errstr() interface returns the English-language text
  3017. ** that describes the [result code], as UTF-8.
  3018. ** ^(Memory to hold the error message string is managed internally
  3019. ** and must not be freed by the application)^.
  3020. **
  3021. ** When the serialized [threading mode] is in use, it might be the
  3022. ** case that a second error occurs on a separate thread in between
  3023. ** the time of the first error and the call to these interfaces.
  3024. ** When that happens, the second error will be reported since these
  3025. ** interfaces always report the most recent result. To avoid
  3026. ** this, each thread can obtain exclusive use of the [database connection] D
  3027. ** by invoking [sqlite3_mutex_enter]([sqlite3_db_mutex](D)) before beginning
  3028. ** to use D and invoking [sqlite3_mutex_leave]([sqlite3_db_mutex](D)) after
  3029. ** all calls to the interfaces listed here are completed.
  3030. **
  3031. ** If an interface fails with SQLITE_MISUSE, that means the interface
  3032. ** was invoked incorrectly by the application. In that case, the
  3033. ** error code and message may or may not be set.
  3034. */
  3035. SQLITE_API int sqlite3_errcode(sqlite3 *db);
  3036. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db);
  3037. SQLITE_API const char *sqlite3_errmsg(sqlite3*);
  3038. SQLITE_API const void *sqlite3_errmsg16(sqlite3*);
  3039. SQLITE_API const char *sqlite3_errstr(int);
  3040. /*
  3041. ** CAPI3REF: SQL Statement Object
  3042. ** KEYWORDS: {prepared statement} {prepared statements}
  3043. **
  3044. ** An instance of this object represents a single SQL statement.
  3045. ** This object is variously known as a "prepared statement" or a
  3046. ** "compiled SQL statement" or simply as a "statement".
  3047. **
  3048. ** The life of a statement object goes something like this:
  3049. **
  3050. ** <ol>
  3051. ** <li> Create the object using [sqlite3_prepare_v2()] or a related
  3052. ** function.
  3053. ** <li> Bind values to [host parameters] using the sqlite3_bind_*()
  3054. ** interfaces.
  3055. ** <li> Run the SQL by calling [sqlite3_step()] one or more times.
  3056. ** <li> Reset the statement using [sqlite3_reset()] then go back
  3057. ** to step 2. Do this zero or more times.
  3058. ** <li> Destroy the object using [sqlite3_finalize()].
  3059. ** </ol>
  3060. **
  3061. ** Refer to documentation on individual methods above for additional
  3062. ** information.
  3063. */
  3064. typedef struct sqlite3_stmt sqlite3_stmt;
  3065. /*
  3066. ** CAPI3REF: Run-time Limits
  3067. **
  3068. ** ^(This interface allows the size of various constructs to be limited
  3069. ** on a connection by connection basis. The first parameter is the
  3070. ** [database connection] whose limit is to be set or queried. The
  3071. ** second parameter is one of the [limit categories] that define a
  3072. ** class of constructs to be size limited. The third parameter is the
  3073. ** new limit for that construct.)^
  3074. **
  3075. ** ^If the new limit is a negative number, the limit is unchanged.
  3076. ** ^(For each limit category SQLITE_LIMIT_<i>NAME</i> there is a
  3077. ** [limits | hard upper bound]
  3078. ** set at compile-time by a C preprocessor macro called
  3079. ** [limits | SQLITE_MAX_<i>NAME</i>].
  3080. ** (The "_LIMIT_" in the name is changed to "_MAX_".))^
  3081. ** ^Attempts to increase a limit above its hard upper bound are
  3082. ** silently truncated to the hard upper bound.
  3083. **
  3084. ** ^Regardless of whether or not the limit was changed, the
  3085. ** [sqlite3_limit()] interface returns the prior value of the limit.
  3086. ** ^Hence, to find the current value of a limit without changing it,
  3087. ** simply invoke this interface with the third parameter set to -1.
  3088. **
  3089. ** Run-time limits are intended for use in applications that manage
  3090. ** both their own internal database and also databases that are controlled
  3091. ** by untrusted external sources. An example application might be a
  3092. ** web browser that has its own databases for storing history and
  3093. ** separate databases controlled by JavaScript applications downloaded
  3094. ** off the Internet. The internal databases can be given the
  3095. ** large, default limits. Databases managed by external sources can
  3096. ** be given much smaller limits designed to prevent a denial of service
  3097. ** attack. Developers might also want to use the [sqlite3_set_authorizer()]
  3098. ** interface to further control untrusted SQL. The size of the database
  3099. ** created by an untrusted script can be contained using the
  3100. ** [max_page_count] [PRAGMA].
  3101. **
  3102. ** New run-time limit categories may be added in future releases.
  3103. */
  3104. SQLITE_API int sqlite3_limit(sqlite3*, int id, int newVal);
  3105. /*
  3106. ** CAPI3REF: Run-Time Limit Categories
  3107. ** KEYWORDS: {limit category} {*limit categories}
  3108. **
  3109. ** These constants define various performance limits
  3110. ** that can be lowered at run-time using [sqlite3_limit()].
  3111. ** The synopsis of the meanings of the various limits is shown below.
  3112. ** Additional information is available at [limits | Limits in SQLite].
  3113. **
  3114. ** <dl>
  3115. ** [[SQLITE_LIMIT_LENGTH]] ^(<dt>SQLITE_LIMIT_LENGTH</dt>
  3116. ** <dd>The maximum size of any string or BLOB or table row, in bytes.<dd>)^
  3117. **
  3118. ** [[SQLITE_LIMIT_SQL_LENGTH]] ^(<dt>SQLITE_LIMIT_SQL_LENGTH</dt>
  3119. ** <dd>The maximum length of an SQL statement, in bytes.</dd>)^
  3120. **
  3121. ** [[SQLITE_LIMIT_COLUMN]] ^(<dt>SQLITE_LIMIT_COLUMN</dt>
  3122. ** <dd>The maximum number of columns in a table definition or in the
  3123. ** result set of a [SELECT] or the maximum number of columns in an index
  3124. ** or in an ORDER BY or GROUP BY clause.</dd>)^
  3125. **
  3126. ** [[SQLITE_LIMIT_EXPR_DEPTH]] ^(<dt>SQLITE_LIMIT_EXPR_DEPTH</dt>
  3127. ** <dd>The maximum depth of the parse tree on any expression.</dd>)^
  3128. **
  3129. ** [[SQLITE_LIMIT_COMPOUND_SELECT]] ^(<dt>SQLITE_LIMIT_COMPOUND_SELECT</dt>
  3130. ** <dd>The maximum number of terms in a compound SELECT statement.</dd>)^
  3131. **
  3132. ** [[SQLITE_LIMIT_VDBE_OP]] ^(<dt>SQLITE_LIMIT_VDBE_OP</dt>
  3133. ** <dd>The maximum number of instructions in a virtual machine program
  3134. ** used to implement an SQL statement. This limit is not currently
  3135. ** enforced, though that might be added in some future release of
  3136. ** SQLite.</dd>)^
  3137. **
  3138. ** [[SQLITE_LIMIT_FUNCTION_ARG]] ^(<dt>SQLITE_LIMIT_FUNCTION_ARG</dt>
  3139. ** <dd>The maximum number of arguments on a function.</dd>)^
  3140. **
  3141. ** [[SQLITE_LIMIT_ATTACHED]] ^(<dt>SQLITE_LIMIT_ATTACHED</dt>
  3142. ** <dd>The maximum number of [ATTACH | attached databases].)^</dd>
  3143. **
  3144. ** [[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]]
  3145. ** ^(<dt>SQLITE_LIMIT_LIKE_PATTERN_LENGTH</dt>
  3146. ** <dd>The maximum length of the pattern argument to the [LIKE] or
  3147. ** [GLOB] operators.</dd>)^
  3148. **
  3149. ** [[SQLITE_LIMIT_VARIABLE_NUMBER]]
  3150. ** ^(<dt>SQLITE_LIMIT_VARIABLE_NUMBER</dt>
  3151. ** <dd>The maximum index number of any [parameter] in an SQL statement.)^
  3152. **
  3153. ** [[SQLITE_LIMIT_TRIGGER_DEPTH]] ^(<dt>SQLITE_LIMIT_TRIGGER_DEPTH</dt>
  3154. ** <dd>The maximum depth of recursion for triggers.</dd>)^
  3155. **
  3156. ** [[SQLITE_LIMIT_WORKER_THREADS]] ^(<dt>SQLITE_LIMIT_WORKER_THREADS</dt>
  3157. ** <dd>The maximum number of auxiliary worker threads that a single
  3158. ** [prepared statement] may start.</dd>)^
  3159. ** </dl>
  3160. */
  3161. #define SQLITE_LIMIT_LENGTH 0
  3162. #define SQLITE_LIMIT_SQL_LENGTH 1
  3163. #define SQLITE_LIMIT_COLUMN 2
  3164. #define SQLITE_LIMIT_EXPR_DEPTH 3
  3165. #define SQLITE_LIMIT_COMPOUND_SELECT 4
  3166. #define SQLITE_LIMIT_VDBE_OP 5
  3167. #define SQLITE_LIMIT_FUNCTION_ARG 6
  3168. #define SQLITE_LIMIT_ATTACHED 7
  3169. #define SQLITE_LIMIT_LIKE_PATTERN_LENGTH 8
  3170. #define SQLITE_LIMIT_VARIABLE_NUMBER 9
  3171. #define SQLITE_LIMIT_TRIGGER_DEPTH 10
  3172. #define SQLITE_LIMIT_WORKER_THREADS 11
  3173. /*
  3174. ** CAPI3REF: Compiling An SQL Statement
  3175. ** KEYWORDS: {SQL statement compiler}
  3176. **
  3177. ** To execute an SQL query, it must first be compiled into a byte-code
  3178. ** program using one of these routines.
  3179. **
  3180. ** The first argument, "db", is a [database connection] obtained from a
  3181. ** prior successful call to [sqlite3_open()], [sqlite3_open_v2()] or
  3182. ** [sqlite3_open16()]. The database connection must not have been closed.
  3183. **
  3184. ** The second argument, "zSql", is the statement to be compiled, encoded
  3185. ** as either UTF-8 or UTF-16. The sqlite3_prepare() and sqlite3_prepare_v2()
  3186. ** interfaces use UTF-8, and sqlite3_prepare16() and sqlite3_prepare16_v2()
  3187. ** use UTF-16.
  3188. **
  3189. ** ^If the nByte argument is less than zero, then zSql is read up to the
  3190. ** first zero terminator. ^If nByte is non-negative, then it is the maximum
  3191. ** number of bytes read from zSql. ^When nByte is non-negative, the
  3192. ** zSql string ends at either the first '\000' or '\u0000' character or
  3193. ** the nByte-th byte, whichever comes first. If the caller knows
  3194. ** that the supplied string is nul-terminated, then there is a small
  3195. ** performance advantage to be gained by passing an nByte parameter that
  3196. ** is equal to the number of bytes in the input string <i>including</i>
  3197. ** the nul-terminator bytes as this saves SQLite from having to
  3198. ** make a copy of the input string.
  3199. **
  3200. ** ^If pzTail is not NULL then *pzTail is made to point to the first byte
  3201. ** past the end of the first SQL statement in zSql. These routines only
  3202. ** compile the first statement in zSql, so *pzTail is left pointing to
  3203. ** what remains uncompiled.
  3204. **
  3205. ** ^*ppStmt is left pointing to a compiled [prepared statement] that can be
  3206. ** executed using [sqlite3_step()]. ^If there is an error, *ppStmt is set
  3207. ** to NULL. ^If the input text contains no SQL (if the input is an empty
  3208. ** string or a comment) then *ppStmt is set to NULL.
  3209. ** The calling procedure is responsible for deleting the compiled
  3210. ** SQL statement using [sqlite3_finalize()] after it has finished with it.
  3211. ** ppStmt may not be NULL.
  3212. **
  3213. ** ^On success, the sqlite3_prepare() family of routines return [SQLITE_OK];
  3214. ** otherwise an [error code] is returned.
  3215. **
  3216. ** The sqlite3_prepare_v2() and sqlite3_prepare16_v2() interfaces are
  3217. ** recommended for all new programs. The two older interfaces are retained
  3218. ** for backwards compatibility, but their use is discouraged.
  3219. ** ^In the "v2" interfaces, the prepared statement
  3220. ** that is returned (the [sqlite3_stmt] object) contains a copy of the
  3221. ** original SQL text. This causes the [sqlite3_step()] interface to
  3222. ** behave differently in three ways:
  3223. **
  3224. ** <ol>
  3225. ** <li>
  3226. ** ^If the database schema changes, instead of returning [SQLITE_SCHEMA] as it
  3227. ** always used to do, [sqlite3_step()] will automatically recompile the SQL
  3228. ** statement and try to run it again. As many as [SQLITE_MAX_SCHEMA_RETRY]
  3229. ** retries will occur before sqlite3_step() gives up and returns an error.
  3230. ** </li>
  3231. **
  3232. ** <li>
  3233. ** ^When an error occurs, [sqlite3_step()] will return one of the detailed
  3234. ** [error codes] or [extended error codes]. ^The legacy behavior was that
  3235. ** [sqlite3_step()] would only return a generic [SQLITE_ERROR] result code
  3236. ** and the application would have to make a second call to [sqlite3_reset()]
  3237. ** in order to find the underlying cause of the problem. With the "v2" prepare
  3238. ** interfaces, the underlying reason for the error is returned immediately.
  3239. ** </li>
  3240. **
  3241. ** <li>
  3242. ** ^If the specific value bound to [parameter | host parameter] in the
  3243. ** WHERE clause might influence the choice of query plan for a statement,
  3244. ** then the statement will be automatically recompiled, as if there had been
  3245. ** a schema change, on the first [sqlite3_step()] call following any change
  3246. ** to the [sqlite3_bind_text | bindings] of that [parameter].
  3247. ** ^The specific value of WHERE-clause [parameter] might influence the
  3248. ** choice of query plan if the parameter is the left-hand side of a [LIKE]
  3249. ** or [GLOB] operator or if the parameter is compared to an indexed column
  3250. ** and the [SQLITE_ENABLE_STAT3] compile-time option is enabled.
  3251. ** </li>
  3252. ** </ol>
  3253. */
  3254. SQLITE_API int sqlite3_prepare(
  3255. sqlite3 *db, /* Database handle */
  3256. const char *zSql, /* SQL statement, UTF-8 encoded */
  3257. int nByte, /* Maximum length of zSql in bytes. */
  3258. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3259. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3260. );
  3261. SQLITE_API int sqlite3_prepare_v2(
  3262. sqlite3 *db, /* Database handle */
  3263. const char *zSql, /* SQL statement, UTF-8 encoded */
  3264. int nByte, /* Maximum length of zSql in bytes. */
  3265. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3266. const char **pzTail /* OUT: Pointer to unused portion of zSql */
  3267. );
  3268. SQLITE_API int sqlite3_prepare16(
  3269. sqlite3 *db, /* Database handle */
  3270. const void *zSql, /* SQL statement, UTF-16 encoded */
  3271. int nByte, /* Maximum length of zSql in bytes. */
  3272. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3273. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3274. );
  3275. SQLITE_API int sqlite3_prepare16_v2(
  3276. sqlite3 *db, /* Database handle */
  3277. const void *zSql, /* SQL statement, UTF-16 encoded */
  3278. int nByte, /* Maximum length of zSql in bytes. */
  3279. sqlite3_stmt **ppStmt, /* OUT: Statement handle */
  3280. const void **pzTail /* OUT: Pointer to unused portion of zSql */
  3281. );
  3282. /*
  3283. ** CAPI3REF: Retrieving Statement SQL
  3284. **
  3285. ** ^This interface can be used to retrieve a saved copy of the original
  3286. ** SQL text used to create a [prepared statement] if that statement was
  3287. ** compiled using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()].
  3288. */
  3289. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt);
  3290. /*
  3291. ** CAPI3REF: Determine If An SQL Statement Writes The Database
  3292. **
  3293. ** ^The sqlite3_stmt_readonly(X) interface returns true (non-zero) if
  3294. ** and only if the [prepared statement] X makes no direct changes to
  3295. ** the content of the database file.
  3296. **
  3297. ** Note that [application-defined SQL functions] or
  3298. ** [virtual tables] might change the database indirectly as a side effect.
  3299. ** ^(For example, if an application defines a function "eval()" that
  3300. ** calls [sqlite3_exec()], then the following SQL statement would
  3301. ** change the database file through side-effects:
  3302. **
  3303. ** <blockquote><pre>
  3304. ** SELECT eval('DELETE FROM t1') FROM t2;
  3305. ** </pre></blockquote>
  3306. **
  3307. ** But because the [SELECT] statement does not change the database file
  3308. ** directly, sqlite3_stmt_readonly() would still return true.)^
  3309. **
  3310. ** ^Transaction control statements such as [BEGIN], [COMMIT], [ROLLBACK],
  3311. ** [SAVEPOINT], and [RELEASE] cause sqlite3_stmt_readonly() to return true,
  3312. ** since the statements themselves do not actually modify the database but
  3313. ** rather they control the timing of when other statements modify the
  3314. ** database. ^The [ATTACH] and [DETACH] statements also cause
  3315. ** sqlite3_stmt_readonly() to return true since, while those statements
  3316. ** change the configuration of a database connection, they do not make
  3317. ** changes to the content of the database files on disk.
  3318. */
  3319. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt);
  3320. /*
  3321. ** CAPI3REF: Determine If A Prepared Statement Has Been Reset
  3322. **
  3323. ** ^The sqlite3_stmt_busy(S) interface returns true (non-zero) if the
  3324. ** [prepared statement] S has been stepped at least once using
  3325. ** [sqlite3_step(S)] but has not run to completion and/or has not
  3326. ** been reset using [sqlite3_reset(S)]. ^The sqlite3_stmt_busy(S)
  3327. ** interface returns false if S is a NULL pointer. If S is not a
  3328. ** NULL pointer and is not a pointer to a valid [prepared statement]
  3329. ** object, then the behavior is undefined and probably undesirable.
  3330. **
  3331. ** This interface can be used in combination [sqlite3_next_stmt()]
  3332. ** to locate all prepared statements associated with a database
  3333. ** connection that are in need of being reset. This can be used,
  3334. ** for example, in diagnostic routines to search for prepared
  3335. ** statements that are holding a transaction open.
  3336. */
  3337. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt*);
  3338. /*
  3339. ** CAPI3REF: Dynamically Typed Value Object
  3340. ** KEYWORDS: {protected sqlite3_value} {unprotected sqlite3_value}
  3341. **
  3342. ** SQLite uses the sqlite3_value object to represent all values
  3343. ** that can be stored in a database table. SQLite uses dynamic typing
  3344. ** for the values it stores. ^Values stored in sqlite3_value objects
  3345. ** can be integers, floating point values, strings, BLOBs, or NULL.
  3346. **
  3347. ** An sqlite3_value object may be either "protected" or "unprotected".
  3348. ** Some interfaces require a protected sqlite3_value. Other interfaces
  3349. ** will accept either a protected or an unprotected sqlite3_value.
  3350. ** Every interface that accepts sqlite3_value arguments specifies
  3351. ** whether or not it requires a protected sqlite3_value.
  3352. **
  3353. ** The terms "protected" and "unprotected" refer to whether or not
  3354. ** a mutex is held. An internal mutex is held for a protected
  3355. ** sqlite3_value object but no mutex is held for an unprotected
  3356. ** sqlite3_value object. If SQLite is compiled to be single-threaded
  3357. ** (with [SQLITE_THREADSAFE=0] and with [sqlite3_threadsafe()] returning 0)
  3358. ** or if SQLite is run in one of reduced mutex modes
  3359. ** [SQLITE_CONFIG_SINGLETHREAD] or [SQLITE_CONFIG_MULTITHREAD]
  3360. ** then there is no distinction between protected and unprotected
  3361. ** sqlite3_value objects and they can be used interchangeably. However,
  3362. ** for maximum code portability it is recommended that applications
  3363. ** still make the distinction between protected and unprotected
  3364. ** sqlite3_value objects even when not strictly required.
  3365. **
  3366. ** ^The sqlite3_value objects that are passed as parameters into the
  3367. ** implementation of [application-defined SQL functions] are protected.
  3368. ** ^The sqlite3_value object returned by
  3369. ** [sqlite3_column_value()] is unprotected.
  3370. ** Unprotected sqlite3_value objects may only be used with
  3371. ** [sqlite3_result_value()] and [sqlite3_bind_value()].
  3372. ** The [sqlite3_value_blob | sqlite3_value_type()] family of
  3373. ** interfaces require protected sqlite3_value objects.
  3374. */
  3375. typedef struct Mem sqlite3_value;
  3376. /*
  3377. ** CAPI3REF: SQL Function Context Object
  3378. **
  3379. ** The context in which an SQL function executes is stored in an
  3380. ** sqlite3_context object. ^A pointer to an sqlite3_context object
  3381. ** is always first parameter to [application-defined SQL functions].
  3382. ** The application-defined SQL function implementation will pass this
  3383. ** pointer through into calls to [sqlite3_result_int | sqlite3_result()],
  3384. ** [sqlite3_aggregate_context()], [sqlite3_user_data()],
  3385. ** [sqlite3_context_db_handle()], [sqlite3_get_auxdata()],
  3386. ** and/or [sqlite3_set_auxdata()].
  3387. */
  3388. typedef struct sqlite3_context sqlite3_context;
  3389. /*
  3390. ** CAPI3REF: Binding Values To Prepared Statements
  3391. ** KEYWORDS: {host parameter} {host parameters} {host parameter name}
  3392. ** KEYWORDS: {SQL parameter} {SQL parameters} {parameter binding}
  3393. **
  3394. ** ^(In the SQL statement text input to [sqlite3_prepare_v2()] and its variants,
  3395. ** literals may be replaced by a [parameter] that matches one of following
  3396. ** templates:
  3397. **
  3398. ** <ul>
  3399. ** <li> ?
  3400. ** <li> ?NNN
  3401. ** <li> :VVV
  3402. ** <li> @VVV
  3403. ** <li> $VVV
  3404. ** </ul>
  3405. **
  3406. ** In the templates above, NNN represents an integer literal,
  3407. ** and VVV represents an alphanumeric identifier.)^ ^The values of these
  3408. ** parameters (also called "host parameter names" or "SQL parameters")
  3409. ** can be set using the sqlite3_bind_*() routines defined here.
  3410. **
  3411. ** ^The first argument to the sqlite3_bind_*() routines is always
  3412. ** a pointer to the [sqlite3_stmt] object returned from
  3413. ** [sqlite3_prepare_v2()] or its variants.
  3414. **
  3415. ** ^The second argument is the index of the SQL parameter to be set.
  3416. ** ^The leftmost SQL parameter has an index of 1. ^When the same named
  3417. ** SQL parameter is used more than once, second and subsequent
  3418. ** occurrences have the same index as the first occurrence.
  3419. ** ^The index for named parameters can be looked up using the
  3420. ** [sqlite3_bind_parameter_index()] API if desired. ^The index
  3421. ** for "?NNN" parameters is the value of NNN.
  3422. ** ^The NNN value must be between 1 and the [sqlite3_limit()]
  3423. ** parameter [SQLITE_LIMIT_VARIABLE_NUMBER] (default value: 999).
  3424. **
  3425. ** ^The third argument is the value to bind to the parameter.
  3426. ** ^If the third parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3427. ** or sqlite3_bind_blob() is a NULL pointer then the fourth parameter
  3428. ** is ignored and the end result is the same as sqlite3_bind_null().
  3429. **
  3430. ** ^(In those routines that have a fourth argument, its value is the
  3431. ** number of bytes in the parameter. To be clear: the value is the
  3432. ** number of <u>bytes</u> in the value, not the number of characters.)^
  3433. ** ^If the fourth parameter to sqlite3_bind_text() or sqlite3_bind_text16()
  3434. ** is negative, then the length of the string is
  3435. ** the number of bytes up to the first zero terminator.
  3436. ** If the fourth parameter to sqlite3_bind_blob() is negative, then
  3437. ** the behavior is undefined.
  3438. ** If a non-negative fourth parameter is provided to sqlite3_bind_text()
  3439. ** or sqlite3_bind_text16() or sqlite3_bind_text64() then
  3440. ** that parameter must be the byte offset
  3441. ** where the NUL terminator would occur assuming the string were NUL
  3442. ** terminated. If any NUL characters occur at byte offsets less than
  3443. ** the value of the fourth parameter then the resulting string value will
  3444. ** contain embedded NULs. The result of expressions involving strings
  3445. ** with embedded NULs is undefined.
  3446. **
  3447. ** ^The fifth argument to the BLOB and string binding interfaces
  3448. ** is a destructor used to dispose of the BLOB or
  3449. ** string after SQLite has finished with it. ^The destructor is called
  3450. ** to dispose of the BLOB or string even if the call to bind API fails.
  3451. ** ^If the fifth argument is
  3452. ** the special value [SQLITE_STATIC], then SQLite assumes that the
  3453. ** information is in static, unmanaged space and does not need to be freed.
  3454. ** ^If the fifth argument has the value [SQLITE_TRANSIENT], then
  3455. ** SQLite makes its own private copy of the data immediately, before
  3456. ** the sqlite3_bind_*() routine returns.
  3457. **
  3458. ** ^The sixth argument to sqlite3_bind_text64() must be one of
  3459. ** [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE]
  3460. ** to specify the encoding of the text in the third parameter. If
  3461. ** the sixth argument to sqlite3_bind_text64() is not one of the
  3462. ** allowed values shown above, or if the text encoding is different
  3463. ** from the encoding specified by the sixth parameter, then the behavior
  3464. ** is undefined.
  3465. **
  3466. ** ^The sqlite3_bind_zeroblob() routine binds a BLOB of length N that
  3467. ** is filled with zeroes. ^A zeroblob uses a fixed amount of memory
  3468. ** (just an integer to hold its size) while it is being processed.
  3469. ** Zeroblobs are intended to serve as placeholders for BLOBs whose
  3470. ** content is later written using
  3471. ** [sqlite3_blob_open | incremental BLOB I/O] routines.
  3472. ** ^A negative value for the zeroblob results in a zero-length BLOB.
  3473. **
  3474. ** ^If any of the sqlite3_bind_*() routines are called with a NULL pointer
  3475. ** for the [prepared statement] or with a prepared statement for which
  3476. ** [sqlite3_step()] has been called more recently than [sqlite3_reset()],
  3477. ** then the call will return [SQLITE_MISUSE]. If any sqlite3_bind_()
  3478. ** routine is passed a [prepared statement] that has been finalized, the
  3479. ** result is undefined and probably harmful.
  3480. **
  3481. ** ^Bindings are not cleared by the [sqlite3_reset()] routine.
  3482. ** ^Unbound parameters are interpreted as NULL.
  3483. **
  3484. ** ^The sqlite3_bind_* routines return [SQLITE_OK] on success or an
  3485. ** [error code] if anything goes wrong.
  3486. ** ^[SQLITE_TOOBIG] might be returned if the size of a string or BLOB
  3487. ** exceeds limits imposed by [sqlite3_limit]([SQLITE_LIMIT_LENGTH]) or
  3488. ** [SQLITE_MAX_LENGTH].
  3489. ** ^[SQLITE_RANGE] is returned if the parameter
  3490. ** index is out of range. ^[SQLITE_NOMEM] is returned if malloc() fails.
  3491. **
  3492. ** See also: [sqlite3_bind_parameter_count()],
  3493. ** [sqlite3_bind_parameter_name()], and [sqlite3_bind_parameter_index()].
  3494. */
  3495. SQLITE_API int sqlite3_bind_blob(sqlite3_stmt*, int, const void*, int n, void(*)(void*));
  3496. SQLITE_API int sqlite3_bind_blob64(sqlite3_stmt*, int, const void*, sqlite3_uint64,
  3497. void(*)(void*));
  3498. SQLITE_API int sqlite3_bind_double(sqlite3_stmt*, int, double);
  3499. SQLITE_API int sqlite3_bind_int(sqlite3_stmt*, int, int);
  3500. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt*, int, sqlite3_int64);
  3501. SQLITE_API int sqlite3_bind_null(sqlite3_stmt*, int);
  3502. SQLITE_API int sqlite3_bind_text(sqlite3_stmt*,int,const char*,int,void(*)(void*));
  3503. SQLITE_API int sqlite3_bind_text16(sqlite3_stmt*, int, const void*, int, void(*)(void*));
  3504. SQLITE_API int sqlite3_bind_text64(sqlite3_stmt*, int, const char*, sqlite3_uint64,
  3505. void(*)(void*), unsigned char encoding);
  3506. SQLITE_API int sqlite3_bind_value(sqlite3_stmt*, int, const sqlite3_value*);
  3507. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt*, int, int n);
  3508. /*
  3509. ** CAPI3REF: Number Of SQL Parameters
  3510. **
  3511. ** ^This routine can be used to find the number of [SQL parameters]
  3512. ** in a [prepared statement]. SQL parameters are tokens of the
  3513. ** form "?", "?NNN", ":AAA", "$AAA", or "@AAA" that serve as
  3514. ** placeholders for values that are [sqlite3_bind_blob | bound]
  3515. ** to the parameters at a later time.
  3516. **
  3517. ** ^(This routine actually returns the index of the largest (rightmost)
  3518. ** parameter. For all forms except ?NNN, this will correspond to the
  3519. ** number of unique parameters. If parameters of the ?NNN form are used,
  3520. ** there may be gaps in the list.)^
  3521. **
  3522. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3523. ** [sqlite3_bind_parameter_name()], and
  3524. ** [sqlite3_bind_parameter_index()].
  3525. */
  3526. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt*);
  3527. /*
  3528. ** CAPI3REF: Name Of A Host Parameter
  3529. **
  3530. ** ^The sqlite3_bind_parameter_name(P,N) interface returns
  3531. ** the name of the N-th [SQL parameter] in the [prepared statement] P.
  3532. ** ^(SQL parameters of the form "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3533. ** have a name which is the string "?NNN" or ":AAA" or "@AAA" or "$AAA"
  3534. ** respectively.
  3535. ** In other words, the initial ":" or "$" or "@" or "?"
  3536. ** is included as part of the name.)^
  3537. ** ^Parameters of the form "?" without a following integer have no name
  3538. ** and are referred to as "nameless" or "anonymous parameters".
  3539. **
  3540. ** ^The first host parameter has an index of 1, not 0.
  3541. **
  3542. ** ^If the value N is out of range or if the N-th parameter is
  3543. ** nameless, then NULL is returned. ^The returned string is
  3544. ** always in UTF-8 encoding even if the named parameter was
  3545. ** originally specified as UTF-16 in [sqlite3_prepare16()] or
  3546. ** [sqlite3_prepare16_v2()].
  3547. **
  3548. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3549. ** [sqlite3_bind_parameter_count()], and
  3550. ** [sqlite3_bind_parameter_index()].
  3551. */
  3552. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt*, int);
  3553. /*
  3554. ** CAPI3REF: Index Of A Parameter With A Given Name
  3555. **
  3556. ** ^Return the index of an SQL parameter given its name. ^The
  3557. ** index value returned is suitable for use as the second
  3558. ** parameter to [sqlite3_bind_blob|sqlite3_bind()]. ^A zero
  3559. ** is returned if no matching parameter is found. ^The parameter
  3560. ** name must be given in UTF-8 even if the original statement
  3561. ** was prepared from UTF-16 text using [sqlite3_prepare16_v2()].
  3562. **
  3563. ** See also: [sqlite3_bind_blob|sqlite3_bind()],
  3564. ** [sqlite3_bind_parameter_count()], and
  3565. ** [sqlite3_bind_parameter_index()].
  3566. */
  3567. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt*, const char *zName);
  3568. /*
  3569. ** CAPI3REF: Reset All Bindings On A Prepared Statement
  3570. **
  3571. ** ^Contrary to the intuition of many, [sqlite3_reset()] does not reset
  3572. ** the [sqlite3_bind_blob | bindings] on a [prepared statement].
  3573. ** ^Use this routine to reset all host parameters to NULL.
  3574. */
  3575. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt*);
  3576. /*
  3577. ** CAPI3REF: Number Of Columns In A Result Set
  3578. **
  3579. ** ^Return the number of columns in the result set returned by the
  3580. ** [prepared statement]. ^This routine returns 0 if pStmt is an SQL
  3581. ** statement that does not return data (for example an [UPDATE]).
  3582. **
  3583. ** See also: [sqlite3_data_count()]
  3584. */
  3585. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt);
  3586. /*
  3587. ** CAPI3REF: Column Names In A Result Set
  3588. **
  3589. ** ^These routines return the name assigned to a particular column
  3590. ** in the result set of a [SELECT] statement. ^The sqlite3_column_name()
  3591. ** interface returns a pointer to a zero-terminated UTF-8 string
  3592. ** and sqlite3_column_name16() returns a pointer to a zero-terminated
  3593. ** UTF-16 string. ^The first parameter is the [prepared statement]
  3594. ** that implements the [SELECT] statement. ^The second parameter is the
  3595. ** column number. ^The leftmost column is number 0.
  3596. **
  3597. ** ^The returned string pointer is valid until either the [prepared statement]
  3598. ** is destroyed by [sqlite3_finalize()] or until the statement is automatically
  3599. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3600. ** or until the next call to
  3601. ** sqlite3_column_name() or sqlite3_column_name16() on the same column.
  3602. **
  3603. ** ^If sqlite3_malloc() fails during the processing of either routine
  3604. ** (for example during a conversion from UTF-8 to UTF-16) then a
  3605. ** NULL pointer is returned.
  3606. **
  3607. ** ^The name of a result column is the value of the "AS" clause for
  3608. ** that column, if there is an AS clause. If there is no AS clause
  3609. ** then the name of the column is unspecified and may change from
  3610. ** one release of SQLite to the next.
  3611. */
  3612. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt*, int N);
  3613. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt*, int N);
  3614. /*
  3615. ** CAPI3REF: Source Of Data In A Query Result
  3616. **
  3617. ** ^These routines provide a means to determine the database, table, and
  3618. ** table column that is the origin of a particular result column in
  3619. ** [SELECT] statement.
  3620. ** ^The name of the database or table or column can be returned as
  3621. ** either a UTF-8 or UTF-16 string. ^The _database_ routines return
  3622. ** the database name, the _table_ routines return the table name, and
  3623. ** the origin_ routines return the column name.
  3624. ** ^The returned string is valid until the [prepared statement] is destroyed
  3625. ** using [sqlite3_finalize()] or until the statement is automatically
  3626. ** reprepared by the first call to [sqlite3_step()] for a particular run
  3627. ** or until the same information is requested
  3628. ** again in a different encoding.
  3629. **
  3630. ** ^The names returned are the original un-aliased names of the
  3631. ** database, table, and column.
  3632. **
  3633. ** ^The first argument to these interfaces is a [prepared statement].
  3634. ** ^These functions return information about the Nth result column returned by
  3635. ** the statement, where N is the second function argument.
  3636. ** ^The left-most column is column 0 for these routines.
  3637. **
  3638. ** ^If the Nth column returned by the statement is an expression or
  3639. ** subquery and is not a column value, then all of these functions return
  3640. ** NULL. ^These routine might also return NULL if a memory allocation error
  3641. ** occurs. ^Otherwise, they return the name of the attached database, table,
  3642. ** or column that query result column was extracted from.
  3643. **
  3644. ** ^As with all other SQLite APIs, those whose names end with "16" return
  3645. ** UTF-16 encoded strings and the other functions return UTF-8.
  3646. **
  3647. ** ^These APIs are only available if the library was compiled with the
  3648. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol.
  3649. **
  3650. ** If two or more threads call one or more of these routines against the same
  3651. ** prepared statement and column at the same time then the results are
  3652. ** undefined.
  3653. **
  3654. ** If two or more threads call one or more
  3655. ** [sqlite3_column_database_name | column metadata interfaces]
  3656. ** for the same [prepared statement] and result column
  3657. ** at the same time then the results are undefined.
  3658. */
  3659. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt*,int);
  3660. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt*,int);
  3661. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt*,int);
  3662. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt*,int);
  3663. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt*,int);
  3664. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt*,int);
  3665. /*
  3666. ** CAPI3REF: Declared Datatype Of A Query Result
  3667. **
  3668. ** ^(The first parameter is a [prepared statement].
  3669. ** If this statement is a [SELECT] statement and the Nth column of the
  3670. ** returned result set of that [SELECT] is a table column (not an
  3671. ** expression or subquery) then the declared type of the table
  3672. ** column is returned.)^ ^If the Nth column of the result set is an
  3673. ** expression or subquery, then a NULL pointer is returned.
  3674. ** ^The returned string is always UTF-8 encoded.
  3675. **
  3676. ** ^(For example, given the database schema:
  3677. **
  3678. ** CREATE TABLE t1(c1 VARIANT);
  3679. **
  3680. ** and the following statement to be compiled:
  3681. **
  3682. ** SELECT c1 + 1, c1 FROM t1;
  3683. **
  3684. ** this routine would return the string "VARIANT" for the second result
  3685. ** column (i==1), and a NULL pointer for the first result column (i==0).)^
  3686. **
  3687. ** ^SQLite uses dynamic run-time typing. ^So just because a column
  3688. ** is declared to contain a particular type does not mean that the
  3689. ** data stored in that column is of the declared type. SQLite is
  3690. ** strongly typed, but the typing is dynamic not static. ^Type
  3691. ** is associated with individual values, not with the containers
  3692. ** used to hold those values.
  3693. */
  3694. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt*,int);
  3695. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt*,int);
  3696. /*
  3697. ** CAPI3REF: Evaluate An SQL Statement
  3698. **
  3699. ** After a [prepared statement] has been prepared using either
  3700. ** [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] or one of the legacy
  3701. ** interfaces [sqlite3_prepare()] or [sqlite3_prepare16()], this function
  3702. ** must be called one or more times to evaluate the statement.
  3703. **
  3704. ** The details of the behavior of the sqlite3_step() interface depend
  3705. ** on whether the statement was prepared using the newer "v2" interface
  3706. ** [sqlite3_prepare_v2()] and [sqlite3_prepare16_v2()] or the older legacy
  3707. ** interface [sqlite3_prepare()] and [sqlite3_prepare16()]. The use of the
  3708. ** new "v2" interface is recommended for new applications but the legacy
  3709. ** interface will continue to be supported.
  3710. **
  3711. ** ^In the legacy interface, the return value will be either [SQLITE_BUSY],
  3712. ** [SQLITE_DONE], [SQLITE_ROW], [SQLITE_ERROR], or [SQLITE_MISUSE].
  3713. ** ^With the "v2" interface, any of the other [result codes] or
  3714. ** [extended result codes] might be returned as well.
  3715. **
  3716. ** ^[SQLITE_BUSY] means that the database engine was unable to acquire the
  3717. ** database locks it needs to do its job. ^If the statement is a [COMMIT]
  3718. ** or occurs outside of an explicit transaction, then you can retry the
  3719. ** statement. If the statement is not a [COMMIT] and occurs within an
  3720. ** explicit transaction then you should rollback the transaction before
  3721. ** continuing.
  3722. **
  3723. ** ^[SQLITE_DONE] means that the statement has finished executing
  3724. ** successfully. sqlite3_step() should not be called again on this virtual
  3725. ** machine without first calling [sqlite3_reset()] to reset the virtual
  3726. ** machine back to its initial state.
  3727. **
  3728. ** ^If the SQL statement being executed returns any data, then [SQLITE_ROW]
  3729. ** is returned each time a new row of data is ready for processing by the
  3730. ** caller. The values may be accessed using the [column access functions].
  3731. ** sqlite3_step() is called again to retrieve the next row of data.
  3732. **
  3733. ** ^[SQLITE_ERROR] means that a run-time error (such as a constraint
  3734. ** violation) has occurred. sqlite3_step() should not be called again on
  3735. ** the VM. More information may be found by calling [sqlite3_errmsg()].
  3736. ** ^With the legacy interface, a more specific error code (for example,
  3737. ** [SQLITE_INTERRUPT], [SQLITE_SCHEMA], [SQLITE_CORRUPT], and so forth)
  3738. ** can be obtained by calling [sqlite3_reset()] on the
  3739. ** [prepared statement]. ^In the "v2" interface,
  3740. ** the more specific error code is returned directly by sqlite3_step().
  3741. **
  3742. ** [SQLITE_MISUSE] means that the this routine was called inappropriately.
  3743. ** Perhaps it was called on a [prepared statement] that has
  3744. ** already been [sqlite3_finalize | finalized] or on one that had
  3745. ** previously returned [SQLITE_ERROR] or [SQLITE_DONE]. Or it could
  3746. ** be the case that the same database connection is being used by two or
  3747. ** more threads at the same moment in time.
  3748. **
  3749. ** For all versions of SQLite up to and including 3.6.23.1, a call to
  3750. ** [sqlite3_reset()] was required after sqlite3_step() returned anything
  3751. ** other than [SQLITE_ROW] before any subsequent invocation of
  3752. ** sqlite3_step(). Failure to reset the prepared statement using
  3753. ** [sqlite3_reset()] would result in an [SQLITE_MISUSE] return from
  3754. ** sqlite3_step(). But after version 3.6.23.1, sqlite3_step() began
  3755. ** calling [sqlite3_reset()] automatically in this circumstance rather
  3756. ** than returning [SQLITE_MISUSE]. This is not considered a compatibility
  3757. ** break because any application that ever receives an SQLITE_MISUSE error
  3758. ** is broken by definition. The [SQLITE_OMIT_AUTORESET] compile-time option
  3759. ** can be used to restore the legacy behavior.
  3760. **
  3761. ** <b>Goofy Interface Alert:</b> In the legacy interface, the sqlite3_step()
  3762. ** API always returns a generic error code, [SQLITE_ERROR], following any
  3763. ** error other than [SQLITE_BUSY] and [SQLITE_MISUSE]. You must call
  3764. ** [sqlite3_reset()] or [sqlite3_finalize()] in order to find one of the
  3765. ** specific [error codes] that better describes the error.
  3766. ** We admit that this is a goofy design. The problem has been fixed
  3767. ** with the "v2" interface. If you prepare all of your SQL statements
  3768. ** using either [sqlite3_prepare_v2()] or [sqlite3_prepare16_v2()] instead
  3769. ** of the legacy [sqlite3_prepare()] and [sqlite3_prepare16()] interfaces,
  3770. ** then the more specific [error codes] are returned directly
  3771. ** by sqlite3_step(). The use of the "v2" interface is recommended.
  3772. */
  3773. SQLITE_API int sqlite3_step(sqlite3_stmt*);
  3774. /*
  3775. ** CAPI3REF: Number of columns in a result set
  3776. **
  3777. ** ^The sqlite3_data_count(P) interface returns the number of columns in the
  3778. ** current row of the result set of [prepared statement] P.
  3779. ** ^If prepared statement P does not have results ready to return
  3780. ** (via calls to the [sqlite3_column_int | sqlite3_column_*()] of
  3781. ** interfaces) then sqlite3_data_count(P) returns 0.
  3782. ** ^The sqlite3_data_count(P) routine also returns 0 if P is a NULL pointer.
  3783. ** ^The sqlite3_data_count(P) routine returns 0 if the previous call to
  3784. ** [sqlite3_step](P) returned [SQLITE_DONE]. ^The sqlite3_data_count(P)
  3785. ** will return non-zero if previous call to [sqlite3_step](P) returned
  3786. ** [SQLITE_ROW], except in the case of the [PRAGMA incremental_vacuum]
  3787. ** where it always returns zero since each step of that multi-step
  3788. ** pragma returns 0 columns of data.
  3789. **
  3790. ** See also: [sqlite3_column_count()]
  3791. */
  3792. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt);
  3793. /*
  3794. ** CAPI3REF: Fundamental Datatypes
  3795. ** KEYWORDS: SQLITE_TEXT
  3796. **
  3797. ** ^(Every value in SQLite has one of five fundamental datatypes:
  3798. **
  3799. ** <ul>
  3800. ** <li> 64-bit signed integer
  3801. ** <li> 64-bit IEEE floating point number
  3802. ** <li> string
  3803. ** <li> BLOB
  3804. ** <li> NULL
  3805. ** </ul>)^
  3806. **
  3807. ** These constants are codes for each of those types.
  3808. **
  3809. ** Note that the SQLITE_TEXT constant was also used in SQLite version 2
  3810. ** for a completely different meaning. Software that links against both
  3811. ** SQLite version 2 and SQLite version 3 should use SQLITE3_TEXT, not
  3812. ** SQLITE_TEXT.
  3813. */
  3814. #define SQLITE_INTEGER 1
  3815. #define SQLITE_FLOAT 2
  3816. #define SQLITE_BLOB 4
  3817. #define SQLITE_NULL 5
  3818. #ifdef SQLITE_TEXT
  3819. # undef SQLITE_TEXT
  3820. #else
  3821. # define SQLITE_TEXT 3
  3822. #endif
  3823. #define SQLITE3_TEXT 3
  3824. /*
  3825. ** CAPI3REF: Result Values From A Query
  3826. ** KEYWORDS: {column access functions}
  3827. **
  3828. ** These routines form the "result set" interface.
  3829. **
  3830. ** ^These routines return information about a single column of the current
  3831. ** result row of a query. ^In every case the first argument is a pointer
  3832. ** to the [prepared statement] that is being evaluated (the [sqlite3_stmt*]
  3833. ** that was returned from [sqlite3_prepare_v2()] or one of its variants)
  3834. ** and the second argument is the index of the column for which information
  3835. ** should be returned. ^The leftmost column of the result set has the index 0.
  3836. ** ^The number of columns in the result can be determined using
  3837. ** [sqlite3_column_count()].
  3838. **
  3839. ** If the SQL statement does not currently point to a valid row, or if the
  3840. ** column index is out of range, the result is undefined.
  3841. ** These routines may only be called when the most recent call to
  3842. ** [sqlite3_step()] has returned [SQLITE_ROW] and neither
  3843. ** [sqlite3_reset()] nor [sqlite3_finalize()] have been called subsequently.
  3844. ** If any of these routines are called after [sqlite3_reset()] or
  3845. ** [sqlite3_finalize()] or after [sqlite3_step()] has returned
  3846. ** something other than [SQLITE_ROW], the results are undefined.
  3847. ** If [sqlite3_step()] or [sqlite3_reset()] or [sqlite3_finalize()]
  3848. ** are called from a different thread while any of these routines
  3849. ** are pending, then the results are undefined.
  3850. **
  3851. ** ^The sqlite3_column_type() routine returns the
  3852. ** [SQLITE_INTEGER | datatype code] for the initial data type
  3853. ** of the result column. ^The returned value is one of [SQLITE_INTEGER],
  3854. ** [SQLITE_FLOAT], [SQLITE_TEXT], [SQLITE_BLOB], or [SQLITE_NULL]. The value
  3855. ** returned by sqlite3_column_type() is only meaningful if no type
  3856. ** conversions have occurred as described below. After a type conversion,
  3857. ** the value returned by sqlite3_column_type() is undefined. Future
  3858. ** versions of SQLite may change the behavior of sqlite3_column_type()
  3859. ** following a type conversion.
  3860. **
  3861. ** ^If the result is a BLOB or UTF-8 string then the sqlite3_column_bytes()
  3862. ** routine returns the number of bytes in that BLOB or string.
  3863. ** ^If the result is a UTF-16 string, then sqlite3_column_bytes() converts
  3864. ** the string to UTF-8 and then returns the number of bytes.
  3865. ** ^If the result is a numeric value then sqlite3_column_bytes() uses
  3866. ** [sqlite3_snprintf()] to convert that value to a UTF-8 string and returns
  3867. ** the number of bytes in that string.
  3868. ** ^If the result is NULL, then sqlite3_column_bytes() returns zero.
  3869. **
  3870. ** ^If the result is a BLOB or UTF-16 string then the sqlite3_column_bytes16()
  3871. ** routine returns the number of bytes in that BLOB or string.
  3872. ** ^If the result is a UTF-8 string, then sqlite3_column_bytes16() converts
  3873. ** the string to UTF-16 and then returns the number of bytes.
  3874. ** ^If the result is a numeric value then sqlite3_column_bytes16() uses
  3875. ** [sqlite3_snprintf()] to convert that value to a UTF-16 string and returns
  3876. ** the number of bytes in that string.
  3877. ** ^If the result is NULL, then sqlite3_column_bytes16() returns zero.
  3878. **
  3879. ** ^The values returned by [sqlite3_column_bytes()] and
  3880. ** [sqlite3_column_bytes16()] do not include the zero terminators at the end
  3881. ** of the string. ^For clarity: the values returned by
  3882. ** [sqlite3_column_bytes()] and [sqlite3_column_bytes16()] are the number of
  3883. ** bytes in the string, not the number of characters.
  3884. **
  3885. ** ^Strings returned by sqlite3_column_text() and sqlite3_column_text16(),
  3886. ** even empty strings, are always zero-terminated. ^The return
  3887. ** value from sqlite3_column_blob() for a zero-length BLOB is a NULL pointer.
  3888. **
  3889. ** ^The object returned by [sqlite3_column_value()] is an
  3890. ** [unprotected sqlite3_value] object. An unprotected sqlite3_value object
  3891. ** may only be used with [sqlite3_bind_value()] and [sqlite3_result_value()].
  3892. ** If the [unprotected sqlite3_value] object returned by
  3893. ** [sqlite3_column_value()] is used in any other way, including calls
  3894. ** to routines like [sqlite3_value_int()], [sqlite3_value_text()],
  3895. ** or [sqlite3_value_bytes()], then the behavior is undefined.
  3896. **
  3897. ** These routines attempt to convert the value where appropriate. ^For
  3898. ** example, if the internal representation is FLOAT and a text result
  3899. ** is requested, [sqlite3_snprintf()] is used internally to perform the
  3900. ** conversion automatically. ^(The following table details the conversions
  3901. ** that are applied:
  3902. **
  3903. ** <blockquote>
  3904. ** <table border="1">
  3905. ** <tr><th> Internal<br>Type <th> Requested<br>Type <th> Conversion
  3906. **
  3907. ** <tr><td> NULL <td> INTEGER <td> Result is 0
  3908. ** <tr><td> NULL <td> FLOAT <td> Result is 0.0
  3909. ** <tr><td> NULL <td> TEXT <td> Result is a NULL pointer
  3910. ** <tr><td> NULL <td> BLOB <td> Result is a NULL pointer
  3911. ** <tr><td> INTEGER <td> FLOAT <td> Convert from integer to float
  3912. ** <tr><td> INTEGER <td> TEXT <td> ASCII rendering of the integer
  3913. ** <tr><td> INTEGER <td> BLOB <td> Same as INTEGER->TEXT
  3914. ** <tr><td> FLOAT <td> INTEGER <td> [CAST] to INTEGER
  3915. ** <tr><td> FLOAT <td> TEXT <td> ASCII rendering of the float
  3916. ** <tr><td> FLOAT <td> BLOB <td> [CAST] to BLOB
  3917. ** <tr><td> TEXT <td> INTEGER <td> [CAST] to INTEGER
  3918. ** <tr><td> TEXT <td> FLOAT <td> [CAST] to REAL
  3919. ** <tr><td> TEXT <td> BLOB <td> No change
  3920. ** <tr><td> BLOB <td> INTEGER <td> [CAST] to INTEGER
  3921. ** <tr><td> BLOB <td> FLOAT <td> [CAST] to REAL
  3922. ** <tr><td> BLOB <td> TEXT <td> Add a zero terminator if needed
  3923. ** </table>
  3924. ** </blockquote>)^
  3925. **
  3926. ** The table above makes reference to standard C library functions atoi()
  3927. ** and atof(). SQLite does not really use these functions. It has its
  3928. ** own equivalent internal routines. The atoi() and atof() names are
  3929. ** used in the table for brevity and because they are familiar to most
  3930. ** C programmers.
  3931. **
  3932. ** Note that when type conversions occur, pointers returned by prior
  3933. ** calls to sqlite3_column_blob(), sqlite3_column_text(), and/or
  3934. ** sqlite3_column_text16() may be invalidated.
  3935. ** Type conversions and pointer invalidations might occur
  3936. ** in the following cases:
  3937. **
  3938. ** <ul>
  3939. ** <li> The initial content is a BLOB and sqlite3_column_text() or
  3940. ** sqlite3_column_text16() is called. A zero-terminator might
  3941. ** need to be added to the string.</li>
  3942. ** <li> The initial content is UTF-8 text and sqlite3_column_bytes16() or
  3943. ** sqlite3_column_text16() is called. The content must be converted
  3944. ** to UTF-16.</li>
  3945. ** <li> The initial content is UTF-16 text and sqlite3_column_bytes() or
  3946. ** sqlite3_column_text() is called. The content must be converted
  3947. ** to UTF-8.</li>
  3948. ** </ul>
  3949. **
  3950. ** ^Conversions between UTF-16be and UTF-16le are always done in place and do
  3951. ** not invalidate a prior pointer, though of course the content of the buffer
  3952. ** that the prior pointer references will have been modified. Other kinds
  3953. ** of conversion are done in place when it is possible, but sometimes they
  3954. ** are not possible and in those cases prior pointers are invalidated.
  3955. **
  3956. ** The safest and easiest to remember policy is to invoke these routines
  3957. ** in one of the following ways:
  3958. **
  3959. ** <ul>
  3960. ** <li>sqlite3_column_text() followed by sqlite3_column_bytes()</li>
  3961. ** <li>sqlite3_column_blob() followed by sqlite3_column_bytes()</li>
  3962. ** <li>sqlite3_column_text16() followed by sqlite3_column_bytes16()</li>
  3963. ** </ul>
  3964. **
  3965. ** In other words, you should call sqlite3_column_text(),
  3966. ** sqlite3_column_blob(), or sqlite3_column_text16() first to force the result
  3967. ** into the desired format, then invoke sqlite3_column_bytes() or
  3968. ** sqlite3_column_bytes16() to find the size of the result. Do not mix calls
  3969. ** to sqlite3_column_text() or sqlite3_column_blob() with calls to
  3970. ** sqlite3_column_bytes16(), and do not mix calls to sqlite3_column_text16()
  3971. ** with calls to sqlite3_column_bytes().
  3972. **
  3973. ** ^The pointers returned are valid until a type conversion occurs as
  3974. ** described above, or until [sqlite3_step()] or [sqlite3_reset()] or
  3975. ** [sqlite3_finalize()] is called. ^The memory space used to hold strings
  3976. ** and BLOBs is freed automatically. Do <b>not</b> pass the pointers returned
  3977. ** from [sqlite3_column_blob()], [sqlite3_column_text()], etc. into
  3978. ** [sqlite3_free()].
  3979. **
  3980. ** ^(If a memory allocation error occurs during the evaluation of any
  3981. ** of these routines, a default value is returned. The default value
  3982. ** is either the integer 0, the floating point number 0.0, or a NULL
  3983. ** pointer. Subsequent calls to [sqlite3_errcode()] will return
  3984. ** [SQLITE_NOMEM].)^
  3985. */
  3986. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt*, int iCol);
  3987. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt*, int iCol);
  3988. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt*, int iCol);
  3989. SQLITE_API double sqlite3_column_double(sqlite3_stmt*, int iCol);
  3990. SQLITE_API int sqlite3_column_int(sqlite3_stmt*, int iCol);
  3991. SQLITE_API sqlite3_int64 sqlite3_column_int64(sqlite3_stmt*, int iCol);
  3992. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt*, int iCol);
  3993. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt*, int iCol);
  3994. SQLITE_API int sqlite3_column_type(sqlite3_stmt*, int iCol);
  3995. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt*, int iCol);
  3996. /*
  3997. ** CAPI3REF: Destroy A Prepared Statement Object
  3998. **
  3999. ** ^The sqlite3_finalize() function is called to delete a [prepared statement].
  4000. ** ^If the most recent evaluation of the statement encountered no errors
  4001. ** or if the statement is never been evaluated, then sqlite3_finalize() returns
  4002. ** SQLITE_OK. ^If the most recent evaluation of statement S failed, then
  4003. ** sqlite3_finalize(S) returns the appropriate [error code] or
  4004. ** [extended error code].
  4005. **
  4006. ** ^The sqlite3_finalize(S) routine can be called at any point during
  4007. ** the life cycle of [prepared statement] S:
  4008. ** before statement S is ever evaluated, after
  4009. ** one or more calls to [sqlite3_reset()], or after any call
  4010. ** to [sqlite3_step()] regardless of whether or not the statement has
  4011. ** completed execution.
  4012. **
  4013. ** ^Invoking sqlite3_finalize() on a NULL pointer is a harmless no-op.
  4014. **
  4015. ** The application must finalize every [prepared statement] in order to avoid
  4016. ** resource leaks. It is a grievous error for the application to try to use
  4017. ** a prepared statement after it has been finalized. Any use of a prepared
  4018. ** statement after it has been finalized can result in undefined and
  4019. ** undesirable behavior such as segfaults and heap corruption.
  4020. */
  4021. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt);
  4022. /*
  4023. ** CAPI3REF: Reset A Prepared Statement Object
  4024. **
  4025. ** The sqlite3_reset() function is called to reset a [prepared statement]
  4026. ** object back to its initial state, ready to be re-executed.
  4027. ** ^Any SQL statement variables that had values bound to them using
  4028. ** the [sqlite3_bind_blob | sqlite3_bind_*() API] retain their values.
  4029. ** Use [sqlite3_clear_bindings()] to reset the bindings.
  4030. **
  4031. ** ^The [sqlite3_reset(S)] interface resets the [prepared statement] S
  4032. ** back to the beginning of its program.
  4033. **
  4034. ** ^If the most recent call to [sqlite3_step(S)] for the
  4035. ** [prepared statement] S returned [SQLITE_ROW] or [SQLITE_DONE],
  4036. ** or if [sqlite3_step(S)] has never before been called on S,
  4037. ** then [sqlite3_reset(S)] returns [SQLITE_OK].
  4038. **
  4039. ** ^If the most recent call to [sqlite3_step(S)] for the
  4040. ** [prepared statement] S indicated an error, then
  4041. ** [sqlite3_reset(S)] returns an appropriate [error code].
  4042. **
  4043. ** ^The [sqlite3_reset(S)] interface does not change the values
  4044. ** of any [sqlite3_bind_blob|bindings] on the [prepared statement] S.
  4045. */
  4046. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt);
  4047. /*
  4048. ** CAPI3REF: Create Or Redefine SQL Functions
  4049. ** KEYWORDS: {function creation routines}
  4050. ** KEYWORDS: {application-defined SQL function}
  4051. ** KEYWORDS: {application-defined SQL functions}
  4052. **
  4053. ** ^These functions (collectively known as "function creation routines")
  4054. ** are used to add SQL functions or aggregates or to redefine the behavior
  4055. ** of existing SQL functions or aggregates. The only differences between
  4056. ** these routines are the text encoding expected for
  4057. ** the second parameter (the name of the function being created)
  4058. ** and the presence or absence of a destructor callback for
  4059. ** the application data pointer.
  4060. **
  4061. ** ^The first parameter is the [database connection] to which the SQL
  4062. ** function is to be added. ^If an application uses more than one database
  4063. ** connection then application-defined SQL functions must be added
  4064. ** to each database connection separately.
  4065. **
  4066. ** ^The second parameter is the name of the SQL function to be created or
  4067. ** redefined. ^The length of the name is limited to 255 bytes in a UTF-8
  4068. ** representation, exclusive of the zero-terminator. ^Note that the name
  4069. ** length limit is in UTF-8 bytes, not characters nor UTF-16 bytes.
  4070. ** ^Any attempt to create a function with a longer name
  4071. ** will result in [SQLITE_MISUSE] being returned.
  4072. **
  4073. ** ^The third parameter (nArg)
  4074. ** is the number of arguments that the SQL function or
  4075. ** aggregate takes. ^If this parameter is -1, then the SQL function or
  4076. ** aggregate may take any number of arguments between 0 and the limit
  4077. ** set by [sqlite3_limit]([SQLITE_LIMIT_FUNCTION_ARG]). If the third
  4078. ** parameter is less than -1 or greater than 127 then the behavior is
  4079. ** undefined.
  4080. **
  4081. ** ^The fourth parameter, eTextRep, specifies what
  4082. ** [SQLITE_UTF8 | text encoding] this SQL function prefers for
  4083. ** its parameters. The application should set this parameter to
  4084. ** [SQLITE_UTF16LE] if the function implementation invokes
  4085. ** [sqlite3_value_text16le()] on an input, or [SQLITE_UTF16BE] if the
  4086. ** implementation invokes [sqlite3_value_text16be()] on an input, or
  4087. ** [SQLITE_UTF16] if [sqlite3_value_text16()] is used, or [SQLITE_UTF8]
  4088. ** otherwise. ^The same SQL function may be registered multiple times using
  4089. ** different preferred text encodings, with different implementations for
  4090. ** each encoding.
  4091. ** ^When multiple implementations of the same function are available, SQLite
  4092. ** will pick the one that involves the least amount of data conversion.
  4093. **
  4094. ** ^The fourth parameter may optionally be ORed with [SQLITE_DETERMINISTIC]
  4095. ** to signal that the function will always return the same result given
  4096. ** the same inputs within a single SQL statement. Most SQL functions are
  4097. ** deterministic. The built-in [random()] SQL function is an example of a
  4098. ** function that is not deterministic. The SQLite query planner is able to
  4099. ** perform additional optimizations on deterministic functions, so use
  4100. ** of the [SQLITE_DETERMINISTIC] flag is recommended where possible.
  4101. **
  4102. ** ^(The fifth parameter is an arbitrary pointer. The implementation of the
  4103. ** function can gain access to this pointer using [sqlite3_user_data()].)^
  4104. **
  4105. ** ^The sixth, seventh and eighth parameters, xFunc, xStep and xFinal, are
  4106. ** pointers to C-language functions that implement the SQL function or
  4107. ** aggregate. ^A scalar SQL function requires an implementation of the xFunc
  4108. ** callback only; NULL pointers must be passed as the xStep and xFinal
  4109. ** parameters. ^An aggregate SQL function requires an implementation of xStep
  4110. ** and xFinal and NULL pointer must be passed for xFunc. ^To delete an existing
  4111. ** SQL function or aggregate, pass NULL pointers for all three function
  4112. ** callbacks.
  4113. **
  4114. ** ^(If the ninth parameter to sqlite3_create_function_v2() is not NULL,
  4115. ** then it is destructor for the application data pointer.
  4116. ** The destructor is invoked when the function is deleted, either by being
  4117. ** overloaded or when the database connection closes.)^
  4118. ** ^The destructor is also invoked if the call to
  4119. ** sqlite3_create_function_v2() fails.
  4120. ** ^When the destructor callback of the tenth parameter is invoked, it
  4121. ** is passed a single argument which is a copy of the application data
  4122. ** pointer which was the fifth parameter to sqlite3_create_function_v2().
  4123. **
  4124. ** ^It is permitted to register multiple implementations of the same
  4125. ** functions with the same name but with either differing numbers of
  4126. ** arguments or differing preferred text encodings. ^SQLite will use
  4127. ** the implementation that most closely matches the way in which the
  4128. ** SQL function is used. ^A function implementation with a non-negative
  4129. ** nArg parameter is a better match than a function implementation with
  4130. ** a negative nArg. ^A function where the preferred text encoding
  4131. ** matches the database encoding is a better
  4132. ** match than a function where the encoding is different.
  4133. ** ^A function where the encoding difference is between UTF16le and UTF16be
  4134. ** is a closer match than a function where the encoding difference is
  4135. ** between UTF8 and UTF16.
  4136. **
  4137. ** ^Built-in functions may be overloaded by new application-defined functions.
  4138. **
  4139. ** ^An application-defined function is permitted to call other
  4140. ** SQLite interfaces. However, such calls must not
  4141. ** close the database connection nor finalize or reset the prepared
  4142. ** statement in which the function is running.
  4143. */
  4144. SQLITE_API int sqlite3_create_function(
  4145. sqlite3 *db,
  4146. const char *zFunctionName,
  4147. int nArg,
  4148. int eTextRep,
  4149. void *pApp,
  4150. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4151. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4152. void (*xFinal)(sqlite3_context*)
  4153. );
  4154. SQLITE_API int sqlite3_create_function16(
  4155. sqlite3 *db,
  4156. const void *zFunctionName,
  4157. int nArg,
  4158. int eTextRep,
  4159. void *pApp,
  4160. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4161. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4162. void (*xFinal)(sqlite3_context*)
  4163. );
  4164. SQLITE_API int sqlite3_create_function_v2(
  4165. sqlite3 *db,
  4166. const char *zFunctionName,
  4167. int nArg,
  4168. int eTextRep,
  4169. void *pApp,
  4170. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  4171. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  4172. void (*xFinal)(sqlite3_context*),
  4173. void(*xDestroy)(void*)
  4174. );
  4175. /*
  4176. ** CAPI3REF: Text Encodings
  4177. **
  4178. ** These constant define integer codes that represent the various
  4179. ** text encodings supported by SQLite.
  4180. */
  4181. #define SQLITE_UTF8 1
  4182. #define SQLITE_UTF16LE 2
  4183. #define SQLITE_UTF16BE 3
  4184. #define SQLITE_UTF16 4 /* Use native byte order */
  4185. #define SQLITE_ANY 5 /* Deprecated */
  4186. #define SQLITE_UTF16_ALIGNED 8 /* sqlite3_create_collation only */
  4187. /*
  4188. ** CAPI3REF: Function Flags
  4189. **
  4190. ** These constants may be ORed together with the
  4191. ** [SQLITE_UTF8 | preferred text encoding] as the fourth argument
  4192. ** to [sqlite3_create_function()], [sqlite3_create_function16()], or
  4193. ** [sqlite3_create_function_v2()].
  4194. */
  4195. #define SQLITE_DETERMINISTIC 0x800
  4196. /*
  4197. ** CAPI3REF: Deprecated Functions
  4198. ** DEPRECATED
  4199. **
  4200. ** These functions are [deprecated]. In order to maintain
  4201. ** backwards compatibility with older code, these functions continue
  4202. ** to be supported. However, new applications should avoid
  4203. ** the use of these functions. To help encourage people to avoid
  4204. ** using these functions, we are not going to tell you what they do.
  4205. */
  4206. #ifndef SQLITE_OMIT_DEPRECATED
  4207. SQLITE_API SQLITE_DEPRECATED int sqlite3_aggregate_count(sqlite3_context*);
  4208. SQLITE_API SQLITE_DEPRECATED int sqlite3_expired(sqlite3_stmt*);
  4209. SQLITE_API SQLITE_DEPRECATED int sqlite3_transfer_bindings(sqlite3_stmt*, sqlite3_stmt*);
  4210. SQLITE_API SQLITE_DEPRECATED int sqlite3_global_recover(void);
  4211. SQLITE_API SQLITE_DEPRECATED void sqlite3_thread_cleanup(void);
  4212. SQLITE_API SQLITE_DEPRECATED int sqlite3_memory_alarm(void(*)(void*,sqlite3_int64,int),
  4213. void*,sqlite3_int64);
  4214. #endif
  4215. /*
  4216. ** CAPI3REF: Obtaining SQL Function Parameter Values
  4217. **
  4218. ** The C-language implementation of SQL functions and aggregates uses
  4219. ** this set of interface routines to access the parameter values on
  4220. ** the function or aggregate.
  4221. **
  4222. ** The xFunc (for scalar functions) or xStep (for aggregates) parameters
  4223. ** to [sqlite3_create_function()] and [sqlite3_create_function16()]
  4224. ** define callbacks that implement the SQL functions and aggregates.
  4225. ** The 3rd parameter to these callbacks is an array of pointers to
  4226. ** [protected sqlite3_value] objects. There is one [sqlite3_value] object for
  4227. ** each parameter to the SQL function. These routines are used to
  4228. ** extract values from the [sqlite3_value] objects.
  4229. **
  4230. ** These routines work only with [protected sqlite3_value] objects.
  4231. ** Any attempt to use these routines on an [unprotected sqlite3_value]
  4232. ** object results in undefined behavior.
  4233. **
  4234. ** ^These routines work just like the corresponding [column access functions]
  4235. ** except that these routines take a single [protected sqlite3_value] object
  4236. ** pointer instead of a [sqlite3_stmt*] pointer and an integer column number.
  4237. **
  4238. ** ^The sqlite3_value_text16() interface extracts a UTF-16 string
  4239. ** in the native byte-order of the host machine. ^The
  4240. ** sqlite3_value_text16be() and sqlite3_value_text16le() interfaces
  4241. ** extract UTF-16 strings as big-endian and little-endian respectively.
  4242. **
  4243. ** ^(The sqlite3_value_numeric_type() interface attempts to apply
  4244. ** numeric affinity to the value. This means that an attempt is
  4245. ** made to convert the value to an integer or floating point. If
  4246. ** such a conversion is possible without loss of information (in other
  4247. ** words, if the value is a string that looks like a number)
  4248. ** then the conversion is performed. Otherwise no conversion occurs.
  4249. ** The [SQLITE_INTEGER | datatype] after conversion is returned.)^
  4250. **
  4251. ** Please pay particular attention to the fact that the pointer returned
  4252. ** from [sqlite3_value_blob()], [sqlite3_value_text()], or
  4253. ** [sqlite3_value_text16()] can be invalidated by a subsequent call to
  4254. ** [sqlite3_value_bytes()], [sqlite3_value_bytes16()], [sqlite3_value_text()],
  4255. ** or [sqlite3_value_text16()].
  4256. **
  4257. ** These routines must be called from the same thread as
  4258. ** the SQL function that supplied the [sqlite3_value*] parameters.
  4259. */
  4260. SQLITE_API const void *sqlite3_value_blob(sqlite3_value*);
  4261. SQLITE_API int sqlite3_value_bytes(sqlite3_value*);
  4262. SQLITE_API int sqlite3_value_bytes16(sqlite3_value*);
  4263. SQLITE_API double sqlite3_value_double(sqlite3_value*);
  4264. SQLITE_API int sqlite3_value_int(sqlite3_value*);
  4265. SQLITE_API sqlite3_int64 sqlite3_value_int64(sqlite3_value*);
  4266. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value*);
  4267. SQLITE_API const void *sqlite3_value_text16(sqlite3_value*);
  4268. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value*);
  4269. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value*);
  4270. SQLITE_API int sqlite3_value_type(sqlite3_value*);
  4271. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value*);
  4272. /*
  4273. ** CAPI3REF: Obtain Aggregate Function Context
  4274. **
  4275. ** Implementations of aggregate SQL functions use this
  4276. ** routine to allocate memory for storing their state.
  4277. **
  4278. ** ^The first time the sqlite3_aggregate_context(C,N) routine is called
  4279. ** for a particular aggregate function, SQLite
  4280. ** allocates N of memory, zeroes out that memory, and returns a pointer
  4281. ** to the new memory. ^On second and subsequent calls to
  4282. ** sqlite3_aggregate_context() for the same aggregate function instance,
  4283. ** the same buffer is returned. Sqlite3_aggregate_context() is normally
  4284. ** called once for each invocation of the xStep callback and then one
  4285. ** last time when the xFinal callback is invoked. ^(When no rows match
  4286. ** an aggregate query, the xStep() callback of the aggregate function
  4287. ** implementation is never called and xFinal() is called exactly once.
  4288. ** In those cases, sqlite3_aggregate_context() might be called for the
  4289. ** first time from within xFinal().)^
  4290. **
  4291. ** ^The sqlite3_aggregate_context(C,N) routine returns a NULL pointer
  4292. ** when first called if N is less than or equal to zero or if a memory
  4293. ** allocate error occurs.
  4294. **
  4295. ** ^(The amount of space allocated by sqlite3_aggregate_context(C,N) is
  4296. ** determined by the N parameter on first successful call. Changing the
  4297. ** value of N in subsequent call to sqlite3_aggregate_context() within
  4298. ** the same aggregate function instance will not resize the memory
  4299. ** allocation.)^ Within the xFinal callback, it is customary to set
  4300. ** N=0 in calls to sqlite3_aggregate_context(C,N) so that no
  4301. ** pointless memory allocations occur.
  4302. **
  4303. ** ^SQLite automatically frees the memory allocated by
  4304. ** sqlite3_aggregate_context() when the aggregate query concludes.
  4305. **
  4306. ** The first parameter must be a copy of the
  4307. ** [sqlite3_context | SQL function context] that is the first parameter
  4308. ** to the xStep or xFinal callback routine that implements the aggregate
  4309. ** function.
  4310. **
  4311. ** This routine must be called from the same thread in which
  4312. ** the aggregate SQL function is running.
  4313. */
  4314. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context*, int nBytes);
  4315. /*
  4316. ** CAPI3REF: User Data For Functions
  4317. **
  4318. ** ^The sqlite3_user_data() interface returns a copy of
  4319. ** the pointer that was the pUserData parameter (the 5th parameter)
  4320. ** of the [sqlite3_create_function()]
  4321. ** and [sqlite3_create_function16()] routines that originally
  4322. ** registered the application defined function.
  4323. **
  4324. ** This routine must be called from the same thread in which
  4325. ** the application-defined function is running.
  4326. */
  4327. SQLITE_API void *sqlite3_user_data(sqlite3_context*);
  4328. /*
  4329. ** CAPI3REF: Database Connection For Functions
  4330. **
  4331. ** ^The sqlite3_context_db_handle() interface returns a copy of
  4332. ** the pointer to the [database connection] (the 1st parameter)
  4333. ** of the [sqlite3_create_function()]
  4334. ** and [sqlite3_create_function16()] routines that originally
  4335. ** registered the application defined function.
  4336. */
  4337. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context*);
  4338. /*
  4339. ** CAPI3REF: Function Auxiliary Data
  4340. **
  4341. ** These functions may be used by (non-aggregate) SQL functions to
  4342. ** associate metadata with argument values. If the same value is passed to
  4343. ** multiple invocations of the same SQL function during query execution, under
  4344. ** some circumstances the associated metadata may be preserved. An example
  4345. ** of where this might be useful is in a regular-expression matching
  4346. ** function. The compiled version of the regular expression can be stored as
  4347. ** metadata associated with the pattern string.
  4348. ** Then as long as the pattern string remains the same,
  4349. ** the compiled regular expression can be reused on multiple
  4350. ** invocations of the same function.
  4351. **
  4352. ** ^The sqlite3_get_auxdata() interface returns a pointer to the metadata
  4353. ** associated by the sqlite3_set_auxdata() function with the Nth argument
  4354. ** value to the application-defined function. ^If there is no metadata
  4355. ** associated with the function argument, this sqlite3_get_auxdata() interface
  4356. ** returns a NULL pointer.
  4357. **
  4358. ** ^The sqlite3_set_auxdata(C,N,P,X) interface saves P as metadata for the N-th
  4359. ** argument of the application-defined function. ^Subsequent
  4360. ** calls to sqlite3_get_auxdata(C,N) return P from the most recent
  4361. ** sqlite3_set_auxdata(C,N,P,X) call if the metadata is still valid or
  4362. ** NULL if the metadata has been discarded.
  4363. ** ^After each call to sqlite3_set_auxdata(C,N,P,X) where X is not NULL,
  4364. ** SQLite will invoke the destructor function X with parameter P exactly
  4365. ** once, when the metadata is discarded.
  4366. ** SQLite is free to discard the metadata at any time, including: <ul>
  4367. ** <li> when the corresponding function parameter changes, or
  4368. ** <li> when [sqlite3_reset()] or [sqlite3_finalize()] is called for the
  4369. ** SQL statement, or
  4370. ** <li> when sqlite3_set_auxdata() is invoked again on the same parameter, or
  4371. ** <li> during the original sqlite3_set_auxdata() call when a memory
  4372. ** allocation error occurs. </ul>)^
  4373. **
  4374. ** Note the last bullet in particular. The destructor X in
  4375. ** sqlite3_set_auxdata(C,N,P,X) might be called immediately, before the
  4376. ** sqlite3_set_auxdata() interface even returns. Hence sqlite3_set_auxdata()
  4377. ** should be called near the end of the function implementation and the
  4378. ** function implementation should not make any use of P after
  4379. ** sqlite3_set_auxdata() has been called.
  4380. **
  4381. ** ^(In practice, metadata is preserved between function calls for
  4382. ** function parameters that are compile-time constants, including literal
  4383. ** values and [parameters] and expressions composed from the same.)^
  4384. **
  4385. ** These routines must be called from the same thread in which
  4386. ** the SQL function is running.
  4387. */
  4388. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context*, int N);
  4389. SQLITE_API void sqlite3_set_auxdata(sqlite3_context*, int N, void*, void (*)(void*));
  4390. /*
  4391. ** CAPI3REF: Constants Defining Special Destructor Behavior
  4392. **
  4393. ** These are special values for the destructor that is passed in as the
  4394. ** final argument to routines like [sqlite3_result_blob()]. ^If the destructor
  4395. ** argument is SQLITE_STATIC, it means that the content pointer is constant
  4396. ** and will never change. It does not need to be destroyed. ^The
  4397. ** SQLITE_TRANSIENT value means that the content will likely change in
  4398. ** the near future and that SQLite should make its own private copy of
  4399. ** the content before returning.
  4400. **
  4401. ** The typedef is necessary to work around problems in certain
  4402. ** C++ compilers.
  4403. */
  4404. typedef void (*sqlite3_destructor_type)(void*);
  4405. #define SQLITE_STATIC ((sqlite3_destructor_type)0)
  4406. #define SQLITE_TRANSIENT ((sqlite3_destructor_type)-1)
  4407. /*
  4408. ** CAPI3REF: Setting The Result Of An SQL Function
  4409. **
  4410. ** These routines are used by the xFunc or xFinal callbacks that
  4411. ** implement SQL functions and aggregates. See
  4412. ** [sqlite3_create_function()] and [sqlite3_create_function16()]
  4413. ** for additional information.
  4414. **
  4415. ** These functions work very much like the [parameter binding] family of
  4416. ** functions used to bind values to host parameters in prepared statements.
  4417. ** Refer to the [SQL parameter] documentation for additional information.
  4418. **
  4419. ** ^The sqlite3_result_blob() interface sets the result from
  4420. ** an application-defined function to be the BLOB whose content is pointed
  4421. ** to by the second parameter and which is N bytes long where N is the
  4422. ** third parameter.
  4423. **
  4424. ** ^The sqlite3_result_zeroblob() interfaces set the result of
  4425. ** the application-defined function to be a BLOB containing all zero
  4426. ** bytes and N bytes in size, where N is the value of the 2nd parameter.
  4427. **
  4428. ** ^The sqlite3_result_double() interface sets the result from
  4429. ** an application-defined function to be a floating point value specified
  4430. ** by its 2nd argument.
  4431. **
  4432. ** ^The sqlite3_result_error() and sqlite3_result_error16() functions
  4433. ** cause the implemented SQL function to throw an exception.
  4434. ** ^SQLite uses the string pointed to by the
  4435. ** 2nd parameter of sqlite3_result_error() or sqlite3_result_error16()
  4436. ** as the text of an error message. ^SQLite interprets the error
  4437. ** message string from sqlite3_result_error() as UTF-8. ^SQLite
  4438. ** interprets the string from sqlite3_result_error16() as UTF-16 in native
  4439. ** byte order. ^If the third parameter to sqlite3_result_error()
  4440. ** or sqlite3_result_error16() is negative then SQLite takes as the error
  4441. ** message all text up through the first zero character.
  4442. ** ^If the third parameter to sqlite3_result_error() or
  4443. ** sqlite3_result_error16() is non-negative then SQLite takes that many
  4444. ** bytes (not characters) from the 2nd parameter as the error message.
  4445. ** ^The sqlite3_result_error() and sqlite3_result_error16()
  4446. ** routines make a private copy of the error message text before
  4447. ** they return. Hence, the calling function can deallocate or
  4448. ** modify the text after they return without harm.
  4449. ** ^The sqlite3_result_error_code() function changes the error code
  4450. ** returned by SQLite as a result of an error in a function. ^By default,
  4451. ** the error code is SQLITE_ERROR. ^A subsequent call to sqlite3_result_error()
  4452. ** or sqlite3_result_error16() resets the error code to SQLITE_ERROR.
  4453. **
  4454. ** ^The sqlite3_result_error_toobig() interface causes SQLite to throw an
  4455. ** error indicating that a string or BLOB is too long to represent.
  4456. **
  4457. ** ^The sqlite3_result_error_nomem() interface causes SQLite to throw an
  4458. ** error indicating that a memory allocation failed.
  4459. **
  4460. ** ^The sqlite3_result_int() interface sets the return value
  4461. ** of the application-defined function to be the 32-bit signed integer
  4462. ** value given in the 2nd argument.
  4463. ** ^The sqlite3_result_int64() interface sets the return value
  4464. ** of the application-defined function to be the 64-bit signed integer
  4465. ** value given in the 2nd argument.
  4466. **
  4467. ** ^The sqlite3_result_null() interface sets the return value
  4468. ** of the application-defined function to be NULL.
  4469. **
  4470. ** ^The sqlite3_result_text(), sqlite3_result_text16(),
  4471. ** sqlite3_result_text16le(), and sqlite3_result_text16be() interfaces
  4472. ** set the return value of the application-defined function to be
  4473. ** a text string which is represented as UTF-8, UTF-16 native byte order,
  4474. ** UTF-16 little endian, or UTF-16 big endian, respectively.
  4475. ** ^The sqlite3_result_text64() interface sets the return value of an
  4476. ** application-defined function to be a text string in an encoding
  4477. ** specified by the fifth (and last) parameter, which must be one
  4478. ** of [SQLITE_UTF8], [SQLITE_UTF16], [SQLITE_UTF16BE], or [SQLITE_UTF16LE].
  4479. ** ^SQLite takes the text result from the application from
  4480. ** the 2nd parameter of the sqlite3_result_text* interfaces.
  4481. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4482. ** is negative, then SQLite takes result text from the 2nd parameter
  4483. ** through the first zero character.
  4484. ** ^If the 3rd parameter to the sqlite3_result_text* interfaces
  4485. ** is non-negative, then as many bytes (not characters) of the text
  4486. ** pointed to by the 2nd parameter are taken as the application-defined
  4487. ** function result. If the 3rd parameter is non-negative, then it
  4488. ** must be the byte offset into the string where the NUL terminator would
  4489. ** appear if the string where NUL terminated. If any NUL characters occur
  4490. ** in the string at a byte offset that is less than the value of the 3rd
  4491. ** parameter, then the resulting string will contain embedded NULs and the
  4492. ** result of expressions operating on strings with embedded NULs is undefined.
  4493. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4494. ** or sqlite3_result_blob is a non-NULL pointer, then SQLite calls that
  4495. ** function as the destructor on the text or BLOB result when it has
  4496. ** finished using that result.
  4497. ** ^If the 4th parameter to the sqlite3_result_text* interfaces or to
  4498. ** sqlite3_result_blob is the special constant SQLITE_STATIC, then SQLite
  4499. ** assumes that the text or BLOB result is in constant space and does not
  4500. ** copy the content of the parameter nor call a destructor on the content
  4501. ** when it has finished using that result.
  4502. ** ^If the 4th parameter to the sqlite3_result_text* interfaces
  4503. ** or sqlite3_result_blob is the special constant SQLITE_TRANSIENT
  4504. ** then SQLite makes a copy of the result into space obtained from
  4505. ** from [sqlite3_malloc()] before it returns.
  4506. **
  4507. ** ^The sqlite3_result_value() interface sets the result of
  4508. ** the application-defined function to be a copy the
  4509. ** [unprotected sqlite3_value] object specified by the 2nd parameter. ^The
  4510. ** sqlite3_result_value() interface makes a copy of the [sqlite3_value]
  4511. ** so that the [sqlite3_value] specified in the parameter may change or
  4512. ** be deallocated after sqlite3_result_value() returns without harm.
  4513. ** ^A [protected sqlite3_value] object may always be used where an
  4514. ** [unprotected sqlite3_value] object is required, so either
  4515. ** kind of [sqlite3_value] object can be used with this interface.
  4516. **
  4517. ** If these routines are called from within the different thread
  4518. ** than the one containing the application-defined function that received
  4519. ** the [sqlite3_context] pointer, the results are undefined.
  4520. */
  4521. SQLITE_API void sqlite3_result_blob(sqlite3_context*, const void*, int, void(*)(void*));
  4522. SQLITE_API void sqlite3_result_blob64(sqlite3_context*,const void*,sqlite3_uint64,void(*)(void*));
  4523. SQLITE_API void sqlite3_result_double(sqlite3_context*, double);
  4524. SQLITE_API void sqlite3_result_error(sqlite3_context*, const char*, int);
  4525. SQLITE_API void sqlite3_result_error16(sqlite3_context*, const void*, int);
  4526. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context*);
  4527. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context*);
  4528. SQLITE_API void sqlite3_result_error_code(sqlite3_context*, int);
  4529. SQLITE_API void sqlite3_result_int(sqlite3_context*, int);
  4530. SQLITE_API void sqlite3_result_int64(sqlite3_context*, sqlite3_int64);
  4531. SQLITE_API void sqlite3_result_null(sqlite3_context*);
  4532. SQLITE_API void sqlite3_result_text(sqlite3_context*, const char*, int, void(*)(void*));
  4533. SQLITE_API void sqlite3_result_text64(sqlite3_context*, const char*,sqlite3_uint64,
  4534. void(*)(void*), unsigned char encoding);
  4535. SQLITE_API void sqlite3_result_text16(sqlite3_context*, const void*, int, void(*)(void*));
  4536. SQLITE_API void sqlite3_result_text16le(sqlite3_context*, const void*, int,void(*)(void*));
  4537. SQLITE_API void sqlite3_result_text16be(sqlite3_context*, const void*, int,void(*)(void*));
  4538. SQLITE_API void sqlite3_result_value(sqlite3_context*, sqlite3_value*);
  4539. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context*, int n);
  4540. /*
  4541. ** CAPI3REF: Define New Collating Sequences
  4542. **
  4543. ** ^These functions add, remove, or modify a [collation] associated
  4544. ** with the [database connection] specified as the first argument.
  4545. **
  4546. ** ^The name of the collation is a UTF-8 string
  4547. ** for sqlite3_create_collation() and sqlite3_create_collation_v2()
  4548. ** and a UTF-16 string in native byte order for sqlite3_create_collation16().
  4549. ** ^Collation names that compare equal according to [sqlite3_strnicmp()] are
  4550. ** considered to be the same name.
  4551. **
  4552. ** ^(The third argument (eTextRep) must be one of the constants:
  4553. ** <ul>
  4554. ** <li> [SQLITE_UTF8],
  4555. ** <li> [SQLITE_UTF16LE],
  4556. ** <li> [SQLITE_UTF16BE],
  4557. ** <li> [SQLITE_UTF16], or
  4558. ** <li> [SQLITE_UTF16_ALIGNED].
  4559. ** </ul>)^
  4560. ** ^The eTextRep argument determines the encoding of strings passed
  4561. ** to the collating function callback, xCallback.
  4562. ** ^The [SQLITE_UTF16] and [SQLITE_UTF16_ALIGNED] values for eTextRep
  4563. ** force strings to be UTF16 with native byte order.
  4564. ** ^The [SQLITE_UTF16_ALIGNED] value for eTextRep forces strings to begin
  4565. ** on an even byte address.
  4566. **
  4567. ** ^The fourth argument, pArg, is an application data pointer that is passed
  4568. ** through as the first argument to the collating function callback.
  4569. **
  4570. ** ^The fifth argument, xCallback, is a pointer to the collating function.
  4571. ** ^Multiple collating functions can be registered using the same name but
  4572. ** with different eTextRep parameters and SQLite will use whichever
  4573. ** function requires the least amount of data transformation.
  4574. ** ^If the xCallback argument is NULL then the collating function is
  4575. ** deleted. ^When all collating functions having the same name are deleted,
  4576. ** that collation is no longer usable.
  4577. **
  4578. ** ^The collating function callback is invoked with a copy of the pArg
  4579. ** application data pointer and with two strings in the encoding specified
  4580. ** by the eTextRep argument. The collating function must return an
  4581. ** integer that is negative, zero, or positive
  4582. ** if the first string is less than, equal to, or greater than the second,
  4583. ** respectively. A collating function must always return the same answer
  4584. ** given the same inputs. If two or more collating functions are registered
  4585. ** to the same collation name (using different eTextRep values) then all
  4586. ** must give an equivalent answer when invoked with equivalent strings.
  4587. ** The collating function must obey the following properties for all
  4588. ** strings A, B, and C:
  4589. **
  4590. ** <ol>
  4591. ** <li> If A==B then B==A.
  4592. ** <li> If A==B and B==C then A==C.
  4593. ** <li> If A&lt;B THEN B&gt;A.
  4594. ** <li> If A&lt;B and B&lt;C then A&lt;C.
  4595. ** </ol>
  4596. **
  4597. ** If a collating function fails any of the above constraints and that
  4598. ** collating function is registered and used, then the behavior of SQLite
  4599. ** is undefined.
  4600. **
  4601. ** ^The sqlite3_create_collation_v2() works like sqlite3_create_collation()
  4602. ** with the addition that the xDestroy callback is invoked on pArg when
  4603. ** the collating function is deleted.
  4604. ** ^Collating functions are deleted when they are overridden by later
  4605. ** calls to the collation creation functions or when the
  4606. ** [database connection] is closed using [sqlite3_close()].
  4607. **
  4608. ** ^The xDestroy callback is <u>not</u> called if the
  4609. ** sqlite3_create_collation_v2() function fails. Applications that invoke
  4610. ** sqlite3_create_collation_v2() with a non-NULL xDestroy argument should
  4611. ** check the return code and dispose of the application data pointer
  4612. ** themselves rather than expecting SQLite to deal with it for them.
  4613. ** This is different from every other SQLite interface. The inconsistency
  4614. ** is unfortunate but cannot be changed without breaking backwards
  4615. ** compatibility.
  4616. **
  4617. ** See also: [sqlite3_collation_needed()] and [sqlite3_collation_needed16()].
  4618. */
  4619. SQLITE_API int sqlite3_create_collation(
  4620. sqlite3*,
  4621. const char *zName,
  4622. int eTextRep,
  4623. void *pArg,
  4624. int(*xCompare)(void*,int,const void*,int,const void*)
  4625. );
  4626. SQLITE_API int sqlite3_create_collation_v2(
  4627. sqlite3*,
  4628. const char *zName,
  4629. int eTextRep,
  4630. void *pArg,
  4631. int(*xCompare)(void*,int,const void*,int,const void*),
  4632. void(*xDestroy)(void*)
  4633. );
  4634. SQLITE_API int sqlite3_create_collation16(
  4635. sqlite3*,
  4636. const void *zName,
  4637. int eTextRep,
  4638. void *pArg,
  4639. int(*xCompare)(void*,int,const void*,int,const void*)
  4640. );
  4641. /*
  4642. ** CAPI3REF: Collation Needed Callbacks
  4643. **
  4644. ** ^To avoid having to register all collation sequences before a database
  4645. ** can be used, a single callback function may be registered with the
  4646. ** [database connection] to be invoked whenever an undefined collation
  4647. ** sequence is required.
  4648. **
  4649. ** ^If the function is registered using the sqlite3_collation_needed() API,
  4650. ** then it is passed the names of undefined collation sequences as strings
  4651. ** encoded in UTF-8. ^If sqlite3_collation_needed16() is used,
  4652. ** the names are passed as UTF-16 in machine native byte order.
  4653. ** ^A call to either function replaces the existing collation-needed callback.
  4654. **
  4655. ** ^(When the callback is invoked, the first argument passed is a copy
  4656. ** of the second argument to sqlite3_collation_needed() or
  4657. ** sqlite3_collation_needed16(). The second argument is the database
  4658. ** connection. The third argument is one of [SQLITE_UTF8], [SQLITE_UTF16BE],
  4659. ** or [SQLITE_UTF16LE], indicating the most desirable form of the collation
  4660. ** sequence function required. The fourth parameter is the name of the
  4661. ** required collation sequence.)^
  4662. **
  4663. ** The callback function should register the desired collation using
  4664. ** [sqlite3_create_collation()], [sqlite3_create_collation16()], or
  4665. ** [sqlite3_create_collation_v2()].
  4666. */
  4667. SQLITE_API int sqlite3_collation_needed(
  4668. sqlite3*,
  4669. void*,
  4670. void(*)(void*,sqlite3*,int eTextRep,const char*)
  4671. );
  4672. SQLITE_API int sqlite3_collation_needed16(
  4673. sqlite3*,
  4674. void*,
  4675. void(*)(void*,sqlite3*,int eTextRep,const void*)
  4676. );
  4677. #ifdef SQLITE_HAS_CODEC
  4678. /*
  4679. ** Specify the key for an encrypted database. This routine should be
  4680. ** called right after sqlite3_open().
  4681. **
  4682. ** The code to implement this API is not available in the public release
  4683. ** of SQLite.
  4684. */
  4685. SQLITE_API int sqlite3_key(
  4686. sqlite3 *db, /* Database to be rekeyed */
  4687. const void *pKey, int nKey /* The key */
  4688. );
  4689. SQLITE_API int sqlite3_key_v2(
  4690. sqlite3 *db, /* Database to be rekeyed */
  4691. const char *zDbName, /* Name of the database */
  4692. const void *pKey, int nKey /* The key */
  4693. );
  4694. /*
  4695. ** Change the key on an open database. If the current database is not
  4696. ** encrypted, this routine will encrypt it. If pNew==0 or nNew==0, the
  4697. ** database is decrypted.
  4698. **
  4699. ** The code to implement this API is not available in the public release
  4700. ** of SQLite.
  4701. */
  4702. SQLITE_API int sqlite3_rekey(
  4703. sqlite3 *db, /* Database to be rekeyed */
  4704. const void *pKey, int nKey /* The new key */
  4705. );
  4706. SQLITE_API int sqlite3_rekey_v2(
  4707. sqlite3 *db, /* Database to be rekeyed */
  4708. const char *zDbName, /* Name of the database */
  4709. const void *pKey, int nKey /* The new key */
  4710. );
  4711. /*
  4712. ** Specify the activation key for a SEE database. Unless
  4713. ** activated, none of the SEE routines will work.
  4714. */
  4715. SQLITE_API void sqlite3_activate_see(
  4716. const char *zPassPhrase /* Activation phrase */
  4717. );
  4718. #endif
  4719. #ifdef SQLITE_ENABLE_CEROD
  4720. /*
  4721. ** Specify the activation key for a CEROD database. Unless
  4722. ** activated, none of the CEROD routines will work.
  4723. */
  4724. SQLITE_API void sqlite3_activate_cerod(
  4725. const char *zPassPhrase /* Activation phrase */
  4726. );
  4727. #endif
  4728. /*
  4729. ** CAPI3REF: Suspend Execution For A Short Time
  4730. **
  4731. ** The sqlite3_sleep() function causes the current thread to suspend execution
  4732. ** for at least a number of milliseconds specified in its parameter.
  4733. **
  4734. ** If the operating system does not support sleep requests with
  4735. ** millisecond time resolution, then the time will be rounded up to
  4736. ** the nearest second. The number of milliseconds of sleep actually
  4737. ** requested from the operating system is returned.
  4738. **
  4739. ** ^SQLite implements this interface by calling the xSleep()
  4740. ** method of the default [sqlite3_vfs] object. If the xSleep() method
  4741. ** of the default VFS is not implemented correctly, or not implemented at
  4742. ** all, then the behavior of sqlite3_sleep() may deviate from the description
  4743. ** in the previous paragraphs.
  4744. */
  4745. SQLITE_API int sqlite3_sleep(int);
  4746. /*
  4747. ** CAPI3REF: Name Of The Folder Holding Temporary Files
  4748. **
  4749. ** ^(If this global variable is made to point to a string which is
  4750. ** the name of a folder (a.k.a. directory), then all temporary files
  4751. ** created by SQLite when using a built-in [sqlite3_vfs | VFS]
  4752. ** will be placed in that directory.)^ ^If this variable
  4753. ** is a NULL pointer, then SQLite performs a search for an appropriate
  4754. ** temporary file directory.
  4755. **
  4756. ** Applications are strongly discouraged from using this global variable.
  4757. ** It is required to set a temporary folder on Windows Runtime (WinRT).
  4758. ** But for all other platforms, it is highly recommended that applications
  4759. ** neither read nor write this variable. This global variable is a relic
  4760. ** that exists for backwards compatibility of legacy applications and should
  4761. ** be avoided in new projects.
  4762. **
  4763. ** It is not safe to read or modify this variable in more than one
  4764. ** thread at a time. It is not safe to read or modify this variable
  4765. ** if a [database connection] is being used at the same time in a separate
  4766. ** thread.
  4767. ** It is intended that this variable be set once
  4768. ** as part of process initialization and before any SQLite interface
  4769. ** routines have been called and that this variable remain unchanged
  4770. ** thereafter.
  4771. **
  4772. ** ^The [temp_store_directory pragma] may modify this variable and cause
  4773. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4774. ** the [temp_store_directory pragma] always assumes that any string
  4775. ** that this variable points to is held in memory obtained from
  4776. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4777. ** using [sqlite3_free].
  4778. ** Hence, if this variable is modified directly, either it should be
  4779. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4780. ** or else the use of the [temp_store_directory pragma] should be avoided.
  4781. ** Except when requested by the [temp_store_directory pragma], SQLite
  4782. ** does not free the memory that sqlite3_temp_directory points to. If
  4783. ** the application wants that memory to be freed, it must do
  4784. ** so itself, taking care to only do so after all [database connection]
  4785. ** objects have been destroyed.
  4786. **
  4787. ** <b>Note to Windows Runtime users:</b> The temporary directory must be set
  4788. ** prior to calling [sqlite3_open] or [sqlite3_open_v2]. Otherwise, various
  4789. ** features that require the use of temporary files may fail. Here is an
  4790. ** example of how to do this using C++ with the Windows Runtime:
  4791. **
  4792. ** <blockquote><pre>
  4793. ** LPCWSTR zPath = Windows::Storage::ApplicationData::Current->
  4794. ** &nbsp; TemporaryFolder->Path->Data();
  4795. ** char zPathBuf&#91;MAX_PATH + 1&#93;;
  4796. ** memset(zPathBuf, 0, sizeof(zPathBuf));
  4797. ** WideCharToMultiByte(CP_UTF8, 0, zPath, -1, zPathBuf, sizeof(zPathBuf),
  4798. ** &nbsp; NULL, NULL);
  4799. ** sqlite3_temp_directory = sqlite3_mprintf("%s", zPathBuf);
  4800. ** </pre></blockquote>
  4801. */
  4802. SQLITE_API char *sqlite3_temp_directory;
  4803. /*
  4804. ** CAPI3REF: Name Of The Folder Holding Database Files
  4805. **
  4806. ** ^(If this global variable is made to point to a string which is
  4807. ** the name of a folder (a.k.a. directory), then all database files
  4808. ** specified with a relative pathname and created or accessed by
  4809. ** SQLite when using a built-in windows [sqlite3_vfs | VFS] will be assumed
  4810. ** to be relative to that directory.)^ ^If this variable is a NULL
  4811. ** pointer, then SQLite assumes that all database files specified
  4812. ** with a relative pathname are relative to the current directory
  4813. ** for the process. Only the windows VFS makes use of this global
  4814. ** variable; it is ignored by the unix VFS.
  4815. **
  4816. ** Changing the value of this variable while a database connection is
  4817. ** open can result in a corrupt database.
  4818. **
  4819. ** It is not safe to read or modify this variable in more than one
  4820. ** thread at a time. It is not safe to read or modify this variable
  4821. ** if a [database connection] is being used at the same time in a separate
  4822. ** thread.
  4823. ** It is intended that this variable be set once
  4824. ** as part of process initialization and before any SQLite interface
  4825. ** routines have been called and that this variable remain unchanged
  4826. ** thereafter.
  4827. **
  4828. ** ^The [data_store_directory pragma] may modify this variable and cause
  4829. ** it to point to memory obtained from [sqlite3_malloc]. ^Furthermore,
  4830. ** the [data_store_directory pragma] always assumes that any string
  4831. ** that this variable points to is held in memory obtained from
  4832. ** [sqlite3_malloc] and the pragma may attempt to free that memory
  4833. ** using [sqlite3_free].
  4834. ** Hence, if this variable is modified directly, either it should be
  4835. ** made NULL or made to point to memory obtained from [sqlite3_malloc]
  4836. ** or else the use of the [data_store_directory pragma] should be avoided.
  4837. */
  4838. SQLITE_API char *sqlite3_data_directory;
  4839. /*
  4840. ** CAPI3REF: Test For Auto-Commit Mode
  4841. ** KEYWORDS: {autocommit mode}
  4842. **
  4843. ** ^The sqlite3_get_autocommit() interface returns non-zero or
  4844. ** zero if the given database connection is or is not in autocommit mode,
  4845. ** respectively. ^Autocommit mode is on by default.
  4846. ** ^Autocommit mode is disabled by a [BEGIN] statement.
  4847. ** ^Autocommit mode is re-enabled by a [COMMIT] or [ROLLBACK].
  4848. **
  4849. ** If certain kinds of errors occur on a statement within a multi-statement
  4850. ** transaction (errors including [SQLITE_FULL], [SQLITE_IOERR],
  4851. ** [SQLITE_NOMEM], [SQLITE_BUSY], and [SQLITE_INTERRUPT]) then the
  4852. ** transaction might be rolled back automatically. The only way to
  4853. ** find out whether SQLite automatically rolled back the transaction after
  4854. ** an error is to use this function.
  4855. **
  4856. ** If another thread changes the autocommit status of the database
  4857. ** connection while this routine is running, then the return value
  4858. ** is undefined.
  4859. */
  4860. SQLITE_API int sqlite3_get_autocommit(sqlite3*);
  4861. /*
  4862. ** CAPI3REF: Find The Database Handle Of A Prepared Statement
  4863. **
  4864. ** ^The sqlite3_db_handle interface returns the [database connection] handle
  4865. ** to which a [prepared statement] belongs. ^The [database connection]
  4866. ** returned by sqlite3_db_handle is the same [database connection]
  4867. ** that was the first argument
  4868. ** to the [sqlite3_prepare_v2()] call (or its variants) that was used to
  4869. ** create the statement in the first place.
  4870. */
  4871. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt*);
  4872. /*
  4873. ** CAPI3REF: Return The Filename For A Database Connection
  4874. **
  4875. ** ^The sqlite3_db_filename(D,N) interface returns a pointer to a filename
  4876. ** associated with database N of connection D. ^The main database file
  4877. ** has the name "main". If there is no attached database N on the database
  4878. ** connection D, or if database N is a temporary or in-memory database, then
  4879. ** a NULL pointer is returned.
  4880. **
  4881. ** ^The filename returned by this function is the output of the
  4882. ** xFullPathname method of the [VFS]. ^In other words, the filename
  4883. ** will be an absolute pathname, even if the filename used
  4884. ** to open the database originally was a URI or relative pathname.
  4885. */
  4886. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName);
  4887. /*
  4888. ** CAPI3REF: Determine if a database is read-only
  4889. **
  4890. ** ^The sqlite3_db_readonly(D,N) interface returns 1 if the database N
  4891. ** of connection D is read-only, 0 if it is read/write, or -1 if N is not
  4892. ** the name of a database on connection D.
  4893. */
  4894. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName);
  4895. /*
  4896. ** CAPI3REF: Find the next prepared statement
  4897. **
  4898. ** ^This interface returns a pointer to the next [prepared statement] after
  4899. ** pStmt associated with the [database connection] pDb. ^If pStmt is NULL
  4900. ** then this interface returns a pointer to the first prepared statement
  4901. ** associated with the database connection pDb. ^If no prepared statement
  4902. ** satisfies the conditions of this routine, it returns NULL.
  4903. **
  4904. ** The [database connection] pointer D in a call to
  4905. ** [sqlite3_next_stmt(D,S)] must refer to an open database
  4906. ** connection and in particular must not be a NULL pointer.
  4907. */
  4908. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt);
  4909. /*
  4910. ** CAPI3REF: Commit And Rollback Notification Callbacks
  4911. **
  4912. ** ^The sqlite3_commit_hook() interface registers a callback
  4913. ** function to be invoked whenever a transaction is [COMMIT | committed].
  4914. ** ^Any callback set by a previous call to sqlite3_commit_hook()
  4915. ** for the same database connection is overridden.
  4916. ** ^The sqlite3_rollback_hook() interface registers a callback
  4917. ** function to be invoked whenever a transaction is [ROLLBACK | rolled back].
  4918. ** ^Any callback set by a previous call to sqlite3_rollback_hook()
  4919. ** for the same database connection is overridden.
  4920. ** ^The pArg argument is passed through to the callback.
  4921. ** ^If the callback on a commit hook function returns non-zero,
  4922. ** then the commit is converted into a rollback.
  4923. **
  4924. ** ^The sqlite3_commit_hook(D,C,P) and sqlite3_rollback_hook(D,C,P) functions
  4925. ** return the P argument from the previous call of the same function
  4926. ** on the same [database connection] D, or NULL for
  4927. ** the first call for each function on D.
  4928. **
  4929. ** The commit and rollback hook callbacks are not reentrant.
  4930. ** The callback implementation must not do anything that will modify
  4931. ** the database connection that invoked the callback. Any actions
  4932. ** to modify the database connection must be deferred until after the
  4933. ** completion of the [sqlite3_step()] call that triggered the commit
  4934. ** or rollback hook in the first place.
  4935. ** Note that running any other SQL statements, including SELECT statements,
  4936. ** or merely calling [sqlite3_prepare_v2()] and [sqlite3_step()] will modify
  4937. ** the database connections for the meaning of "modify" in this paragraph.
  4938. **
  4939. ** ^Registering a NULL function disables the callback.
  4940. **
  4941. ** ^When the commit hook callback routine returns zero, the [COMMIT]
  4942. ** operation is allowed to continue normally. ^If the commit hook
  4943. ** returns non-zero, then the [COMMIT] is converted into a [ROLLBACK].
  4944. ** ^The rollback hook is invoked on a rollback that results from a commit
  4945. ** hook returning non-zero, just as it would be with any other rollback.
  4946. **
  4947. ** ^For the purposes of this API, a transaction is said to have been
  4948. ** rolled back if an explicit "ROLLBACK" statement is executed, or
  4949. ** an error or constraint causes an implicit rollback to occur.
  4950. ** ^The rollback callback is not invoked if a transaction is
  4951. ** automatically rolled back because the database connection is closed.
  4952. **
  4953. ** See also the [sqlite3_update_hook()] interface.
  4954. */
  4955. SQLITE_API void *sqlite3_commit_hook(sqlite3*, int(*)(void*), void*);
  4956. SQLITE_API void *sqlite3_rollback_hook(sqlite3*, void(*)(void *), void*);
  4957. /*
  4958. ** CAPI3REF: Data Change Notification Callbacks
  4959. **
  4960. ** ^The sqlite3_update_hook() interface registers a callback function
  4961. ** with the [database connection] identified by the first argument
  4962. ** to be invoked whenever a row is updated, inserted or deleted in
  4963. ** a rowid table.
  4964. ** ^Any callback set by a previous call to this function
  4965. ** for the same database connection is overridden.
  4966. **
  4967. ** ^The second argument is a pointer to the function to invoke when a
  4968. ** row is updated, inserted or deleted in a rowid table.
  4969. ** ^The first argument to the callback is a copy of the third argument
  4970. ** to sqlite3_update_hook().
  4971. ** ^The second callback argument is one of [SQLITE_INSERT], [SQLITE_DELETE],
  4972. ** or [SQLITE_UPDATE], depending on the operation that caused the callback
  4973. ** to be invoked.
  4974. ** ^The third and fourth arguments to the callback contain pointers to the
  4975. ** database and table name containing the affected row.
  4976. ** ^The final callback parameter is the [rowid] of the row.
  4977. ** ^In the case of an update, this is the [rowid] after the update takes place.
  4978. **
  4979. ** ^(The update hook is not invoked when internal system tables are
  4980. ** modified (i.e. sqlite_master and sqlite_sequence).)^
  4981. ** ^The update hook is not invoked when [WITHOUT ROWID] tables are modified.
  4982. **
  4983. ** ^In the current implementation, the update hook
  4984. ** is not invoked when duplication rows are deleted because of an
  4985. ** [ON CONFLICT | ON CONFLICT REPLACE] clause. ^Nor is the update hook
  4986. ** invoked when rows are deleted using the [truncate optimization].
  4987. ** The exceptions defined in this paragraph might change in a future
  4988. ** release of SQLite.
  4989. **
  4990. ** The update hook implementation must not do anything that will modify
  4991. ** the database connection that invoked the update hook. Any actions
  4992. ** to modify the database connection must be deferred until after the
  4993. ** completion of the [sqlite3_step()] call that triggered the update hook.
  4994. ** Note that [sqlite3_prepare_v2()] and [sqlite3_step()] both modify their
  4995. ** database connections for the meaning of "modify" in this paragraph.
  4996. **
  4997. ** ^The sqlite3_update_hook(D,C,P) function
  4998. ** returns the P argument from the previous call
  4999. ** on the same [database connection] D, or NULL for
  5000. ** the first call on D.
  5001. **
  5002. ** See also the [sqlite3_commit_hook()] and [sqlite3_rollback_hook()]
  5003. ** interfaces.
  5004. */
  5005. SQLITE_API void *sqlite3_update_hook(
  5006. sqlite3*,
  5007. void(*)(void *,int ,char const *,char const *,sqlite3_int64),
  5008. void*
  5009. );
  5010. /*
  5011. ** CAPI3REF: Enable Or Disable Shared Pager Cache
  5012. **
  5013. ** ^(This routine enables or disables the sharing of the database cache
  5014. ** and schema data structures between [database connection | connections]
  5015. ** to the same database. Sharing is enabled if the argument is true
  5016. ** and disabled if the argument is false.)^
  5017. **
  5018. ** ^Cache sharing is enabled and disabled for an entire process.
  5019. ** This is a change as of SQLite version 3.5.0. In prior versions of SQLite,
  5020. ** sharing was enabled or disabled for each thread separately.
  5021. **
  5022. ** ^(The cache sharing mode set by this interface effects all subsequent
  5023. ** calls to [sqlite3_open()], [sqlite3_open_v2()], and [sqlite3_open16()].
  5024. ** Existing database connections continue use the sharing mode
  5025. ** that was in effect at the time they were opened.)^
  5026. **
  5027. ** ^(This routine returns [SQLITE_OK] if shared cache was enabled or disabled
  5028. ** successfully. An [error code] is returned otherwise.)^
  5029. **
  5030. ** ^Shared cache is disabled by default. But this might change in
  5031. ** future releases of SQLite. Applications that care about shared
  5032. ** cache setting should set it explicitly.
  5033. **
  5034. ** This interface is threadsafe on processors where writing a
  5035. ** 32-bit integer is atomic.
  5036. **
  5037. ** See Also: [SQLite Shared-Cache Mode]
  5038. */
  5039. SQLITE_API int sqlite3_enable_shared_cache(int);
  5040. /*
  5041. ** CAPI3REF: Attempt To Free Heap Memory
  5042. **
  5043. ** ^The sqlite3_release_memory() interface attempts to free N bytes
  5044. ** of heap memory by deallocating non-essential memory allocations
  5045. ** held by the database library. Memory used to cache database
  5046. ** pages to improve performance is an example of non-essential memory.
  5047. ** ^sqlite3_release_memory() returns the number of bytes actually freed,
  5048. ** which might be more or less than the amount requested.
  5049. ** ^The sqlite3_release_memory() routine is a no-op returning zero
  5050. ** if SQLite is not compiled with [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5051. **
  5052. ** See also: [sqlite3_db_release_memory()]
  5053. */
  5054. SQLITE_API int sqlite3_release_memory(int);
  5055. /*
  5056. ** CAPI3REF: Free Memory Used By A Database Connection
  5057. **
  5058. ** ^The sqlite3_db_release_memory(D) interface attempts to free as much heap
  5059. ** memory as possible from database connection D. Unlike the
  5060. ** [sqlite3_release_memory()] interface, this interface is in effect even
  5061. ** when the [SQLITE_ENABLE_MEMORY_MANAGEMENT] compile-time option is
  5062. ** omitted.
  5063. **
  5064. ** See also: [sqlite3_release_memory()]
  5065. */
  5066. SQLITE_API int sqlite3_db_release_memory(sqlite3*);
  5067. /*
  5068. ** CAPI3REF: Impose A Limit On Heap Size
  5069. **
  5070. ** ^The sqlite3_soft_heap_limit64() interface sets and/or queries the
  5071. ** soft limit on the amount of heap memory that may be allocated by SQLite.
  5072. ** ^SQLite strives to keep heap memory utilization below the soft heap
  5073. ** limit by reducing the number of pages held in the page cache
  5074. ** as heap memory usages approaches the limit.
  5075. ** ^The soft heap limit is "soft" because even though SQLite strives to stay
  5076. ** below the limit, it will exceed the limit rather than generate
  5077. ** an [SQLITE_NOMEM] error. In other words, the soft heap limit
  5078. ** is advisory only.
  5079. **
  5080. ** ^The return value from sqlite3_soft_heap_limit64() is the size of
  5081. ** the soft heap limit prior to the call, or negative in the case of an
  5082. ** error. ^If the argument N is negative
  5083. ** then no change is made to the soft heap limit. Hence, the current
  5084. ** size of the soft heap limit can be determined by invoking
  5085. ** sqlite3_soft_heap_limit64() with a negative argument.
  5086. **
  5087. ** ^If the argument N is zero then the soft heap limit is disabled.
  5088. **
  5089. ** ^(The soft heap limit is not enforced in the current implementation
  5090. ** if one or more of following conditions are true:
  5091. **
  5092. ** <ul>
  5093. ** <li> The soft heap limit is set to zero.
  5094. ** <li> Memory accounting is disabled using a combination of the
  5095. ** [sqlite3_config]([SQLITE_CONFIG_MEMSTATUS],...) start-time option and
  5096. ** the [SQLITE_DEFAULT_MEMSTATUS] compile-time option.
  5097. ** <li> An alternative page cache implementation is specified using
  5098. ** [sqlite3_config]([SQLITE_CONFIG_PCACHE2],...).
  5099. ** <li> The page cache allocates from its own memory pool supplied
  5100. ** by [sqlite3_config]([SQLITE_CONFIG_PAGECACHE],...) rather than
  5101. ** from the heap.
  5102. ** </ul>)^
  5103. **
  5104. ** Beginning with SQLite version 3.7.3, the soft heap limit is enforced
  5105. ** regardless of whether or not the [SQLITE_ENABLE_MEMORY_MANAGEMENT]
  5106. ** compile-time option is invoked. With [SQLITE_ENABLE_MEMORY_MANAGEMENT],
  5107. ** the soft heap limit is enforced on every memory allocation. Without
  5108. ** [SQLITE_ENABLE_MEMORY_MANAGEMENT], the soft heap limit is only enforced
  5109. ** when memory is allocated by the page cache. Testing suggests that because
  5110. ** the page cache is the predominate memory user in SQLite, most
  5111. ** applications will achieve adequate soft heap limit enforcement without
  5112. ** the use of [SQLITE_ENABLE_MEMORY_MANAGEMENT].
  5113. **
  5114. ** The circumstances under which SQLite will enforce the soft heap limit may
  5115. ** changes in future releases of SQLite.
  5116. */
  5117. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 N);
  5118. /*
  5119. ** CAPI3REF: Deprecated Soft Heap Limit Interface
  5120. ** DEPRECATED
  5121. **
  5122. ** This is a deprecated version of the [sqlite3_soft_heap_limit64()]
  5123. ** interface. This routine is provided for historical compatibility
  5124. ** only. All new applications should use the
  5125. ** [sqlite3_soft_heap_limit64()] interface rather than this one.
  5126. */
  5127. SQLITE_API SQLITE_DEPRECATED void sqlite3_soft_heap_limit(int N);
  5128. /*
  5129. ** CAPI3REF: Extract Metadata About A Column Of A Table
  5130. **
  5131. ** ^This routine returns metadata about a specific column of a specific
  5132. ** database table accessible using the [database connection] handle
  5133. ** passed as the first function argument.
  5134. **
  5135. ** ^The column is identified by the second, third and fourth parameters to
  5136. ** this function. ^The second parameter is either the name of the database
  5137. ** (i.e. "main", "temp", or an attached database) containing the specified
  5138. ** table or NULL. ^If it is NULL, then all attached databases are searched
  5139. ** for the table using the same algorithm used by the database engine to
  5140. ** resolve unqualified table references.
  5141. **
  5142. ** ^The third and fourth parameters to this function are the table and column
  5143. ** name of the desired column, respectively. Neither of these parameters
  5144. ** may be NULL.
  5145. **
  5146. ** ^Metadata is returned by writing to the memory locations passed as the 5th
  5147. ** and subsequent parameters to this function. ^Any of these arguments may be
  5148. ** NULL, in which case the corresponding element of metadata is omitted.
  5149. **
  5150. ** ^(<blockquote>
  5151. ** <table border="1">
  5152. ** <tr><th> Parameter <th> Output<br>Type <th> Description
  5153. **
  5154. ** <tr><td> 5th <td> const char* <td> Data type
  5155. ** <tr><td> 6th <td> const char* <td> Name of default collation sequence
  5156. ** <tr><td> 7th <td> int <td> True if column has a NOT NULL constraint
  5157. ** <tr><td> 8th <td> int <td> True if column is part of the PRIMARY KEY
  5158. ** <tr><td> 9th <td> int <td> True if column is [AUTOINCREMENT]
  5159. ** </table>
  5160. ** </blockquote>)^
  5161. **
  5162. ** ^The memory pointed to by the character pointers returned for the
  5163. ** declaration type and collation sequence is valid only until the next
  5164. ** call to any SQLite API function.
  5165. **
  5166. ** ^If the specified table is actually a view, an [error code] is returned.
  5167. **
  5168. ** ^If the specified column is "rowid", "oid" or "_rowid_" and an
  5169. ** [INTEGER PRIMARY KEY] column has been explicitly declared, then the output
  5170. ** parameters are set for the explicitly declared column. ^(If there is no
  5171. ** explicitly declared [INTEGER PRIMARY KEY] column, then the output
  5172. ** parameters are set as follows:
  5173. **
  5174. ** <pre>
  5175. ** data type: "INTEGER"
  5176. ** collation sequence: "BINARY"
  5177. ** not null: 0
  5178. ** primary key: 1
  5179. ** auto increment: 0
  5180. ** </pre>)^
  5181. **
  5182. ** ^(This function may load one or more schemas from database files. If an
  5183. ** error occurs during this process, or if the requested table or column
  5184. ** cannot be found, an [error code] is returned and an error message left
  5185. ** in the [database connection] (to be retrieved using sqlite3_errmsg()).)^
  5186. **
  5187. ** ^This API is only available if the library was compiled with the
  5188. ** [SQLITE_ENABLE_COLUMN_METADATA] C-preprocessor symbol defined.
  5189. */
  5190. SQLITE_API int sqlite3_table_column_metadata(
  5191. sqlite3 *db, /* Connection handle */
  5192. const char *zDbName, /* Database name or NULL */
  5193. const char *zTableName, /* Table name */
  5194. const char *zColumnName, /* Column name */
  5195. char const **pzDataType, /* OUTPUT: Declared data type */
  5196. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  5197. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  5198. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  5199. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  5200. );
  5201. /*
  5202. ** CAPI3REF: Load An Extension
  5203. **
  5204. ** ^This interface loads an SQLite extension library from the named file.
  5205. **
  5206. ** ^The sqlite3_load_extension() interface attempts to load an
  5207. ** [SQLite extension] library contained in the file zFile. If
  5208. ** the file cannot be loaded directly, attempts are made to load
  5209. ** with various operating-system specific extensions added.
  5210. ** So for example, if "samplelib" cannot be loaded, then names like
  5211. ** "samplelib.so" or "samplelib.dylib" or "samplelib.dll" might
  5212. ** be tried also.
  5213. **
  5214. ** ^The entry point is zProc.
  5215. ** ^(zProc may be 0, in which case SQLite will try to come up with an
  5216. ** entry point name on its own. It first tries "sqlite3_extension_init".
  5217. ** If that does not work, it constructs a name "sqlite3_X_init" where the
  5218. ** X is consists of the lower-case equivalent of all ASCII alphabetic
  5219. ** characters in the filename from the last "/" to the first following
  5220. ** "." and omitting any initial "lib".)^
  5221. ** ^The sqlite3_load_extension() interface returns
  5222. ** [SQLITE_OK] on success and [SQLITE_ERROR] if something goes wrong.
  5223. ** ^If an error occurs and pzErrMsg is not 0, then the
  5224. ** [sqlite3_load_extension()] interface shall attempt to
  5225. ** fill *pzErrMsg with error message text stored in memory
  5226. ** obtained from [sqlite3_malloc()]. The calling function
  5227. ** should free this memory by calling [sqlite3_free()].
  5228. **
  5229. ** ^Extension loading must be enabled using
  5230. ** [sqlite3_enable_load_extension()] prior to calling this API,
  5231. ** otherwise an error will be returned.
  5232. **
  5233. ** See also the [load_extension() SQL function].
  5234. */
  5235. SQLITE_API int sqlite3_load_extension(
  5236. sqlite3 *db, /* Load the extension into this database connection */
  5237. const char *zFile, /* Name of the shared library containing extension */
  5238. const char *zProc, /* Entry point. Derived from zFile if 0 */
  5239. char **pzErrMsg /* Put error message here if not 0 */
  5240. );
  5241. /*
  5242. ** CAPI3REF: Enable Or Disable Extension Loading
  5243. **
  5244. ** ^So as not to open security holes in older applications that are
  5245. ** unprepared to deal with [extension loading], and as a means of disabling
  5246. ** [extension loading] while evaluating user-entered SQL, the following API
  5247. ** is provided to turn the [sqlite3_load_extension()] mechanism on and off.
  5248. **
  5249. ** ^Extension loading is off by default.
  5250. ** ^Call the sqlite3_enable_load_extension() routine with onoff==1
  5251. ** to turn extension loading on and call it with onoff==0 to turn
  5252. ** it back off again.
  5253. */
  5254. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff);
  5255. /*
  5256. ** CAPI3REF: Automatically Load Statically Linked Extensions
  5257. **
  5258. ** ^This interface causes the xEntryPoint() function to be invoked for
  5259. ** each new [database connection] that is created. The idea here is that
  5260. ** xEntryPoint() is the entry point for a statically linked [SQLite extension]
  5261. ** that is to be automatically loaded into all new database connections.
  5262. **
  5263. ** ^(Even though the function prototype shows that xEntryPoint() takes
  5264. ** no arguments and returns void, SQLite invokes xEntryPoint() with three
  5265. ** arguments and expects and integer result as if the signature of the
  5266. ** entry point where as follows:
  5267. **
  5268. ** <blockquote><pre>
  5269. ** &nbsp; int xEntryPoint(
  5270. ** &nbsp; sqlite3 *db,
  5271. ** &nbsp; const char **pzErrMsg,
  5272. ** &nbsp; const struct sqlite3_api_routines *pThunk
  5273. ** &nbsp; );
  5274. ** </pre></blockquote>)^
  5275. **
  5276. ** If the xEntryPoint routine encounters an error, it should make *pzErrMsg
  5277. ** point to an appropriate error message (obtained from [sqlite3_mprintf()])
  5278. ** and return an appropriate [error code]. ^SQLite ensures that *pzErrMsg
  5279. ** is NULL before calling the xEntryPoint(). ^SQLite will invoke
  5280. ** [sqlite3_free()] on *pzErrMsg after xEntryPoint() returns. ^If any
  5281. ** xEntryPoint() returns an error, the [sqlite3_open()], [sqlite3_open16()],
  5282. ** or [sqlite3_open_v2()] call that provoked the xEntryPoint() will fail.
  5283. **
  5284. ** ^Calling sqlite3_auto_extension(X) with an entry point X that is already
  5285. ** on the list of automatic extensions is a harmless no-op. ^No entry point
  5286. ** will be called more than once for each database connection that is opened.
  5287. **
  5288. ** See also: [sqlite3_reset_auto_extension()]
  5289. ** and [sqlite3_cancel_auto_extension()]
  5290. */
  5291. SQLITE_API int sqlite3_auto_extension(void (*xEntryPoint)(void));
  5292. /*
  5293. ** CAPI3REF: Cancel Automatic Extension Loading
  5294. **
  5295. ** ^The [sqlite3_cancel_auto_extension(X)] interface unregisters the
  5296. ** initialization routine X that was registered using a prior call to
  5297. ** [sqlite3_auto_extension(X)]. ^The [sqlite3_cancel_auto_extension(X)]
  5298. ** routine returns 1 if initialization routine X was successfully
  5299. ** unregistered and it returns 0 if X was not on the list of initialization
  5300. ** routines.
  5301. */
  5302. SQLITE_API int sqlite3_cancel_auto_extension(void (*xEntryPoint)(void));
  5303. /*
  5304. ** CAPI3REF: Reset Automatic Extension Loading
  5305. **
  5306. ** ^This interface disables all automatic extensions previously
  5307. ** registered using [sqlite3_auto_extension()].
  5308. */
  5309. SQLITE_API void sqlite3_reset_auto_extension(void);
  5310. /*
  5311. ** The interface to the virtual-table mechanism is currently considered
  5312. ** to be experimental. The interface might change in incompatible ways.
  5313. ** If this is a problem for you, do not use the interface at this time.
  5314. **
  5315. ** When the virtual-table mechanism stabilizes, we will declare the
  5316. ** interface fixed, support it indefinitely, and remove this comment.
  5317. */
  5318. /*
  5319. ** Structures used by the virtual table interface
  5320. */
  5321. typedef struct sqlite3_vtab sqlite3_vtab;
  5322. typedef struct sqlite3_index_info sqlite3_index_info;
  5323. typedef struct sqlite3_vtab_cursor sqlite3_vtab_cursor;
  5324. typedef struct sqlite3_module sqlite3_module;
  5325. /*
  5326. ** CAPI3REF: Virtual Table Object
  5327. ** KEYWORDS: sqlite3_module {virtual table module}
  5328. **
  5329. ** This structure, sometimes called a "virtual table module",
  5330. ** defines the implementation of a [virtual tables].
  5331. ** This structure consists mostly of methods for the module.
  5332. **
  5333. ** ^A virtual table module is created by filling in a persistent
  5334. ** instance of this structure and passing a pointer to that instance
  5335. ** to [sqlite3_create_module()] or [sqlite3_create_module_v2()].
  5336. ** ^The registration remains valid until it is replaced by a different
  5337. ** module or until the [database connection] closes. The content
  5338. ** of this structure must not change while it is registered with
  5339. ** any database connection.
  5340. */
  5341. struct sqlite3_module {
  5342. int iVersion;
  5343. int (*xCreate)(sqlite3*, void *pAux,
  5344. int argc, const char *const*argv,
  5345. sqlite3_vtab **ppVTab, char**);
  5346. int (*xConnect)(sqlite3*, void *pAux,
  5347. int argc, const char *const*argv,
  5348. sqlite3_vtab **ppVTab, char**);
  5349. int (*xBestIndex)(sqlite3_vtab *pVTab, sqlite3_index_info*);
  5350. int (*xDisconnect)(sqlite3_vtab *pVTab);
  5351. int (*xDestroy)(sqlite3_vtab *pVTab);
  5352. int (*xOpen)(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor);
  5353. int (*xClose)(sqlite3_vtab_cursor*);
  5354. int (*xFilter)(sqlite3_vtab_cursor*, int idxNum, const char *idxStr,
  5355. int argc, sqlite3_value **argv);
  5356. int (*xNext)(sqlite3_vtab_cursor*);
  5357. int (*xEof)(sqlite3_vtab_cursor*);
  5358. int (*xColumn)(sqlite3_vtab_cursor*, sqlite3_context*, int);
  5359. int (*xRowid)(sqlite3_vtab_cursor*, sqlite3_int64 *pRowid);
  5360. int (*xUpdate)(sqlite3_vtab *, int, sqlite3_value **, sqlite3_int64 *);
  5361. int (*xBegin)(sqlite3_vtab *pVTab);
  5362. int (*xSync)(sqlite3_vtab *pVTab);
  5363. int (*xCommit)(sqlite3_vtab *pVTab);
  5364. int (*xRollback)(sqlite3_vtab *pVTab);
  5365. int (*xFindFunction)(sqlite3_vtab *pVtab, int nArg, const char *zName,
  5366. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**),
  5367. void **ppArg);
  5368. int (*xRename)(sqlite3_vtab *pVtab, const char *zNew);
  5369. /* The methods above are in version 1 of the sqlite_module object. Those
  5370. ** below are for version 2 and greater. */
  5371. int (*xSavepoint)(sqlite3_vtab *pVTab, int);
  5372. int (*xRelease)(sqlite3_vtab *pVTab, int);
  5373. int (*xRollbackTo)(sqlite3_vtab *pVTab, int);
  5374. };
  5375. /*
  5376. ** CAPI3REF: Virtual Table Indexing Information
  5377. ** KEYWORDS: sqlite3_index_info
  5378. **
  5379. ** The sqlite3_index_info structure and its substructures is used as part
  5380. ** of the [virtual table] interface to
  5381. ** pass information into and receive the reply from the [xBestIndex]
  5382. ** method of a [virtual table module]. The fields under **Inputs** are the
  5383. ** inputs to xBestIndex and are read-only. xBestIndex inserts its
  5384. ** results into the **Outputs** fields.
  5385. **
  5386. ** ^(The aConstraint[] array records WHERE clause constraints of the form:
  5387. **
  5388. ** <blockquote>column OP expr</blockquote>
  5389. **
  5390. ** where OP is =, &lt;, &lt;=, &gt;, or &gt;=.)^ ^(The particular operator is
  5391. ** stored in aConstraint[].op using one of the
  5392. ** [SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_ values].)^
  5393. ** ^(The index of the column is stored in
  5394. ** aConstraint[].iColumn.)^ ^(aConstraint[].usable is TRUE if the
  5395. ** expr on the right-hand side can be evaluated (and thus the constraint
  5396. ** is usable) and false if it cannot.)^
  5397. **
  5398. ** ^The optimizer automatically inverts terms of the form "expr OP column"
  5399. ** and makes other simplifications to the WHERE clause in an attempt to
  5400. ** get as many WHERE clause terms into the form shown above as possible.
  5401. ** ^The aConstraint[] array only reports WHERE clause terms that are
  5402. ** relevant to the particular virtual table being queried.
  5403. **
  5404. ** ^Information about the ORDER BY clause is stored in aOrderBy[].
  5405. ** ^Each term of aOrderBy records a column of the ORDER BY clause.
  5406. **
  5407. ** The [xBestIndex] method must fill aConstraintUsage[] with information
  5408. ** about what parameters to pass to xFilter. ^If argvIndex>0 then
  5409. ** the right-hand side of the corresponding aConstraint[] is evaluated
  5410. ** and becomes the argvIndex-th entry in argv. ^(If aConstraintUsage[].omit
  5411. ** is true, then the constraint is assumed to be fully handled by the
  5412. ** virtual table and is not checked again by SQLite.)^
  5413. **
  5414. ** ^The idxNum and idxPtr values are recorded and passed into the
  5415. ** [xFilter] method.
  5416. ** ^[sqlite3_free()] is used to free idxPtr if and only if
  5417. ** needToFreeIdxPtr is true.
  5418. **
  5419. ** ^The orderByConsumed means that output from [xFilter]/[xNext] will occur in
  5420. ** the correct order to satisfy the ORDER BY clause so that no separate
  5421. ** sorting step is required.
  5422. **
  5423. ** ^The estimatedCost value is an estimate of the cost of a particular
  5424. ** strategy. A cost of N indicates that the cost of the strategy is similar
  5425. ** to a linear scan of an SQLite table with N rows. A cost of log(N)
  5426. ** indicates that the expense of the operation is similar to that of a
  5427. ** binary search on a unique indexed field of an SQLite table with N rows.
  5428. **
  5429. ** ^The estimatedRows value is an estimate of the number of rows that
  5430. ** will be returned by the strategy.
  5431. **
  5432. ** IMPORTANT: The estimatedRows field was added to the sqlite3_index_info
  5433. ** structure for SQLite version 3.8.2. If a virtual table extension is
  5434. ** used with an SQLite version earlier than 3.8.2, the results of attempting
  5435. ** to read or write the estimatedRows field are undefined (but are likely
  5436. ** to included crashing the application). The estimatedRows field should
  5437. ** therefore only be used if [sqlite3_libversion_number()] returns a
  5438. ** value greater than or equal to 3008002.
  5439. */
  5440. struct sqlite3_index_info {
  5441. /* Inputs */
  5442. int nConstraint; /* Number of entries in aConstraint */
  5443. struct sqlite3_index_constraint {
  5444. int iColumn; /* Column on left-hand side of constraint */
  5445. unsigned char op; /* Constraint operator */
  5446. unsigned char usable; /* True if this constraint is usable */
  5447. int iTermOffset; /* Used internally - xBestIndex should ignore */
  5448. } *aConstraint; /* Table of WHERE clause constraints */
  5449. int nOrderBy; /* Number of terms in the ORDER BY clause */
  5450. struct sqlite3_index_orderby {
  5451. int iColumn; /* Column number */
  5452. unsigned char desc; /* True for DESC. False for ASC. */
  5453. } *aOrderBy; /* The ORDER BY clause */
  5454. /* Outputs */
  5455. struct sqlite3_index_constraint_usage {
  5456. int argvIndex; /* if >0, constraint is part of argv to xFilter */
  5457. unsigned char omit; /* Do not code a test for this constraint */
  5458. } *aConstraintUsage;
  5459. int idxNum; /* Number used to identify the index */
  5460. char *idxStr; /* String, possibly obtained from sqlite3_malloc */
  5461. int needToFreeIdxStr; /* Free idxStr using sqlite3_free() if true */
  5462. int orderByConsumed; /* True if output is already ordered */
  5463. double estimatedCost; /* Estimated cost of using this index */
  5464. /* Fields below are only available in SQLite 3.8.2 and later */
  5465. sqlite3_int64 estimatedRows; /* Estimated number of rows returned */
  5466. };
  5467. /*
  5468. ** CAPI3REF: Virtual Table Constraint Operator Codes
  5469. **
  5470. ** These macros defined the allowed values for the
  5471. ** [sqlite3_index_info].aConstraint[].op field. Each value represents
  5472. ** an operator that is part of a constraint term in the wHERE clause of
  5473. ** a query that uses a [virtual table].
  5474. */
  5475. #define SQLITE_INDEX_CONSTRAINT_EQ 2
  5476. #define SQLITE_INDEX_CONSTRAINT_GT 4
  5477. #define SQLITE_INDEX_CONSTRAINT_LE 8
  5478. #define SQLITE_INDEX_CONSTRAINT_LT 16
  5479. #define SQLITE_INDEX_CONSTRAINT_GE 32
  5480. #define SQLITE_INDEX_CONSTRAINT_MATCH 64
  5481. /*
  5482. ** CAPI3REF: Register A Virtual Table Implementation
  5483. **
  5484. ** ^These routines are used to register a new [virtual table module] name.
  5485. ** ^Module names must be registered before
  5486. ** creating a new [virtual table] using the module and before using a
  5487. ** preexisting [virtual table] for the module.
  5488. **
  5489. ** ^The module name is registered on the [database connection] specified
  5490. ** by the first parameter. ^The name of the module is given by the
  5491. ** second parameter. ^The third parameter is a pointer to
  5492. ** the implementation of the [virtual table module]. ^The fourth
  5493. ** parameter is an arbitrary client data pointer that is passed through
  5494. ** into the [xCreate] and [xConnect] methods of the virtual table module
  5495. ** when a new virtual table is be being created or reinitialized.
  5496. **
  5497. ** ^The sqlite3_create_module_v2() interface has a fifth parameter which
  5498. ** is a pointer to a destructor for the pClientData. ^SQLite will
  5499. ** invoke the destructor function (if it is not NULL) when SQLite
  5500. ** no longer needs the pClientData pointer. ^The destructor will also
  5501. ** be invoked if the call to sqlite3_create_module_v2() fails.
  5502. ** ^The sqlite3_create_module()
  5503. ** interface is equivalent to sqlite3_create_module_v2() with a NULL
  5504. ** destructor.
  5505. */
  5506. SQLITE_API int sqlite3_create_module(
  5507. sqlite3 *db, /* SQLite connection to register module with */
  5508. const char *zName, /* Name of the module */
  5509. const sqlite3_module *p, /* Methods for the module */
  5510. void *pClientData /* Client data for xCreate/xConnect */
  5511. );
  5512. SQLITE_API int sqlite3_create_module_v2(
  5513. sqlite3 *db, /* SQLite connection to register module with */
  5514. const char *zName, /* Name of the module */
  5515. const sqlite3_module *p, /* Methods for the module */
  5516. void *pClientData, /* Client data for xCreate/xConnect */
  5517. void(*xDestroy)(void*) /* Module destructor function */
  5518. );
  5519. /*
  5520. ** CAPI3REF: Virtual Table Instance Object
  5521. ** KEYWORDS: sqlite3_vtab
  5522. **
  5523. ** Every [virtual table module] implementation uses a subclass
  5524. ** of this object to describe a particular instance
  5525. ** of the [virtual table]. Each subclass will
  5526. ** be tailored to the specific needs of the module implementation.
  5527. ** The purpose of this superclass is to define certain fields that are
  5528. ** common to all module implementations.
  5529. **
  5530. ** ^Virtual tables methods can set an error message by assigning a
  5531. ** string obtained from [sqlite3_mprintf()] to zErrMsg. The method should
  5532. ** take care that any prior string is freed by a call to [sqlite3_free()]
  5533. ** prior to assigning a new string to zErrMsg. ^After the error message
  5534. ** is delivered up to the client application, the string will be automatically
  5535. ** freed by sqlite3_free() and the zErrMsg field will be zeroed.
  5536. */
  5537. struct sqlite3_vtab {
  5538. const sqlite3_module *pModule; /* The module for this virtual table */
  5539. int nRef; /* NO LONGER USED */
  5540. char *zErrMsg; /* Error message from sqlite3_mprintf() */
  5541. /* Virtual table implementations will typically add additional fields */
  5542. };
  5543. /*
  5544. ** CAPI3REF: Virtual Table Cursor Object
  5545. ** KEYWORDS: sqlite3_vtab_cursor {virtual table cursor}
  5546. **
  5547. ** Every [virtual table module] implementation uses a subclass of the
  5548. ** following structure to describe cursors that point into the
  5549. ** [virtual table] and are used
  5550. ** to loop through the virtual table. Cursors are created using the
  5551. ** [sqlite3_module.xOpen | xOpen] method of the module and are destroyed
  5552. ** by the [sqlite3_module.xClose | xClose] method. Cursors are used
  5553. ** by the [xFilter], [xNext], [xEof], [xColumn], and [xRowid] methods
  5554. ** of the module. Each module implementation will define
  5555. ** the content of a cursor structure to suit its own needs.
  5556. **
  5557. ** This superclass exists in order to define fields of the cursor that
  5558. ** are common to all implementations.
  5559. */
  5560. struct sqlite3_vtab_cursor {
  5561. sqlite3_vtab *pVtab; /* Virtual table of this cursor */
  5562. /* Virtual table implementations will typically add additional fields */
  5563. };
  5564. /*
  5565. ** CAPI3REF: Declare The Schema Of A Virtual Table
  5566. **
  5567. ** ^The [xCreate] and [xConnect] methods of a
  5568. ** [virtual table module] call this interface
  5569. ** to declare the format (the names and datatypes of the columns) of
  5570. ** the virtual tables they implement.
  5571. */
  5572. SQLITE_API int sqlite3_declare_vtab(sqlite3*, const char *zSQL);
  5573. /*
  5574. ** CAPI3REF: Overload A Function For A Virtual Table
  5575. **
  5576. ** ^(Virtual tables can provide alternative implementations of functions
  5577. ** using the [xFindFunction] method of the [virtual table module].
  5578. ** But global versions of those functions
  5579. ** must exist in order to be overloaded.)^
  5580. **
  5581. ** ^(This API makes sure a global version of a function with a particular
  5582. ** name and number of parameters exists. If no such function exists
  5583. ** before this API is called, a new function is created.)^ ^The implementation
  5584. ** of the new function always causes an exception to be thrown. So
  5585. ** the new function is not good for anything by itself. Its only
  5586. ** purpose is to be a placeholder function that can be overloaded
  5587. ** by a [virtual table].
  5588. */
  5589. SQLITE_API int sqlite3_overload_function(sqlite3*, const char *zFuncName, int nArg);
  5590. /*
  5591. ** The interface to the virtual-table mechanism defined above (back up
  5592. ** to a comment remarkably similar to this one) is currently considered
  5593. ** to be experimental. The interface might change in incompatible ways.
  5594. ** If this is a problem for you, do not use the interface at this time.
  5595. **
  5596. ** When the virtual-table mechanism stabilizes, we will declare the
  5597. ** interface fixed, support it indefinitely, and remove this comment.
  5598. */
  5599. /*
  5600. ** CAPI3REF: A Handle To An Open BLOB
  5601. ** KEYWORDS: {BLOB handle} {BLOB handles}
  5602. **
  5603. ** An instance of this object represents an open BLOB on which
  5604. ** [sqlite3_blob_open | incremental BLOB I/O] can be performed.
  5605. ** ^Objects of this type are created by [sqlite3_blob_open()]
  5606. ** and destroyed by [sqlite3_blob_close()].
  5607. ** ^The [sqlite3_blob_read()] and [sqlite3_blob_write()] interfaces
  5608. ** can be used to read or write small subsections of the BLOB.
  5609. ** ^The [sqlite3_blob_bytes()] interface returns the size of the BLOB in bytes.
  5610. */
  5611. typedef struct sqlite3_blob sqlite3_blob;
  5612. /*
  5613. ** CAPI3REF: Open A BLOB For Incremental I/O
  5614. **
  5615. ** ^(This interfaces opens a [BLOB handle | handle] to the BLOB located
  5616. ** in row iRow, column zColumn, table zTable in database zDb;
  5617. ** in other words, the same BLOB that would be selected by:
  5618. **
  5619. ** <pre>
  5620. ** SELECT zColumn FROM zDb.zTable WHERE [rowid] = iRow;
  5621. ** </pre>)^
  5622. **
  5623. ** ^If the flags parameter is non-zero, then the BLOB is opened for read
  5624. ** and write access. ^If it is zero, the BLOB is opened for read access.
  5625. ** ^It is not possible to open a column that is part of an index or primary
  5626. ** key for writing. ^If [foreign key constraints] are enabled, it is
  5627. ** not possible to open a column that is part of a [child key] for writing.
  5628. **
  5629. ** ^Note that the database name is not the filename that contains
  5630. ** the database but rather the symbolic name of the database that
  5631. ** appears after the AS keyword when the database is connected using [ATTACH].
  5632. ** ^For the main database file, the database name is "main".
  5633. ** ^For TEMP tables, the database name is "temp".
  5634. **
  5635. ** ^(On success, [SQLITE_OK] is returned and the new [BLOB handle] is written
  5636. ** to *ppBlob. Otherwise an [error code] is returned and *ppBlob is set
  5637. ** to be a null pointer.)^
  5638. ** ^This function sets the [database connection] error code and message
  5639. ** accessible via [sqlite3_errcode()] and [sqlite3_errmsg()] and related
  5640. ** functions. ^Note that the *ppBlob variable is always initialized in a
  5641. ** way that makes it safe to invoke [sqlite3_blob_close()] on *ppBlob
  5642. ** regardless of the success or failure of this routine.
  5643. **
  5644. ** ^(If the row that a BLOB handle points to is modified by an
  5645. ** [UPDATE], [DELETE], or by [ON CONFLICT] side-effects
  5646. ** then the BLOB handle is marked as "expired".
  5647. ** This is true if any column of the row is changed, even a column
  5648. ** other than the one the BLOB handle is open on.)^
  5649. ** ^Calls to [sqlite3_blob_read()] and [sqlite3_blob_write()] for
  5650. ** an expired BLOB handle fail with a return code of [SQLITE_ABORT].
  5651. ** ^(Changes written into a BLOB prior to the BLOB expiring are not
  5652. ** rolled back by the expiration of the BLOB. Such changes will eventually
  5653. ** commit if the transaction continues to completion.)^
  5654. **
  5655. ** ^Use the [sqlite3_blob_bytes()] interface to determine the size of
  5656. ** the opened blob. ^The size of a blob may not be changed by this
  5657. ** interface. Use the [UPDATE] SQL command to change the size of a
  5658. ** blob.
  5659. **
  5660. ** ^The [sqlite3_blob_open()] interface will fail for a [WITHOUT ROWID]
  5661. ** table. Incremental BLOB I/O is not possible on [WITHOUT ROWID] tables.
  5662. **
  5663. ** ^The [sqlite3_bind_zeroblob()] and [sqlite3_result_zeroblob()] interfaces
  5664. ** and the built-in [zeroblob] SQL function can be used, if desired,
  5665. ** to create an empty, zero-filled blob in which to read or write using
  5666. ** this interface.
  5667. **
  5668. ** To avoid a resource leak, every open [BLOB handle] should eventually
  5669. ** be released by a call to [sqlite3_blob_close()].
  5670. */
  5671. SQLITE_API int sqlite3_blob_open(
  5672. sqlite3*,
  5673. const char *zDb,
  5674. const char *zTable,
  5675. const char *zColumn,
  5676. sqlite3_int64 iRow,
  5677. int flags,
  5678. sqlite3_blob **ppBlob
  5679. );
  5680. /*
  5681. ** CAPI3REF: Move a BLOB Handle to a New Row
  5682. **
  5683. ** ^This function is used to move an existing blob handle so that it points
  5684. ** to a different row of the same database table. ^The new row is identified
  5685. ** by the rowid value passed as the second argument. Only the row can be
  5686. ** changed. ^The database, table and column on which the blob handle is open
  5687. ** remain the same. Moving an existing blob handle to a new row can be
  5688. ** faster than closing the existing handle and opening a new one.
  5689. **
  5690. ** ^(The new row must meet the same criteria as for [sqlite3_blob_open()] -
  5691. ** it must exist and there must be either a blob or text value stored in
  5692. ** the nominated column.)^ ^If the new row is not present in the table, or if
  5693. ** it does not contain a blob or text value, or if another error occurs, an
  5694. ** SQLite error code is returned and the blob handle is considered aborted.
  5695. ** ^All subsequent calls to [sqlite3_blob_read()], [sqlite3_blob_write()] or
  5696. ** [sqlite3_blob_reopen()] on an aborted blob handle immediately return
  5697. ** SQLITE_ABORT. ^Calling [sqlite3_blob_bytes()] on an aborted blob handle
  5698. ** always returns zero.
  5699. **
  5700. ** ^This function sets the database handle error code and message.
  5701. */
  5702. SQLITE_API SQLITE_EXPERIMENTAL int sqlite3_blob_reopen(sqlite3_blob *, sqlite3_int64);
  5703. /*
  5704. ** CAPI3REF: Close A BLOB Handle
  5705. **
  5706. ** ^Closes an open [BLOB handle].
  5707. **
  5708. ** ^Closing a BLOB shall cause the current transaction to commit
  5709. ** if there are no other BLOBs, no pending prepared statements, and the
  5710. ** database connection is in [autocommit mode].
  5711. ** ^If any writes were made to the BLOB, they might be held in cache
  5712. ** until the close operation if they will fit.
  5713. **
  5714. ** ^(Closing the BLOB often forces the changes
  5715. ** out to disk and so if any I/O errors occur, they will likely occur
  5716. ** at the time when the BLOB is closed. Any errors that occur during
  5717. ** closing are reported as a non-zero return value.)^
  5718. **
  5719. ** ^(The BLOB is closed unconditionally. Even if this routine returns
  5720. ** an error code, the BLOB is still closed.)^
  5721. **
  5722. ** ^Calling this routine with a null pointer (such as would be returned
  5723. ** by a failed call to [sqlite3_blob_open()]) is a harmless no-op.
  5724. */
  5725. SQLITE_API int sqlite3_blob_close(sqlite3_blob *);
  5726. /*
  5727. ** CAPI3REF: Return The Size Of An Open BLOB
  5728. **
  5729. ** ^Returns the size in bytes of the BLOB accessible via the
  5730. ** successfully opened [BLOB handle] in its only argument. ^The
  5731. ** incremental blob I/O routines can only read or overwriting existing
  5732. ** blob content; they cannot change the size of a blob.
  5733. **
  5734. ** This routine only works on a [BLOB handle] which has been created
  5735. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5736. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5737. ** to this routine results in undefined and probably undesirable behavior.
  5738. */
  5739. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *);
  5740. /*
  5741. ** CAPI3REF: Read Data From A BLOB Incrementally
  5742. **
  5743. ** ^(This function is used to read data from an open [BLOB handle] into a
  5744. ** caller-supplied buffer. N bytes of data are copied into buffer Z
  5745. ** from the open BLOB, starting at offset iOffset.)^
  5746. **
  5747. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5748. ** [SQLITE_ERROR] is returned and no data is read. ^If N or iOffset is
  5749. ** less than zero, [SQLITE_ERROR] is returned and no data is read.
  5750. ** ^The size of the blob (and hence the maximum value of N+iOffset)
  5751. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5752. **
  5753. ** ^An attempt to read from an expired [BLOB handle] fails with an
  5754. ** error code of [SQLITE_ABORT].
  5755. **
  5756. ** ^(On success, sqlite3_blob_read() returns SQLITE_OK.
  5757. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5758. **
  5759. ** This routine only works on a [BLOB handle] which has been created
  5760. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5761. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5762. ** to this routine results in undefined and probably undesirable behavior.
  5763. **
  5764. ** See also: [sqlite3_blob_write()].
  5765. */
  5766. SQLITE_API int sqlite3_blob_read(sqlite3_blob *, void *Z, int N, int iOffset);
  5767. /*
  5768. ** CAPI3REF: Write Data Into A BLOB Incrementally
  5769. **
  5770. ** ^This function is used to write data into an open [BLOB handle] from a
  5771. ** caller-supplied buffer. ^N bytes of data are copied from the buffer Z
  5772. ** into the open BLOB, starting at offset iOffset.
  5773. **
  5774. ** ^If the [BLOB handle] passed as the first argument was not opened for
  5775. ** writing (the flags parameter to [sqlite3_blob_open()] was zero),
  5776. ** this function returns [SQLITE_READONLY].
  5777. **
  5778. ** ^This function may only modify the contents of the BLOB; it is
  5779. ** not possible to increase the size of a BLOB using this API.
  5780. ** ^If offset iOffset is less than N bytes from the end of the BLOB,
  5781. ** [SQLITE_ERROR] is returned and no data is written. ^If N is
  5782. ** less than zero [SQLITE_ERROR] is returned and no data is written.
  5783. ** The size of the BLOB (and hence the maximum value of N+iOffset)
  5784. ** can be determined using the [sqlite3_blob_bytes()] interface.
  5785. **
  5786. ** ^An attempt to write to an expired [BLOB handle] fails with an
  5787. ** error code of [SQLITE_ABORT]. ^Writes to the BLOB that occurred
  5788. ** before the [BLOB handle] expired are not rolled back by the
  5789. ** expiration of the handle, though of course those changes might
  5790. ** have been overwritten by the statement that expired the BLOB handle
  5791. ** or by other independent statements.
  5792. **
  5793. ** ^(On success, sqlite3_blob_write() returns SQLITE_OK.
  5794. ** Otherwise, an [error code] or an [extended error code] is returned.)^
  5795. **
  5796. ** This routine only works on a [BLOB handle] which has been created
  5797. ** by a prior successful call to [sqlite3_blob_open()] and which has not
  5798. ** been closed by [sqlite3_blob_close()]. Passing any other pointer in
  5799. ** to this routine results in undefined and probably undesirable behavior.
  5800. **
  5801. ** See also: [sqlite3_blob_read()].
  5802. */
  5803. SQLITE_API int sqlite3_blob_write(sqlite3_blob *, const void *z, int n, int iOffset);
  5804. /*
  5805. ** CAPI3REF: Virtual File System Objects
  5806. **
  5807. ** A virtual filesystem (VFS) is an [sqlite3_vfs] object
  5808. ** that SQLite uses to interact
  5809. ** with the underlying operating system. Most SQLite builds come with a
  5810. ** single default VFS that is appropriate for the host computer.
  5811. ** New VFSes can be registered and existing VFSes can be unregistered.
  5812. ** The following interfaces are provided.
  5813. **
  5814. ** ^The sqlite3_vfs_find() interface returns a pointer to a VFS given its name.
  5815. ** ^Names are case sensitive.
  5816. ** ^Names are zero-terminated UTF-8 strings.
  5817. ** ^If there is no match, a NULL pointer is returned.
  5818. ** ^If zVfsName is NULL then the default VFS is returned.
  5819. **
  5820. ** ^New VFSes are registered with sqlite3_vfs_register().
  5821. ** ^Each new VFS becomes the default VFS if the makeDflt flag is set.
  5822. ** ^The same VFS can be registered multiple times without injury.
  5823. ** ^To make an existing VFS into the default VFS, register it again
  5824. ** with the makeDflt flag set. If two different VFSes with the
  5825. ** same name are registered, the behavior is undefined. If a
  5826. ** VFS is registered with a name that is NULL or an empty string,
  5827. ** then the behavior is undefined.
  5828. **
  5829. ** ^Unregister a VFS with the sqlite3_vfs_unregister() interface.
  5830. ** ^(If the default VFS is unregistered, another VFS is chosen as
  5831. ** the default. The choice for the new VFS is arbitrary.)^
  5832. */
  5833. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfsName);
  5834. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs*, int makeDflt);
  5835. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs*);
  5836. /*
  5837. ** CAPI3REF: Mutexes
  5838. **
  5839. ** The SQLite core uses these routines for thread
  5840. ** synchronization. Though they are intended for internal
  5841. ** use by SQLite, code that links against SQLite is
  5842. ** permitted to use any of these routines.
  5843. **
  5844. ** The SQLite source code contains multiple implementations
  5845. ** of these mutex routines. An appropriate implementation
  5846. ** is selected automatically at compile-time. ^(The following
  5847. ** implementations are available in the SQLite core:
  5848. **
  5849. ** <ul>
  5850. ** <li> SQLITE_MUTEX_PTHREADS
  5851. ** <li> SQLITE_MUTEX_W32
  5852. ** <li> SQLITE_MUTEX_NOOP
  5853. ** </ul>)^
  5854. **
  5855. ** ^The SQLITE_MUTEX_NOOP implementation is a set of routines
  5856. ** that does no real locking and is appropriate for use in
  5857. ** a single-threaded application. ^The SQLITE_MUTEX_PTHREADS and
  5858. ** SQLITE_MUTEX_W32 implementations are appropriate for use on Unix
  5859. ** and Windows.
  5860. **
  5861. ** ^(If SQLite is compiled with the SQLITE_MUTEX_APPDEF preprocessor
  5862. ** macro defined (with "-DSQLITE_MUTEX_APPDEF=1"), then no mutex
  5863. ** implementation is included with the library. In this case the
  5864. ** application must supply a custom mutex implementation using the
  5865. ** [SQLITE_CONFIG_MUTEX] option of the sqlite3_config() function
  5866. ** before calling sqlite3_initialize() or any other public sqlite3_
  5867. ** function that calls sqlite3_initialize().)^
  5868. **
  5869. ** ^The sqlite3_mutex_alloc() routine allocates a new
  5870. ** mutex and returns a pointer to it. ^If it returns NULL
  5871. ** that means that a mutex could not be allocated. ^SQLite
  5872. ** will unwind its stack and return an error. ^(The argument
  5873. ** to sqlite3_mutex_alloc() is one of these integer constants:
  5874. **
  5875. ** <ul>
  5876. ** <li> SQLITE_MUTEX_FAST
  5877. ** <li> SQLITE_MUTEX_RECURSIVE
  5878. ** <li> SQLITE_MUTEX_STATIC_MASTER
  5879. ** <li> SQLITE_MUTEX_STATIC_MEM
  5880. ** <li> SQLITE_MUTEX_STATIC_OPEN
  5881. ** <li> SQLITE_MUTEX_STATIC_PRNG
  5882. ** <li> SQLITE_MUTEX_STATIC_LRU
  5883. ** <li> SQLITE_MUTEX_STATIC_PMEM
  5884. ** <li> SQLITE_MUTEX_STATIC_APP1
  5885. ** <li> SQLITE_MUTEX_STATIC_APP2
  5886. ** </ul>)^
  5887. **
  5888. ** ^The first two constants (SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE)
  5889. ** cause sqlite3_mutex_alloc() to create
  5890. ** a new mutex. ^The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  5891. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  5892. ** The mutex implementation does not need to make a distinction
  5893. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  5894. ** not want to. ^SQLite will only request a recursive mutex in
  5895. ** cases where it really needs one. ^If a faster non-recursive mutex
  5896. ** implementation is available on the host platform, the mutex subsystem
  5897. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  5898. **
  5899. ** ^The other allowed parameters to sqlite3_mutex_alloc() (anything other
  5900. ** than SQLITE_MUTEX_FAST and SQLITE_MUTEX_RECURSIVE) each return
  5901. ** a pointer to a static preexisting mutex. ^Six static mutexes are
  5902. ** used by the current version of SQLite. Future versions of SQLite
  5903. ** may add additional static mutexes. Static mutexes are for internal
  5904. ** use by SQLite only. Applications that use SQLite mutexes should
  5905. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  5906. ** SQLITE_MUTEX_RECURSIVE.
  5907. **
  5908. ** ^Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  5909. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  5910. ** returns a different mutex on every call. ^But for the static
  5911. ** mutex types, the same mutex is returned on every call that has
  5912. ** the same type number.
  5913. **
  5914. ** ^The sqlite3_mutex_free() routine deallocates a previously
  5915. ** allocated dynamic mutex. ^SQLite is careful to deallocate every
  5916. ** dynamic mutex that it allocates. The dynamic mutexes must not be in
  5917. ** use when they are deallocated. Attempting to deallocate a static
  5918. ** mutex results in undefined behavior. ^SQLite never deallocates
  5919. ** a static mutex.
  5920. **
  5921. ** ^The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  5922. ** to enter a mutex. ^If another thread is already within the mutex,
  5923. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  5924. ** SQLITE_BUSY. ^The sqlite3_mutex_try() interface returns [SQLITE_OK]
  5925. ** upon successful entry. ^(Mutexes created using
  5926. ** SQLITE_MUTEX_RECURSIVE can be entered multiple times by the same thread.
  5927. ** In such cases the,
  5928. ** mutex must be exited an equal number of times before another thread
  5929. ** can enter.)^ ^(If the same thread tries to enter any other
  5930. ** kind of mutex more than once, the behavior is undefined.
  5931. ** SQLite will never exhibit
  5932. ** such behavior in its own use of mutexes.)^
  5933. **
  5934. ** ^(Some systems (for example, Windows 95) do not support the operation
  5935. ** implemented by sqlite3_mutex_try(). On those systems, sqlite3_mutex_try()
  5936. ** will always return SQLITE_BUSY. The SQLite core only ever uses
  5937. ** sqlite3_mutex_try() as an optimization so this is acceptable behavior.)^
  5938. **
  5939. ** ^The sqlite3_mutex_leave() routine exits a mutex that was
  5940. ** previously entered by the same thread. ^(The behavior
  5941. ** is undefined if the mutex is not currently entered by the
  5942. ** calling thread or is not currently allocated. SQLite will
  5943. ** never do either.)^
  5944. **
  5945. ** ^If the argument to sqlite3_mutex_enter(), sqlite3_mutex_try(), or
  5946. ** sqlite3_mutex_leave() is a NULL pointer, then all three routines
  5947. ** behave as no-ops.
  5948. **
  5949. ** See also: [sqlite3_mutex_held()] and [sqlite3_mutex_notheld()].
  5950. */
  5951. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int);
  5952. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex*);
  5953. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex*);
  5954. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex*);
  5955. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex*);
  5956. /*
  5957. ** CAPI3REF: Mutex Methods Object
  5958. **
  5959. ** An instance of this structure defines the low-level routines
  5960. ** used to allocate and use mutexes.
  5961. **
  5962. ** Usually, the default mutex implementations provided by SQLite are
  5963. ** sufficient, however the user has the option of substituting a custom
  5964. ** implementation for specialized deployments or systems for which SQLite
  5965. ** does not provide a suitable implementation. In this case, the user
  5966. ** creates and populates an instance of this structure to pass
  5967. ** to sqlite3_config() along with the [SQLITE_CONFIG_MUTEX] option.
  5968. ** Additionally, an instance of this structure can be used as an
  5969. ** output variable when querying the system for the current mutex
  5970. ** implementation, using the [SQLITE_CONFIG_GETMUTEX] option.
  5971. **
  5972. ** ^The xMutexInit method defined by this structure is invoked as
  5973. ** part of system initialization by the sqlite3_initialize() function.
  5974. ** ^The xMutexInit routine is called by SQLite exactly once for each
  5975. ** effective call to [sqlite3_initialize()].
  5976. **
  5977. ** ^The xMutexEnd method defined by this structure is invoked as
  5978. ** part of system shutdown by the sqlite3_shutdown() function. The
  5979. ** implementation of this method is expected to release all outstanding
  5980. ** resources obtained by the mutex methods implementation, especially
  5981. ** those obtained by the xMutexInit method. ^The xMutexEnd()
  5982. ** interface is invoked exactly once for each call to [sqlite3_shutdown()].
  5983. **
  5984. ** ^(The remaining seven methods defined by this structure (xMutexAlloc,
  5985. ** xMutexFree, xMutexEnter, xMutexTry, xMutexLeave, xMutexHeld and
  5986. ** xMutexNotheld) implement the following interfaces (respectively):
  5987. **
  5988. ** <ul>
  5989. ** <li> [sqlite3_mutex_alloc()] </li>
  5990. ** <li> [sqlite3_mutex_free()] </li>
  5991. ** <li> [sqlite3_mutex_enter()] </li>
  5992. ** <li> [sqlite3_mutex_try()] </li>
  5993. ** <li> [sqlite3_mutex_leave()] </li>
  5994. ** <li> [sqlite3_mutex_held()] </li>
  5995. ** <li> [sqlite3_mutex_notheld()] </li>
  5996. ** </ul>)^
  5997. **
  5998. ** The only difference is that the public sqlite3_XXX functions enumerated
  5999. ** above silently ignore any invocations that pass a NULL pointer instead
  6000. ** of a valid mutex handle. The implementations of the methods defined
  6001. ** by this structure are not required to handle this case, the results
  6002. ** of passing a NULL pointer instead of a valid mutex handle are undefined
  6003. ** (i.e. it is acceptable to provide an implementation that segfaults if
  6004. ** it is passed a NULL pointer).
  6005. **
  6006. ** The xMutexInit() method must be threadsafe. ^It must be harmless to
  6007. ** invoke xMutexInit() multiple times within the same process and without
  6008. ** intervening calls to xMutexEnd(). Second and subsequent calls to
  6009. ** xMutexInit() must be no-ops.
  6010. **
  6011. ** ^xMutexInit() must not use SQLite memory allocation ([sqlite3_malloc()]
  6012. ** and its associates). ^Similarly, xMutexAlloc() must not use SQLite memory
  6013. ** allocation for a static mutex. ^However xMutexAlloc() may use SQLite
  6014. ** memory allocation for a fast or recursive mutex.
  6015. **
  6016. ** ^SQLite will invoke the xMutexEnd() method when [sqlite3_shutdown()] is
  6017. ** called, but only if the prior call to xMutexInit returned SQLITE_OK.
  6018. ** If xMutexInit fails in any way, it is expected to clean up after itself
  6019. ** prior to returning.
  6020. */
  6021. typedef struct sqlite3_mutex_methods sqlite3_mutex_methods;
  6022. struct sqlite3_mutex_methods {
  6023. int (*xMutexInit)(void);
  6024. int (*xMutexEnd)(void);
  6025. sqlite3_mutex *(*xMutexAlloc)(int);
  6026. void (*xMutexFree)(sqlite3_mutex *);
  6027. void (*xMutexEnter)(sqlite3_mutex *);
  6028. int (*xMutexTry)(sqlite3_mutex *);
  6029. void (*xMutexLeave)(sqlite3_mutex *);
  6030. int (*xMutexHeld)(sqlite3_mutex *);
  6031. int (*xMutexNotheld)(sqlite3_mutex *);
  6032. };
  6033. /*
  6034. ** CAPI3REF: Mutex Verification Routines
  6035. **
  6036. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routines
  6037. ** are intended for use inside assert() statements. ^The SQLite core
  6038. ** never uses these routines except inside an assert() and applications
  6039. ** are advised to follow the lead of the core. ^The SQLite core only
  6040. ** provides implementations for these routines when it is compiled
  6041. ** with the SQLITE_DEBUG flag. ^External mutex implementations
  6042. ** are only required to provide these routines if SQLITE_DEBUG is
  6043. ** defined and if NDEBUG is not defined.
  6044. **
  6045. ** ^These routines should return true if the mutex in their argument
  6046. ** is held or not held, respectively, by the calling thread.
  6047. **
  6048. ** ^The implementation is not required to provide versions of these
  6049. ** routines that actually work. If the implementation does not provide working
  6050. ** versions of these routines, it should at least provide stubs that always
  6051. ** return true so that one does not get spurious assertion failures.
  6052. **
  6053. ** ^If the argument to sqlite3_mutex_held() is a NULL pointer then
  6054. ** the routine should return 1. This seems counter-intuitive since
  6055. ** clearly the mutex cannot be held if it does not exist. But
  6056. ** the reason the mutex does not exist is because the build is not
  6057. ** using mutexes. And we do not want the assert() containing the
  6058. ** call to sqlite3_mutex_held() to fail, so a non-zero return is
  6059. ** the appropriate thing to do. ^The sqlite3_mutex_notheld()
  6060. ** interface should also return 1 when given a NULL pointer.
  6061. */
  6062. #ifndef NDEBUG
  6063. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex*);
  6064. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex*);
  6065. #endif
  6066. /*
  6067. ** CAPI3REF: Mutex Types
  6068. **
  6069. ** The [sqlite3_mutex_alloc()] interface takes a single argument
  6070. ** which is one of these integer constants.
  6071. **
  6072. ** The set of static mutexes may change from one SQLite release to the
  6073. ** next. Applications that override the built-in mutex logic must be
  6074. ** prepared to accommodate additional static mutexes.
  6075. */
  6076. #define SQLITE_MUTEX_FAST 0
  6077. #define SQLITE_MUTEX_RECURSIVE 1
  6078. #define SQLITE_MUTEX_STATIC_MASTER 2
  6079. #define SQLITE_MUTEX_STATIC_MEM 3 /* sqlite3_malloc() */
  6080. #define SQLITE_MUTEX_STATIC_MEM2 4 /* NOT USED */
  6081. #define SQLITE_MUTEX_STATIC_OPEN 4 /* sqlite3BtreeOpen() */
  6082. #define SQLITE_MUTEX_STATIC_PRNG 5 /* sqlite3_random() */
  6083. #define SQLITE_MUTEX_STATIC_LRU 6 /* lru page list */
  6084. #define SQLITE_MUTEX_STATIC_LRU2 7 /* NOT USED */
  6085. #define SQLITE_MUTEX_STATIC_PMEM 7 /* sqlite3PageMalloc() */
  6086. #define SQLITE_MUTEX_STATIC_APP1 8 /* For use by application */
  6087. #define SQLITE_MUTEX_STATIC_APP2 9 /* For use by application */
  6088. #define SQLITE_MUTEX_STATIC_APP3 10 /* For use by application */
  6089. /*
  6090. ** CAPI3REF: Retrieve the mutex for a database connection
  6091. **
  6092. ** ^This interface returns a pointer the [sqlite3_mutex] object that
  6093. ** serializes access to the [database connection] given in the argument
  6094. ** when the [threading mode] is Serialized.
  6095. ** ^If the [threading mode] is Single-thread or Multi-thread then this
  6096. ** routine returns a NULL pointer.
  6097. */
  6098. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3*);
  6099. /*
  6100. ** CAPI3REF: Low-Level Control Of Database Files
  6101. **
  6102. ** ^The [sqlite3_file_control()] interface makes a direct call to the
  6103. ** xFileControl method for the [sqlite3_io_methods] object associated
  6104. ** with a particular database identified by the second argument. ^The
  6105. ** name of the database is "main" for the main database or "temp" for the
  6106. ** TEMP database, or the name that appears after the AS keyword for
  6107. ** databases that are added using the [ATTACH] SQL command.
  6108. ** ^A NULL pointer can be used in place of "main" to refer to the
  6109. ** main database file.
  6110. ** ^The third and fourth parameters to this routine
  6111. ** are passed directly through to the second and third parameters of
  6112. ** the xFileControl method. ^The return value of the xFileControl
  6113. ** method becomes the return value of this routine.
  6114. **
  6115. ** ^The SQLITE_FCNTL_FILE_POINTER value for the op parameter causes
  6116. ** a pointer to the underlying [sqlite3_file] object to be written into
  6117. ** the space pointed to by the 4th parameter. ^The SQLITE_FCNTL_FILE_POINTER
  6118. ** case is a short-circuit path which does not actually invoke the
  6119. ** underlying sqlite3_io_methods.xFileControl method.
  6120. **
  6121. ** ^If the second parameter (zDbName) does not match the name of any
  6122. ** open database file, then SQLITE_ERROR is returned. ^This error
  6123. ** code is not remembered and will not be recalled by [sqlite3_errcode()]
  6124. ** or [sqlite3_errmsg()]. The underlying xFileControl method might
  6125. ** also return SQLITE_ERROR. There is no way to distinguish between
  6126. ** an incorrect zDbName and an SQLITE_ERROR return from the underlying
  6127. ** xFileControl method.
  6128. **
  6129. ** See also: [SQLITE_FCNTL_LOCKSTATE]
  6130. */
  6131. SQLITE_API int sqlite3_file_control(sqlite3*, const char *zDbName, int op, void*);
  6132. /*
  6133. ** CAPI3REF: Testing Interface
  6134. **
  6135. ** ^The sqlite3_test_control() interface is used to read out internal
  6136. ** state of SQLite and to inject faults into SQLite for testing
  6137. ** purposes. ^The first parameter is an operation code that determines
  6138. ** the number, meaning, and operation of all subsequent parameters.
  6139. **
  6140. ** This interface is not for use by applications. It exists solely
  6141. ** for verifying the correct operation of the SQLite library. Depending
  6142. ** on how the SQLite library is compiled, this interface might not exist.
  6143. **
  6144. ** The details of the operation codes, their meanings, the parameters
  6145. ** they take, and what they do are all subject to change without notice.
  6146. ** Unlike most of the SQLite API, this function is not guaranteed to
  6147. ** operate consistently from one release to the next.
  6148. */
  6149. SQLITE_API int sqlite3_test_control(int op, ...);
  6150. /*
  6151. ** CAPI3REF: Testing Interface Operation Codes
  6152. **
  6153. ** These constants are the valid operation code parameters used
  6154. ** as the first argument to [sqlite3_test_control()].
  6155. **
  6156. ** These parameters and their meanings are subject to change
  6157. ** without notice. These values are for testing purposes only.
  6158. ** Applications should not use any of these parameters or the
  6159. ** [sqlite3_test_control()] interface.
  6160. */
  6161. #define SQLITE_TESTCTRL_FIRST 5
  6162. #define SQLITE_TESTCTRL_PRNG_SAVE 5
  6163. #define SQLITE_TESTCTRL_PRNG_RESTORE 6
  6164. #define SQLITE_TESTCTRL_PRNG_RESET 7
  6165. #define SQLITE_TESTCTRL_BITVEC_TEST 8
  6166. #define SQLITE_TESTCTRL_FAULT_INSTALL 9
  6167. #define SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS 10
  6168. #define SQLITE_TESTCTRL_PENDING_BYTE 11
  6169. #define SQLITE_TESTCTRL_ASSERT 12
  6170. #define SQLITE_TESTCTRL_ALWAYS 13
  6171. #define SQLITE_TESTCTRL_RESERVE 14
  6172. #define SQLITE_TESTCTRL_OPTIMIZATIONS 15
  6173. #define SQLITE_TESTCTRL_ISKEYWORD 16
  6174. #define SQLITE_TESTCTRL_SCRATCHMALLOC 17
  6175. #define SQLITE_TESTCTRL_LOCALTIME_FAULT 18
  6176. #define SQLITE_TESTCTRL_EXPLAIN_STMT 19 /* NOT USED */
  6177. #define SQLITE_TESTCTRL_NEVER_CORRUPT 20
  6178. #define SQLITE_TESTCTRL_VDBE_COVERAGE 21
  6179. #define SQLITE_TESTCTRL_BYTEORDER 22
  6180. #define SQLITE_TESTCTRL_ISINIT 23
  6181. #define SQLITE_TESTCTRL_SORTER_MMAP 24
  6182. #define SQLITE_TESTCTRL_LAST 24
  6183. /*
  6184. ** CAPI3REF: SQLite Runtime Status
  6185. **
  6186. ** ^This interface is used to retrieve runtime status information
  6187. ** about the performance of SQLite, and optionally to reset various
  6188. ** highwater marks. ^The first argument is an integer code for
  6189. ** the specific parameter to measure. ^(Recognized integer codes
  6190. ** are of the form [status parameters | SQLITE_STATUS_...].)^
  6191. ** ^The current value of the parameter is returned into *pCurrent.
  6192. ** ^The highest recorded value is returned in *pHighwater. ^If the
  6193. ** resetFlag is true, then the highest record value is reset after
  6194. ** *pHighwater is written. ^(Some parameters do not record the highest
  6195. ** value. For those parameters
  6196. ** nothing is written into *pHighwater and the resetFlag is ignored.)^
  6197. ** ^(Other parameters record only the highwater mark and not the current
  6198. ** value. For these latter parameters nothing is written into *pCurrent.)^
  6199. **
  6200. ** ^The sqlite3_status() routine returns SQLITE_OK on success and a
  6201. ** non-zero [error code] on failure.
  6202. **
  6203. ** This routine is threadsafe but is not atomic. This routine can be
  6204. ** called while other threads are running the same or different SQLite
  6205. ** interfaces. However the values returned in *pCurrent and
  6206. ** *pHighwater reflect the status of SQLite at different points in time
  6207. ** and it is possible that another thread might change the parameter
  6208. ** in between the times when *pCurrent and *pHighwater are written.
  6209. **
  6210. ** See also: [sqlite3_db_status()]
  6211. */
  6212. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag);
  6213. /*
  6214. ** CAPI3REF: Status Parameters
  6215. ** KEYWORDS: {status parameters}
  6216. **
  6217. ** These integer constants designate various run-time status parameters
  6218. ** that can be returned by [sqlite3_status()].
  6219. **
  6220. ** <dl>
  6221. ** [[SQLITE_STATUS_MEMORY_USED]] ^(<dt>SQLITE_STATUS_MEMORY_USED</dt>
  6222. ** <dd>This parameter is the current amount of memory checked out
  6223. ** using [sqlite3_malloc()], either directly or indirectly. The
  6224. ** figure includes calls made to [sqlite3_malloc()] by the application
  6225. ** and internal memory usage by the SQLite library. Scratch memory
  6226. ** controlled by [SQLITE_CONFIG_SCRATCH] and auxiliary page-cache
  6227. ** memory controlled by [SQLITE_CONFIG_PAGECACHE] is not included in
  6228. ** this parameter. The amount returned is the sum of the allocation
  6229. ** sizes as reported by the xSize method in [sqlite3_mem_methods].</dd>)^
  6230. **
  6231. ** [[SQLITE_STATUS_MALLOC_SIZE]] ^(<dt>SQLITE_STATUS_MALLOC_SIZE</dt>
  6232. ** <dd>This parameter records the largest memory allocation request
  6233. ** handed to [sqlite3_malloc()] or [sqlite3_realloc()] (or their
  6234. ** internal equivalents). Only the value returned in the
  6235. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6236. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6237. **
  6238. ** [[SQLITE_STATUS_MALLOC_COUNT]] ^(<dt>SQLITE_STATUS_MALLOC_COUNT</dt>
  6239. ** <dd>This parameter records the number of separate memory allocations
  6240. ** currently checked out.</dd>)^
  6241. **
  6242. ** [[SQLITE_STATUS_PAGECACHE_USED]] ^(<dt>SQLITE_STATUS_PAGECACHE_USED</dt>
  6243. ** <dd>This parameter returns the number of pages used out of the
  6244. ** [pagecache memory allocator] that was configured using
  6245. ** [SQLITE_CONFIG_PAGECACHE]. The
  6246. ** value returned is in pages, not in bytes.</dd>)^
  6247. **
  6248. ** [[SQLITE_STATUS_PAGECACHE_OVERFLOW]]
  6249. ** ^(<dt>SQLITE_STATUS_PAGECACHE_OVERFLOW</dt>
  6250. ** <dd>This parameter returns the number of bytes of page cache
  6251. ** allocation which could not be satisfied by the [SQLITE_CONFIG_PAGECACHE]
  6252. ** buffer and where forced to overflow to [sqlite3_malloc()]. The
  6253. ** returned value includes allocations that overflowed because they
  6254. ** where too large (they were larger than the "sz" parameter to
  6255. ** [SQLITE_CONFIG_PAGECACHE]) and allocations that overflowed because
  6256. ** no space was left in the page cache.</dd>)^
  6257. **
  6258. ** [[SQLITE_STATUS_PAGECACHE_SIZE]] ^(<dt>SQLITE_STATUS_PAGECACHE_SIZE</dt>
  6259. ** <dd>This parameter records the largest memory allocation request
  6260. ** handed to [pagecache memory allocator]. Only the value returned in the
  6261. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6262. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6263. **
  6264. ** [[SQLITE_STATUS_SCRATCH_USED]] ^(<dt>SQLITE_STATUS_SCRATCH_USED</dt>
  6265. ** <dd>This parameter returns the number of allocations used out of the
  6266. ** [scratch memory allocator] configured using
  6267. ** [SQLITE_CONFIG_SCRATCH]. The value returned is in allocations, not
  6268. ** in bytes. Since a single thread may only have one scratch allocation
  6269. ** outstanding at time, this parameter also reports the number of threads
  6270. ** using scratch memory at the same time.</dd>)^
  6271. **
  6272. ** [[SQLITE_STATUS_SCRATCH_OVERFLOW]] ^(<dt>SQLITE_STATUS_SCRATCH_OVERFLOW</dt>
  6273. ** <dd>This parameter returns the number of bytes of scratch memory
  6274. ** allocation which could not be satisfied by the [SQLITE_CONFIG_SCRATCH]
  6275. ** buffer and where forced to overflow to [sqlite3_malloc()]. The values
  6276. ** returned include overflows because the requested allocation was too
  6277. ** larger (that is, because the requested allocation was larger than the
  6278. ** "sz" parameter to [SQLITE_CONFIG_SCRATCH]) and because no scratch buffer
  6279. ** slots were available.
  6280. ** </dd>)^
  6281. **
  6282. ** [[SQLITE_STATUS_SCRATCH_SIZE]] ^(<dt>SQLITE_STATUS_SCRATCH_SIZE</dt>
  6283. ** <dd>This parameter records the largest memory allocation request
  6284. ** handed to [scratch memory allocator]. Only the value returned in the
  6285. ** *pHighwater parameter to [sqlite3_status()] is of interest.
  6286. ** The value written into the *pCurrent parameter is undefined.</dd>)^
  6287. **
  6288. ** [[SQLITE_STATUS_PARSER_STACK]] ^(<dt>SQLITE_STATUS_PARSER_STACK</dt>
  6289. ** <dd>This parameter records the deepest parser stack. It is only
  6290. ** meaningful if SQLite is compiled with [YYTRACKMAXSTACKDEPTH].</dd>)^
  6291. ** </dl>
  6292. **
  6293. ** New status parameters may be added from time to time.
  6294. */
  6295. #define SQLITE_STATUS_MEMORY_USED 0
  6296. #define SQLITE_STATUS_PAGECACHE_USED 1
  6297. #define SQLITE_STATUS_PAGECACHE_OVERFLOW 2
  6298. #define SQLITE_STATUS_SCRATCH_USED 3
  6299. #define SQLITE_STATUS_SCRATCH_OVERFLOW 4
  6300. #define SQLITE_STATUS_MALLOC_SIZE 5
  6301. #define SQLITE_STATUS_PARSER_STACK 6
  6302. #define SQLITE_STATUS_PAGECACHE_SIZE 7
  6303. #define SQLITE_STATUS_SCRATCH_SIZE 8
  6304. #define SQLITE_STATUS_MALLOC_COUNT 9
  6305. /*
  6306. ** CAPI3REF: Database Connection Status
  6307. **
  6308. ** ^This interface is used to retrieve runtime status information
  6309. ** about a single [database connection]. ^The first argument is the
  6310. ** database connection object to be interrogated. ^The second argument
  6311. ** is an integer constant, taken from the set of
  6312. ** [SQLITE_DBSTATUS options], that
  6313. ** determines the parameter to interrogate. The set of
  6314. ** [SQLITE_DBSTATUS options] is likely
  6315. ** to grow in future releases of SQLite.
  6316. **
  6317. ** ^The current value of the requested parameter is written into *pCur
  6318. ** and the highest instantaneous value is written into *pHiwtr. ^If
  6319. ** the resetFlg is true, then the highest instantaneous value is
  6320. ** reset back down to the current value.
  6321. **
  6322. ** ^The sqlite3_db_status() routine returns SQLITE_OK on success and a
  6323. ** non-zero [error code] on failure.
  6324. **
  6325. ** See also: [sqlite3_status()] and [sqlite3_stmt_status()].
  6326. */
  6327. SQLITE_API int sqlite3_db_status(sqlite3*, int op, int *pCur, int *pHiwtr, int resetFlg);
  6328. /*
  6329. ** CAPI3REF: Status Parameters for database connections
  6330. ** KEYWORDS: {SQLITE_DBSTATUS options}
  6331. **
  6332. ** These constants are the available integer "verbs" that can be passed as
  6333. ** the second argument to the [sqlite3_db_status()] interface.
  6334. **
  6335. ** New verbs may be added in future releases of SQLite. Existing verbs
  6336. ** might be discontinued. Applications should check the return code from
  6337. ** [sqlite3_db_status()] to make sure that the call worked.
  6338. ** The [sqlite3_db_status()] interface will return a non-zero error code
  6339. ** if a discontinued or unsupported verb is invoked.
  6340. **
  6341. ** <dl>
  6342. ** [[SQLITE_DBSTATUS_LOOKASIDE_USED]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_USED</dt>
  6343. ** <dd>This parameter returns the number of lookaside memory slots currently
  6344. ** checked out.</dd>)^
  6345. **
  6346. ** [[SQLITE_DBSTATUS_LOOKASIDE_HIT]] ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_HIT</dt>
  6347. ** <dd>This parameter returns the number malloc attempts that were
  6348. ** satisfied using lookaside memory. Only the high-water value is meaningful;
  6349. ** the current value is always zero.)^
  6350. **
  6351. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE]]
  6352. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE</dt>
  6353. ** <dd>This parameter returns the number malloc attempts that might have
  6354. ** been satisfied using lookaside memory but failed due to the amount of
  6355. ** memory requested being larger than the lookaside slot size.
  6356. ** Only the high-water value is meaningful;
  6357. ** the current value is always zero.)^
  6358. **
  6359. ** [[SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL]]
  6360. ** ^(<dt>SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL</dt>
  6361. ** <dd>This parameter returns the number malloc attempts that might have
  6362. ** been satisfied using lookaside memory but failed due to all lookaside
  6363. ** memory already being in use.
  6364. ** Only the high-water value is meaningful;
  6365. ** the current value is always zero.)^
  6366. **
  6367. ** [[SQLITE_DBSTATUS_CACHE_USED]] ^(<dt>SQLITE_DBSTATUS_CACHE_USED</dt>
  6368. ** <dd>This parameter returns the approximate number of bytes of heap
  6369. ** memory used by all pager caches associated with the database connection.)^
  6370. ** ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_USED is always 0.
  6371. **
  6372. ** [[SQLITE_DBSTATUS_SCHEMA_USED]] ^(<dt>SQLITE_DBSTATUS_SCHEMA_USED</dt>
  6373. ** <dd>This parameter returns the approximate number of bytes of heap
  6374. ** memory used to store the schema for all databases associated
  6375. ** with the connection - main, temp, and any [ATTACH]-ed databases.)^
  6376. ** ^The full amount of memory used by the schemas is reported, even if the
  6377. ** schema memory is shared with other database connections due to
  6378. ** [shared cache mode] being enabled.
  6379. ** ^The highwater mark associated with SQLITE_DBSTATUS_SCHEMA_USED is always 0.
  6380. **
  6381. ** [[SQLITE_DBSTATUS_STMT_USED]] ^(<dt>SQLITE_DBSTATUS_STMT_USED</dt>
  6382. ** <dd>This parameter returns the approximate number of bytes of heap
  6383. ** and lookaside memory used by all prepared statements associated with
  6384. ** the database connection.)^
  6385. ** ^The highwater mark associated with SQLITE_DBSTATUS_STMT_USED is always 0.
  6386. ** </dd>
  6387. **
  6388. ** [[SQLITE_DBSTATUS_CACHE_HIT]] ^(<dt>SQLITE_DBSTATUS_CACHE_HIT</dt>
  6389. ** <dd>This parameter returns the number of pager cache hits that have
  6390. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_HIT
  6391. ** is always 0.
  6392. ** </dd>
  6393. **
  6394. ** [[SQLITE_DBSTATUS_CACHE_MISS]] ^(<dt>SQLITE_DBSTATUS_CACHE_MISS</dt>
  6395. ** <dd>This parameter returns the number of pager cache misses that have
  6396. ** occurred.)^ ^The highwater mark associated with SQLITE_DBSTATUS_CACHE_MISS
  6397. ** is always 0.
  6398. ** </dd>
  6399. **
  6400. ** [[SQLITE_DBSTATUS_CACHE_WRITE]] ^(<dt>SQLITE_DBSTATUS_CACHE_WRITE</dt>
  6401. ** <dd>This parameter returns the number of dirty cache entries that have
  6402. ** been written to disk. Specifically, the number of pages written to the
  6403. ** wal file in wal mode databases, or the number of pages written to the
  6404. ** database file in rollback mode databases. Any pages written as part of
  6405. ** transaction rollback or database recovery operations are not included.
  6406. ** If an IO or other error occurs while writing a page to disk, the effect
  6407. ** on subsequent SQLITE_DBSTATUS_CACHE_WRITE requests is undefined.)^ ^The
  6408. ** highwater mark associated with SQLITE_DBSTATUS_CACHE_WRITE is always 0.
  6409. ** </dd>
  6410. **
  6411. ** [[SQLITE_DBSTATUS_DEFERRED_FKS]] ^(<dt>SQLITE_DBSTATUS_DEFERRED_FKS</dt>
  6412. ** <dd>This parameter returns zero for the current value if and only if
  6413. ** all foreign key constraints (deferred or immediate) have been
  6414. ** resolved.)^ ^The highwater mark is always 0.
  6415. ** </dd>
  6416. ** </dl>
  6417. */
  6418. #define SQLITE_DBSTATUS_LOOKASIDE_USED 0
  6419. #define SQLITE_DBSTATUS_CACHE_USED 1
  6420. #define SQLITE_DBSTATUS_SCHEMA_USED 2
  6421. #define SQLITE_DBSTATUS_STMT_USED 3
  6422. #define SQLITE_DBSTATUS_LOOKASIDE_HIT 4
  6423. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE 5
  6424. #define SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL 6
  6425. #define SQLITE_DBSTATUS_CACHE_HIT 7
  6426. #define SQLITE_DBSTATUS_CACHE_MISS 8
  6427. #define SQLITE_DBSTATUS_CACHE_WRITE 9
  6428. #define SQLITE_DBSTATUS_DEFERRED_FKS 10
  6429. #define SQLITE_DBSTATUS_MAX 10 /* Largest defined DBSTATUS */
  6430. /*
  6431. ** CAPI3REF: Prepared Statement Status
  6432. **
  6433. ** ^(Each prepared statement maintains various
  6434. ** [SQLITE_STMTSTATUS counters] that measure the number
  6435. ** of times it has performed specific operations.)^ These counters can
  6436. ** be used to monitor the performance characteristics of the prepared
  6437. ** statements. For example, if the number of table steps greatly exceeds
  6438. ** the number of table searches or result rows, that would tend to indicate
  6439. ** that the prepared statement is using a full table scan rather than
  6440. ** an index.
  6441. **
  6442. ** ^(This interface is used to retrieve and reset counter values from
  6443. ** a [prepared statement]. The first argument is the prepared statement
  6444. ** object to be interrogated. The second argument
  6445. ** is an integer code for a specific [SQLITE_STMTSTATUS counter]
  6446. ** to be interrogated.)^
  6447. ** ^The current value of the requested counter is returned.
  6448. ** ^If the resetFlg is true, then the counter is reset to zero after this
  6449. ** interface call returns.
  6450. **
  6451. ** See also: [sqlite3_status()] and [sqlite3_db_status()].
  6452. */
  6453. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt*, int op,int resetFlg);
  6454. /*
  6455. ** CAPI3REF: Status Parameters for prepared statements
  6456. ** KEYWORDS: {SQLITE_STMTSTATUS counter} {SQLITE_STMTSTATUS counters}
  6457. **
  6458. ** These preprocessor macros define integer codes that name counter
  6459. ** values associated with the [sqlite3_stmt_status()] interface.
  6460. ** The meanings of the various counters are as follows:
  6461. **
  6462. ** <dl>
  6463. ** [[SQLITE_STMTSTATUS_FULLSCAN_STEP]] <dt>SQLITE_STMTSTATUS_FULLSCAN_STEP</dt>
  6464. ** <dd>^This is the number of times that SQLite has stepped forward in
  6465. ** a table as part of a full table scan. Large numbers for this counter
  6466. ** may indicate opportunities for performance improvement through
  6467. ** careful use of indices.</dd>
  6468. **
  6469. ** [[SQLITE_STMTSTATUS_SORT]] <dt>SQLITE_STMTSTATUS_SORT</dt>
  6470. ** <dd>^This is the number of sort operations that have occurred.
  6471. ** A non-zero value in this counter may indicate an opportunity to
  6472. ** improvement performance through careful use of indices.</dd>
  6473. **
  6474. ** [[SQLITE_STMTSTATUS_AUTOINDEX]] <dt>SQLITE_STMTSTATUS_AUTOINDEX</dt>
  6475. ** <dd>^This is the number of rows inserted into transient indices that
  6476. ** were created automatically in order to help joins run faster.
  6477. ** A non-zero value in this counter may indicate an opportunity to
  6478. ** improvement performance by adding permanent indices that do not
  6479. ** need to be reinitialized each time the statement is run.</dd>
  6480. **
  6481. ** [[SQLITE_STMTSTATUS_VM_STEP]] <dt>SQLITE_STMTSTATUS_VM_STEP</dt>
  6482. ** <dd>^This is the number of virtual machine operations executed
  6483. ** by the prepared statement if that number is less than or equal
  6484. ** to 2147483647. The number of virtual machine operations can be
  6485. ** used as a proxy for the total work done by the prepared statement.
  6486. ** If the number of virtual machine operations exceeds 2147483647
  6487. ** then the value returned by this statement status code is undefined.
  6488. ** </dd>
  6489. ** </dl>
  6490. */
  6491. #define SQLITE_STMTSTATUS_FULLSCAN_STEP 1
  6492. #define SQLITE_STMTSTATUS_SORT 2
  6493. #define SQLITE_STMTSTATUS_AUTOINDEX 3
  6494. #define SQLITE_STMTSTATUS_VM_STEP 4
  6495. /*
  6496. ** CAPI3REF: Custom Page Cache Object
  6497. **
  6498. ** The sqlite3_pcache type is opaque. It is implemented by
  6499. ** the pluggable module. The SQLite core has no knowledge of
  6500. ** its size or internal structure and never deals with the
  6501. ** sqlite3_pcache object except by holding and passing pointers
  6502. ** to the object.
  6503. **
  6504. ** See [sqlite3_pcache_methods2] for additional information.
  6505. */
  6506. typedef struct sqlite3_pcache sqlite3_pcache;
  6507. /*
  6508. ** CAPI3REF: Custom Page Cache Object
  6509. **
  6510. ** The sqlite3_pcache_page object represents a single page in the
  6511. ** page cache. The page cache will allocate instances of this
  6512. ** object. Various methods of the page cache use pointers to instances
  6513. ** of this object as parameters or as their return value.
  6514. **
  6515. ** See [sqlite3_pcache_methods2] for additional information.
  6516. */
  6517. typedef struct sqlite3_pcache_page sqlite3_pcache_page;
  6518. struct sqlite3_pcache_page {
  6519. void *pBuf; /* The content of the page */
  6520. void *pExtra; /* Extra information associated with the page */
  6521. };
  6522. /*
  6523. ** CAPI3REF: Application Defined Page Cache.
  6524. ** KEYWORDS: {page cache}
  6525. **
  6526. ** ^(The [sqlite3_config]([SQLITE_CONFIG_PCACHE2], ...) interface can
  6527. ** register an alternative page cache implementation by passing in an
  6528. ** instance of the sqlite3_pcache_methods2 structure.)^
  6529. ** In many applications, most of the heap memory allocated by
  6530. ** SQLite is used for the page cache.
  6531. ** By implementing a
  6532. ** custom page cache using this API, an application can better control
  6533. ** the amount of memory consumed by SQLite, the way in which
  6534. ** that memory is allocated and released, and the policies used to
  6535. ** determine exactly which parts of a database file are cached and for
  6536. ** how long.
  6537. **
  6538. ** The alternative page cache mechanism is an
  6539. ** extreme measure that is only needed by the most demanding applications.
  6540. ** The built-in page cache is recommended for most uses.
  6541. **
  6542. ** ^(The contents of the sqlite3_pcache_methods2 structure are copied to an
  6543. ** internal buffer by SQLite within the call to [sqlite3_config]. Hence
  6544. ** the application may discard the parameter after the call to
  6545. ** [sqlite3_config()] returns.)^
  6546. **
  6547. ** [[the xInit() page cache method]]
  6548. ** ^(The xInit() method is called once for each effective
  6549. ** call to [sqlite3_initialize()])^
  6550. ** (usually only once during the lifetime of the process). ^(The xInit()
  6551. ** method is passed a copy of the sqlite3_pcache_methods2.pArg value.)^
  6552. ** The intent of the xInit() method is to set up global data structures
  6553. ** required by the custom page cache implementation.
  6554. ** ^(If the xInit() method is NULL, then the
  6555. ** built-in default page cache is used instead of the application defined
  6556. ** page cache.)^
  6557. **
  6558. ** [[the xShutdown() page cache method]]
  6559. ** ^The xShutdown() method is called by [sqlite3_shutdown()].
  6560. ** It can be used to clean up
  6561. ** any outstanding resources before process shutdown, if required.
  6562. ** ^The xShutdown() method may be NULL.
  6563. **
  6564. ** ^SQLite automatically serializes calls to the xInit method,
  6565. ** so the xInit method need not be threadsafe. ^The
  6566. ** xShutdown method is only called from [sqlite3_shutdown()] so it does
  6567. ** not need to be threadsafe either. All other methods must be threadsafe
  6568. ** in multithreaded applications.
  6569. **
  6570. ** ^SQLite will never invoke xInit() more than once without an intervening
  6571. ** call to xShutdown().
  6572. **
  6573. ** [[the xCreate() page cache methods]]
  6574. ** ^SQLite invokes the xCreate() method to construct a new cache instance.
  6575. ** SQLite will typically create one cache instance for each open database file,
  6576. ** though this is not guaranteed. ^The
  6577. ** first parameter, szPage, is the size in bytes of the pages that must
  6578. ** be allocated by the cache. ^szPage will always a power of two. ^The
  6579. ** second parameter szExtra is a number of bytes of extra storage
  6580. ** associated with each page cache entry. ^The szExtra parameter will
  6581. ** a number less than 250. SQLite will use the
  6582. ** extra szExtra bytes on each page to store metadata about the underlying
  6583. ** database page on disk. The value passed into szExtra depends
  6584. ** on the SQLite version, the target platform, and how SQLite was compiled.
  6585. ** ^The third argument to xCreate(), bPurgeable, is true if the cache being
  6586. ** created will be used to cache database pages of a file stored on disk, or
  6587. ** false if it is used for an in-memory database. The cache implementation
  6588. ** does not have to do anything special based with the value of bPurgeable;
  6589. ** it is purely advisory. ^On a cache where bPurgeable is false, SQLite will
  6590. ** never invoke xUnpin() except to deliberately delete a page.
  6591. ** ^In other words, calls to xUnpin() on a cache with bPurgeable set to
  6592. ** false will always have the "discard" flag set to true.
  6593. ** ^Hence, a cache created with bPurgeable false will
  6594. ** never contain any unpinned pages.
  6595. **
  6596. ** [[the xCachesize() page cache method]]
  6597. ** ^(The xCachesize() method may be called at any time by SQLite to set the
  6598. ** suggested maximum cache-size (number of pages stored by) the cache
  6599. ** instance passed as the first argument. This is the value configured using
  6600. ** the SQLite "[PRAGMA cache_size]" command.)^ As with the bPurgeable
  6601. ** parameter, the implementation is not required to do anything with this
  6602. ** value; it is advisory only.
  6603. **
  6604. ** [[the xPagecount() page cache methods]]
  6605. ** The xPagecount() method must return the number of pages currently
  6606. ** stored in the cache, both pinned and unpinned.
  6607. **
  6608. ** [[the xFetch() page cache methods]]
  6609. ** The xFetch() method locates a page in the cache and returns a pointer to
  6610. ** an sqlite3_pcache_page object associated with that page, or a NULL pointer.
  6611. ** The pBuf element of the returned sqlite3_pcache_page object will be a
  6612. ** pointer to a buffer of szPage bytes used to store the content of a
  6613. ** single database page. The pExtra element of sqlite3_pcache_page will be
  6614. ** a pointer to the szExtra bytes of extra storage that SQLite has requested
  6615. ** for each entry in the page cache.
  6616. **
  6617. ** The page to be fetched is determined by the key. ^The minimum key value
  6618. ** is 1. After it has been retrieved using xFetch, the page is considered
  6619. ** to be "pinned".
  6620. **
  6621. ** If the requested page is already in the page cache, then the page cache
  6622. ** implementation must return a pointer to the page buffer with its content
  6623. ** intact. If the requested page is not already in the cache, then the
  6624. ** cache implementation should use the value of the createFlag
  6625. ** parameter to help it determined what action to take:
  6626. **
  6627. ** <table border=1 width=85% align=center>
  6628. ** <tr><th> createFlag <th> Behavior when page is not already in cache
  6629. ** <tr><td> 0 <td> Do not allocate a new page. Return NULL.
  6630. ** <tr><td> 1 <td> Allocate a new page if it easy and convenient to do so.
  6631. ** Otherwise return NULL.
  6632. ** <tr><td> 2 <td> Make every effort to allocate a new page. Only return
  6633. ** NULL if allocating a new page is effectively impossible.
  6634. ** </table>
  6635. **
  6636. ** ^(SQLite will normally invoke xFetch() with a createFlag of 0 or 1. SQLite
  6637. ** will only use a createFlag of 2 after a prior call with a createFlag of 1
  6638. ** failed.)^ In between the to xFetch() calls, SQLite may
  6639. ** attempt to unpin one or more cache pages by spilling the content of
  6640. ** pinned pages to disk and synching the operating system disk cache.
  6641. **
  6642. ** [[the xUnpin() page cache method]]
  6643. ** ^xUnpin() is called by SQLite with a pointer to a currently pinned page
  6644. ** as its second argument. If the third parameter, discard, is non-zero,
  6645. ** then the page must be evicted from the cache.
  6646. ** ^If the discard parameter is
  6647. ** zero, then the page may be discarded or retained at the discretion of
  6648. ** page cache implementation. ^The page cache implementation
  6649. ** may choose to evict unpinned pages at any time.
  6650. **
  6651. ** The cache must not perform any reference counting. A single
  6652. ** call to xUnpin() unpins the page regardless of the number of prior calls
  6653. ** to xFetch().
  6654. **
  6655. ** [[the xRekey() page cache methods]]
  6656. ** The xRekey() method is used to change the key value associated with the
  6657. ** page passed as the second argument. If the cache
  6658. ** previously contains an entry associated with newKey, it must be
  6659. ** discarded. ^Any prior cache entry associated with newKey is guaranteed not
  6660. ** to be pinned.
  6661. **
  6662. ** When SQLite calls the xTruncate() method, the cache must discard all
  6663. ** existing cache entries with page numbers (keys) greater than or equal
  6664. ** to the value of the iLimit parameter passed to xTruncate(). If any
  6665. ** of these pages are pinned, they are implicitly unpinned, meaning that
  6666. ** they can be safely discarded.
  6667. **
  6668. ** [[the xDestroy() page cache method]]
  6669. ** ^The xDestroy() method is used to delete a cache allocated by xCreate().
  6670. ** All resources associated with the specified cache should be freed. ^After
  6671. ** calling the xDestroy() method, SQLite considers the [sqlite3_pcache*]
  6672. ** handle invalid, and will not use it with any other sqlite3_pcache_methods2
  6673. ** functions.
  6674. **
  6675. ** [[the xShrink() page cache method]]
  6676. ** ^SQLite invokes the xShrink() method when it wants the page cache to
  6677. ** free up as much of heap memory as possible. The page cache implementation
  6678. ** is not obligated to free any memory, but well-behaved implementations should
  6679. ** do their best.
  6680. */
  6681. typedef struct sqlite3_pcache_methods2 sqlite3_pcache_methods2;
  6682. struct sqlite3_pcache_methods2 {
  6683. int iVersion;
  6684. void *pArg;
  6685. int (*xInit)(void*);
  6686. void (*xShutdown)(void*);
  6687. sqlite3_pcache *(*xCreate)(int szPage, int szExtra, int bPurgeable);
  6688. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6689. int (*xPagecount)(sqlite3_pcache*);
  6690. sqlite3_pcache_page *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6691. void (*xUnpin)(sqlite3_pcache*, sqlite3_pcache_page*, int discard);
  6692. void (*xRekey)(sqlite3_pcache*, sqlite3_pcache_page*,
  6693. unsigned oldKey, unsigned newKey);
  6694. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6695. void (*xDestroy)(sqlite3_pcache*);
  6696. void (*xShrink)(sqlite3_pcache*);
  6697. };
  6698. /*
  6699. ** This is the obsolete pcache_methods object that has now been replaced
  6700. ** by sqlite3_pcache_methods2. This object is not used by SQLite. It is
  6701. ** retained in the header file for backwards compatibility only.
  6702. */
  6703. typedef struct sqlite3_pcache_methods sqlite3_pcache_methods;
  6704. struct sqlite3_pcache_methods {
  6705. void *pArg;
  6706. int (*xInit)(void*);
  6707. void (*xShutdown)(void*);
  6708. sqlite3_pcache *(*xCreate)(int szPage, int bPurgeable);
  6709. void (*xCachesize)(sqlite3_pcache*, int nCachesize);
  6710. int (*xPagecount)(sqlite3_pcache*);
  6711. void *(*xFetch)(sqlite3_pcache*, unsigned key, int createFlag);
  6712. void (*xUnpin)(sqlite3_pcache*, void*, int discard);
  6713. void (*xRekey)(sqlite3_pcache*, void*, unsigned oldKey, unsigned newKey);
  6714. void (*xTruncate)(sqlite3_pcache*, unsigned iLimit);
  6715. void (*xDestroy)(sqlite3_pcache*);
  6716. };
  6717. /*
  6718. ** CAPI3REF: Online Backup Object
  6719. **
  6720. ** The sqlite3_backup object records state information about an ongoing
  6721. ** online backup operation. ^The sqlite3_backup object is created by
  6722. ** a call to [sqlite3_backup_init()] and is destroyed by a call to
  6723. ** [sqlite3_backup_finish()].
  6724. **
  6725. ** See Also: [Using the SQLite Online Backup API]
  6726. */
  6727. typedef struct sqlite3_backup sqlite3_backup;
  6728. /*
  6729. ** CAPI3REF: Online Backup API.
  6730. **
  6731. ** The backup API copies the content of one database into another.
  6732. ** It is useful either for creating backups of databases or
  6733. ** for copying in-memory databases to or from persistent files.
  6734. **
  6735. ** See Also: [Using the SQLite Online Backup API]
  6736. **
  6737. ** ^SQLite holds a write transaction open on the destination database file
  6738. ** for the duration of the backup operation.
  6739. ** ^The source database is read-locked only while it is being read;
  6740. ** it is not locked continuously for the entire backup operation.
  6741. ** ^Thus, the backup may be performed on a live source database without
  6742. ** preventing other database connections from
  6743. ** reading or writing to the source database while the backup is underway.
  6744. **
  6745. ** ^(To perform a backup operation:
  6746. ** <ol>
  6747. ** <li><b>sqlite3_backup_init()</b> is called once to initialize the
  6748. ** backup,
  6749. ** <li><b>sqlite3_backup_step()</b> is called one or more times to transfer
  6750. ** the data between the two databases, and finally
  6751. ** <li><b>sqlite3_backup_finish()</b> is called to release all resources
  6752. ** associated with the backup operation.
  6753. ** </ol>)^
  6754. ** There should be exactly one call to sqlite3_backup_finish() for each
  6755. ** successful call to sqlite3_backup_init().
  6756. **
  6757. ** [[sqlite3_backup_init()]] <b>sqlite3_backup_init()</b>
  6758. **
  6759. ** ^The D and N arguments to sqlite3_backup_init(D,N,S,M) are the
  6760. ** [database connection] associated with the destination database
  6761. ** and the database name, respectively.
  6762. ** ^The database name is "main" for the main database, "temp" for the
  6763. ** temporary database, or the name specified after the AS keyword in
  6764. ** an [ATTACH] statement for an attached database.
  6765. ** ^The S and M arguments passed to
  6766. ** sqlite3_backup_init(D,N,S,M) identify the [database connection]
  6767. ** and database name of the source database, respectively.
  6768. ** ^The source and destination [database connections] (parameters S and D)
  6769. ** must be different or else sqlite3_backup_init(D,N,S,M) will fail with
  6770. ** an error.
  6771. **
  6772. ** ^If an error occurs within sqlite3_backup_init(D,N,S,M), then NULL is
  6773. ** returned and an error code and error message are stored in the
  6774. ** destination [database connection] D.
  6775. ** ^The error code and message for the failed call to sqlite3_backup_init()
  6776. ** can be retrieved using the [sqlite3_errcode()], [sqlite3_errmsg()], and/or
  6777. ** [sqlite3_errmsg16()] functions.
  6778. ** ^A successful call to sqlite3_backup_init() returns a pointer to an
  6779. ** [sqlite3_backup] object.
  6780. ** ^The [sqlite3_backup] object may be used with the sqlite3_backup_step() and
  6781. ** sqlite3_backup_finish() functions to perform the specified backup
  6782. ** operation.
  6783. **
  6784. ** [[sqlite3_backup_step()]] <b>sqlite3_backup_step()</b>
  6785. **
  6786. ** ^Function sqlite3_backup_step(B,N) will copy up to N pages between
  6787. ** the source and destination databases specified by [sqlite3_backup] object B.
  6788. ** ^If N is negative, all remaining source pages are copied.
  6789. ** ^If sqlite3_backup_step(B,N) successfully copies N pages and there
  6790. ** are still more pages to be copied, then the function returns [SQLITE_OK].
  6791. ** ^If sqlite3_backup_step(B,N) successfully finishes copying all pages
  6792. ** from source to destination, then it returns [SQLITE_DONE].
  6793. ** ^If an error occurs while running sqlite3_backup_step(B,N),
  6794. ** then an [error code] is returned. ^As well as [SQLITE_OK] and
  6795. ** [SQLITE_DONE], a call to sqlite3_backup_step() may return [SQLITE_READONLY],
  6796. ** [SQLITE_NOMEM], [SQLITE_BUSY], [SQLITE_LOCKED], or an
  6797. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX] extended error code.
  6798. **
  6799. ** ^(The sqlite3_backup_step() might return [SQLITE_READONLY] if
  6800. ** <ol>
  6801. ** <li> the destination database was opened read-only, or
  6802. ** <li> the destination database is using write-ahead-log journaling
  6803. ** and the destination and source page sizes differ, or
  6804. ** <li> the destination database is an in-memory database and the
  6805. ** destination and source page sizes differ.
  6806. ** </ol>)^
  6807. **
  6808. ** ^If sqlite3_backup_step() cannot obtain a required file-system lock, then
  6809. ** the [sqlite3_busy_handler | busy-handler function]
  6810. ** is invoked (if one is specified). ^If the
  6811. ** busy-handler returns non-zero before the lock is available, then
  6812. ** [SQLITE_BUSY] is returned to the caller. ^In this case the call to
  6813. ** sqlite3_backup_step() can be retried later. ^If the source
  6814. ** [database connection]
  6815. ** is being used to write to the source database when sqlite3_backup_step()
  6816. ** is called, then [SQLITE_LOCKED] is returned immediately. ^Again, in this
  6817. ** case the call to sqlite3_backup_step() can be retried later on. ^(If
  6818. ** [SQLITE_IOERR_ACCESS | SQLITE_IOERR_XXX], [SQLITE_NOMEM], or
  6819. ** [SQLITE_READONLY] is returned, then
  6820. ** there is no point in retrying the call to sqlite3_backup_step(). These
  6821. ** errors are considered fatal.)^ The application must accept
  6822. ** that the backup operation has failed and pass the backup operation handle
  6823. ** to the sqlite3_backup_finish() to release associated resources.
  6824. **
  6825. ** ^The first call to sqlite3_backup_step() obtains an exclusive lock
  6826. ** on the destination file. ^The exclusive lock is not released until either
  6827. ** sqlite3_backup_finish() is called or the backup operation is complete
  6828. ** and sqlite3_backup_step() returns [SQLITE_DONE]. ^Every call to
  6829. ** sqlite3_backup_step() obtains a [shared lock] on the source database that
  6830. ** lasts for the duration of the sqlite3_backup_step() call.
  6831. ** ^Because the source database is not locked between calls to
  6832. ** sqlite3_backup_step(), the source database may be modified mid-way
  6833. ** through the backup process. ^If the source database is modified by an
  6834. ** external process or via a database connection other than the one being
  6835. ** used by the backup operation, then the backup will be automatically
  6836. ** restarted by the next call to sqlite3_backup_step(). ^If the source
  6837. ** database is modified by the using the same database connection as is used
  6838. ** by the backup operation, then the backup database is automatically
  6839. ** updated at the same time.
  6840. **
  6841. ** [[sqlite3_backup_finish()]] <b>sqlite3_backup_finish()</b>
  6842. **
  6843. ** When sqlite3_backup_step() has returned [SQLITE_DONE], or when the
  6844. ** application wishes to abandon the backup operation, the application
  6845. ** should destroy the [sqlite3_backup] by passing it to sqlite3_backup_finish().
  6846. ** ^The sqlite3_backup_finish() interfaces releases all
  6847. ** resources associated with the [sqlite3_backup] object.
  6848. ** ^If sqlite3_backup_step() has not yet returned [SQLITE_DONE], then any
  6849. ** active write-transaction on the destination database is rolled back.
  6850. ** The [sqlite3_backup] object is invalid
  6851. ** and may not be used following a call to sqlite3_backup_finish().
  6852. **
  6853. ** ^The value returned by sqlite3_backup_finish is [SQLITE_OK] if no
  6854. ** sqlite3_backup_step() errors occurred, regardless or whether or not
  6855. ** sqlite3_backup_step() completed.
  6856. ** ^If an out-of-memory condition or IO error occurred during any prior
  6857. ** sqlite3_backup_step() call on the same [sqlite3_backup] object, then
  6858. ** sqlite3_backup_finish() returns the corresponding [error code].
  6859. **
  6860. ** ^A return of [SQLITE_BUSY] or [SQLITE_LOCKED] from sqlite3_backup_step()
  6861. ** is not a permanent error and does not affect the return value of
  6862. ** sqlite3_backup_finish().
  6863. **
  6864. ** [[sqlite3_backup__remaining()]] [[sqlite3_backup_pagecount()]]
  6865. ** <b>sqlite3_backup_remaining() and sqlite3_backup_pagecount()</b>
  6866. **
  6867. ** ^Each call to sqlite3_backup_step() sets two values inside
  6868. ** the [sqlite3_backup] object: the number of pages still to be backed
  6869. ** up and the total number of pages in the source database file.
  6870. ** The sqlite3_backup_remaining() and sqlite3_backup_pagecount() interfaces
  6871. ** retrieve these two values, respectively.
  6872. **
  6873. ** ^The values returned by these functions are only updated by
  6874. ** sqlite3_backup_step(). ^If the source database is modified during a backup
  6875. ** operation, then the values are not updated to account for any extra
  6876. ** pages that need to be updated or the size of the source database file
  6877. ** changing.
  6878. **
  6879. ** <b>Concurrent Usage of Database Handles</b>
  6880. **
  6881. ** ^The source [database connection] may be used by the application for other
  6882. ** purposes while a backup operation is underway or being initialized.
  6883. ** ^If SQLite is compiled and configured to support threadsafe database
  6884. ** connections, then the source database connection may be used concurrently
  6885. ** from within other threads.
  6886. **
  6887. ** However, the application must guarantee that the destination
  6888. ** [database connection] is not passed to any other API (by any thread) after
  6889. ** sqlite3_backup_init() is called and before the corresponding call to
  6890. ** sqlite3_backup_finish(). SQLite does not currently check to see
  6891. ** if the application incorrectly accesses the destination [database connection]
  6892. ** and so no error code is reported, but the operations may malfunction
  6893. ** nevertheless. Use of the destination database connection while a
  6894. ** backup is in progress might also also cause a mutex deadlock.
  6895. **
  6896. ** If running in [shared cache mode], the application must
  6897. ** guarantee that the shared cache used by the destination database
  6898. ** is not accessed while the backup is running. In practice this means
  6899. ** that the application must guarantee that the disk file being
  6900. ** backed up to is not accessed by any connection within the process,
  6901. ** not just the specific connection that was passed to sqlite3_backup_init().
  6902. **
  6903. ** The [sqlite3_backup] object itself is partially threadsafe. Multiple
  6904. ** threads may safely make multiple concurrent calls to sqlite3_backup_step().
  6905. ** However, the sqlite3_backup_remaining() and sqlite3_backup_pagecount()
  6906. ** APIs are not strictly speaking threadsafe. If they are invoked at the
  6907. ** same time as another thread is invoking sqlite3_backup_step() it is
  6908. ** possible that they return invalid values.
  6909. */
  6910. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  6911. sqlite3 *pDest, /* Destination database handle */
  6912. const char *zDestName, /* Destination database name */
  6913. sqlite3 *pSource, /* Source database handle */
  6914. const char *zSourceName /* Source database name */
  6915. );
  6916. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage);
  6917. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p);
  6918. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p);
  6919. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p);
  6920. /*
  6921. ** CAPI3REF: Unlock Notification
  6922. **
  6923. ** ^When running in shared-cache mode, a database operation may fail with
  6924. ** an [SQLITE_LOCKED] error if the required locks on the shared-cache or
  6925. ** individual tables within the shared-cache cannot be obtained. See
  6926. ** [SQLite Shared-Cache Mode] for a description of shared-cache locking.
  6927. ** ^This API may be used to register a callback that SQLite will invoke
  6928. ** when the connection currently holding the required lock relinquishes it.
  6929. ** ^This API is only available if the library was compiled with the
  6930. ** [SQLITE_ENABLE_UNLOCK_NOTIFY] C-preprocessor symbol defined.
  6931. **
  6932. ** See Also: [Using the SQLite Unlock Notification Feature].
  6933. **
  6934. ** ^Shared-cache locks are released when a database connection concludes
  6935. ** its current transaction, either by committing it or rolling it back.
  6936. **
  6937. ** ^When a connection (known as the blocked connection) fails to obtain a
  6938. ** shared-cache lock and SQLITE_LOCKED is returned to the caller, the
  6939. ** identity of the database connection (the blocking connection) that
  6940. ** has locked the required resource is stored internally. ^After an
  6941. ** application receives an SQLITE_LOCKED error, it may call the
  6942. ** sqlite3_unlock_notify() method with the blocked connection handle as
  6943. ** the first argument to register for a callback that will be invoked
  6944. ** when the blocking connections current transaction is concluded. ^The
  6945. ** callback is invoked from within the [sqlite3_step] or [sqlite3_close]
  6946. ** call that concludes the blocking connections transaction.
  6947. **
  6948. ** ^(If sqlite3_unlock_notify() is called in a multi-threaded application,
  6949. ** there is a chance that the blocking connection will have already
  6950. ** concluded its transaction by the time sqlite3_unlock_notify() is invoked.
  6951. ** If this happens, then the specified callback is invoked immediately,
  6952. ** from within the call to sqlite3_unlock_notify().)^
  6953. **
  6954. ** ^If the blocked connection is attempting to obtain a write-lock on a
  6955. ** shared-cache table, and more than one other connection currently holds
  6956. ** a read-lock on the same table, then SQLite arbitrarily selects one of
  6957. ** the other connections to use as the blocking connection.
  6958. **
  6959. ** ^(There may be at most one unlock-notify callback registered by a
  6960. ** blocked connection. If sqlite3_unlock_notify() is called when the
  6961. ** blocked connection already has a registered unlock-notify callback,
  6962. ** then the new callback replaces the old.)^ ^If sqlite3_unlock_notify() is
  6963. ** called with a NULL pointer as its second argument, then any existing
  6964. ** unlock-notify callback is canceled. ^The blocked connections
  6965. ** unlock-notify callback may also be canceled by closing the blocked
  6966. ** connection using [sqlite3_close()].
  6967. **
  6968. ** The unlock-notify callback is not reentrant. If an application invokes
  6969. ** any sqlite3_xxx API functions from within an unlock-notify callback, a
  6970. ** crash or deadlock may be the result.
  6971. **
  6972. ** ^Unless deadlock is detected (see below), sqlite3_unlock_notify() always
  6973. ** returns SQLITE_OK.
  6974. **
  6975. ** <b>Callback Invocation Details</b>
  6976. **
  6977. ** When an unlock-notify callback is registered, the application provides a
  6978. ** single void* pointer that is passed to the callback when it is invoked.
  6979. ** However, the signature of the callback function allows SQLite to pass
  6980. ** it an array of void* context pointers. The first argument passed to
  6981. ** an unlock-notify callback is a pointer to an array of void* pointers,
  6982. ** and the second is the number of entries in the array.
  6983. **
  6984. ** When a blocking connections transaction is concluded, there may be
  6985. ** more than one blocked connection that has registered for an unlock-notify
  6986. ** callback. ^If two or more such blocked connections have specified the
  6987. ** same callback function, then instead of invoking the callback function
  6988. ** multiple times, it is invoked once with the set of void* context pointers
  6989. ** specified by the blocked connections bundled together into an array.
  6990. ** This gives the application an opportunity to prioritize any actions
  6991. ** related to the set of unblocked database connections.
  6992. **
  6993. ** <b>Deadlock Detection</b>
  6994. **
  6995. ** Assuming that after registering for an unlock-notify callback a
  6996. ** database waits for the callback to be issued before taking any further
  6997. ** action (a reasonable assumption), then using this API may cause the
  6998. ** application to deadlock. For example, if connection X is waiting for
  6999. ** connection Y's transaction to be concluded, and similarly connection
  7000. ** Y is waiting on connection X's transaction, then neither connection
  7001. ** will proceed and the system may remain deadlocked indefinitely.
  7002. **
  7003. ** To avoid this scenario, the sqlite3_unlock_notify() performs deadlock
  7004. ** detection. ^If a given call to sqlite3_unlock_notify() would put the
  7005. ** system in a deadlocked state, then SQLITE_LOCKED is returned and no
  7006. ** unlock-notify callback is registered. The system is said to be in
  7007. ** a deadlocked state if connection A has registered for an unlock-notify
  7008. ** callback on the conclusion of connection B's transaction, and connection
  7009. ** B has itself registered for an unlock-notify callback when connection
  7010. ** A's transaction is concluded. ^Indirect deadlock is also detected, so
  7011. ** the system is also considered to be deadlocked if connection B has
  7012. ** registered for an unlock-notify callback on the conclusion of connection
  7013. ** C's transaction, where connection C is waiting on connection A. ^Any
  7014. ** number of levels of indirection are allowed.
  7015. **
  7016. ** <b>The "DROP TABLE" Exception</b>
  7017. **
  7018. ** When a call to [sqlite3_step()] returns SQLITE_LOCKED, it is almost
  7019. ** always appropriate to call sqlite3_unlock_notify(). There is however,
  7020. ** one exception. When executing a "DROP TABLE" or "DROP INDEX" statement,
  7021. ** SQLite checks if there are any currently executing SELECT statements
  7022. ** that belong to the same connection. If there are, SQLITE_LOCKED is
  7023. ** returned. In this case there is no "blocking connection", so invoking
  7024. ** sqlite3_unlock_notify() results in the unlock-notify callback being
  7025. ** invoked immediately. If the application then re-attempts the "DROP TABLE"
  7026. ** or "DROP INDEX" query, an infinite loop might be the result.
  7027. **
  7028. ** One way around this problem is to check the extended error code returned
  7029. ** by an sqlite3_step() call. ^(If there is a blocking connection, then the
  7030. ** extended error code is set to SQLITE_LOCKED_SHAREDCACHE. Otherwise, in
  7031. ** the special "DROP TABLE/INDEX" case, the extended error code is just
  7032. ** SQLITE_LOCKED.)^
  7033. */
  7034. SQLITE_API int sqlite3_unlock_notify(
  7035. sqlite3 *pBlocked, /* Waiting connection */
  7036. void (*xNotify)(void **apArg, int nArg), /* Callback function to invoke */
  7037. void *pNotifyArg /* Argument to pass to xNotify */
  7038. );
  7039. /*
  7040. ** CAPI3REF: String Comparison
  7041. **
  7042. ** ^The [sqlite3_stricmp()] and [sqlite3_strnicmp()] APIs allow applications
  7043. ** and extensions to compare the contents of two buffers containing UTF-8
  7044. ** strings in a case-independent fashion, using the same definition of "case
  7045. ** independence" that SQLite uses internally when comparing identifiers.
  7046. */
  7047. SQLITE_API int sqlite3_stricmp(const char *, const char *);
  7048. SQLITE_API int sqlite3_strnicmp(const char *, const char *, int);
  7049. /*
  7050. ** CAPI3REF: String Globbing
  7051. *
  7052. ** ^The [sqlite3_strglob(P,X)] interface returns zero if string X matches
  7053. ** the glob pattern P, and it returns non-zero if string X does not match
  7054. ** the glob pattern P. ^The definition of glob pattern matching used in
  7055. ** [sqlite3_strglob(P,X)] is the same as for the "X GLOB P" operator in the
  7056. ** SQL dialect used by SQLite. ^The sqlite3_strglob(P,X) function is case
  7057. ** sensitive.
  7058. **
  7059. ** Note that this routine returns zero on a match and non-zero if the strings
  7060. ** do not match, the same as [sqlite3_stricmp()] and [sqlite3_strnicmp()].
  7061. */
  7062. SQLITE_API int sqlite3_strglob(const char *zGlob, const char *zStr);
  7063. /*
  7064. ** CAPI3REF: Error Logging Interface
  7065. **
  7066. ** ^The [sqlite3_log()] interface writes a message into the [error log]
  7067. ** established by the [SQLITE_CONFIG_LOG] option to [sqlite3_config()].
  7068. ** ^If logging is enabled, the zFormat string and subsequent arguments are
  7069. ** used with [sqlite3_snprintf()] to generate the final output string.
  7070. **
  7071. ** The sqlite3_log() interface is intended for use by extensions such as
  7072. ** virtual tables, collating functions, and SQL functions. While there is
  7073. ** nothing to prevent an application from calling sqlite3_log(), doing so
  7074. ** is considered bad form.
  7075. **
  7076. ** The zFormat string must not be NULL.
  7077. **
  7078. ** To avoid deadlocks and other threading problems, the sqlite3_log() routine
  7079. ** will not use dynamically allocated memory. The log message is stored in
  7080. ** a fixed-length buffer on the stack. If the log message is longer than
  7081. ** a few hundred characters, it will be truncated to the length of the
  7082. ** buffer.
  7083. */
  7084. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...);
  7085. /*
  7086. ** CAPI3REF: Write-Ahead Log Commit Hook
  7087. **
  7088. ** ^The [sqlite3_wal_hook()] function is used to register a callback that
  7089. ** will be invoked each time a database connection commits data to a
  7090. ** [write-ahead log] (i.e. whenever a transaction is committed in
  7091. ** [journal_mode | journal_mode=WAL mode]).
  7092. **
  7093. ** ^The callback is invoked by SQLite after the commit has taken place and
  7094. ** the associated write-lock on the database released, so the implementation
  7095. ** may read, write or [checkpoint] the database as required.
  7096. **
  7097. ** ^The first parameter passed to the callback function when it is invoked
  7098. ** is a copy of the third parameter passed to sqlite3_wal_hook() when
  7099. ** registering the callback. ^The second is a copy of the database handle.
  7100. ** ^The third parameter is the name of the database that was written to -
  7101. ** either "main" or the name of an [ATTACH]-ed database. ^The fourth parameter
  7102. ** is the number of pages currently in the write-ahead log file,
  7103. ** including those that were just committed.
  7104. **
  7105. ** The callback function should normally return [SQLITE_OK]. ^If an error
  7106. ** code is returned, that error will propagate back up through the
  7107. ** SQLite code base to cause the statement that provoked the callback
  7108. ** to report an error, though the commit will have still occurred. If the
  7109. ** callback returns [SQLITE_ROW] or [SQLITE_DONE], or if it returns a value
  7110. ** that does not correspond to any valid SQLite error code, the results
  7111. ** are undefined.
  7112. **
  7113. ** A single database handle may have at most a single write-ahead log callback
  7114. ** registered at one time. ^Calling [sqlite3_wal_hook()] replaces any
  7115. ** previously registered write-ahead log callback. ^Note that the
  7116. ** [sqlite3_wal_autocheckpoint()] interface and the
  7117. ** [wal_autocheckpoint pragma] both invoke [sqlite3_wal_hook()] and will
  7118. ** those overwrite any prior [sqlite3_wal_hook()] settings.
  7119. */
  7120. SQLITE_API void *sqlite3_wal_hook(
  7121. sqlite3*,
  7122. int(*)(void *,sqlite3*,const char*,int),
  7123. void*
  7124. );
  7125. /*
  7126. ** CAPI3REF: Configure an auto-checkpoint
  7127. **
  7128. ** ^The [sqlite3_wal_autocheckpoint(D,N)] is a wrapper around
  7129. ** [sqlite3_wal_hook()] that causes any database on [database connection] D
  7130. ** to automatically [checkpoint]
  7131. ** after committing a transaction if there are N or
  7132. ** more frames in the [write-ahead log] file. ^Passing zero or
  7133. ** a negative value as the nFrame parameter disables automatic
  7134. ** checkpoints entirely.
  7135. **
  7136. ** ^The callback registered by this function replaces any existing callback
  7137. ** registered using [sqlite3_wal_hook()]. ^Likewise, registering a callback
  7138. ** using [sqlite3_wal_hook()] disables the automatic checkpoint mechanism
  7139. ** configured by this function.
  7140. **
  7141. ** ^The [wal_autocheckpoint pragma] can be used to invoke this interface
  7142. ** from SQL.
  7143. **
  7144. ** ^Checkpoints initiated by this mechanism are
  7145. ** [sqlite3_wal_checkpoint_v2|PASSIVE].
  7146. **
  7147. ** ^Every new [database connection] defaults to having the auto-checkpoint
  7148. ** enabled with a threshold of 1000 or [SQLITE_DEFAULT_WAL_AUTOCHECKPOINT]
  7149. ** pages. The use of this interface
  7150. ** is only necessary if the default setting is found to be suboptimal
  7151. ** for a particular application.
  7152. */
  7153. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int N);
  7154. /*
  7155. ** CAPI3REF: Checkpoint a database
  7156. **
  7157. ** ^The [sqlite3_wal_checkpoint(D,X)] interface causes database named X
  7158. ** on [database connection] D to be [checkpointed]. ^If X is NULL or an
  7159. ** empty string, then a checkpoint is run on all databases of
  7160. ** connection D. ^If the database connection D is not in
  7161. ** [WAL | write-ahead log mode] then this interface is a harmless no-op.
  7162. ** ^The [sqlite3_wal_checkpoint(D,X)] interface initiates a
  7163. ** [sqlite3_wal_checkpoint_v2|PASSIVE] checkpoint.
  7164. ** Use the [sqlite3_wal_checkpoint_v2()] interface to get a FULL
  7165. ** or RESET checkpoint.
  7166. **
  7167. ** ^The [wal_checkpoint pragma] can be used to invoke this interface
  7168. ** from SQL. ^The [sqlite3_wal_autocheckpoint()] interface and the
  7169. ** [wal_autocheckpoint pragma] can be used to cause this interface to be
  7170. ** run whenever the WAL reaches a certain size threshold.
  7171. **
  7172. ** See also: [sqlite3_wal_checkpoint_v2()]
  7173. */
  7174. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb);
  7175. /*
  7176. ** CAPI3REF: Checkpoint a database
  7177. **
  7178. ** Run a checkpoint operation on WAL database zDb attached to database
  7179. ** handle db. The specific operation is determined by the value of the
  7180. ** eMode parameter:
  7181. **
  7182. ** <dl>
  7183. ** <dt>SQLITE_CHECKPOINT_PASSIVE<dd>
  7184. ** Checkpoint as many frames as possible without waiting for any database
  7185. ** readers or writers to finish. Sync the db file if all frames in the log
  7186. ** are checkpointed. This mode is the same as calling
  7187. ** sqlite3_wal_checkpoint(). The [sqlite3_busy_handler|busy-handler callback]
  7188. ** is never invoked.
  7189. **
  7190. ** <dt>SQLITE_CHECKPOINT_FULL<dd>
  7191. ** This mode blocks (it invokes the
  7192. ** [sqlite3_busy_handler|busy-handler callback]) until there is no
  7193. ** database writer and all readers are reading from the most recent database
  7194. ** snapshot. It then checkpoints all frames in the log file and syncs the
  7195. ** database file. This call blocks database writers while it is running,
  7196. ** but not database readers.
  7197. **
  7198. ** <dt>SQLITE_CHECKPOINT_RESTART<dd>
  7199. ** This mode works the same way as SQLITE_CHECKPOINT_FULL, except after
  7200. ** checkpointing the log file it blocks (calls the
  7201. ** [sqlite3_busy_handler|busy-handler callback])
  7202. ** until all readers are reading from the database file only. This ensures
  7203. ** that the next client to write to the database file restarts the log file
  7204. ** from the beginning. This call blocks database writers while it is running,
  7205. ** but not database readers.
  7206. ** </dl>
  7207. **
  7208. ** If pnLog is not NULL, then *pnLog is set to the total number of frames in
  7209. ** the log file before returning. If pnCkpt is not NULL, then *pnCkpt is set to
  7210. ** the total number of checkpointed frames (including any that were already
  7211. ** checkpointed when this function is called). *pnLog and *pnCkpt may be
  7212. ** populated even if sqlite3_wal_checkpoint_v2() returns other than SQLITE_OK.
  7213. ** If no values are available because of an error, they are both set to -1
  7214. ** before returning to communicate this to the caller.
  7215. **
  7216. ** All calls obtain an exclusive "checkpoint" lock on the database file. If
  7217. ** any other process is running a checkpoint operation at the same time, the
  7218. ** lock cannot be obtained and SQLITE_BUSY is returned. Even if there is a
  7219. ** busy-handler configured, it will not be invoked in this case.
  7220. **
  7221. ** The SQLITE_CHECKPOINT_FULL and RESTART modes also obtain the exclusive
  7222. ** "writer" lock on the database file. If the writer lock cannot be obtained
  7223. ** immediately, and a busy-handler is configured, it is invoked and the writer
  7224. ** lock retried until either the busy-handler returns 0 or the lock is
  7225. ** successfully obtained. The busy-handler is also invoked while waiting for
  7226. ** database readers as described above. If the busy-handler returns 0 before
  7227. ** the writer lock is obtained or while waiting for database readers, the
  7228. ** checkpoint operation proceeds from that point in the same way as
  7229. ** SQLITE_CHECKPOINT_PASSIVE - checkpointing as many frames as possible
  7230. ** without blocking any further. SQLITE_BUSY is returned in this case.
  7231. **
  7232. ** If parameter zDb is NULL or points to a zero length string, then the
  7233. ** specified operation is attempted on all WAL databases. In this case the
  7234. ** values written to output parameters *pnLog and *pnCkpt are undefined. If
  7235. ** an SQLITE_BUSY error is encountered when processing one or more of the
  7236. ** attached WAL databases, the operation is still attempted on any remaining
  7237. ** attached databases and SQLITE_BUSY is returned to the caller. If any other
  7238. ** error occurs while processing an attached database, processing is abandoned
  7239. ** and the error code returned to the caller immediately. If no error
  7240. ** (SQLITE_BUSY or otherwise) is encountered while processing the attached
  7241. ** databases, SQLITE_OK is returned.
  7242. **
  7243. ** If database zDb is the name of an attached database that is not in WAL
  7244. ** mode, SQLITE_OK is returned and both *pnLog and *pnCkpt set to -1. If
  7245. ** zDb is not NULL (or a zero length string) and is not the name of any
  7246. ** attached database, SQLITE_ERROR is returned to the caller.
  7247. */
  7248. SQLITE_API int sqlite3_wal_checkpoint_v2(
  7249. sqlite3 *db, /* Database handle */
  7250. const char *zDb, /* Name of attached database (or NULL) */
  7251. int eMode, /* SQLITE_CHECKPOINT_* value */
  7252. int *pnLog, /* OUT: Size of WAL log in frames */
  7253. int *pnCkpt /* OUT: Total number of frames checkpointed */
  7254. );
  7255. /*
  7256. ** CAPI3REF: Checkpoint operation parameters
  7257. **
  7258. ** These constants can be used as the 3rd parameter to
  7259. ** [sqlite3_wal_checkpoint_v2()]. See the [sqlite3_wal_checkpoint_v2()]
  7260. ** documentation for additional information about the meaning and use of
  7261. ** each of these values.
  7262. */
  7263. #define SQLITE_CHECKPOINT_PASSIVE 0
  7264. #define SQLITE_CHECKPOINT_FULL 1
  7265. #define SQLITE_CHECKPOINT_RESTART 2
  7266. /*
  7267. ** CAPI3REF: Virtual Table Interface Configuration
  7268. **
  7269. ** This function may be called by either the [xConnect] or [xCreate] method
  7270. ** of a [virtual table] implementation to configure
  7271. ** various facets of the virtual table interface.
  7272. **
  7273. ** If this interface is invoked outside the context of an xConnect or
  7274. ** xCreate virtual table method then the behavior is undefined.
  7275. **
  7276. ** At present, there is only one option that may be configured using
  7277. ** this function. (See [SQLITE_VTAB_CONSTRAINT_SUPPORT].) Further options
  7278. ** may be added in the future.
  7279. */
  7280. SQLITE_API int sqlite3_vtab_config(sqlite3*, int op, ...);
  7281. /*
  7282. ** CAPI3REF: Virtual Table Configuration Options
  7283. **
  7284. ** These macros define the various options to the
  7285. ** [sqlite3_vtab_config()] interface that [virtual table] implementations
  7286. ** can use to customize and optimize their behavior.
  7287. **
  7288. ** <dl>
  7289. ** <dt>SQLITE_VTAB_CONSTRAINT_SUPPORT
  7290. ** <dd>Calls of the form
  7291. ** [sqlite3_vtab_config](db,SQLITE_VTAB_CONSTRAINT_SUPPORT,X) are supported,
  7292. ** where X is an integer. If X is zero, then the [virtual table] whose
  7293. ** [xCreate] or [xConnect] method invoked [sqlite3_vtab_config()] does not
  7294. ** support constraints. In this configuration (which is the default) if
  7295. ** a call to the [xUpdate] method returns [SQLITE_CONSTRAINT], then the entire
  7296. ** statement is rolled back as if [ON CONFLICT | OR ABORT] had been
  7297. ** specified as part of the users SQL statement, regardless of the actual
  7298. ** ON CONFLICT mode specified.
  7299. **
  7300. ** If X is non-zero, then the virtual table implementation guarantees
  7301. ** that if [xUpdate] returns [SQLITE_CONSTRAINT], it will do so before
  7302. ** any modifications to internal or persistent data structures have been made.
  7303. ** If the [ON CONFLICT] mode is ABORT, FAIL, IGNORE or ROLLBACK, SQLite
  7304. ** is able to roll back a statement or database transaction, and abandon
  7305. ** or continue processing the current SQL statement as appropriate.
  7306. ** If the ON CONFLICT mode is REPLACE and the [xUpdate] method returns
  7307. ** [SQLITE_CONSTRAINT], SQLite handles this as if the ON CONFLICT mode
  7308. ** had been ABORT.
  7309. **
  7310. ** Virtual table implementations that are required to handle OR REPLACE
  7311. ** must do so within the [xUpdate] method. If a call to the
  7312. ** [sqlite3_vtab_on_conflict()] function indicates that the current ON
  7313. ** CONFLICT policy is REPLACE, the virtual table implementation should
  7314. ** silently replace the appropriate rows within the xUpdate callback and
  7315. ** return SQLITE_OK. Or, if this is not possible, it may return
  7316. ** SQLITE_CONSTRAINT, in which case SQLite falls back to OR ABORT
  7317. ** constraint handling.
  7318. ** </dl>
  7319. */
  7320. #define SQLITE_VTAB_CONSTRAINT_SUPPORT 1
  7321. /*
  7322. ** CAPI3REF: Determine The Virtual Table Conflict Policy
  7323. **
  7324. ** This function may only be called from within a call to the [xUpdate] method
  7325. ** of a [virtual table] implementation for an INSERT or UPDATE operation. ^The
  7326. ** value returned is one of [SQLITE_ROLLBACK], [SQLITE_IGNORE], [SQLITE_FAIL],
  7327. ** [SQLITE_ABORT], or [SQLITE_REPLACE], according to the [ON CONFLICT] mode
  7328. ** of the SQL statement that triggered the call to the [xUpdate] method of the
  7329. ** [virtual table].
  7330. */
  7331. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *);
  7332. /*
  7333. ** CAPI3REF: Conflict resolution modes
  7334. ** KEYWORDS: {conflict resolution mode}
  7335. **
  7336. ** These constants are returned by [sqlite3_vtab_on_conflict()] to
  7337. ** inform a [virtual table] implementation what the [ON CONFLICT] mode
  7338. ** is for the SQL statement being evaluated.
  7339. **
  7340. ** Note that the [SQLITE_IGNORE] constant is also used as a potential
  7341. ** return value from the [sqlite3_set_authorizer()] callback and that
  7342. ** [SQLITE_ABORT] is also a [result code].
  7343. */
  7344. #define SQLITE_ROLLBACK 1
  7345. /* #define SQLITE_IGNORE 2 // Also used by sqlite3_authorizer() callback */
  7346. #define SQLITE_FAIL 3
  7347. /* #define SQLITE_ABORT 4 // Also an error code */
  7348. #define SQLITE_REPLACE 5
  7349. /*
  7350. ** Undo the hack that converts floating point types to integer for
  7351. ** builds on processors without floating point support.
  7352. */
  7353. #ifdef SQLITE_OMIT_FLOATING_POINT
  7354. # undef double
  7355. #endif
  7356. #if 0
  7357. } /* End of the 'extern "C"' block */
  7358. #endif
  7359. #endif /* _SQLITE3_H_ */
  7360. /*
  7361. ** 2010 August 30
  7362. **
  7363. ** The author disclaims copyright to this source code. In place of
  7364. ** a legal notice, here is a blessing:
  7365. **
  7366. ** May you do good and not evil.
  7367. ** May you find forgiveness for yourself and forgive others.
  7368. ** May you share freely, never taking more than you give.
  7369. **
  7370. *************************************************************************
  7371. */
  7372. #ifndef _SQLITE3RTREE_H_
  7373. #define _SQLITE3RTREE_H_
  7374. #if 0
  7375. extern "C" {
  7376. #endif
  7377. typedef struct sqlite3_rtree_geometry sqlite3_rtree_geometry;
  7378. typedef struct sqlite3_rtree_query_info sqlite3_rtree_query_info;
  7379. /* The double-precision datatype used by RTree depends on the
  7380. ** SQLITE_RTREE_INT_ONLY compile-time option.
  7381. */
  7382. #ifdef SQLITE_RTREE_INT_ONLY
  7383. typedef sqlite3_int64 sqlite3_rtree_dbl;
  7384. #else
  7385. typedef double sqlite3_rtree_dbl;
  7386. #endif
  7387. /*
  7388. ** Register a geometry callback named zGeom that can be used as part of an
  7389. ** R-Tree geometry query as follows:
  7390. **
  7391. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zGeom(... params ...)
  7392. */
  7393. SQLITE_API int sqlite3_rtree_geometry_callback(
  7394. sqlite3 *db,
  7395. const char *zGeom,
  7396. int (*xGeom)(sqlite3_rtree_geometry*, int, sqlite3_rtree_dbl*,int*),
  7397. void *pContext
  7398. );
  7399. /*
  7400. ** A pointer to a structure of the following type is passed as the first
  7401. ** argument to callbacks registered using rtree_geometry_callback().
  7402. */
  7403. struct sqlite3_rtree_geometry {
  7404. void *pContext; /* Copy of pContext passed to s_r_g_c() */
  7405. int nParam; /* Size of array aParam[] */
  7406. sqlite3_rtree_dbl *aParam; /* Parameters passed to SQL geom function */
  7407. void *pUser; /* Callback implementation user data */
  7408. void (*xDelUser)(void *); /* Called by SQLite to clean up pUser */
  7409. };
  7410. /*
  7411. ** Register a 2nd-generation geometry callback named zScore that can be
  7412. ** used as part of an R-Tree geometry query as follows:
  7413. **
  7414. ** SELECT ... FROM <rtree> WHERE <rtree col> MATCH $zQueryFunc(... params ...)
  7415. */
  7416. SQLITE_API int sqlite3_rtree_query_callback(
  7417. sqlite3 *db,
  7418. const char *zQueryFunc,
  7419. int (*xQueryFunc)(sqlite3_rtree_query_info*),
  7420. void *pContext,
  7421. void (*xDestructor)(void*)
  7422. );
  7423. /*
  7424. ** A pointer to a structure of the following type is passed as the
  7425. ** argument to scored geometry callback registered using
  7426. ** sqlite3_rtree_query_callback().
  7427. **
  7428. ** Note that the first 5 fields of this structure are identical to
  7429. ** sqlite3_rtree_geometry. This structure is a subclass of
  7430. ** sqlite3_rtree_geometry.
  7431. */
  7432. struct sqlite3_rtree_query_info {
  7433. void *pContext; /* pContext from when function registered */
  7434. int nParam; /* Number of function parameters */
  7435. sqlite3_rtree_dbl *aParam; /* value of function parameters */
  7436. void *pUser; /* callback can use this, if desired */
  7437. void (*xDelUser)(void*); /* function to free pUser */
  7438. sqlite3_rtree_dbl *aCoord; /* Coordinates of node or entry to check */
  7439. unsigned int *anQueue; /* Number of pending entries in the queue */
  7440. int nCoord; /* Number of coordinates */
  7441. int iLevel; /* Level of current node or entry */
  7442. int mxLevel; /* The largest iLevel value in the tree */
  7443. sqlite3_int64 iRowid; /* Rowid for current entry */
  7444. sqlite3_rtree_dbl rParentScore; /* Score of parent node */
  7445. int eParentWithin; /* Visibility of parent node */
  7446. int eWithin; /* OUT: Visiblity */
  7447. sqlite3_rtree_dbl rScore; /* OUT: Write the score here */
  7448. };
  7449. /*
  7450. ** Allowed values for sqlite3_rtree_query.eWithin and .eParentWithin.
  7451. */
  7452. #define NOT_WITHIN 0 /* Object completely outside of query region */
  7453. #define PARTLY_WITHIN 1 /* Object partially overlaps query region */
  7454. #define FULLY_WITHIN 2 /* Object fully contained within query region */
  7455. #if 0
  7456. } /* end of the 'extern "C"' block */
  7457. #endif
  7458. #endif /* ifndef _SQLITE3RTREE_H_ */
  7459. /************** End of sqlite3.h *********************************************/
  7460. /************** Continuing where we left off in sqliteInt.h ******************/
  7461. /*
  7462. ** Include the configuration header output by 'configure' if we're using the
  7463. ** autoconf-based build
  7464. */
  7465. #ifdef _HAVE_SQLITE_CONFIG_H
  7466. #include "config.h"
  7467. #endif
  7468. /************** Include sqliteLimit.h in the middle of sqliteInt.h ***********/
  7469. /************** Begin file sqliteLimit.h *************************************/
  7470. /*
  7471. ** 2007 May 7
  7472. **
  7473. ** The author disclaims copyright to this source code. In place of
  7474. ** a legal notice, here is a blessing:
  7475. **
  7476. ** May you do good and not evil.
  7477. ** May you find forgiveness for yourself and forgive others.
  7478. ** May you share freely, never taking more than you give.
  7479. **
  7480. *************************************************************************
  7481. **
  7482. ** This file defines various limits of what SQLite can process.
  7483. */
  7484. /*
  7485. ** The maximum length of a TEXT or BLOB in bytes. This also
  7486. ** limits the size of a row in a table or index.
  7487. **
  7488. ** The hard limit is the ability of a 32-bit signed integer
  7489. ** to count the size: 2^31-1 or 2147483647.
  7490. */
  7491. #ifndef SQLITE_MAX_LENGTH
  7492. # define SQLITE_MAX_LENGTH 1000000000
  7493. #endif
  7494. /*
  7495. ** This is the maximum number of
  7496. **
  7497. ** * Columns in a table
  7498. ** * Columns in an index
  7499. ** * Columns in a view
  7500. ** * Terms in the SET clause of an UPDATE statement
  7501. ** * Terms in the result set of a SELECT statement
  7502. ** * Terms in the GROUP BY or ORDER BY clauses of a SELECT statement.
  7503. ** * Terms in the VALUES clause of an INSERT statement
  7504. **
  7505. ** The hard upper limit here is 32676. Most database people will
  7506. ** tell you that in a well-normalized database, you usually should
  7507. ** not have more than a dozen or so columns in any table. And if
  7508. ** that is the case, there is no point in having more than a few
  7509. ** dozen values in any of the other situations described above.
  7510. */
  7511. #ifndef SQLITE_MAX_COLUMN
  7512. # define SQLITE_MAX_COLUMN 2000
  7513. #endif
  7514. /*
  7515. ** The maximum length of a single SQL statement in bytes.
  7516. **
  7517. ** It used to be the case that setting this value to zero would
  7518. ** turn the limit off. That is no longer true. It is not possible
  7519. ** to turn this limit off.
  7520. */
  7521. #ifndef SQLITE_MAX_SQL_LENGTH
  7522. # define SQLITE_MAX_SQL_LENGTH 1000000000
  7523. #endif
  7524. /*
  7525. ** The maximum depth of an expression tree. This is limited to
  7526. ** some extent by SQLITE_MAX_SQL_LENGTH. But sometime you might
  7527. ** want to place more severe limits on the complexity of an
  7528. ** expression.
  7529. **
  7530. ** A value of 0 used to mean that the limit was not enforced.
  7531. ** But that is no longer true. The limit is now strictly enforced
  7532. ** at all times.
  7533. */
  7534. #ifndef SQLITE_MAX_EXPR_DEPTH
  7535. # define SQLITE_MAX_EXPR_DEPTH 1000
  7536. #endif
  7537. /*
  7538. ** The maximum number of terms in a compound SELECT statement.
  7539. ** The code generator for compound SELECT statements does one
  7540. ** level of recursion for each term. A stack overflow can result
  7541. ** if the number of terms is too large. In practice, most SQL
  7542. ** never has more than 3 or 4 terms. Use a value of 0 to disable
  7543. ** any limit on the number of terms in a compount SELECT.
  7544. */
  7545. #ifndef SQLITE_MAX_COMPOUND_SELECT
  7546. # define SQLITE_MAX_COMPOUND_SELECT 500
  7547. #endif
  7548. /*
  7549. ** The maximum number of opcodes in a VDBE program.
  7550. ** Not currently enforced.
  7551. */
  7552. #ifndef SQLITE_MAX_VDBE_OP
  7553. # define SQLITE_MAX_VDBE_OP 25000
  7554. #endif
  7555. /*
  7556. ** The maximum number of arguments to an SQL function.
  7557. */
  7558. #ifndef SQLITE_MAX_FUNCTION_ARG
  7559. # define SQLITE_MAX_FUNCTION_ARG 127
  7560. #endif
  7561. /*
  7562. ** The maximum number of in-memory pages to use for the main database
  7563. ** table and for temporary tables. The SQLITE_DEFAULT_CACHE_SIZE
  7564. */
  7565. #ifndef SQLITE_DEFAULT_CACHE_SIZE
  7566. # define SQLITE_DEFAULT_CACHE_SIZE 2000
  7567. #endif
  7568. #ifndef SQLITE_DEFAULT_TEMP_CACHE_SIZE
  7569. # define SQLITE_DEFAULT_TEMP_CACHE_SIZE 500
  7570. #endif
  7571. /*
  7572. ** The default number of frames to accumulate in the log file before
  7573. ** checkpointing the database in WAL mode.
  7574. */
  7575. #ifndef SQLITE_DEFAULT_WAL_AUTOCHECKPOINT
  7576. # define SQLITE_DEFAULT_WAL_AUTOCHECKPOINT 1000
  7577. #endif
  7578. /*
  7579. ** The maximum number of attached databases. This must be between 0
  7580. ** and 62. The upper bound on 62 is because a 64-bit integer bitmap
  7581. ** is used internally to track attached databases.
  7582. */
  7583. #ifndef SQLITE_MAX_ATTACHED
  7584. # define SQLITE_MAX_ATTACHED 10
  7585. #endif
  7586. /*
  7587. ** The maximum value of a ?nnn wildcard that the parser will accept.
  7588. */
  7589. #ifndef SQLITE_MAX_VARIABLE_NUMBER
  7590. # define SQLITE_MAX_VARIABLE_NUMBER 999
  7591. #endif
  7592. /* Maximum page size. The upper bound on this value is 65536. This a limit
  7593. ** imposed by the use of 16-bit offsets within each page.
  7594. **
  7595. ** Earlier versions of SQLite allowed the user to change this value at
  7596. ** compile time. This is no longer permitted, on the grounds that it creates
  7597. ** a library that is technically incompatible with an SQLite library
  7598. ** compiled with a different limit. If a process operating on a database
  7599. ** with a page-size of 65536 bytes crashes, then an instance of SQLite
  7600. ** compiled with the default page-size limit will not be able to rollback
  7601. ** the aborted transaction. This could lead to database corruption.
  7602. */
  7603. #ifdef SQLITE_MAX_PAGE_SIZE
  7604. # undef SQLITE_MAX_PAGE_SIZE
  7605. #endif
  7606. #define SQLITE_MAX_PAGE_SIZE 65536
  7607. /*
  7608. ** The default size of a database page.
  7609. */
  7610. #ifndef SQLITE_DEFAULT_PAGE_SIZE
  7611. # define SQLITE_DEFAULT_PAGE_SIZE 1024
  7612. #endif
  7613. #if SQLITE_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7614. # undef SQLITE_DEFAULT_PAGE_SIZE
  7615. # define SQLITE_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7616. #endif
  7617. /*
  7618. ** Ordinarily, if no value is explicitly provided, SQLite creates databases
  7619. ** with page size SQLITE_DEFAULT_PAGE_SIZE. However, based on certain
  7620. ** device characteristics (sector-size and atomic write() support),
  7621. ** SQLite may choose a larger value. This constant is the maximum value
  7622. ** SQLite will choose on its own.
  7623. */
  7624. #ifndef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7625. # define SQLITE_MAX_DEFAULT_PAGE_SIZE 8192
  7626. #endif
  7627. #if SQLITE_MAX_DEFAULT_PAGE_SIZE>SQLITE_MAX_PAGE_SIZE
  7628. # undef SQLITE_MAX_DEFAULT_PAGE_SIZE
  7629. # define SQLITE_MAX_DEFAULT_PAGE_SIZE SQLITE_MAX_PAGE_SIZE
  7630. #endif
  7631. /*
  7632. ** Maximum number of pages in one database file.
  7633. **
  7634. ** This is really just the default value for the max_page_count pragma.
  7635. ** This value can be lowered (or raised) at run-time using that the
  7636. ** max_page_count macro.
  7637. */
  7638. #ifndef SQLITE_MAX_PAGE_COUNT
  7639. # define SQLITE_MAX_PAGE_COUNT 1073741823
  7640. #endif
  7641. /*
  7642. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  7643. ** operator.
  7644. */
  7645. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  7646. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  7647. #endif
  7648. /*
  7649. ** Maximum depth of recursion for triggers.
  7650. **
  7651. ** A value of 1 means that a trigger program will not be able to itself
  7652. ** fire any triggers. A value of 0 means that no trigger programs at all
  7653. ** may be executed.
  7654. */
  7655. #ifndef SQLITE_MAX_TRIGGER_DEPTH
  7656. # define SQLITE_MAX_TRIGGER_DEPTH 1000
  7657. #endif
  7658. /************** End of sqliteLimit.h *****************************************/
  7659. /************** Continuing where we left off in sqliteInt.h ******************/
  7660. /* Disable nuisance warnings on Borland compilers */
  7661. #if defined(__BORLANDC__)
  7662. #pragma warn -rch /* unreachable code */
  7663. #pragma warn -ccc /* Condition is always true or false */
  7664. #pragma warn -aus /* Assigned value is never used */
  7665. #pragma warn -csu /* Comparing signed and unsigned */
  7666. #pragma warn -spa /* Suspicious pointer arithmetic */
  7667. #endif
  7668. /*
  7669. ** Include standard header files as necessary
  7670. */
  7671. #ifdef HAVE_STDINT_H
  7672. #include <stdint.h>
  7673. #endif
  7674. #ifdef HAVE_INTTYPES_H
  7675. #include <inttypes.h>
  7676. #endif
  7677. /*
  7678. ** The following macros are used to cast pointers to integers and
  7679. ** integers to pointers. The way you do this varies from one compiler
  7680. ** to the next, so we have developed the following set of #if statements
  7681. ** to generate appropriate macros for a wide range of compilers.
  7682. **
  7683. ** The correct "ANSI" way to do this is to use the intptr_t type.
  7684. ** Unfortunately, that typedef is not available on all compilers, or
  7685. ** if it is available, it requires an #include of specific headers
  7686. ** that vary from one machine to the next.
  7687. **
  7688. ** Ticket #3860: The llvm-gcc-4.2 compiler from Apple chokes on
  7689. ** the ((void*)&((char*)0)[X]) construct. But MSVC chokes on ((void*)(X)).
  7690. ** So we have to define the macros in different ways depending on the
  7691. ** compiler.
  7692. */
  7693. #if defined(__PTRDIFF_TYPE__) /* This case should work for GCC */
  7694. # define SQLITE_INT_TO_PTR(X) ((void*)(__PTRDIFF_TYPE__)(X))
  7695. # define SQLITE_PTR_TO_INT(X) ((int)(__PTRDIFF_TYPE__)(X))
  7696. #elif !defined(__GNUC__) /* Works for compilers other than LLVM */
  7697. # define SQLITE_INT_TO_PTR(X) ((void*)&((char*)0)[X])
  7698. # define SQLITE_PTR_TO_INT(X) ((int)(((char*)X)-(char*)0))
  7699. #elif defined(HAVE_STDINT_H) /* Use this case if we have ANSI headers */
  7700. # define SQLITE_INT_TO_PTR(X) ((void*)(intptr_t)(X))
  7701. # define SQLITE_PTR_TO_INT(X) ((int)(intptr_t)(X))
  7702. #else /* Generates a warning - but it always works */
  7703. # define SQLITE_INT_TO_PTR(X) ((void*)(X))
  7704. # define SQLITE_PTR_TO_INT(X) ((int)(X))
  7705. #endif
  7706. /*
  7707. ** A macro to hint to the compiler that a function should not be
  7708. ** inlined.
  7709. */
  7710. #if defined(__GNUC__)
  7711. # define SQLITE_NOINLINE __attribute__((noinline))
  7712. #elif defined(_MSC_VER) && _MSC_VER>=1310
  7713. # define SQLITE_NOINLINE __declspec(noinline)
  7714. #else
  7715. # define SQLITE_NOINLINE
  7716. #endif
  7717. /*
  7718. ** The SQLITE_THREADSAFE macro must be defined as 0, 1, or 2.
  7719. ** 0 means mutexes are permanently disable and the library is never
  7720. ** threadsafe. 1 means the library is serialized which is the highest
  7721. ** level of threadsafety. 2 means the library is multithreaded - multiple
  7722. ** threads can use SQLite as long as no two threads try to use the same
  7723. ** database connection at the same time.
  7724. **
  7725. ** Older versions of SQLite used an optional THREADSAFE macro.
  7726. ** We support that for legacy.
  7727. */
  7728. #if !defined(SQLITE_THREADSAFE)
  7729. # if defined(THREADSAFE)
  7730. # define SQLITE_THREADSAFE THREADSAFE
  7731. # else
  7732. # define SQLITE_THREADSAFE 1 /* IMP: R-07272-22309 */
  7733. # endif
  7734. #endif
  7735. /*
  7736. ** Powersafe overwrite is on by default. But can be turned off using
  7737. ** the -DSQLITE_POWERSAFE_OVERWRITE=0 command-line option.
  7738. */
  7739. #ifndef SQLITE_POWERSAFE_OVERWRITE
  7740. # define SQLITE_POWERSAFE_OVERWRITE 1
  7741. #endif
  7742. /*
  7743. ** The SQLITE_DEFAULT_MEMSTATUS macro must be defined as either 0 or 1.
  7744. ** It determines whether or not the features related to
  7745. ** SQLITE_CONFIG_MEMSTATUS are available by default or not. This value can
  7746. ** be overridden at runtime using the sqlite3_config() API.
  7747. */
  7748. #if !defined(SQLITE_DEFAULT_MEMSTATUS)
  7749. # define SQLITE_DEFAULT_MEMSTATUS 1
  7750. #endif
  7751. /*
  7752. ** Exactly one of the following macros must be defined in order to
  7753. ** specify which memory allocation subsystem to use.
  7754. **
  7755. ** SQLITE_SYSTEM_MALLOC // Use normal system malloc()
  7756. ** SQLITE_WIN32_MALLOC // Use Win32 native heap API
  7757. ** SQLITE_ZERO_MALLOC // Use a stub allocator that always fails
  7758. ** SQLITE_MEMDEBUG // Debugging version of system malloc()
  7759. **
  7760. ** On Windows, if the SQLITE_WIN32_MALLOC_VALIDATE macro is defined and the
  7761. ** assert() macro is enabled, each call into the Win32 native heap subsystem
  7762. ** will cause HeapValidate to be called. If heap validation should fail, an
  7763. ** assertion will be triggered.
  7764. **
  7765. ** If none of the above are defined, then set SQLITE_SYSTEM_MALLOC as
  7766. ** the default.
  7767. */
  7768. #if defined(SQLITE_SYSTEM_MALLOC) \
  7769. + defined(SQLITE_WIN32_MALLOC) \
  7770. + defined(SQLITE_ZERO_MALLOC) \
  7771. + defined(SQLITE_MEMDEBUG)>1
  7772. # error "Two or more of the following compile-time configuration options\
  7773. are defined but at most one is allowed:\
  7774. SQLITE_SYSTEM_MALLOC, SQLITE_WIN32_MALLOC, SQLITE_MEMDEBUG,\
  7775. SQLITE_ZERO_MALLOC"
  7776. #endif
  7777. #if defined(SQLITE_SYSTEM_MALLOC) \
  7778. + defined(SQLITE_WIN32_MALLOC) \
  7779. + defined(SQLITE_ZERO_MALLOC) \
  7780. + defined(SQLITE_MEMDEBUG)==0
  7781. # define SQLITE_SYSTEM_MALLOC 1
  7782. #endif
  7783. /*
  7784. ** If SQLITE_MALLOC_SOFT_LIMIT is not zero, then try to keep the
  7785. ** sizes of memory allocations below this value where possible.
  7786. */
  7787. #if !defined(SQLITE_MALLOC_SOFT_LIMIT)
  7788. # define SQLITE_MALLOC_SOFT_LIMIT 1024
  7789. #endif
  7790. /*
  7791. ** We need to define _XOPEN_SOURCE as follows in order to enable
  7792. ** recursive mutexes on most Unix systems and fchmod() on OpenBSD.
  7793. ** But _XOPEN_SOURCE define causes problems for Mac OS X, so omit
  7794. ** it.
  7795. */
  7796. #if !defined(_XOPEN_SOURCE) && !defined(__DARWIN__) && !defined(__APPLE__)
  7797. # define _XOPEN_SOURCE 600
  7798. #endif
  7799. /*
  7800. ** NDEBUG and SQLITE_DEBUG are opposites. It should always be true that
  7801. ** defined(NDEBUG)==!defined(SQLITE_DEBUG). If this is not currently true,
  7802. ** make it true by defining or undefining NDEBUG.
  7803. **
  7804. ** Setting NDEBUG makes the code smaller and faster by disabling the
  7805. ** assert() statements in the code. So we want the default action
  7806. ** to be for NDEBUG to be set and NDEBUG to be undefined only if SQLITE_DEBUG
  7807. ** is set. Thus NDEBUG becomes an opt-in rather than an opt-out
  7808. ** feature.
  7809. */
  7810. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  7811. # define NDEBUG 1
  7812. #endif
  7813. #if defined(NDEBUG) && defined(SQLITE_DEBUG)
  7814. # undef NDEBUG
  7815. #endif
  7816. /*
  7817. ** Enable SQLITE_ENABLE_EXPLAIN_COMMENTS if SQLITE_DEBUG is turned on.
  7818. */
  7819. #if !defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) && defined(SQLITE_DEBUG)
  7820. # define SQLITE_ENABLE_EXPLAIN_COMMENTS 1
  7821. #endif
  7822. /*
  7823. ** The testcase() macro is used to aid in coverage testing. When
  7824. ** doing coverage testing, the condition inside the argument to
  7825. ** testcase() must be evaluated both true and false in order to
  7826. ** get full branch coverage. The testcase() macro is inserted
  7827. ** to help ensure adequate test coverage in places where simple
  7828. ** condition/decision coverage is inadequate. For example, testcase()
  7829. ** can be used to make sure boundary values are tested. For
  7830. ** bitmask tests, testcase() can be used to make sure each bit
  7831. ** is significant and used at least once. On switch statements
  7832. ** where multiple cases go to the same block of code, testcase()
  7833. ** can insure that all cases are evaluated.
  7834. **
  7835. */
  7836. #ifdef SQLITE_COVERAGE_TEST
  7837. SQLITE_PRIVATE void sqlite3Coverage(int);
  7838. # define testcase(X) if( X ){ sqlite3Coverage(__LINE__); }
  7839. #else
  7840. # define testcase(X)
  7841. #endif
  7842. /*
  7843. ** The TESTONLY macro is used to enclose variable declarations or
  7844. ** other bits of code that are needed to support the arguments
  7845. ** within testcase() and assert() macros.
  7846. */
  7847. #if !defined(NDEBUG) || defined(SQLITE_COVERAGE_TEST)
  7848. # define TESTONLY(X) X
  7849. #else
  7850. # define TESTONLY(X)
  7851. #endif
  7852. /*
  7853. ** Sometimes we need a small amount of code such as a variable initialization
  7854. ** to setup for a later assert() statement. We do not want this code to
  7855. ** appear when assert() is disabled. The following macro is therefore
  7856. ** used to contain that setup code. The "VVA" acronym stands for
  7857. ** "Verification, Validation, and Accreditation". In other words, the
  7858. ** code within VVA_ONLY() will only run during verification processes.
  7859. */
  7860. #ifndef NDEBUG
  7861. # define VVA_ONLY(X) X
  7862. #else
  7863. # define VVA_ONLY(X)
  7864. #endif
  7865. /*
  7866. ** The ALWAYS and NEVER macros surround boolean expressions which
  7867. ** are intended to always be true or false, respectively. Such
  7868. ** expressions could be omitted from the code completely. But they
  7869. ** are included in a few cases in order to enhance the resilience
  7870. ** of SQLite to unexpected behavior - to make the code "self-healing"
  7871. ** or "ductile" rather than being "brittle" and crashing at the first
  7872. ** hint of unplanned behavior.
  7873. **
  7874. ** In other words, ALWAYS and NEVER are added for defensive code.
  7875. **
  7876. ** When doing coverage testing ALWAYS and NEVER are hard-coded to
  7877. ** be true and false so that the unreachable code they specify will
  7878. ** not be counted as untested code.
  7879. */
  7880. #if defined(SQLITE_COVERAGE_TEST)
  7881. # define ALWAYS(X) (1)
  7882. # define NEVER(X) (0)
  7883. #elif !defined(NDEBUG)
  7884. # define ALWAYS(X) ((X)?1:(assert(0),0))
  7885. # define NEVER(X) ((X)?(assert(0),1):0)
  7886. #else
  7887. # define ALWAYS(X) (X)
  7888. # define NEVER(X) (X)
  7889. #endif
  7890. /*
  7891. ** Return true (non-zero) if the input is an integer that is too large
  7892. ** to fit in 32-bits. This macro is used inside of various testcase()
  7893. ** macros to verify that we have tested SQLite for large-file support.
  7894. */
  7895. #define IS_BIG_INT(X) (((X)&~(i64)0xffffffff)!=0)
  7896. /*
  7897. ** The macro unlikely() is a hint that surrounds a boolean
  7898. ** expression that is usually false. Macro likely() surrounds
  7899. ** a boolean expression that is usually true. These hints could,
  7900. ** in theory, be used by the compiler to generate better code, but
  7901. ** currently they are just comments for human readers.
  7902. */
  7903. #define likely(X) (X)
  7904. #define unlikely(X) (X)
  7905. /************** Include hash.h in the middle of sqliteInt.h ******************/
  7906. /************** Begin file hash.h ********************************************/
  7907. /*
  7908. ** 2001 September 22
  7909. **
  7910. ** The author disclaims copyright to this source code. In place of
  7911. ** a legal notice, here is a blessing:
  7912. **
  7913. ** May you do good and not evil.
  7914. ** May you find forgiveness for yourself and forgive others.
  7915. ** May you share freely, never taking more than you give.
  7916. **
  7917. *************************************************************************
  7918. ** This is the header file for the generic hash-table implementation
  7919. ** used in SQLite.
  7920. */
  7921. #ifndef _SQLITE_HASH_H_
  7922. #define _SQLITE_HASH_H_
  7923. /* Forward declarations of structures. */
  7924. typedef struct Hash Hash;
  7925. typedef struct HashElem HashElem;
  7926. /* A complete hash table is an instance of the following structure.
  7927. ** The internals of this structure are intended to be opaque -- client
  7928. ** code should not attempt to access or modify the fields of this structure
  7929. ** directly. Change this structure only by using the routines below.
  7930. ** However, some of the "procedures" and "functions" for modifying and
  7931. ** accessing this structure are really macros, so we can't really make
  7932. ** this structure opaque.
  7933. **
  7934. ** All elements of the hash table are on a single doubly-linked list.
  7935. ** Hash.first points to the head of this list.
  7936. **
  7937. ** There are Hash.htsize buckets. Each bucket points to a spot in
  7938. ** the global doubly-linked list. The contents of the bucket are the
  7939. ** element pointed to plus the next _ht.count-1 elements in the list.
  7940. **
  7941. ** Hash.htsize and Hash.ht may be zero. In that case lookup is done
  7942. ** by a linear search of the global list. For small tables, the
  7943. ** Hash.ht table is never allocated because if there are few elements
  7944. ** in the table, it is faster to do a linear search than to manage
  7945. ** the hash table.
  7946. */
  7947. struct Hash {
  7948. unsigned int htsize; /* Number of buckets in the hash table */
  7949. unsigned int count; /* Number of entries in this table */
  7950. HashElem *first; /* The first element of the array */
  7951. struct _ht { /* the hash table */
  7952. int count; /* Number of entries with this hash */
  7953. HashElem *chain; /* Pointer to first entry with this hash */
  7954. } *ht;
  7955. };
  7956. /* Each element in the hash table is an instance of the following
  7957. ** structure. All elements are stored on a single doubly-linked list.
  7958. **
  7959. ** Again, this structure is intended to be opaque, but it can't really
  7960. ** be opaque because it is used by macros.
  7961. */
  7962. struct HashElem {
  7963. HashElem *next, *prev; /* Next and previous elements in the table */
  7964. void *data; /* Data associated with this element */
  7965. const char *pKey; /* Key associated with this element */
  7966. };
  7967. /*
  7968. ** Access routines. To delete, insert a NULL pointer.
  7969. */
  7970. SQLITE_PRIVATE void sqlite3HashInit(Hash*);
  7971. SQLITE_PRIVATE void *sqlite3HashInsert(Hash*, const char *pKey, void *pData);
  7972. SQLITE_PRIVATE void *sqlite3HashFind(const Hash*, const char *pKey);
  7973. SQLITE_PRIVATE void sqlite3HashClear(Hash*);
  7974. /*
  7975. ** Macros for looping over all elements of a hash table. The idiom is
  7976. ** like this:
  7977. **
  7978. ** Hash h;
  7979. ** HashElem *p;
  7980. ** ...
  7981. ** for(p=sqliteHashFirst(&h); p; p=sqliteHashNext(p)){
  7982. ** SomeStructure *pData = sqliteHashData(p);
  7983. ** // do something with pData
  7984. ** }
  7985. */
  7986. #define sqliteHashFirst(H) ((H)->first)
  7987. #define sqliteHashNext(E) ((E)->next)
  7988. #define sqliteHashData(E) ((E)->data)
  7989. /* #define sqliteHashKey(E) ((E)->pKey) // NOT USED */
  7990. /* #define sqliteHashKeysize(E) ((E)->nKey) // NOT USED */
  7991. /*
  7992. ** Number of entries in a hash table
  7993. */
  7994. /* #define sqliteHashCount(H) ((H)->count) // NOT USED */
  7995. #endif /* _SQLITE_HASH_H_ */
  7996. /************** End of hash.h ************************************************/
  7997. /************** Continuing where we left off in sqliteInt.h ******************/
  7998. /************** Include parse.h in the middle of sqliteInt.h *****************/
  7999. /************** Begin file parse.h *******************************************/
  8000. #define TK_SEMI 1
  8001. #define TK_EXPLAIN 2
  8002. #define TK_QUERY 3
  8003. #define TK_PLAN 4
  8004. #define TK_BEGIN 5
  8005. #define TK_TRANSACTION 6
  8006. #define TK_DEFERRED 7
  8007. #define TK_IMMEDIATE 8
  8008. #define TK_EXCLUSIVE 9
  8009. #define TK_COMMIT 10
  8010. #define TK_END 11
  8011. #define TK_ROLLBACK 12
  8012. #define TK_SAVEPOINT 13
  8013. #define TK_RELEASE 14
  8014. #define TK_TO 15
  8015. #define TK_TABLE 16
  8016. #define TK_CREATE 17
  8017. #define TK_IF 18
  8018. #define TK_NOT 19
  8019. #define TK_EXISTS 20
  8020. #define TK_TEMP 21
  8021. #define TK_LP 22
  8022. #define TK_RP 23
  8023. #define TK_AS 24
  8024. #define TK_WITHOUT 25
  8025. #define TK_COMMA 26
  8026. #define TK_ID 27
  8027. #define TK_INDEXED 28
  8028. #define TK_ABORT 29
  8029. #define TK_ACTION 30
  8030. #define TK_AFTER 31
  8031. #define TK_ANALYZE 32
  8032. #define TK_ASC 33
  8033. #define TK_ATTACH 34
  8034. #define TK_BEFORE 35
  8035. #define TK_BY 36
  8036. #define TK_CASCADE 37
  8037. #define TK_CAST 38
  8038. #define TK_COLUMNKW 39
  8039. #define TK_CONFLICT 40
  8040. #define TK_DATABASE 41
  8041. #define TK_DESC 42
  8042. #define TK_DETACH 43
  8043. #define TK_EACH 44
  8044. #define TK_FAIL 45
  8045. #define TK_FOR 46
  8046. #define TK_IGNORE 47
  8047. #define TK_INITIALLY 48
  8048. #define TK_INSTEAD 49
  8049. #define TK_LIKE_KW 50
  8050. #define TK_MATCH 51
  8051. #define TK_NO 52
  8052. #define TK_KEY 53
  8053. #define TK_OF 54
  8054. #define TK_OFFSET 55
  8055. #define TK_PRAGMA 56
  8056. #define TK_RAISE 57
  8057. #define TK_RECURSIVE 58
  8058. #define TK_REPLACE 59
  8059. #define TK_RESTRICT 60
  8060. #define TK_ROW 61
  8061. #define TK_TRIGGER 62
  8062. #define TK_VACUUM 63
  8063. #define TK_VIEW 64
  8064. #define TK_VIRTUAL 65
  8065. #define TK_WITH 66
  8066. #define TK_REINDEX 67
  8067. #define TK_RENAME 68
  8068. #define TK_CTIME_KW 69
  8069. #define TK_ANY 70
  8070. #define TK_OR 71
  8071. #define TK_AND 72
  8072. #define TK_IS 73
  8073. #define TK_BETWEEN 74
  8074. #define TK_IN 75
  8075. #define TK_ISNULL 76
  8076. #define TK_NOTNULL 77
  8077. #define TK_NE 78
  8078. #define TK_EQ 79
  8079. #define TK_GT 80
  8080. #define TK_LE 81
  8081. #define TK_LT 82
  8082. #define TK_GE 83
  8083. #define TK_ESCAPE 84
  8084. #define TK_BITAND 85
  8085. #define TK_BITOR 86
  8086. #define TK_LSHIFT 87
  8087. #define TK_RSHIFT 88
  8088. #define TK_PLUS 89
  8089. #define TK_MINUS 90
  8090. #define TK_STAR 91
  8091. #define TK_SLASH 92
  8092. #define TK_REM 93
  8093. #define TK_CONCAT 94
  8094. #define TK_COLLATE 95
  8095. #define TK_BITNOT 96
  8096. #define TK_STRING 97
  8097. #define TK_JOIN_KW 98
  8098. #define TK_CONSTRAINT 99
  8099. #define TK_DEFAULT 100
  8100. #define TK_NULL 101
  8101. #define TK_PRIMARY 102
  8102. #define TK_UNIQUE 103
  8103. #define TK_CHECK 104
  8104. #define TK_REFERENCES 105
  8105. #define TK_AUTOINCR 106
  8106. #define TK_ON 107
  8107. #define TK_INSERT 108
  8108. #define TK_DELETE 109
  8109. #define TK_UPDATE 110
  8110. #define TK_SET 111
  8111. #define TK_DEFERRABLE 112
  8112. #define TK_FOREIGN 113
  8113. #define TK_DROP 114
  8114. #define TK_UNION 115
  8115. #define TK_ALL 116
  8116. #define TK_EXCEPT 117
  8117. #define TK_INTERSECT 118
  8118. #define TK_SELECT 119
  8119. #define TK_VALUES 120
  8120. #define TK_DISTINCT 121
  8121. #define TK_DOT 122
  8122. #define TK_FROM 123
  8123. #define TK_JOIN 124
  8124. #define TK_USING 125
  8125. #define TK_ORDER 126
  8126. #define TK_GROUP 127
  8127. #define TK_HAVING 128
  8128. #define TK_LIMIT 129
  8129. #define TK_WHERE 130
  8130. #define TK_INTO 131
  8131. #define TK_INTEGER 132
  8132. #define TK_FLOAT 133
  8133. #define TK_BLOB 134
  8134. #define TK_VARIABLE 135
  8135. #define TK_CASE 136
  8136. #define TK_WHEN 137
  8137. #define TK_THEN 138
  8138. #define TK_ELSE 139
  8139. #define TK_INDEX 140
  8140. #define TK_ALTER 141
  8141. #define TK_ADD 142
  8142. #define TK_TO_TEXT 143
  8143. #define TK_TO_BLOB 144
  8144. #define TK_TO_NUMERIC 145
  8145. #define TK_TO_INT 146
  8146. #define TK_TO_REAL 147
  8147. #define TK_ISNOT 148
  8148. #define TK_END_OF_FILE 149
  8149. #define TK_ILLEGAL 150
  8150. #define TK_SPACE 151
  8151. #define TK_UNCLOSED_STRING 152
  8152. #define TK_FUNCTION 153
  8153. #define TK_COLUMN 154
  8154. #define TK_AGG_FUNCTION 155
  8155. #define TK_AGG_COLUMN 156
  8156. #define TK_UMINUS 157
  8157. #define TK_UPLUS 158
  8158. #define TK_REGISTER 159
  8159. /************** End of parse.h ***********************************************/
  8160. /************** Continuing where we left off in sqliteInt.h ******************/
  8161. #include <stdio.h>
  8162. #include <stdlib.h>
  8163. #include <string.h>
  8164. #include <assert.h>
  8165. #include <stddef.h>
  8166. /*
  8167. ** If compiling for a processor that lacks floating point support,
  8168. ** substitute integer for floating-point
  8169. */
  8170. #ifdef SQLITE_OMIT_FLOATING_POINT
  8171. # define double sqlite_int64
  8172. # define float sqlite_int64
  8173. # define LONGDOUBLE_TYPE sqlite_int64
  8174. # ifndef SQLITE_BIG_DBL
  8175. # define SQLITE_BIG_DBL (((sqlite3_int64)1)<<50)
  8176. # endif
  8177. # define SQLITE_OMIT_DATETIME_FUNCS 1
  8178. # define SQLITE_OMIT_TRACE 1
  8179. # undef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  8180. # undef SQLITE_HAVE_ISNAN
  8181. #endif
  8182. #ifndef SQLITE_BIG_DBL
  8183. # define SQLITE_BIG_DBL (1e99)
  8184. #endif
  8185. /*
  8186. ** OMIT_TEMPDB is set to 1 if SQLITE_OMIT_TEMPDB is defined, or 0
  8187. ** afterward. Having this macro allows us to cause the C compiler
  8188. ** to omit code used by TEMP tables without messy #ifndef statements.
  8189. */
  8190. #ifdef SQLITE_OMIT_TEMPDB
  8191. #define OMIT_TEMPDB 1
  8192. #else
  8193. #define OMIT_TEMPDB 0
  8194. #endif
  8195. /*
  8196. ** The "file format" number is an integer that is incremented whenever
  8197. ** the VDBE-level file format changes. The following macros define the
  8198. ** the default file format for new databases and the maximum file format
  8199. ** that the library can read.
  8200. */
  8201. #define SQLITE_MAX_FILE_FORMAT 4
  8202. #ifndef SQLITE_DEFAULT_FILE_FORMAT
  8203. # define SQLITE_DEFAULT_FILE_FORMAT 4
  8204. #endif
  8205. /*
  8206. ** Determine whether triggers are recursive by default. This can be
  8207. ** changed at run-time using a pragma.
  8208. */
  8209. #ifndef SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  8210. # define SQLITE_DEFAULT_RECURSIVE_TRIGGERS 0
  8211. #endif
  8212. /*
  8213. ** Provide a default value for SQLITE_TEMP_STORE in case it is not specified
  8214. ** on the command-line
  8215. */
  8216. #ifndef SQLITE_TEMP_STORE
  8217. # define SQLITE_TEMP_STORE 1
  8218. # define SQLITE_TEMP_STORE_xc 1 /* Exclude from ctime.c */
  8219. #endif
  8220. /*
  8221. ** If no value has been provided for SQLITE_MAX_WORKER_THREADS, or if
  8222. ** SQLITE_TEMP_STORE is set to 3 (never use temporary files), set it
  8223. ** to zero.
  8224. */
  8225. #if SQLITE_TEMP_STORE==3 || SQLITE_THREADSAFE==0
  8226. # undef SQLITE_MAX_WORKER_THREADS
  8227. # define SQLITE_MAX_WORKER_THREADS 0
  8228. #endif
  8229. #ifndef SQLITE_MAX_WORKER_THREADS
  8230. # define SQLITE_MAX_WORKER_THREADS 8
  8231. #endif
  8232. #ifndef SQLITE_DEFAULT_WORKER_THREADS
  8233. # define SQLITE_DEFAULT_WORKER_THREADS 0
  8234. #endif
  8235. #if SQLITE_DEFAULT_WORKER_THREADS>SQLITE_MAX_WORKER_THREADS
  8236. # undef SQLITE_MAX_WORKER_THREADS
  8237. # define SQLITE_MAX_WORKER_THREADS SQLITE_DEFAULT_WORKER_THREADS
  8238. #endif
  8239. /*
  8240. ** GCC does not define the offsetof() macro so we'll have to do it
  8241. ** ourselves.
  8242. */
  8243. #ifndef offsetof
  8244. #define offsetof(STRUCTURE,FIELD) ((int)((char*)&((STRUCTURE*)0)->FIELD))
  8245. #endif
  8246. /*
  8247. ** Macros to compute minimum and maximum of two numbers.
  8248. */
  8249. #define MIN(A,B) ((A)<(B)?(A):(B))
  8250. #define MAX(A,B) ((A)>(B)?(A):(B))
  8251. /*
  8252. ** Swap two objects of type TYPE.
  8253. */
  8254. #define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
  8255. /*
  8256. ** Check to see if this machine uses EBCDIC. (Yes, believe it or
  8257. ** not, there are still machines out there that use EBCDIC.)
  8258. */
  8259. #if 'A' == '\301'
  8260. # define SQLITE_EBCDIC 1
  8261. #else
  8262. # define SQLITE_ASCII 1
  8263. #endif
  8264. /*
  8265. ** Integers of known sizes. These typedefs might change for architectures
  8266. ** where the sizes very. Preprocessor macros are available so that the
  8267. ** types can be conveniently redefined at compile-type. Like this:
  8268. **
  8269. ** cc '-DUINTPTR_TYPE=long long int' ...
  8270. */
  8271. #ifndef UINT32_TYPE
  8272. # ifdef HAVE_UINT32_T
  8273. # define UINT32_TYPE uint32_t
  8274. # else
  8275. # define UINT32_TYPE unsigned int
  8276. # endif
  8277. #endif
  8278. #ifndef UINT16_TYPE
  8279. # ifdef HAVE_UINT16_T
  8280. # define UINT16_TYPE uint16_t
  8281. # else
  8282. # define UINT16_TYPE unsigned short int
  8283. # endif
  8284. #endif
  8285. #ifndef INT16_TYPE
  8286. # ifdef HAVE_INT16_T
  8287. # define INT16_TYPE int16_t
  8288. # else
  8289. # define INT16_TYPE short int
  8290. # endif
  8291. #endif
  8292. #ifndef UINT8_TYPE
  8293. # ifdef HAVE_UINT8_T
  8294. # define UINT8_TYPE uint8_t
  8295. # else
  8296. # define UINT8_TYPE unsigned char
  8297. # endif
  8298. #endif
  8299. #ifndef INT8_TYPE
  8300. # ifdef HAVE_INT8_T
  8301. # define INT8_TYPE int8_t
  8302. # else
  8303. # define INT8_TYPE signed char
  8304. # endif
  8305. #endif
  8306. #ifndef LONGDOUBLE_TYPE
  8307. # define LONGDOUBLE_TYPE long double
  8308. #endif
  8309. typedef sqlite_int64 i64; /* 8-byte signed integer */
  8310. typedef sqlite_uint64 u64; /* 8-byte unsigned integer */
  8311. typedef UINT32_TYPE u32; /* 4-byte unsigned integer */
  8312. typedef UINT16_TYPE u16; /* 2-byte unsigned integer */
  8313. typedef INT16_TYPE i16; /* 2-byte signed integer */
  8314. typedef UINT8_TYPE u8; /* 1-byte unsigned integer */
  8315. typedef INT8_TYPE i8; /* 1-byte signed integer */
  8316. /*
  8317. ** SQLITE_MAX_U32 is a u64 constant that is the maximum u64 value
  8318. ** that can be stored in a u32 without loss of data. The value
  8319. ** is 0x00000000ffffffff. But because of quirks of some compilers, we
  8320. ** have to specify the value in the less intuitive manner shown:
  8321. */
  8322. #define SQLITE_MAX_U32 ((((u64)1)<<32)-1)
  8323. /*
  8324. ** The datatype used to store estimates of the number of rows in a
  8325. ** table or index. This is an unsigned integer type. For 99.9% of
  8326. ** the world, a 32-bit integer is sufficient. But a 64-bit integer
  8327. ** can be used at compile-time if desired.
  8328. */
  8329. #ifdef SQLITE_64BIT_STATS
  8330. typedef u64 tRowcnt; /* 64-bit only if requested at compile-time */
  8331. #else
  8332. typedef u32 tRowcnt; /* 32-bit is the default */
  8333. #endif
  8334. /*
  8335. ** Estimated quantities used for query planning are stored as 16-bit
  8336. ** logarithms. For quantity X, the value stored is 10*log2(X). This
  8337. ** gives a possible range of values of approximately 1.0e986 to 1e-986.
  8338. ** But the allowed values are "grainy". Not every value is representable.
  8339. ** For example, quantities 16 and 17 are both represented by a LogEst
  8340. ** of 40. However, since LogEst quantaties are suppose to be estimates,
  8341. ** not exact values, this imprecision is not a problem.
  8342. **
  8343. ** "LogEst" is short for "Logarithmic Estimate".
  8344. **
  8345. ** Examples:
  8346. ** 1 -> 0 20 -> 43 10000 -> 132
  8347. ** 2 -> 10 25 -> 46 25000 -> 146
  8348. ** 3 -> 16 100 -> 66 1000000 -> 199
  8349. ** 4 -> 20 1000 -> 99 1048576 -> 200
  8350. ** 10 -> 33 1024 -> 100 4294967296 -> 320
  8351. **
  8352. ** The LogEst can be negative to indicate fractional values.
  8353. ** Examples:
  8354. **
  8355. ** 0.5 -> -10 0.1 -> -33 0.0625 -> -40
  8356. */
  8357. typedef INT16_TYPE LogEst;
  8358. /*
  8359. ** Macros to determine whether the machine is big or little endian,
  8360. ** and whether or not that determination is run-time or compile-time.
  8361. **
  8362. ** For best performance, an attempt is made to guess at the byte-order
  8363. ** using C-preprocessor macros. If that is unsuccessful, or if
  8364. ** -DSQLITE_RUNTIME_BYTEORDER=1 is set, then byte-order is determined
  8365. ** at run-time.
  8366. */
  8367. #ifdef SQLITE_AMALGAMATION
  8368. SQLITE_PRIVATE const int sqlite3one = 1;
  8369. #else
  8370. SQLITE_PRIVATE const int sqlite3one;
  8371. #endif
  8372. #if (defined(i386) || defined(__i386__) || defined(_M_IX86) || \
  8373. defined(__x86_64) || defined(__x86_64__) || defined(_M_X64) || \
  8374. defined(_M_AMD64) || defined(_M_ARM) || defined(__x86) || \
  8375. defined(__arm__)) && !defined(SQLITE_RUNTIME_BYTEORDER)
  8376. # define SQLITE_BYTEORDER 1234
  8377. # define SQLITE_BIGENDIAN 0
  8378. # define SQLITE_LITTLEENDIAN 1
  8379. # define SQLITE_UTF16NATIVE SQLITE_UTF16LE
  8380. #endif
  8381. #if (defined(sparc) || defined(__ppc__)) \
  8382. && !defined(SQLITE_RUNTIME_BYTEORDER)
  8383. # define SQLITE_BYTEORDER 4321
  8384. # define SQLITE_BIGENDIAN 1
  8385. # define SQLITE_LITTLEENDIAN 0
  8386. # define SQLITE_UTF16NATIVE SQLITE_UTF16BE
  8387. #endif
  8388. #if !defined(SQLITE_BYTEORDER)
  8389. # define SQLITE_BYTEORDER 0 /* 0 means "unknown at compile-time" */
  8390. # define SQLITE_BIGENDIAN (*(char *)(&sqlite3one)==0)
  8391. # define SQLITE_LITTLEENDIAN (*(char *)(&sqlite3one)==1)
  8392. # define SQLITE_UTF16NATIVE (SQLITE_BIGENDIAN?SQLITE_UTF16BE:SQLITE_UTF16LE)
  8393. #endif
  8394. /*
  8395. ** Constants for the largest and smallest possible 64-bit signed integers.
  8396. ** These macros are designed to work correctly on both 32-bit and 64-bit
  8397. ** compilers.
  8398. */
  8399. #define LARGEST_INT64 (0xffffffff|(((i64)0x7fffffff)<<32))
  8400. #define SMALLEST_INT64 (((i64)-1) - LARGEST_INT64)
  8401. /*
  8402. ** Round up a number to the next larger multiple of 8. This is used
  8403. ** to force 8-byte alignment on 64-bit architectures.
  8404. */
  8405. #define ROUND8(x) (((x)+7)&~7)
  8406. /*
  8407. ** Round down to the nearest multiple of 8
  8408. */
  8409. #define ROUNDDOWN8(x) ((x)&~7)
  8410. /*
  8411. ** Assert that the pointer X is aligned to an 8-byte boundary. This
  8412. ** macro is used only within assert() to verify that the code gets
  8413. ** all alignment restrictions correct.
  8414. **
  8415. ** Except, if SQLITE_4_BYTE_ALIGNED_MALLOC is defined, then the
  8416. ** underlying malloc() implementation might return us 4-byte aligned
  8417. ** pointers. In that case, only verify 4-byte alignment.
  8418. */
  8419. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  8420. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&3)==0)
  8421. #else
  8422. # define EIGHT_BYTE_ALIGNMENT(X) ((((char*)(X) - (char*)0)&7)==0)
  8423. #endif
  8424. /*
  8425. ** Disable MMAP on platforms where it is known to not work
  8426. */
  8427. #if defined(__OpenBSD__) || defined(__QNXNTO__)
  8428. # undef SQLITE_MAX_MMAP_SIZE
  8429. # define SQLITE_MAX_MMAP_SIZE 0
  8430. #endif
  8431. /*
  8432. ** Default maximum size of memory used by memory-mapped I/O in the VFS
  8433. */
  8434. #ifdef __APPLE__
  8435. # include <TargetConditionals.h>
  8436. # if TARGET_OS_IPHONE
  8437. # undef SQLITE_MAX_MMAP_SIZE
  8438. # define SQLITE_MAX_MMAP_SIZE 0
  8439. # endif
  8440. #endif
  8441. #ifndef SQLITE_MAX_MMAP_SIZE
  8442. # if defined(__linux__) \
  8443. || defined(_WIN32) \
  8444. || (defined(__APPLE__) && defined(__MACH__)) \
  8445. || defined(__sun)
  8446. # define SQLITE_MAX_MMAP_SIZE 0x7fff0000 /* 2147418112 */
  8447. # else
  8448. # define SQLITE_MAX_MMAP_SIZE 0
  8449. # endif
  8450. # define SQLITE_MAX_MMAP_SIZE_xc 1 /* exclude from ctime.c */
  8451. #endif
  8452. /*
  8453. ** The default MMAP_SIZE is zero on all platforms. Or, even if a larger
  8454. ** default MMAP_SIZE is specified at compile-time, make sure that it does
  8455. ** not exceed the maximum mmap size.
  8456. */
  8457. #ifndef SQLITE_DEFAULT_MMAP_SIZE
  8458. # define SQLITE_DEFAULT_MMAP_SIZE 0
  8459. # define SQLITE_DEFAULT_MMAP_SIZE_xc 1 /* Exclude from ctime.c */
  8460. #endif
  8461. #if SQLITE_DEFAULT_MMAP_SIZE>SQLITE_MAX_MMAP_SIZE
  8462. # undef SQLITE_DEFAULT_MMAP_SIZE
  8463. # define SQLITE_DEFAULT_MMAP_SIZE SQLITE_MAX_MMAP_SIZE
  8464. #endif
  8465. /*
  8466. ** Only one of SQLITE_ENABLE_STAT3 or SQLITE_ENABLE_STAT4 can be defined.
  8467. ** Priority is given to SQLITE_ENABLE_STAT4. If either are defined, also
  8468. ** define SQLITE_ENABLE_STAT3_OR_STAT4
  8469. */
  8470. #ifdef SQLITE_ENABLE_STAT4
  8471. # undef SQLITE_ENABLE_STAT3
  8472. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8473. #elif SQLITE_ENABLE_STAT3
  8474. # define SQLITE_ENABLE_STAT3_OR_STAT4 1
  8475. #elif SQLITE_ENABLE_STAT3_OR_STAT4
  8476. # undef SQLITE_ENABLE_STAT3_OR_STAT4
  8477. #endif
  8478. /*
  8479. ** SELECTTRACE_ENABLED will be either 1 or 0 depending on whether or not
  8480. ** the Select query generator tracing logic is turned on.
  8481. */
  8482. #if defined(SQLITE_DEBUG) || defined(SQLITE_ENABLE_SELECTTRACE)
  8483. # define SELECTTRACE_ENABLED 1
  8484. #else
  8485. # define SELECTTRACE_ENABLED 0
  8486. #endif
  8487. /*
  8488. ** An instance of the following structure is used to store the busy-handler
  8489. ** callback for a given sqlite handle.
  8490. **
  8491. ** The sqlite.busyHandler member of the sqlite struct contains the busy
  8492. ** callback for the database handle. Each pager opened via the sqlite
  8493. ** handle is passed a pointer to sqlite.busyHandler. The busy-handler
  8494. ** callback is currently invoked only from within pager.c.
  8495. */
  8496. typedef struct BusyHandler BusyHandler;
  8497. struct BusyHandler {
  8498. int (*xFunc)(void *,int); /* The busy callback */
  8499. void *pArg; /* First arg to busy callback */
  8500. int nBusy; /* Incremented with each busy call */
  8501. };
  8502. /*
  8503. ** Name of the master database table. The master database table
  8504. ** is a special table that holds the names and attributes of all
  8505. ** user tables and indices.
  8506. */
  8507. #define MASTER_NAME "sqlite_master"
  8508. #define TEMP_MASTER_NAME "sqlite_temp_master"
  8509. /*
  8510. ** The root-page of the master database table.
  8511. */
  8512. #define MASTER_ROOT 1
  8513. /*
  8514. ** The name of the schema table.
  8515. */
  8516. #define SCHEMA_TABLE(x) ((!OMIT_TEMPDB)&&(x==1)?TEMP_MASTER_NAME:MASTER_NAME)
  8517. /*
  8518. ** A convenience macro that returns the number of elements in
  8519. ** an array.
  8520. */
  8521. #define ArraySize(X) ((int)(sizeof(X)/sizeof(X[0])))
  8522. /*
  8523. ** Determine if the argument is a power of two
  8524. */
  8525. #define IsPowerOfTwo(X) (((X)&((X)-1))==0)
  8526. /*
  8527. ** The following value as a destructor means to use sqlite3DbFree().
  8528. ** The sqlite3DbFree() routine requires two parameters instead of the
  8529. ** one parameter that destructors normally want. So we have to introduce
  8530. ** this magic value that the code knows to handle differently. Any
  8531. ** pointer will work here as long as it is distinct from SQLITE_STATIC
  8532. ** and SQLITE_TRANSIENT.
  8533. */
  8534. #define SQLITE_DYNAMIC ((sqlite3_destructor_type)sqlite3MallocSize)
  8535. /*
  8536. ** When SQLITE_OMIT_WSD is defined, it means that the target platform does
  8537. ** not support Writable Static Data (WSD) such as global and static variables.
  8538. ** All variables must either be on the stack or dynamically allocated from
  8539. ** the heap. When WSD is unsupported, the variable declarations scattered
  8540. ** throughout the SQLite code must become constants instead. The SQLITE_WSD
  8541. ** macro is used for this purpose. And instead of referencing the variable
  8542. ** directly, we use its constant as a key to lookup the run-time allocated
  8543. ** buffer that holds real variable. The constant is also the initializer
  8544. ** for the run-time allocated buffer.
  8545. **
  8546. ** In the usual case where WSD is supported, the SQLITE_WSD and GLOBAL
  8547. ** macros become no-ops and have zero performance impact.
  8548. */
  8549. #ifdef SQLITE_OMIT_WSD
  8550. #define SQLITE_WSD const
  8551. #define GLOBAL(t,v) (*(t*)sqlite3_wsd_find((void*)&(v), sizeof(v)))
  8552. #define sqlite3GlobalConfig GLOBAL(struct Sqlite3Config, sqlite3Config)
  8553. SQLITE_API int sqlite3_wsd_init(int N, int J);
  8554. SQLITE_API void *sqlite3_wsd_find(void *K, int L);
  8555. #else
  8556. #define SQLITE_WSD
  8557. #define GLOBAL(t,v) v
  8558. #define sqlite3GlobalConfig sqlite3Config
  8559. #endif
  8560. /*
  8561. ** The following macros are used to suppress compiler warnings and to
  8562. ** make it clear to human readers when a function parameter is deliberately
  8563. ** left unused within the body of a function. This usually happens when
  8564. ** a function is called via a function pointer. For example the
  8565. ** implementation of an SQL aggregate step callback may not use the
  8566. ** parameter indicating the number of arguments passed to the aggregate,
  8567. ** if it knows that this is enforced elsewhere.
  8568. **
  8569. ** When a function parameter is not used at all within the body of a function,
  8570. ** it is generally named "NotUsed" or "NotUsed2" to make things even clearer.
  8571. ** However, these macros may also be used to suppress warnings related to
  8572. ** parameters that may or may not be used depending on compilation options.
  8573. ** For example those parameters only used in assert() statements. In these
  8574. ** cases the parameters are named as per the usual conventions.
  8575. */
  8576. #define UNUSED_PARAMETER(x) (void)(x)
  8577. #define UNUSED_PARAMETER2(x,y) UNUSED_PARAMETER(x),UNUSED_PARAMETER(y)
  8578. /*
  8579. ** Forward references to structures
  8580. */
  8581. typedef struct AggInfo AggInfo;
  8582. typedef struct AuthContext AuthContext;
  8583. typedef struct AutoincInfo AutoincInfo;
  8584. typedef struct Bitvec Bitvec;
  8585. typedef struct CollSeq CollSeq;
  8586. typedef struct Column Column;
  8587. typedef struct Db Db;
  8588. typedef struct Schema Schema;
  8589. typedef struct Expr Expr;
  8590. typedef struct ExprList ExprList;
  8591. typedef struct ExprSpan ExprSpan;
  8592. typedef struct FKey FKey;
  8593. typedef struct FuncDestructor FuncDestructor;
  8594. typedef struct FuncDef FuncDef;
  8595. typedef struct FuncDefHash FuncDefHash;
  8596. typedef struct IdList IdList;
  8597. typedef struct Index Index;
  8598. typedef struct IndexSample IndexSample;
  8599. typedef struct KeyClass KeyClass;
  8600. typedef struct KeyInfo KeyInfo;
  8601. typedef struct Lookaside Lookaside;
  8602. typedef struct LookasideSlot LookasideSlot;
  8603. typedef struct Module Module;
  8604. typedef struct NameContext NameContext;
  8605. typedef struct Parse Parse;
  8606. typedef struct PrintfArguments PrintfArguments;
  8607. typedef struct RowSet RowSet;
  8608. typedef struct Savepoint Savepoint;
  8609. typedef struct Select Select;
  8610. typedef struct SQLiteThread SQLiteThread;
  8611. typedef struct SelectDest SelectDest;
  8612. typedef struct SrcList SrcList;
  8613. typedef struct StrAccum StrAccum;
  8614. typedef struct Table Table;
  8615. typedef struct TableLock TableLock;
  8616. typedef struct Token Token;
  8617. typedef struct TreeView TreeView;
  8618. typedef struct Trigger Trigger;
  8619. typedef struct TriggerPrg TriggerPrg;
  8620. typedef struct TriggerStep TriggerStep;
  8621. typedef struct UnpackedRecord UnpackedRecord;
  8622. typedef struct VTable VTable;
  8623. typedef struct VtabCtx VtabCtx;
  8624. typedef struct Walker Walker;
  8625. typedef struct WhereInfo WhereInfo;
  8626. typedef struct With With;
  8627. /*
  8628. ** Defer sourcing vdbe.h and btree.h until after the "u8" and
  8629. ** "BusyHandler" typedefs. vdbe.h also requires a few of the opaque
  8630. ** pointer types (i.e. FuncDef) defined above.
  8631. */
  8632. /************** Include btree.h in the middle of sqliteInt.h *****************/
  8633. /************** Begin file btree.h *******************************************/
  8634. /*
  8635. ** 2001 September 15
  8636. **
  8637. ** The author disclaims copyright to this source code. In place of
  8638. ** a legal notice, here is a blessing:
  8639. **
  8640. ** May you do good and not evil.
  8641. ** May you find forgiveness for yourself and forgive others.
  8642. ** May you share freely, never taking more than you give.
  8643. **
  8644. *************************************************************************
  8645. ** This header file defines the interface that the sqlite B-Tree file
  8646. ** subsystem. See comments in the source code for a detailed description
  8647. ** of what each interface routine does.
  8648. */
  8649. #ifndef _BTREE_H_
  8650. #define _BTREE_H_
  8651. /* TODO: This definition is just included so other modules compile. It
  8652. ** needs to be revisited.
  8653. */
  8654. #define SQLITE_N_BTREE_META 10
  8655. /*
  8656. ** If defined as non-zero, auto-vacuum is enabled by default. Otherwise
  8657. ** it must be turned on for each database using "PRAGMA auto_vacuum = 1".
  8658. */
  8659. #ifndef SQLITE_DEFAULT_AUTOVACUUM
  8660. #define SQLITE_DEFAULT_AUTOVACUUM 0
  8661. #endif
  8662. #define BTREE_AUTOVACUUM_NONE 0 /* Do not do auto-vacuum */
  8663. #define BTREE_AUTOVACUUM_FULL 1 /* Do full auto-vacuum */
  8664. #define BTREE_AUTOVACUUM_INCR 2 /* Incremental vacuum */
  8665. /*
  8666. ** Forward declarations of structure
  8667. */
  8668. typedef struct Btree Btree;
  8669. typedef struct BtCursor BtCursor;
  8670. typedef struct BtShared BtShared;
  8671. SQLITE_PRIVATE int sqlite3BtreeOpen(
  8672. sqlite3_vfs *pVfs, /* VFS to use with this b-tree */
  8673. const char *zFilename, /* Name of database file to open */
  8674. sqlite3 *db, /* Associated database connection */
  8675. Btree **ppBtree, /* Return open Btree* here */
  8676. int flags, /* Flags */
  8677. int vfsFlags /* Flags passed through to VFS open */
  8678. );
  8679. /* The flags parameter to sqlite3BtreeOpen can be the bitwise or of the
  8680. ** following values.
  8681. **
  8682. ** NOTE: These values must match the corresponding PAGER_ values in
  8683. ** pager.h.
  8684. */
  8685. #define BTREE_OMIT_JOURNAL 1 /* Do not create or use a rollback journal */
  8686. #define BTREE_MEMORY 2 /* This is an in-memory DB */
  8687. #define BTREE_SINGLE 4 /* The file contains at most 1 b-tree */
  8688. #define BTREE_UNORDERED 8 /* Use of a hash implementation is OK */
  8689. SQLITE_PRIVATE int sqlite3BtreeClose(Btree*);
  8690. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree*,int);
  8691. #if SQLITE_MAX_MMAP_SIZE>0
  8692. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree*,sqlite3_int64);
  8693. #endif
  8694. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(Btree*,unsigned);
  8695. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree*);
  8696. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int nPagesize, int nReserve, int eFix);
  8697. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree*);
  8698. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree*,int);
  8699. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree*);
  8700. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree*,int);
  8701. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree*);
  8702. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  8703. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p);
  8704. #endif
  8705. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *, int);
  8706. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *);
  8707. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree*,int);
  8708. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree*, const char *zMaster);
  8709. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree*, int);
  8710. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree*);
  8711. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree*,int,int);
  8712. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree*,int);
  8713. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree*, int*, int flags);
  8714. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree*);
  8715. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree*);
  8716. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree*);
  8717. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *, int, void(*)(void *));
  8718. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *pBtree);
  8719. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *pBtree, int iTab, u8 isWriteLock);
  8720. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *, int, int);
  8721. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *);
  8722. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *);
  8723. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *, Btree *);
  8724. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *);
  8725. /* The flags parameter to sqlite3BtreeCreateTable can be the bitwise OR
  8726. ** of the flags shown below.
  8727. **
  8728. ** Every SQLite table must have either BTREE_INTKEY or BTREE_BLOBKEY set.
  8729. ** With BTREE_INTKEY, the table key is a 64-bit integer and arbitrary data
  8730. ** is stored in the leaves. (BTREE_INTKEY is used for SQL tables.) With
  8731. ** BTREE_BLOBKEY, the key is an arbitrary BLOB and no content is stored
  8732. ** anywhere - the key is the content. (BTREE_BLOBKEY is used for SQL
  8733. ** indices.)
  8734. */
  8735. #define BTREE_INTKEY 1 /* Table has only 64-bit signed integer keys */
  8736. #define BTREE_BLOBKEY 2 /* Table has keys only - no data */
  8737. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree*, int, int*);
  8738. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree*, int, int*);
  8739. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor*);
  8740. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree*, int, int);
  8741. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *pBtree, int idx, u32 *pValue);
  8742. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree*, int idx, u32 value);
  8743. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p);
  8744. /*
  8745. ** The second parameter to sqlite3BtreeGetMeta or sqlite3BtreeUpdateMeta
  8746. ** should be one of the following values. The integer values are assigned
  8747. ** to constants so that the offset of the corresponding field in an
  8748. ** SQLite database header may be found using the following formula:
  8749. **
  8750. ** offset = 36 + (idx * 4)
  8751. **
  8752. ** For example, the free-page-count field is located at byte offset 36 of
  8753. ** the database file header. The incr-vacuum-flag field is located at
  8754. ** byte offset 64 (== 36+4*7).
  8755. */
  8756. #define BTREE_FREE_PAGE_COUNT 0
  8757. #define BTREE_SCHEMA_VERSION 1
  8758. #define BTREE_FILE_FORMAT 2
  8759. #define BTREE_DEFAULT_CACHE_SIZE 3
  8760. #define BTREE_LARGEST_ROOT_PAGE 4
  8761. #define BTREE_TEXT_ENCODING 5
  8762. #define BTREE_USER_VERSION 6
  8763. #define BTREE_INCR_VACUUM 7
  8764. #define BTREE_APPLICATION_ID 8
  8765. /*
  8766. ** Values that may be OR'd together to form the second argument of an
  8767. ** sqlite3BtreeCursorHints() call.
  8768. */
  8769. #define BTREE_BULKLOAD 0x00000001
  8770. SQLITE_PRIVATE int sqlite3BtreeCursor(
  8771. Btree*, /* BTree containing table to open */
  8772. int iTable, /* Index of root page */
  8773. int wrFlag, /* 1 for writing. 0 for read-only */
  8774. struct KeyInfo*, /* First argument to compare function */
  8775. BtCursor *pCursor /* Space to write cursor structure */
  8776. );
  8777. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void);
  8778. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor*);
  8779. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor*);
  8780. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  8781. BtCursor*,
  8782. UnpackedRecord *pUnKey,
  8783. i64 intKey,
  8784. int bias,
  8785. int *pRes
  8786. );
  8787. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor*);
  8788. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor*, int*);
  8789. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor*);
  8790. SQLITE_PRIVATE int sqlite3BtreeInsert(BtCursor*, const void *pKey, i64 nKey,
  8791. const void *pData, int nData,
  8792. int nZero, int bias, int seekResult);
  8793. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor*, int *pRes);
  8794. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor*, int *pRes);
  8795. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor*, int *pRes);
  8796. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor*);
  8797. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor*, int *pRes);
  8798. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor*, i64 *pSize);
  8799. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor*, u32 offset, u32 amt, void*);
  8800. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor*, u32 *pAmt);
  8801. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor*, u32 *pAmt);
  8802. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor*, u32 *pSize);
  8803. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor*, u32 offset, u32 amt, void*);
  8804. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(Btree*, int *aRoot, int nRoot, int, int*);
  8805. SQLITE_PRIVATE struct Pager *sqlite3BtreePager(Btree*);
  8806. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor*, u32 offset, u32 amt, void*);
  8807. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *);
  8808. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *);
  8809. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBt, int iVersion);
  8810. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *, unsigned int mask);
  8811. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *pBt);
  8812. #ifndef NDEBUG
  8813. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor*);
  8814. #endif
  8815. #ifndef SQLITE_OMIT_BTREECOUNT
  8816. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *, i64 *);
  8817. #endif
  8818. #ifdef SQLITE_TEST
  8819. SQLITE_PRIVATE int sqlite3BtreeCursorInfo(BtCursor*, int*, int);
  8820. SQLITE_PRIVATE void sqlite3BtreeCursorList(Btree*);
  8821. #endif
  8822. #ifndef SQLITE_OMIT_WAL
  8823. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree*, int, int *, int *);
  8824. #endif
  8825. /*
  8826. ** If we are not using shared cache, then there is no need to
  8827. ** use mutexes to access the BtShared structures. So make the
  8828. ** Enter and Leave procedures no-ops.
  8829. */
  8830. #ifndef SQLITE_OMIT_SHARED_CACHE
  8831. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree*);
  8832. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3*);
  8833. #else
  8834. # define sqlite3BtreeEnter(X)
  8835. # define sqlite3BtreeEnterAll(X)
  8836. #endif
  8837. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE
  8838. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree*);
  8839. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree*);
  8840. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor*);
  8841. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor*);
  8842. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3*);
  8843. #ifndef NDEBUG
  8844. /* These routines are used inside assert() statements only. */
  8845. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree*);
  8846. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3*);
  8847. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3*,int,Schema*);
  8848. #endif
  8849. #else
  8850. # define sqlite3BtreeSharable(X) 0
  8851. # define sqlite3BtreeLeave(X)
  8852. # define sqlite3BtreeEnterCursor(X)
  8853. # define sqlite3BtreeLeaveCursor(X)
  8854. # define sqlite3BtreeLeaveAll(X)
  8855. # define sqlite3BtreeHoldsMutex(X) 1
  8856. # define sqlite3BtreeHoldsAllMutexes(X) 1
  8857. # define sqlite3SchemaMutexHeld(X,Y,Z) 1
  8858. #endif
  8859. #endif /* _BTREE_H_ */
  8860. /************** End of btree.h ***********************************************/
  8861. /************** Continuing where we left off in sqliteInt.h ******************/
  8862. /************** Include vdbe.h in the middle of sqliteInt.h ******************/
  8863. /************** Begin file vdbe.h ********************************************/
  8864. /*
  8865. ** 2001 September 15
  8866. **
  8867. ** The author disclaims copyright to this source code. In place of
  8868. ** a legal notice, here is a blessing:
  8869. **
  8870. ** May you do good and not evil.
  8871. ** May you find forgiveness for yourself and forgive others.
  8872. ** May you share freely, never taking more than you give.
  8873. **
  8874. *************************************************************************
  8875. ** Header file for the Virtual DataBase Engine (VDBE)
  8876. **
  8877. ** This header defines the interface to the virtual database engine
  8878. ** or VDBE. The VDBE implements an abstract machine that runs a
  8879. ** simple program to access and modify the underlying database.
  8880. */
  8881. #ifndef _SQLITE_VDBE_H_
  8882. #define _SQLITE_VDBE_H_
  8883. /* #include <stdio.h> */
  8884. /*
  8885. ** A single VDBE is an opaque structure named "Vdbe". Only routines
  8886. ** in the source file sqliteVdbe.c are allowed to see the insides
  8887. ** of this structure.
  8888. */
  8889. typedef struct Vdbe Vdbe;
  8890. /*
  8891. ** The names of the following types declared in vdbeInt.h are required
  8892. ** for the VdbeOp definition.
  8893. */
  8894. typedef struct Mem Mem;
  8895. typedef struct SubProgram SubProgram;
  8896. /*
  8897. ** A single instruction of the virtual machine has an opcode
  8898. ** and as many as three operands. The instruction is recorded
  8899. ** as an instance of the following structure:
  8900. */
  8901. struct VdbeOp {
  8902. u8 opcode; /* What operation to perform */
  8903. signed char p4type; /* One of the P4_xxx constants for p4 */
  8904. u8 opflags; /* Mask of the OPFLG_* flags in opcodes.h */
  8905. u8 p5; /* Fifth parameter is an unsigned character */
  8906. int p1; /* First operand */
  8907. int p2; /* Second parameter (often the jump destination) */
  8908. int p3; /* The third parameter */
  8909. union { /* fourth parameter */
  8910. int i; /* Integer value if p4type==P4_INT32 */
  8911. void *p; /* Generic pointer */
  8912. char *z; /* Pointer to data for string (char array) types */
  8913. i64 *pI64; /* Used when p4type is P4_INT64 */
  8914. double *pReal; /* Used when p4type is P4_REAL */
  8915. FuncDef *pFunc; /* Used when p4type is P4_FUNCDEF */
  8916. CollSeq *pColl; /* Used when p4type is P4_COLLSEQ */
  8917. Mem *pMem; /* Used when p4type is P4_MEM */
  8918. VTable *pVtab; /* Used when p4type is P4_VTAB */
  8919. KeyInfo *pKeyInfo; /* Used when p4type is P4_KEYINFO */
  8920. int *ai; /* Used when p4type is P4_INTARRAY */
  8921. SubProgram *pProgram; /* Used when p4type is P4_SUBPROGRAM */
  8922. int (*xAdvance)(BtCursor *, int *);
  8923. } p4;
  8924. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  8925. char *zComment; /* Comment to improve readability */
  8926. #endif
  8927. #ifdef VDBE_PROFILE
  8928. u32 cnt; /* Number of times this instruction was executed */
  8929. u64 cycles; /* Total time spent executing this instruction */
  8930. #endif
  8931. #ifdef SQLITE_VDBE_COVERAGE
  8932. int iSrcLine; /* Source-code line that generated this opcode */
  8933. #endif
  8934. };
  8935. typedef struct VdbeOp VdbeOp;
  8936. /*
  8937. ** A sub-routine used to implement a trigger program.
  8938. */
  8939. struct SubProgram {
  8940. VdbeOp *aOp; /* Array of opcodes for sub-program */
  8941. int nOp; /* Elements in aOp[] */
  8942. int nMem; /* Number of memory cells required */
  8943. int nCsr; /* Number of cursors required */
  8944. int nOnce; /* Number of OP_Once instructions */
  8945. void *token; /* id that may be used to recursive triggers */
  8946. SubProgram *pNext; /* Next sub-program already visited */
  8947. };
  8948. /*
  8949. ** A smaller version of VdbeOp used for the VdbeAddOpList() function because
  8950. ** it takes up less space.
  8951. */
  8952. struct VdbeOpList {
  8953. u8 opcode; /* What operation to perform */
  8954. signed char p1; /* First operand */
  8955. signed char p2; /* Second parameter (often the jump destination) */
  8956. signed char p3; /* Third parameter */
  8957. };
  8958. typedef struct VdbeOpList VdbeOpList;
  8959. /*
  8960. ** Allowed values of VdbeOp.p4type
  8961. */
  8962. #define P4_NOTUSED 0 /* The P4 parameter is not used */
  8963. #define P4_DYNAMIC (-1) /* Pointer to a string obtained from sqliteMalloc() */
  8964. #define P4_STATIC (-2) /* Pointer to a static string */
  8965. #define P4_COLLSEQ (-4) /* P4 is a pointer to a CollSeq structure */
  8966. #define P4_FUNCDEF (-5) /* P4 is a pointer to a FuncDef structure */
  8967. #define P4_KEYINFO (-6) /* P4 is a pointer to a KeyInfo structure */
  8968. #define P4_MEM (-8) /* P4 is a pointer to a Mem* structure */
  8969. #define P4_TRANSIENT 0 /* P4 is a pointer to a transient string */
  8970. #define P4_VTAB (-10) /* P4 is a pointer to an sqlite3_vtab structure */
  8971. #define P4_MPRINTF (-11) /* P4 is a string obtained from sqlite3_mprintf() */
  8972. #define P4_REAL (-12) /* P4 is a 64-bit floating point value */
  8973. #define P4_INT64 (-13) /* P4 is a 64-bit signed integer */
  8974. #define P4_INT32 (-14) /* P4 is a 32-bit signed integer */
  8975. #define P4_INTARRAY (-15) /* P4 is a vector of 32-bit integers */
  8976. #define P4_SUBPROGRAM (-18) /* P4 is a pointer to a SubProgram structure */
  8977. #define P4_ADVANCE (-19) /* P4 is a pointer to BtreeNext() or BtreePrev() */
  8978. /* Error message codes for OP_Halt */
  8979. #define P5_ConstraintNotNull 1
  8980. #define P5_ConstraintUnique 2
  8981. #define P5_ConstraintCheck 3
  8982. #define P5_ConstraintFK 4
  8983. /*
  8984. ** The Vdbe.aColName array contains 5n Mem structures, where n is the
  8985. ** number of columns of data returned by the statement.
  8986. */
  8987. #define COLNAME_NAME 0
  8988. #define COLNAME_DECLTYPE 1
  8989. #define COLNAME_DATABASE 2
  8990. #define COLNAME_TABLE 3
  8991. #define COLNAME_COLUMN 4
  8992. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  8993. # define COLNAME_N 5 /* Number of COLNAME_xxx symbols */
  8994. #else
  8995. # ifdef SQLITE_OMIT_DECLTYPE
  8996. # define COLNAME_N 1 /* Store only the name */
  8997. # else
  8998. # define COLNAME_N 2 /* Store the name and decltype */
  8999. # endif
  9000. #endif
  9001. /*
  9002. ** The following macro converts a relative address in the p2 field
  9003. ** of a VdbeOp structure into a negative number so that
  9004. ** sqlite3VdbeAddOpList() knows that the address is relative. Calling
  9005. ** the macro again restores the address.
  9006. */
  9007. #define ADDR(X) (-1-(X))
  9008. /*
  9009. ** The makefile scans the vdbe.c source file and creates the "opcodes.h"
  9010. ** header file that defines a number for each opcode used by the VDBE.
  9011. */
  9012. /************** Include opcodes.h in the middle of vdbe.h ********************/
  9013. /************** Begin file opcodes.h *****************************************/
  9014. /* Automatically generated. Do not edit */
  9015. /* See the mkopcodeh.awk script for details */
  9016. #define OP_Function 1 /* synopsis: r[P3]=func(r[P2@P5]) */
  9017. #define OP_Savepoint 2
  9018. #define OP_AutoCommit 3
  9019. #define OP_Transaction 4
  9020. #define OP_SorterNext 5
  9021. #define OP_PrevIfOpen 6
  9022. #define OP_NextIfOpen 7
  9023. #define OP_Prev 8
  9024. #define OP_Next 9
  9025. #define OP_AggStep 10 /* synopsis: accum=r[P3] step(r[P2@P5]) */
  9026. #define OP_Checkpoint 11
  9027. #define OP_JournalMode 12
  9028. #define OP_Vacuum 13
  9029. #define OP_VFilter 14 /* synopsis: iplan=r[P3] zplan='P4' */
  9030. #define OP_VUpdate 15 /* synopsis: data=r[P3@P2] */
  9031. #define OP_Goto 16
  9032. #define OP_Gosub 17
  9033. #define OP_Return 18
  9034. #define OP_Not 19 /* same as TK_NOT, synopsis: r[P2]= !r[P1] */
  9035. #define OP_InitCoroutine 20
  9036. #define OP_EndCoroutine 21
  9037. #define OP_Yield 22
  9038. #define OP_HaltIfNull 23 /* synopsis: if r[P3]=null halt */
  9039. #define OP_Halt 24
  9040. #define OP_Integer 25 /* synopsis: r[P2]=P1 */
  9041. #define OP_Int64 26 /* synopsis: r[P2]=P4 */
  9042. #define OP_String 27 /* synopsis: r[P2]='P4' (len=P1) */
  9043. #define OP_Null 28 /* synopsis: r[P2..P3]=NULL */
  9044. #define OP_SoftNull 29 /* synopsis: r[P1]=NULL */
  9045. #define OP_Blob 30 /* synopsis: r[P2]=P4 (len=P1) */
  9046. #define OP_Variable 31 /* synopsis: r[P2]=parameter(P1,P4) */
  9047. #define OP_Move 32 /* synopsis: r[P2@P3]=r[P1@P3] */
  9048. #define OP_Copy 33 /* synopsis: r[P2@P3+1]=r[P1@P3+1] */
  9049. #define OP_SCopy 34 /* synopsis: r[P2]=r[P1] */
  9050. #define OP_ResultRow 35 /* synopsis: output=r[P1@P2] */
  9051. #define OP_CollSeq 36
  9052. #define OP_AddImm 37 /* synopsis: r[P1]=r[P1]+P2 */
  9053. #define OP_MustBeInt 38
  9054. #define OP_RealAffinity 39
  9055. #define OP_Cast 40 /* synopsis: affinity(r[P1]) */
  9056. #define OP_Permutation 41
  9057. #define OP_Compare 42 /* synopsis: r[P1@P3] <-> r[P2@P3] */
  9058. #define OP_Jump 43
  9059. #define OP_Once 44
  9060. #define OP_If 45
  9061. #define OP_IfNot 46
  9062. #define OP_Column 47 /* synopsis: r[P3]=PX */
  9063. #define OP_Affinity 48 /* synopsis: affinity(r[P1@P2]) */
  9064. #define OP_MakeRecord 49 /* synopsis: r[P3]=mkrec(r[P1@P2]) */
  9065. #define OP_Count 50 /* synopsis: r[P2]=count() */
  9066. #define OP_ReadCookie 51
  9067. #define OP_SetCookie 52
  9068. #define OP_ReopenIdx 53 /* synopsis: root=P2 iDb=P3 */
  9069. #define OP_OpenRead 54 /* synopsis: root=P2 iDb=P3 */
  9070. #define OP_OpenWrite 55 /* synopsis: root=P2 iDb=P3 */
  9071. #define OP_OpenAutoindex 56 /* synopsis: nColumn=P2 */
  9072. #define OP_OpenEphemeral 57 /* synopsis: nColumn=P2 */
  9073. #define OP_SorterOpen 58
  9074. #define OP_SequenceTest 59 /* synopsis: if( cursor[P1].ctr++ ) pc = P2 */
  9075. #define OP_OpenPseudo 60 /* synopsis: P3 columns in r[P2] */
  9076. #define OP_Close 61
  9077. #define OP_SeekLT 62 /* synopsis: key=r[P3@P4] */
  9078. #define OP_SeekLE 63 /* synopsis: key=r[P3@P4] */
  9079. #define OP_SeekGE 64 /* synopsis: key=r[P3@P4] */
  9080. #define OP_SeekGT 65 /* synopsis: key=r[P3@P4] */
  9081. #define OP_Seek 66 /* synopsis: intkey=r[P2] */
  9082. #define OP_NoConflict 67 /* synopsis: key=r[P3@P4] */
  9083. #define OP_NotFound 68 /* synopsis: key=r[P3@P4] */
  9084. #define OP_Found 69 /* synopsis: key=r[P3@P4] */
  9085. #define OP_NotExists 70 /* synopsis: intkey=r[P3] */
  9086. #define OP_Or 71 /* same as TK_OR, synopsis: r[P3]=(r[P1] || r[P2]) */
  9087. #define OP_And 72 /* same as TK_AND, synopsis: r[P3]=(r[P1] && r[P2]) */
  9088. #define OP_Sequence 73 /* synopsis: r[P2]=cursor[P1].ctr++ */
  9089. #define OP_NewRowid 74 /* synopsis: r[P2]=rowid */
  9090. #define OP_Insert 75 /* synopsis: intkey=r[P3] data=r[P2] */
  9091. #define OP_IsNull 76 /* same as TK_ISNULL, synopsis: if r[P1]==NULL goto P2 */
  9092. #define OP_NotNull 77 /* same as TK_NOTNULL, synopsis: if r[P1]!=NULL goto P2 */
  9093. #define OP_Ne 78 /* same as TK_NE, synopsis: if r[P1]!=r[P3] goto P2 */
  9094. #define OP_Eq 79 /* same as TK_EQ, synopsis: if r[P1]==r[P3] goto P2 */
  9095. #define OP_Gt 80 /* same as TK_GT, synopsis: if r[P1]>r[P3] goto P2 */
  9096. #define OP_Le 81 /* same as TK_LE, synopsis: if r[P1]<=r[P3] goto P2 */
  9097. #define OP_Lt 82 /* same as TK_LT, synopsis: if r[P1]<r[P3] goto P2 */
  9098. #define OP_Ge 83 /* same as TK_GE, synopsis: if r[P1]>=r[P3] goto P2 */
  9099. #define OP_InsertInt 84 /* synopsis: intkey=P3 data=r[P2] */
  9100. #define OP_BitAnd 85 /* same as TK_BITAND, synopsis: r[P3]=r[P1]&r[P2] */
  9101. #define OP_BitOr 86 /* same as TK_BITOR, synopsis: r[P3]=r[P1]|r[P2] */
  9102. #define OP_ShiftLeft 87 /* same as TK_LSHIFT, synopsis: r[P3]=r[P2]<<r[P1] */
  9103. #define OP_ShiftRight 88 /* same as TK_RSHIFT, synopsis: r[P3]=r[P2]>>r[P1] */
  9104. #define OP_Add 89 /* same as TK_PLUS, synopsis: r[P3]=r[P1]+r[P2] */
  9105. #define OP_Subtract 90 /* same as TK_MINUS, synopsis: r[P3]=r[P2]-r[P1] */
  9106. #define OP_Multiply 91 /* same as TK_STAR, synopsis: r[P3]=r[P1]*r[P2] */
  9107. #define OP_Divide 92 /* same as TK_SLASH, synopsis: r[P3]=r[P2]/r[P1] */
  9108. #define OP_Remainder 93 /* same as TK_REM, synopsis: r[P3]=r[P2]%r[P1] */
  9109. #define OP_Concat 94 /* same as TK_CONCAT, synopsis: r[P3]=r[P2]+r[P1] */
  9110. #define OP_Delete 95
  9111. #define OP_BitNot 96 /* same as TK_BITNOT, synopsis: r[P1]= ~r[P1] */
  9112. #define OP_String8 97 /* same as TK_STRING, synopsis: r[P2]='P4' */
  9113. #define OP_ResetCount 98
  9114. #define OP_SorterCompare 99 /* synopsis: if key(P1)!=trim(r[P3],P4) goto P2 */
  9115. #define OP_SorterData 100 /* synopsis: r[P2]=data */
  9116. #define OP_RowKey 101 /* synopsis: r[P2]=key */
  9117. #define OP_RowData 102 /* synopsis: r[P2]=data */
  9118. #define OP_Rowid 103 /* synopsis: r[P2]=rowid */
  9119. #define OP_NullRow 104
  9120. #define OP_Last 105
  9121. #define OP_SorterSort 106
  9122. #define OP_Sort 107
  9123. #define OP_Rewind 108
  9124. #define OP_SorterInsert 109
  9125. #define OP_IdxInsert 110 /* synopsis: key=r[P2] */
  9126. #define OP_IdxDelete 111 /* synopsis: key=r[P2@P3] */
  9127. #define OP_IdxRowid 112 /* synopsis: r[P2]=rowid */
  9128. #define OP_IdxLE 113 /* synopsis: key=r[P3@P4] */
  9129. #define OP_IdxGT 114 /* synopsis: key=r[P3@P4] */
  9130. #define OP_IdxLT 115 /* synopsis: key=r[P3@P4] */
  9131. #define OP_IdxGE 116 /* synopsis: key=r[P3@P4] */
  9132. #define OP_Destroy 117
  9133. #define OP_Clear 118
  9134. #define OP_ResetSorter 119
  9135. #define OP_CreateIndex 120 /* synopsis: r[P2]=root iDb=P1 */
  9136. #define OP_CreateTable 121 /* synopsis: r[P2]=root iDb=P1 */
  9137. #define OP_ParseSchema 122
  9138. #define OP_LoadAnalysis 123
  9139. #define OP_DropTable 124
  9140. #define OP_DropIndex 125
  9141. #define OP_DropTrigger 126
  9142. #define OP_IntegrityCk 127
  9143. #define OP_RowSetAdd 128 /* synopsis: rowset(P1)=r[P2] */
  9144. #define OP_RowSetRead 129 /* synopsis: r[P3]=rowset(P1) */
  9145. #define OP_RowSetTest 130 /* synopsis: if r[P3] in rowset(P1) goto P2 */
  9146. #define OP_Program 131
  9147. #define OP_Param 132
  9148. #define OP_Real 133 /* same as TK_FLOAT, synopsis: r[P2]=P4 */
  9149. #define OP_FkCounter 134 /* synopsis: fkctr[P1]+=P2 */
  9150. #define OP_FkIfZero 135 /* synopsis: if fkctr[P1]==0 goto P2 */
  9151. #define OP_MemMax 136 /* synopsis: r[P1]=max(r[P1],r[P2]) */
  9152. #define OP_IfPos 137 /* synopsis: if r[P1]>0 goto P2 */
  9153. #define OP_IfNeg 138 /* synopsis: r[P1]+=P3, if r[P1]<0 goto P2 */
  9154. #define OP_IfZero 139 /* synopsis: r[P1]+=P3, if r[P1]==0 goto P2 */
  9155. #define OP_AggFinal 140 /* synopsis: accum=r[P1] N=P2 */
  9156. #define OP_IncrVacuum 141
  9157. #define OP_Expire 142
  9158. #define OP_TableLock 143 /* synopsis: iDb=P1 root=P2 write=P3 */
  9159. #define OP_VBegin 144
  9160. #define OP_VCreate 145
  9161. #define OP_VDestroy 146
  9162. #define OP_VOpen 147
  9163. #define OP_VColumn 148 /* synopsis: r[P3]=vcolumn(P2) */
  9164. #define OP_VNext 149
  9165. #define OP_VRename 150
  9166. #define OP_Pagecount 151
  9167. #define OP_MaxPgcnt 152
  9168. #define OP_Init 153 /* synopsis: Start at P2 */
  9169. #define OP_Noop 154
  9170. #define OP_Explain 155
  9171. /* Properties such as "out2" or "jump" that are specified in
  9172. ** comments following the "case" for each opcode in the vdbe.c
  9173. ** are encoded into bitvectors as follows:
  9174. */
  9175. #define OPFLG_JUMP 0x0001 /* jump: P2 holds jmp target */
  9176. #define OPFLG_OUT2_PRERELEASE 0x0002 /* out2-prerelease: */
  9177. #define OPFLG_IN1 0x0004 /* in1: P1 is an input */
  9178. #define OPFLG_IN2 0x0008 /* in2: P2 is an input */
  9179. #define OPFLG_IN3 0x0010 /* in3: P3 is an input */
  9180. #define OPFLG_OUT2 0x0020 /* out2: P2 is an output */
  9181. #define OPFLG_OUT3 0x0040 /* out3: P3 is an output */
  9182. #define OPFLG_INITIALIZER {\
  9183. /* 0 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x01, 0x01,\
  9184. /* 8 */ 0x01, 0x01, 0x00, 0x00, 0x02, 0x00, 0x01, 0x00,\
  9185. /* 16 */ 0x01, 0x01, 0x04, 0x24, 0x01, 0x04, 0x05, 0x10,\
  9186. /* 24 */ 0x00, 0x02, 0x02, 0x02, 0x02, 0x00, 0x02, 0x02,\
  9187. /* 32 */ 0x00, 0x00, 0x20, 0x00, 0x00, 0x04, 0x05, 0x04,\
  9188. /* 40 */ 0x04, 0x00, 0x00, 0x01, 0x01, 0x05, 0x05, 0x00,\
  9189. /* 48 */ 0x00, 0x00, 0x02, 0x02, 0x10, 0x00, 0x00, 0x00,\
  9190. /* 56 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x11,\
  9191. /* 64 */ 0x11, 0x11, 0x08, 0x11, 0x11, 0x11, 0x11, 0x4c,\
  9192. /* 72 */ 0x4c, 0x02, 0x02, 0x00, 0x05, 0x05, 0x15, 0x15,\
  9193. /* 80 */ 0x15, 0x15, 0x15, 0x15, 0x00, 0x4c, 0x4c, 0x4c,\
  9194. /* 88 */ 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x4c, 0x00,\
  9195. /* 96 */ 0x24, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02,\
  9196. /* 104 */ 0x00, 0x01, 0x01, 0x01, 0x01, 0x08, 0x08, 0x00,\
  9197. /* 112 */ 0x02, 0x01, 0x01, 0x01, 0x01, 0x02, 0x00, 0x00,\
  9198. /* 120 */ 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\
  9199. /* 128 */ 0x0c, 0x45, 0x15, 0x01, 0x02, 0x02, 0x00, 0x01,\
  9200. /* 136 */ 0x08, 0x05, 0x05, 0x05, 0x00, 0x01, 0x00, 0x00,\
  9201. /* 144 */ 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02,\
  9202. /* 152 */ 0x02, 0x01, 0x00, 0x00,}
  9203. /************** End of opcodes.h *********************************************/
  9204. /************** Continuing where we left off in vdbe.h ***********************/
  9205. /*
  9206. ** Prototypes for the VDBE interface. See comments on the implementation
  9207. ** for a description of what each of these routines does.
  9208. */
  9209. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse*);
  9210. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe*,int);
  9211. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe*,int,int);
  9212. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe*,int,int,int);
  9213. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe*,int,int,int,int);
  9214. SQLITE_PRIVATE int sqlite3VdbeAddOp4(Vdbe*,int,int,int,int,const char *zP4,int);
  9215. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(Vdbe*,int,int,int,int,int);
  9216. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe*, int nOp, VdbeOpList const *aOp, int iLineno);
  9217. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe*,int,char*);
  9218. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe*, u32 addr, int P1);
  9219. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe*, u32 addr, int P2);
  9220. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe*, u32 addr, int P3);
  9221. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe*, u8 P5);
  9222. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe*, int addr);
  9223. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe*, int addr);
  9224. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe*, u8 op);
  9225. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe*, int addr, const char *zP4, int N);
  9226. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse*, Index*);
  9227. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe*, int);
  9228. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe*, int);
  9229. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe*);
  9230. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe*);
  9231. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe*);
  9232. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3*,Vdbe*);
  9233. SQLITE_PRIVATE void sqlite3VdbeMakeReady(Vdbe*,Parse*);
  9234. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe*);
  9235. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe*, int);
  9236. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe*);
  9237. #ifdef SQLITE_DEBUG
  9238. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *, int);
  9239. #endif
  9240. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe*);
  9241. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe*);
  9242. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe*);
  9243. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe*,int);
  9244. SQLITE_PRIVATE int sqlite3VdbeSetColName(Vdbe*, int, int, const char *, void(*)(void*));
  9245. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe*);
  9246. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe*);
  9247. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe*, const char *z, int n, int);
  9248. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe*,Vdbe*);
  9249. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe*, int*, int*);
  9250. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe*, int, u8);
  9251. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe*, int);
  9252. #ifndef SQLITE_OMIT_TRACE
  9253. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(Vdbe*, const char*);
  9254. #endif
  9255. SQLITE_PRIVATE int sqlite3MemCompare(const Mem*, const Mem*, const CollSeq*);
  9256. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(KeyInfo*,int,const void*,UnpackedRecord*);
  9257. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(int,const void*,UnpackedRecord*);
  9258. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(KeyInfo *, char *, int, char **);
  9259. typedef int (*RecordCompare)(int,const void*,UnpackedRecord*);
  9260. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord*);
  9261. #ifndef SQLITE_OMIT_TRIGGER
  9262. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *, SubProgram *);
  9263. #endif
  9264. /* Use SQLITE_ENABLE_COMMENTS to enable generation of extra comments on
  9265. ** each VDBE opcode.
  9266. **
  9267. ** Use the SQLITE_ENABLE_MODULE_COMMENTS macro to see some extra no-op
  9268. ** comments in VDBE programs that show key decision points in the code
  9269. ** generator.
  9270. */
  9271. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  9272. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe*, const char*, ...);
  9273. # define VdbeComment(X) sqlite3VdbeComment X
  9274. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe*, const char*, ...);
  9275. # define VdbeNoopComment(X) sqlite3VdbeNoopComment X
  9276. # ifdef SQLITE_ENABLE_MODULE_COMMENTS
  9277. # define VdbeModuleComment(X) sqlite3VdbeNoopComment X
  9278. # else
  9279. # define VdbeModuleComment(X)
  9280. # endif
  9281. #else
  9282. # define VdbeComment(X)
  9283. # define VdbeNoopComment(X)
  9284. # define VdbeModuleComment(X)
  9285. #endif
  9286. /*
  9287. ** The VdbeCoverage macros are used to set a coverage testing point
  9288. ** for VDBE branch instructions. The coverage testing points are line
  9289. ** numbers in the sqlite3.c source file. VDBE branch coverage testing
  9290. ** only works with an amalagmation build. That's ok since a VDBE branch
  9291. ** coverage build designed for testing the test suite only. No application
  9292. ** should ever ship with VDBE branch coverage measuring turned on.
  9293. **
  9294. ** VdbeCoverage(v) // Mark the previously coded instruction
  9295. ** // as a branch
  9296. **
  9297. ** VdbeCoverageIf(v, conditional) // Mark previous if conditional true
  9298. **
  9299. ** VdbeCoverageAlwaysTaken(v) // Previous branch is always taken
  9300. **
  9301. ** VdbeCoverageNeverTaken(v) // Previous branch is never taken
  9302. **
  9303. ** Every VDBE branch operation must be tagged with one of the macros above.
  9304. ** If not, then when "make test" is run with -DSQLITE_VDBE_COVERAGE and
  9305. ** -DSQLITE_DEBUG then an ALWAYS() will fail in the vdbeTakeBranch()
  9306. ** routine in vdbe.c, alerting the developer to the missed tag.
  9307. */
  9308. #ifdef SQLITE_VDBE_COVERAGE
  9309. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe*,int);
  9310. # define VdbeCoverage(v) sqlite3VdbeSetLineNumber(v,__LINE__)
  9311. # define VdbeCoverageIf(v,x) if(x)sqlite3VdbeSetLineNumber(v,__LINE__)
  9312. # define VdbeCoverageAlwaysTaken(v) sqlite3VdbeSetLineNumber(v,2);
  9313. # define VdbeCoverageNeverTaken(v) sqlite3VdbeSetLineNumber(v,1);
  9314. # define VDBE_OFFSET_LINENO(x) (__LINE__+x)
  9315. #else
  9316. # define VdbeCoverage(v)
  9317. # define VdbeCoverageIf(v,x)
  9318. # define VdbeCoverageAlwaysTaken(v)
  9319. # define VdbeCoverageNeverTaken(v)
  9320. # define VDBE_OFFSET_LINENO(x) 0
  9321. #endif
  9322. #endif
  9323. /************** End of vdbe.h ************************************************/
  9324. /************** Continuing where we left off in sqliteInt.h ******************/
  9325. /************** Include pager.h in the middle of sqliteInt.h *****************/
  9326. /************** Begin file pager.h *******************************************/
  9327. /*
  9328. ** 2001 September 15
  9329. **
  9330. ** The author disclaims copyright to this source code. In place of
  9331. ** a legal notice, here is a blessing:
  9332. **
  9333. ** May you do good and not evil.
  9334. ** May you find forgiveness for yourself and forgive others.
  9335. ** May you share freely, never taking more than you give.
  9336. **
  9337. *************************************************************************
  9338. ** This header file defines the interface that the sqlite page cache
  9339. ** subsystem. The page cache subsystem reads and writes a file a page
  9340. ** at a time and provides a journal for rollback.
  9341. */
  9342. #ifndef _PAGER_H_
  9343. #define _PAGER_H_
  9344. /*
  9345. ** Default maximum size for persistent journal files. A negative
  9346. ** value means no limit. This value may be overridden using the
  9347. ** sqlite3PagerJournalSizeLimit() API. See also "PRAGMA journal_size_limit".
  9348. */
  9349. #ifndef SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT
  9350. #define SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT -1
  9351. #endif
  9352. /*
  9353. ** The type used to represent a page number. The first page in a file
  9354. ** is called page 1. 0 is used to represent "not a page".
  9355. */
  9356. typedef u32 Pgno;
  9357. /*
  9358. ** Each open file is managed by a separate instance of the "Pager" structure.
  9359. */
  9360. typedef struct Pager Pager;
  9361. /*
  9362. ** Handle type for pages.
  9363. */
  9364. typedef struct PgHdr DbPage;
  9365. /*
  9366. ** Page number PAGER_MJ_PGNO is never used in an SQLite database (it is
  9367. ** reserved for working around a windows/posix incompatibility). It is
  9368. ** used in the journal to signify that the remainder of the journal file
  9369. ** is devoted to storing a master journal name - there are no more pages to
  9370. ** roll back. See comments for function writeMasterJournal() in pager.c
  9371. ** for details.
  9372. */
  9373. #define PAGER_MJ_PGNO(x) ((Pgno)((PENDING_BYTE/((x)->pageSize))+1))
  9374. /*
  9375. ** Allowed values for the flags parameter to sqlite3PagerOpen().
  9376. **
  9377. ** NOTE: These values must match the corresponding BTREE_ values in btree.h.
  9378. */
  9379. #define PAGER_OMIT_JOURNAL 0x0001 /* Do not use a rollback journal */
  9380. #define PAGER_MEMORY 0x0002 /* In-memory database */
  9381. /*
  9382. ** Valid values for the second argument to sqlite3PagerLockingMode().
  9383. */
  9384. #define PAGER_LOCKINGMODE_QUERY -1
  9385. #define PAGER_LOCKINGMODE_NORMAL 0
  9386. #define PAGER_LOCKINGMODE_EXCLUSIVE 1
  9387. /*
  9388. ** Numeric constants that encode the journalmode.
  9389. */
  9390. #define PAGER_JOURNALMODE_QUERY (-1) /* Query the value of journalmode */
  9391. #define PAGER_JOURNALMODE_DELETE 0 /* Commit by deleting journal file */
  9392. #define PAGER_JOURNALMODE_PERSIST 1 /* Commit by zeroing journal header */
  9393. #define PAGER_JOURNALMODE_OFF 2 /* Journal omitted. */
  9394. #define PAGER_JOURNALMODE_TRUNCATE 3 /* Commit by truncating journal */
  9395. #define PAGER_JOURNALMODE_MEMORY 4 /* In-memory journal file */
  9396. #define PAGER_JOURNALMODE_WAL 5 /* Use write-ahead logging */
  9397. /*
  9398. ** Flags that make up the mask passed to sqlite3PagerAcquire().
  9399. */
  9400. #define PAGER_GET_NOCONTENT 0x01 /* Do not load data from disk */
  9401. #define PAGER_GET_READONLY 0x02 /* Read-only page is acceptable */
  9402. /*
  9403. ** Flags for sqlite3PagerSetFlags()
  9404. */
  9405. #define PAGER_SYNCHRONOUS_OFF 0x01 /* PRAGMA synchronous=OFF */
  9406. #define PAGER_SYNCHRONOUS_NORMAL 0x02 /* PRAGMA synchronous=NORMAL */
  9407. #define PAGER_SYNCHRONOUS_FULL 0x03 /* PRAGMA synchronous=FULL */
  9408. #define PAGER_SYNCHRONOUS_MASK 0x03 /* Mask for three values above */
  9409. #define PAGER_FULLFSYNC 0x04 /* PRAGMA fullfsync=ON */
  9410. #define PAGER_CKPT_FULLFSYNC 0x08 /* PRAGMA checkpoint_fullfsync=ON */
  9411. #define PAGER_CACHESPILL 0x10 /* PRAGMA cache_spill=ON */
  9412. #define PAGER_FLAGS_MASK 0x1c /* All above except SYNCHRONOUS */
  9413. /*
  9414. ** The remainder of this file contains the declarations of the functions
  9415. ** that make up the Pager sub-system API. See source code comments for
  9416. ** a detailed description of each routine.
  9417. */
  9418. /* Open and close a Pager connection. */
  9419. SQLITE_PRIVATE int sqlite3PagerOpen(
  9420. sqlite3_vfs*,
  9421. Pager **ppPager,
  9422. const char*,
  9423. int,
  9424. int,
  9425. int,
  9426. void(*)(DbPage*)
  9427. );
  9428. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager);
  9429. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager*, int, unsigned char*);
  9430. /* Functions used to configure a Pager object. */
  9431. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(Pager*, int(*)(void *), void *);
  9432. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager*, u32*, int);
  9433. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager*, int);
  9434. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager*, int);
  9435. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *, sqlite3_int64);
  9436. SQLITE_PRIVATE void sqlite3PagerShrink(Pager*);
  9437. SQLITE_PRIVATE void sqlite3PagerSetFlags(Pager*,unsigned);
  9438. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *, int);
  9439. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *, int);
  9440. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager*);
  9441. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager*);
  9442. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *, i64);
  9443. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager*);
  9444. /* Functions used to obtain and release page references. */
  9445. SQLITE_PRIVATE int sqlite3PagerAcquire(Pager *pPager, Pgno pgno, DbPage **ppPage, int clrFlag);
  9446. #define sqlite3PagerGet(A,B,C) sqlite3PagerAcquire(A,B,C,0)
  9447. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno);
  9448. SQLITE_PRIVATE void sqlite3PagerRef(DbPage*);
  9449. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage*);
  9450. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage*);
  9451. /* Operations on page references. */
  9452. SQLITE_PRIVATE int sqlite3PagerWrite(DbPage*);
  9453. SQLITE_PRIVATE void sqlite3PagerDontWrite(DbPage*);
  9454. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager*,DbPage*,Pgno,int);
  9455. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage*);
  9456. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *);
  9457. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *);
  9458. /* Functions used to manage pager transactions and savepoints. */
  9459. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager*, int*);
  9460. SQLITE_PRIVATE int sqlite3PagerBegin(Pager*, int exFlag, int);
  9461. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(Pager*,const char *zMaster, int);
  9462. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager*);
  9463. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster);
  9464. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager*);
  9465. SQLITE_PRIVATE int sqlite3PagerRollback(Pager*);
  9466. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int n);
  9467. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint);
  9468. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager);
  9469. #ifndef SQLITE_OMIT_WAL
  9470. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int, int*, int*);
  9471. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager);
  9472. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager);
  9473. SQLITE_PRIVATE int sqlite3PagerOpenWal(Pager *pPager, int *pisOpen);
  9474. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager);
  9475. #endif
  9476. #ifdef SQLITE_ENABLE_ZIPVFS
  9477. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager);
  9478. #endif
  9479. /* Functions used to query pager state and configuration. */
  9480. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager*);
  9481. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager*);
  9482. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager*);
  9483. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager*, int);
  9484. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager*);
  9485. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager*);
  9486. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager*);
  9487. SQLITE_PRIVATE int sqlite3PagerNosync(Pager*);
  9488. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager*);
  9489. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager*);
  9490. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *, int, int, int *);
  9491. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *);
  9492. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *);
  9493. /* Functions used to truncate the database file. */
  9494. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager*,Pgno);
  9495. #if defined(SQLITE_HAS_CODEC) && !defined(SQLITE_OMIT_WAL)
  9496. SQLITE_PRIVATE void *sqlite3PagerCodec(DbPage *);
  9497. #endif
  9498. /* Functions to support testing and debugging. */
  9499. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  9500. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage*);
  9501. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage*);
  9502. #endif
  9503. #ifdef SQLITE_TEST
  9504. SQLITE_PRIVATE int *sqlite3PagerStats(Pager*);
  9505. SQLITE_PRIVATE void sqlite3PagerRefdump(Pager*);
  9506. void disable_simulated_io_errors(void);
  9507. void enable_simulated_io_errors(void);
  9508. #else
  9509. # define disable_simulated_io_errors()
  9510. # define enable_simulated_io_errors()
  9511. #endif
  9512. #endif /* _PAGER_H_ */
  9513. /************** End of pager.h ***********************************************/
  9514. /************** Continuing where we left off in sqliteInt.h ******************/
  9515. /************** Include pcache.h in the middle of sqliteInt.h ****************/
  9516. /************** Begin file pcache.h ******************************************/
  9517. /*
  9518. ** 2008 August 05
  9519. **
  9520. ** The author disclaims copyright to this source code. In place of
  9521. ** a legal notice, here is a blessing:
  9522. **
  9523. ** May you do good and not evil.
  9524. ** May you find forgiveness for yourself and forgive others.
  9525. ** May you share freely, never taking more than you give.
  9526. **
  9527. *************************************************************************
  9528. ** This header file defines the interface that the sqlite page cache
  9529. ** subsystem.
  9530. */
  9531. #ifndef _PCACHE_H_
  9532. typedef struct PgHdr PgHdr;
  9533. typedef struct PCache PCache;
  9534. /*
  9535. ** Every page in the cache is controlled by an instance of the following
  9536. ** structure.
  9537. */
  9538. struct PgHdr {
  9539. sqlite3_pcache_page *pPage; /* Pcache object page handle */
  9540. void *pData; /* Page data */
  9541. void *pExtra; /* Extra content */
  9542. PgHdr *pDirty; /* Transient list of dirty pages */
  9543. Pager *pPager; /* The pager this page is part of */
  9544. Pgno pgno; /* Page number for this page */
  9545. #ifdef SQLITE_CHECK_PAGES
  9546. u32 pageHash; /* Hash of page content */
  9547. #endif
  9548. u16 flags; /* PGHDR flags defined below */
  9549. /**********************************************************************
  9550. ** Elements above are public. All that follows is private to pcache.c
  9551. ** and should not be accessed by other modules.
  9552. */
  9553. i16 nRef; /* Number of users of this page */
  9554. PCache *pCache; /* Cache that owns this page */
  9555. PgHdr *pDirtyNext; /* Next element in list of dirty pages */
  9556. PgHdr *pDirtyPrev; /* Previous element in list of dirty pages */
  9557. };
  9558. /* Bit values for PgHdr.flags */
  9559. #define PGHDR_DIRTY 0x002 /* Page has changed */
  9560. #define PGHDR_NEED_SYNC 0x004 /* Fsync the rollback journal before
  9561. ** writing this page to the database */
  9562. #define PGHDR_NEED_READ 0x008 /* Content is unread */
  9563. #define PGHDR_REUSE_UNLIKELY 0x010 /* A hint that reuse is unlikely */
  9564. #define PGHDR_DONT_WRITE 0x020 /* Do not write content to disk */
  9565. #define PGHDR_MMAP 0x040 /* This is an mmap page object */
  9566. /* Initialize and shutdown the page cache subsystem */
  9567. SQLITE_PRIVATE int sqlite3PcacheInitialize(void);
  9568. SQLITE_PRIVATE void sqlite3PcacheShutdown(void);
  9569. /* Page cache buffer management:
  9570. ** These routines implement SQLITE_CONFIG_PAGECACHE.
  9571. */
  9572. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *, int sz, int n);
  9573. /* Create a new pager cache.
  9574. ** Under memory stress, invoke xStress to try to make pages clean.
  9575. ** Only clean and unpinned pages can be reclaimed.
  9576. */
  9577. SQLITE_PRIVATE int sqlite3PcacheOpen(
  9578. int szPage, /* Size of every page */
  9579. int szExtra, /* Extra space associated with each page */
  9580. int bPurgeable, /* True if pages are on backing store */
  9581. int (*xStress)(void*, PgHdr*), /* Call to try to make pages clean */
  9582. void *pStress, /* Argument to xStress */
  9583. PCache *pToInit /* Preallocated space for the PCache */
  9584. );
  9585. /* Modify the page-size after the cache has been created. */
  9586. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *, int);
  9587. /* Return the size in bytes of a PCache object. Used to preallocate
  9588. ** storage space.
  9589. */
  9590. SQLITE_PRIVATE int sqlite3PcacheSize(void);
  9591. /* One release per successful fetch. Page is pinned until released.
  9592. ** Reference counted.
  9593. */
  9594. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(PCache*, Pgno, int createFlag);
  9595. SQLITE_PRIVATE int sqlite3PcacheFetchStress(PCache*, Pgno, sqlite3_pcache_page**);
  9596. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(PCache*, Pgno, sqlite3_pcache_page *pPage);
  9597. SQLITE_PRIVATE void sqlite3PcacheRelease(PgHdr*);
  9598. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr*); /* Remove page from cache */
  9599. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr*); /* Make sure page is marked dirty */
  9600. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr*); /* Mark a single page as clean */
  9601. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache*); /* Mark all dirty list pages as clean */
  9602. /* Change a page number. Used by incr-vacuum. */
  9603. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr*, Pgno);
  9604. /* Remove all pages with pgno>x. Reset the cache if x==0 */
  9605. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache*, Pgno x);
  9606. /* Get a list of all dirty pages in the cache, sorted by page number */
  9607. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache*);
  9608. /* Reset and close the cache object */
  9609. SQLITE_PRIVATE void sqlite3PcacheClose(PCache*);
  9610. /* Clear flags from pages of the page cache */
  9611. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *);
  9612. /* Discard the contents of the cache */
  9613. SQLITE_PRIVATE void sqlite3PcacheClear(PCache*);
  9614. /* Return the total number of outstanding page references */
  9615. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache*);
  9616. /* Increment the reference count of an existing page */
  9617. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr*);
  9618. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr*);
  9619. /* Return the total number of pages stored in the cache */
  9620. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache*);
  9621. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  9622. /* Iterate through all dirty pages currently stored in the cache. This
  9623. ** interface is only available if SQLITE_CHECK_PAGES is defined when the
  9624. ** library is built.
  9625. */
  9626. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *));
  9627. #endif
  9628. /* Set and get the suggested cache-size for the specified pager-cache.
  9629. **
  9630. ** If no global maximum is configured, then the system attempts to limit
  9631. ** the total number of pages cached by purgeable pager-caches to the sum
  9632. ** of the suggested cache-sizes.
  9633. */
  9634. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *, int);
  9635. #ifdef SQLITE_TEST
  9636. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *);
  9637. #endif
  9638. /* Free up as much memory as possible from the page cache */
  9639. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache*);
  9640. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  9641. /* Try to return memory used by the pcache module to the main memory heap */
  9642. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int);
  9643. #endif
  9644. #ifdef SQLITE_TEST
  9645. SQLITE_PRIVATE void sqlite3PcacheStats(int*,int*,int*,int*);
  9646. #endif
  9647. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void);
  9648. #endif /* _PCACHE_H_ */
  9649. /************** End of pcache.h **********************************************/
  9650. /************** Continuing where we left off in sqliteInt.h ******************/
  9651. /************** Include os.h in the middle of sqliteInt.h ********************/
  9652. /************** Begin file os.h **********************************************/
  9653. /*
  9654. ** 2001 September 16
  9655. **
  9656. ** The author disclaims copyright to this source code. In place of
  9657. ** a legal notice, here is a blessing:
  9658. **
  9659. ** May you do good and not evil.
  9660. ** May you find forgiveness for yourself and forgive others.
  9661. ** May you share freely, never taking more than you give.
  9662. **
  9663. ******************************************************************************
  9664. **
  9665. ** This header file (together with is companion C source-code file
  9666. ** "os.c") attempt to abstract the underlying operating system so that
  9667. ** the SQLite library will work on both POSIX and windows systems.
  9668. **
  9669. ** This header file is #include-ed by sqliteInt.h and thus ends up
  9670. ** being included by every source file.
  9671. */
  9672. #ifndef _SQLITE_OS_H_
  9673. #define _SQLITE_OS_H_
  9674. /*
  9675. ** Attempt to automatically detect the operating system and setup the
  9676. ** necessary pre-processor macros for it.
  9677. */
  9678. /************** Include os_setup.h in the middle of os.h *********************/
  9679. /************** Begin file os_setup.h ****************************************/
  9680. /*
  9681. ** 2013 November 25
  9682. **
  9683. ** The author disclaims copyright to this source code. In place of
  9684. ** a legal notice, here is a blessing:
  9685. **
  9686. ** May you do good and not evil.
  9687. ** May you find forgiveness for yourself and forgive others.
  9688. ** May you share freely, never taking more than you give.
  9689. **
  9690. ******************************************************************************
  9691. **
  9692. ** This file contains pre-processor directives related to operating system
  9693. ** detection and/or setup.
  9694. */
  9695. #ifndef _OS_SETUP_H_
  9696. #define _OS_SETUP_H_
  9697. /*
  9698. ** Figure out if we are dealing with Unix, Windows, or some other operating
  9699. ** system.
  9700. **
  9701. ** After the following block of preprocess macros, all of SQLITE_OS_UNIX,
  9702. ** SQLITE_OS_WIN, and SQLITE_OS_OTHER will defined to either 1 or 0. One of
  9703. ** the three will be 1. The other two will be 0.
  9704. */
  9705. #if defined(SQLITE_OS_OTHER)
  9706. # if SQLITE_OS_OTHER==1
  9707. # undef SQLITE_OS_UNIX
  9708. # define SQLITE_OS_UNIX 0
  9709. # undef SQLITE_OS_WIN
  9710. # define SQLITE_OS_WIN 0
  9711. # else
  9712. # undef SQLITE_OS_OTHER
  9713. # endif
  9714. #endif
  9715. #if !defined(SQLITE_OS_UNIX) && !defined(SQLITE_OS_OTHER)
  9716. # define SQLITE_OS_OTHER 0
  9717. # ifndef SQLITE_OS_WIN
  9718. # if defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || \
  9719. defined(__MINGW32__) || defined(__BORLANDC__)
  9720. # define SQLITE_OS_WIN 1
  9721. # define SQLITE_OS_UNIX 0
  9722. # else
  9723. # define SQLITE_OS_WIN 0
  9724. # define SQLITE_OS_UNIX 1
  9725. # endif
  9726. # else
  9727. # define SQLITE_OS_UNIX 0
  9728. # endif
  9729. #else
  9730. # ifndef SQLITE_OS_WIN
  9731. # define SQLITE_OS_WIN 0
  9732. # endif
  9733. #endif
  9734. #endif /* _OS_SETUP_H_ */
  9735. /************** End of os_setup.h ********************************************/
  9736. /************** Continuing where we left off in os.h *************************/
  9737. /* If the SET_FULLSYNC macro is not defined above, then make it
  9738. ** a no-op
  9739. */
  9740. #ifndef SET_FULLSYNC
  9741. # define SET_FULLSYNC(x,y)
  9742. #endif
  9743. /*
  9744. ** The default size of a disk sector
  9745. */
  9746. #ifndef SQLITE_DEFAULT_SECTOR_SIZE
  9747. # define SQLITE_DEFAULT_SECTOR_SIZE 4096
  9748. #endif
  9749. /*
  9750. ** Temporary files are named starting with this prefix followed by 16 random
  9751. ** alphanumeric characters, and no file extension. They are stored in the
  9752. ** OS's standard temporary file directory, and are deleted prior to exit.
  9753. ** If sqlite is being embedded in another program, you may wish to change the
  9754. ** prefix to reflect your program's name, so that if your program exits
  9755. ** prematurely, old temporary files can be easily identified. This can be done
  9756. ** using -DSQLITE_TEMP_FILE_PREFIX=myprefix_ on the compiler command line.
  9757. **
  9758. ** 2006-10-31: The default prefix used to be "sqlite_". But then
  9759. ** Mcafee started using SQLite in their anti-virus product and it
  9760. ** started putting files with the "sqlite" name in the c:/temp folder.
  9761. ** This annoyed many windows users. Those users would then do a
  9762. ** Google search for "sqlite", find the telephone numbers of the
  9763. ** developers and call to wake them up at night and complain.
  9764. ** For this reason, the default name prefix is changed to be "sqlite"
  9765. ** spelled backwards. So the temp files are still identified, but
  9766. ** anybody smart enough to figure out the code is also likely smart
  9767. ** enough to know that calling the developer will not help get rid
  9768. ** of the file.
  9769. */
  9770. #ifndef SQLITE_TEMP_FILE_PREFIX
  9771. # define SQLITE_TEMP_FILE_PREFIX "etilqs_"
  9772. #endif
  9773. /*
  9774. ** The following values may be passed as the second argument to
  9775. ** sqlite3OsLock(). The various locks exhibit the following semantics:
  9776. **
  9777. ** SHARED: Any number of processes may hold a SHARED lock simultaneously.
  9778. ** RESERVED: A single process may hold a RESERVED lock on a file at
  9779. ** any time. Other processes may hold and obtain new SHARED locks.
  9780. ** PENDING: A single process may hold a PENDING lock on a file at
  9781. ** any one time. Existing SHARED locks may persist, but no new
  9782. ** SHARED locks may be obtained by other processes.
  9783. ** EXCLUSIVE: An EXCLUSIVE lock precludes all other locks.
  9784. **
  9785. ** PENDING_LOCK may not be passed directly to sqlite3OsLock(). Instead, a
  9786. ** process that requests an EXCLUSIVE lock may actually obtain a PENDING
  9787. ** lock. This can be upgraded to an EXCLUSIVE lock by a subsequent call to
  9788. ** sqlite3OsLock().
  9789. */
  9790. #define NO_LOCK 0
  9791. #define SHARED_LOCK 1
  9792. #define RESERVED_LOCK 2
  9793. #define PENDING_LOCK 3
  9794. #define EXCLUSIVE_LOCK 4
  9795. /*
  9796. ** File Locking Notes: (Mostly about windows but also some info for Unix)
  9797. **
  9798. ** We cannot use LockFileEx() or UnlockFileEx() on Win95/98/ME because
  9799. ** those functions are not available. So we use only LockFile() and
  9800. ** UnlockFile().
  9801. **
  9802. ** LockFile() prevents not just writing but also reading by other processes.
  9803. ** A SHARED_LOCK is obtained by locking a single randomly-chosen
  9804. ** byte out of a specific range of bytes. The lock byte is obtained at
  9805. ** random so two separate readers can probably access the file at the
  9806. ** same time, unless they are unlucky and choose the same lock byte.
  9807. ** An EXCLUSIVE_LOCK is obtained by locking all bytes in the range.
  9808. ** There can only be one writer. A RESERVED_LOCK is obtained by locking
  9809. ** a single byte of the file that is designated as the reserved lock byte.
  9810. ** A PENDING_LOCK is obtained by locking a designated byte different from
  9811. ** the RESERVED_LOCK byte.
  9812. **
  9813. ** On WinNT/2K/XP systems, LockFileEx() and UnlockFileEx() are available,
  9814. ** which means we can use reader/writer locks. When reader/writer locks
  9815. ** are used, the lock is placed on the same range of bytes that is used
  9816. ** for probabilistic locking in Win95/98/ME. Hence, the locking scheme
  9817. ** will support two or more Win95 readers or two or more WinNT readers.
  9818. ** But a single Win95 reader will lock out all WinNT readers and a single
  9819. ** WinNT reader will lock out all other Win95 readers.
  9820. **
  9821. ** The following #defines specify the range of bytes used for locking.
  9822. ** SHARED_SIZE is the number of bytes available in the pool from which
  9823. ** a random byte is selected for a shared lock. The pool of bytes for
  9824. ** shared locks begins at SHARED_FIRST.
  9825. **
  9826. ** The same locking strategy and
  9827. ** byte ranges are used for Unix. This leaves open the possibility of having
  9828. ** clients on win95, winNT, and unix all talking to the same shared file
  9829. ** and all locking correctly. To do so would require that samba (or whatever
  9830. ** tool is being used for file sharing) implements locks correctly between
  9831. ** windows and unix. I'm guessing that isn't likely to happen, but by
  9832. ** using the same locking range we are at least open to the possibility.
  9833. **
  9834. ** Locking in windows is manditory. For this reason, we cannot store
  9835. ** actual data in the bytes used for locking. The pager never allocates
  9836. ** the pages involved in locking therefore. SHARED_SIZE is selected so
  9837. ** that all locks will fit on a single page even at the minimum page size.
  9838. ** PENDING_BYTE defines the beginning of the locks. By default PENDING_BYTE
  9839. ** is set high so that we don't have to allocate an unused page except
  9840. ** for very large databases. But one should test the page skipping logic
  9841. ** by setting PENDING_BYTE low and running the entire regression suite.
  9842. **
  9843. ** Changing the value of PENDING_BYTE results in a subtly incompatible
  9844. ** file format. Depending on how it is changed, you might not notice
  9845. ** the incompatibility right away, even running a full regression test.
  9846. ** The default location of PENDING_BYTE is the first byte past the
  9847. ** 1GB boundary.
  9848. **
  9849. */
  9850. #ifdef SQLITE_OMIT_WSD
  9851. # define PENDING_BYTE (0x40000000)
  9852. #else
  9853. # define PENDING_BYTE sqlite3PendingByte
  9854. #endif
  9855. #define RESERVED_BYTE (PENDING_BYTE+1)
  9856. #define SHARED_FIRST (PENDING_BYTE+2)
  9857. #define SHARED_SIZE 510
  9858. /*
  9859. ** Wrapper around OS specific sqlite3_os_init() function.
  9860. */
  9861. SQLITE_PRIVATE int sqlite3OsInit(void);
  9862. /*
  9863. ** Functions for accessing sqlite3_file methods
  9864. */
  9865. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file*);
  9866. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file*, void*, int amt, i64 offset);
  9867. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file*, const void*, int amt, i64 offset);
  9868. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file*, i64 size);
  9869. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file*, int);
  9870. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file*, i64 *pSize);
  9871. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file*, int);
  9872. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file*, int);
  9873. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut);
  9874. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file*,int,void*);
  9875. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file*,int,void*);
  9876. #define SQLITE_FCNTL_DB_UNCHANGED 0xca093fa0
  9877. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id);
  9878. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id);
  9879. SQLITE_PRIVATE int sqlite3OsShmMap(sqlite3_file *,int,int,int,void volatile **);
  9880. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int, int, int);
  9881. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id);
  9882. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int);
  9883. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64, int, void **);
  9884. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *, i64, void *);
  9885. /*
  9886. ** Functions for accessing sqlite3_vfs methods
  9887. */
  9888. SQLITE_PRIVATE int sqlite3OsOpen(sqlite3_vfs *, const char *, sqlite3_file*, int, int *);
  9889. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *, const char *, int);
  9890. SQLITE_PRIVATE int sqlite3OsAccess(sqlite3_vfs *, const char *, int, int *pResOut);
  9891. SQLITE_PRIVATE int sqlite3OsFullPathname(sqlite3_vfs *, const char *, int, char *);
  9892. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  9893. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *, const char *);
  9894. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *, int, char *);
  9895. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *, void *, const char *))(void);
  9896. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *, void *);
  9897. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  9898. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *, int, char *);
  9899. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *, int);
  9900. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *, sqlite3_int64*);
  9901. /*
  9902. ** Convenience functions for opening and closing files using
  9903. ** sqlite3_malloc() to obtain space for the file-handle structure.
  9904. */
  9905. SQLITE_PRIVATE int sqlite3OsOpenMalloc(sqlite3_vfs *, const char *, sqlite3_file **, int,int*);
  9906. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *);
  9907. #endif /* _SQLITE_OS_H_ */
  9908. /************** End of os.h **************************************************/
  9909. /************** Continuing where we left off in sqliteInt.h ******************/
  9910. /************** Include mutex.h in the middle of sqliteInt.h *****************/
  9911. /************** Begin file mutex.h *******************************************/
  9912. /*
  9913. ** 2007 August 28
  9914. **
  9915. ** The author disclaims copyright to this source code. In place of
  9916. ** a legal notice, here is a blessing:
  9917. **
  9918. ** May you do good and not evil.
  9919. ** May you find forgiveness for yourself and forgive others.
  9920. ** May you share freely, never taking more than you give.
  9921. **
  9922. *************************************************************************
  9923. **
  9924. ** This file contains the common header for all mutex implementations.
  9925. ** The sqliteInt.h header #includes this file so that it is available
  9926. ** to all source files. We break it out in an effort to keep the code
  9927. ** better organized.
  9928. **
  9929. ** NOTE: source files should *not* #include this header file directly.
  9930. ** Source files should #include the sqliteInt.h file and let that file
  9931. ** include this one indirectly.
  9932. */
  9933. /*
  9934. ** Figure out what version of the code to use. The choices are
  9935. **
  9936. ** SQLITE_MUTEX_OMIT No mutex logic. Not even stubs. The
  9937. ** mutexes implementation cannot be overridden
  9938. ** at start-time.
  9939. **
  9940. ** SQLITE_MUTEX_NOOP For single-threaded applications. No
  9941. ** mutual exclusion is provided. But this
  9942. ** implementation can be overridden at
  9943. ** start-time.
  9944. **
  9945. ** SQLITE_MUTEX_PTHREADS For multi-threaded applications on Unix.
  9946. **
  9947. ** SQLITE_MUTEX_W32 For multi-threaded applications on Win32.
  9948. */
  9949. #if !SQLITE_THREADSAFE
  9950. # define SQLITE_MUTEX_OMIT
  9951. #endif
  9952. #if SQLITE_THREADSAFE && !defined(SQLITE_MUTEX_NOOP)
  9953. # if SQLITE_OS_UNIX
  9954. # define SQLITE_MUTEX_PTHREADS
  9955. # elif SQLITE_OS_WIN
  9956. # define SQLITE_MUTEX_W32
  9957. # else
  9958. # define SQLITE_MUTEX_NOOP
  9959. # endif
  9960. #endif
  9961. #ifdef SQLITE_MUTEX_OMIT
  9962. /*
  9963. ** If this is a no-op implementation, implement everything as macros.
  9964. */
  9965. #define sqlite3_mutex_alloc(X) ((sqlite3_mutex*)8)
  9966. #define sqlite3_mutex_free(X)
  9967. #define sqlite3_mutex_enter(X)
  9968. #define sqlite3_mutex_try(X) SQLITE_OK
  9969. #define sqlite3_mutex_leave(X)
  9970. #define sqlite3_mutex_held(X) ((void)(X),1)
  9971. #define sqlite3_mutex_notheld(X) ((void)(X),1)
  9972. #define sqlite3MutexAlloc(X) ((sqlite3_mutex*)8)
  9973. #define sqlite3MutexInit() SQLITE_OK
  9974. #define sqlite3MutexEnd()
  9975. #define MUTEX_LOGIC(X)
  9976. #else
  9977. #define MUTEX_LOGIC(X) X
  9978. #endif /* defined(SQLITE_MUTEX_OMIT) */
  9979. /************** End of mutex.h ***********************************************/
  9980. /************** Continuing where we left off in sqliteInt.h ******************/
  9981. /*
  9982. ** Each database file to be accessed by the system is an instance
  9983. ** of the following structure. There are normally two of these structures
  9984. ** in the sqlite.aDb[] array. aDb[0] is the main database file and
  9985. ** aDb[1] is the database file used to hold temporary tables. Additional
  9986. ** databases may be attached.
  9987. */
  9988. struct Db {
  9989. char *zName; /* Name of this database */
  9990. Btree *pBt; /* The B*Tree structure for this database file */
  9991. u8 safety_level; /* How aggressive at syncing data to disk */
  9992. Schema *pSchema; /* Pointer to database schema (possibly shared) */
  9993. };
  9994. /*
  9995. ** An instance of the following structure stores a database schema.
  9996. **
  9997. ** Most Schema objects are associated with a Btree. The exception is
  9998. ** the Schema for the TEMP databaes (sqlite3.aDb[1]) which is free-standing.
  9999. ** In shared cache mode, a single Schema object can be shared by multiple
  10000. ** Btrees that refer to the same underlying BtShared object.
  10001. **
  10002. ** Schema objects are automatically deallocated when the last Btree that
  10003. ** references them is destroyed. The TEMP Schema is manually freed by
  10004. ** sqlite3_close().
  10005. *
  10006. ** A thread must be holding a mutex on the corresponding Btree in order
  10007. ** to access Schema content. This implies that the thread must also be
  10008. ** holding a mutex on the sqlite3 connection pointer that owns the Btree.
  10009. ** For a TEMP Schema, only the connection mutex is required.
  10010. */
  10011. struct Schema {
  10012. int schema_cookie; /* Database schema version number for this file */
  10013. int iGeneration; /* Generation counter. Incremented with each change */
  10014. Hash tblHash; /* All tables indexed by name */
  10015. Hash idxHash; /* All (named) indices indexed by name */
  10016. Hash trigHash; /* All triggers indexed by name */
  10017. Hash fkeyHash; /* All foreign keys by referenced table name */
  10018. Table *pSeqTab; /* The sqlite_sequence table used by AUTOINCREMENT */
  10019. u8 file_format; /* Schema format version for this file */
  10020. u8 enc; /* Text encoding used by this database */
  10021. u16 schemaFlags; /* Flags associated with this schema */
  10022. int cache_size; /* Number of pages to use in the cache */
  10023. };
  10024. /*
  10025. ** These macros can be used to test, set, or clear bits in the
  10026. ** Db.pSchema->flags field.
  10027. */
  10028. #define DbHasProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))==(P))
  10029. #define DbHasAnyProperty(D,I,P) (((D)->aDb[I].pSchema->schemaFlags&(P))!=0)
  10030. #define DbSetProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags|=(P)
  10031. #define DbClearProperty(D,I,P) (D)->aDb[I].pSchema->schemaFlags&=~(P)
  10032. /*
  10033. ** Allowed values for the DB.pSchema->flags field.
  10034. **
  10035. ** The DB_SchemaLoaded flag is set after the database schema has been
  10036. ** read into internal hash tables.
  10037. **
  10038. ** DB_UnresetViews means that one or more views have column names that
  10039. ** have been filled out. If the schema changes, these column names might
  10040. ** changes and so the view will need to be reset.
  10041. */
  10042. #define DB_SchemaLoaded 0x0001 /* The schema has been loaded */
  10043. #define DB_UnresetViews 0x0002 /* Some views have defined column names */
  10044. #define DB_Empty 0x0004 /* The file is empty (length 0 bytes) */
  10045. /*
  10046. ** The number of different kinds of things that can be limited
  10047. ** using the sqlite3_limit() interface.
  10048. */
  10049. #define SQLITE_N_LIMIT (SQLITE_LIMIT_WORKER_THREADS+1)
  10050. /*
  10051. ** Lookaside malloc is a set of fixed-size buffers that can be used
  10052. ** to satisfy small transient memory allocation requests for objects
  10053. ** associated with a particular database connection. The use of
  10054. ** lookaside malloc provides a significant performance enhancement
  10055. ** (approx 10%) by avoiding numerous malloc/free requests while parsing
  10056. ** SQL statements.
  10057. **
  10058. ** The Lookaside structure holds configuration information about the
  10059. ** lookaside malloc subsystem. Each available memory allocation in
  10060. ** the lookaside subsystem is stored on a linked list of LookasideSlot
  10061. ** objects.
  10062. **
  10063. ** Lookaside allocations are only allowed for objects that are associated
  10064. ** with a particular database connection. Hence, schema information cannot
  10065. ** be stored in lookaside because in shared cache mode the schema information
  10066. ** is shared by multiple database connections. Therefore, while parsing
  10067. ** schema information, the Lookaside.bEnabled flag is cleared so that
  10068. ** lookaside allocations are not used to construct the schema objects.
  10069. */
  10070. struct Lookaside {
  10071. u16 sz; /* Size of each buffer in bytes */
  10072. u8 bEnabled; /* False to disable new lookaside allocations */
  10073. u8 bMalloced; /* True if pStart obtained from sqlite3_malloc() */
  10074. int nOut; /* Number of buffers currently checked out */
  10075. int mxOut; /* Highwater mark for nOut */
  10076. int anStat[3]; /* 0: hits. 1: size misses. 2: full misses */
  10077. LookasideSlot *pFree; /* List of available buffers */
  10078. void *pStart; /* First byte of available memory space */
  10079. void *pEnd; /* First byte past end of available space */
  10080. };
  10081. struct LookasideSlot {
  10082. LookasideSlot *pNext; /* Next buffer in the list of free buffers */
  10083. };
  10084. /*
  10085. ** A hash table for function definitions.
  10086. **
  10087. ** Hash each FuncDef structure into one of the FuncDefHash.a[] slots.
  10088. ** Collisions are on the FuncDef.pHash chain.
  10089. */
  10090. struct FuncDefHash {
  10091. FuncDef *a[23]; /* Hash table for functions */
  10092. };
  10093. #ifdef SQLITE_USER_AUTHENTICATION
  10094. /*
  10095. ** Information held in the "sqlite3" database connection object and used
  10096. ** to manage user authentication.
  10097. */
  10098. typedef struct sqlite3_userauth sqlite3_userauth;
  10099. struct sqlite3_userauth {
  10100. u8 authLevel; /* Current authentication level */
  10101. int nAuthPW; /* Size of the zAuthPW in bytes */
  10102. char *zAuthPW; /* Password used to authenticate */
  10103. char *zAuthUser; /* User name used to authenticate */
  10104. };
  10105. /* Allowed values for sqlite3_userauth.authLevel */
  10106. #define UAUTH_Unknown 0 /* Authentication not yet checked */
  10107. #define UAUTH_Fail 1 /* User authentication failed */
  10108. #define UAUTH_User 2 /* Authenticated as a normal user */
  10109. #define UAUTH_Admin 3 /* Authenticated as an administrator */
  10110. /* Functions used only by user authorization logic */
  10111. SQLITE_PRIVATE int sqlite3UserAuthTable(const char*);
  10112. SQLITE_PRIVATE int sqlite3UserAuthCheckLogin(sqlite3*,const char*,u8*);
  10113. SQLITE_PRIVATE void sqlite3UserAuthInit(sqlite3*);
  10114. SQLITE_PRIVATE void sqlite3CryptFunc(sqlite3_context*,int,sqlite3_value**);
  10115. #endif /* SQLITE_USER_AUTHENTICATION */
  10116. /*
  10117. ** typedef for the authorization callback function.
  10118. */
  10119. #ifdef SQLITE_USER_AUTHENTICATION
  10120. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  10121. const char*, const char*);
  10122. #else
  10123. typedef int (*sqlite3_xauth)(void*,int,const char*,const char*,const char*,
  10124. const char*);
  10125. #endif
  10126. /*
  10127. ** Each database connection is an instance of the following structure.
  10128. */
  10129. struct sqlite3 {
  10130. sqlite3_vfs *pVfs; /* OS Interface */
  10131. struct Vdbe *pVdbe; /* List of active virtual machines */
  10132. CollSeq *pDfltColl; /* The default collating sequence (BINARY) */
  10133. sqlite3_mutex *mutex; /* Connection mutex */
  10134. Db *aDb; /* All backends */
  10135. int nDb; /* Number of backends currently in use */
  10136. int flags; /* Miscellaneous flags. See below */
  10137. i64 lastRowid; /* ROWID of most recent insert (see above) */
  10138. i64 szMmap; /* Default mmap_size setting */
  10139. unsigned int openFlags; /* Flags passed to sqlite3_vfs.xOpen() */
  10140. int errCode; /* Most recent error code (SQLITE_*) */
  10141. int errMask; /* & result codes with this before returning */
  10142. u16 dbOptFlags; /* Flags to enable/disable optimizations */
  10143. u8 autoCommit; /* The auto-commit flag. */
  10144. u8 temp_store; /* 1: file 2: memory 0: default */
  10145. u8 mallocFailed; /* True if we have seen a malloc failure */
  10146. u8 dfltLockMode; /* Default locking-mode for attached dbs */
  10147. signed char nextAutovac; /* Autovac setting after VACUUM if >=0 */
  10148. u8 suppressErr; /* Do not issue error messages if true */
  10149. u8 vtabOnConflict; /* Value to return for s3_vtab_on_conflict() */
  10150. u8 isTransactionSavepoint; /* True if the outermost savepoint is a TS */
  10151. int nextPagesize; /* Pagesize after VACUUM if >0 */
  10152. u32 magic; /* Magic number for detect library misuse */
  10153. int nChange; /* Value returned by sqlite3_changes() */
  10154. int nTotalChange; /* Value returned by sqlite3_total_changes() */
  10155. int aLimit[SQLITE_N_LIMIT]; /* Limits */
  10156. int nMaxSorterMmap; /* Maximum size of regions mapped by sorter */
  10157. struct sqlite3InitInfo { /* Information used during initialization */
  10158. int newTnum; /* Rootpage of table being initialized */
  10159. u8 iDb; /* Which db file is being initialized */
  10160. u8 busy; /* TRUE if currently initializing */
  10161. u8 orphanTrigger; /* Last statement is orphaned TEMP trigger */
  10162. } init;
  10163. int nVdbeActive; /* Number of VDBEs currently running */
  10164. int nVdbeRead; /* Number of active VDBEs that read or write */
  10165. int nVdbeWrite; /* Number of active VDBEs that read and write */
  10166. int nVdbeExec; /* Number of nested calls to VdbeExec() */
  10167. int nExtension; /* Number of loaded extensions */
  10168. void **aExtension; /* Array of shared library handles */
  10169. void (*xTrace)(void*,const char*); /* Trace function */
  10170. void *pTraceArg; /* Argument to the trace function */
  10171. void (*xProfile)(void*,const char*,u64); /* Profiling function */
  10172. void *pProfileArg; /* Argument to profile function */
  10173. void *pCommitArg; /* Argument to xCommitCallback() */
  10174. int (*xCommitCallback)(void*); /* Invoked at every commit. */
  10175. void *pRollbackArg; /* Argument to xRollbackCallback() */
  10176. void (*xRollbackCallback)(void*); /* Invoked at every commit. */
  10177. void *pUpdateArg;
  10178. void (*xUpdateCallback)(void*,int, const char*,const char*,sqlite_int64);
  10179. #ifndef SQLITE_OMIT_WAL
  10180. int (*xWalCallback)(void *, sqlite3 *, const char *, int);
  10181. void *pWalArg;
  10182. #endif
  10183. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*);
  10184. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*);
  10185. void *pCollNeededArg;
  10186. sqlite3_value *pErr; /* Most recent error message */
  10187. union {
  10188. volatile int isInterrupted; /* True if sqlite3_interrupt has been called */
  10189. double notUsed1; /* Spacer */
  10190. } u1;
  10191. Lookaside lookaside; /* Lookaside malloc configuration */
  10192. #ifndef SQLITE_OMIT_AUTHORIZATION
  10193. sqlite3_xauth xAuth; /* Access authorization function */
  10194. void *pAuthArg; /* 1st argument to the access auth function */
  10195. #endif
  10196. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  10197. int (*xProgress)(void *); /* The progress callback */
  10198. void *pProgressArg; /* Argument to the progress callback */
  10199. unsigned nProgressOps; /* Number of opcodes for progress callback */
  10200. #endif
  10201. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10202. int nVTrans; /* Allocated size of aVTrans */
  10203. Hash aModule; /* populated by sqlite3_create_module() */
  10204. VtabCtx *pVtabCtx; /* Context for active vtab connect/create */
  10205. VTable **aVTrans; /* Virtual tables with open transactions */
  10206. VTable *pDisconnect; /* Disconnect these in next sqlite3_prepare() */
  10207. #endif
  10208. FuncDefHash aFunc; /* Hash table of connection functions */
  10209. Hash aCollSeq; /* All collating sequences */
  10210. BusyHandler busyHandler; /* Busy callback */
  10211. Db aDbStatic[2]; /* Static space for the 2 default backends */
  10212. Savepoint *pSavepoint; /* List of active savepoints */
  10213. int busyTimeout; /* Busy handler timeout, in msec */
  10214. int nSavepoint; /* Number of non-transaction savepoints */
  10215. int nStatement; /* Number of nested statement-transactions */
  10216. i64 nDeferredCons; /* Net deferred constraints this transaction. */
  10217. i64 nDeferredImmCons; /* Net deferred immediate constraints */
  10218. int *pnBytesFreed; /* If not NULL, increment this in DbFree() */
  10219. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  10220. /* The following variables are all protected by the STATIC_MASTER
  10221. ** mutex, not by sqlite3.mutex. They are used by code in notify.c.
  10222. **
  10223. ** When X.pUnlockConnection==Y, that means that X is waiting for Y to
  10224. ** unlock so that it can proceed.
  10225. **
  10226. ** When X.pBlockingConnection==Y, that means that something that X tried
  10227. ** tried to do recently failed with an SQLITE_LOCKED error due to locks
  10228. ** held by Y.
  10229. */
  10230. sqlite3 *pBlockingConnection; /* Connection that caused SQLITE_LOCKED */
  10231. sqlite3 *pUnlockConnection; /* Connection to watch for unlock */
  10232. void *pUnlockArg; /* Argument to xUnlockNotify */
  10233. void (*xUnlockNotify)(void **, int); /* Unlock notify callback */
  10234. sqlite3 *pNextBlocked; /* Next in list of all blocked connections */
  10235. #endif
  10236. #ifdef SQLITE_USER_AUTHENTICATION
  10237. sqlite3_userauth auth; /* User authentication information */
  10238. #endif
  10239. };
  10240. /*
  10241. ** A macro to discover the encoding of a database.
  10242. */
  10243. #define ENC(db) ((db)->aDb[0].pSchema->enc)
  10244. /*
  10245. ** Possible values for the sqlite3.flags.
  10246. */
  10247. #define SQLITE_VdbeTrace 0x00000001 /* True to trace VDBE execution */
  10248. #define SQLITE_InternChanges 0x00000002 /* Uncommitted Hash table changes */
  10249. #define SQLITE_FullFSync 0x00000004 /* Use full fsync on the backend */
  10250. #define SQLITE_CkptFullFSync 0x00000008 /* Use full fsync for checkpoint */
  10251. #define SQLITE_CacheSpill 0x00000010 /* OK to spill pager cache */
  10252. #define SQLITE_FullColNames 0x00000020 /* Show full column names on SELECT */
  10253. #define SQLITE_ShortColNames 0x00000040 /* Show short columns names */
  10254. #define SQLITE_CountRows 0x00000080 /* Count rows changed by INSERT, */
  10255. /* DELETE, or UPDATE and return */
  10256. /* the count using a callback. */
  10257. #define SQLITE_NullCallback 0x00000100 /* Invoke the callback once if the */
  10258. /* result set is empty */
  10259. #define SQLITE_SqlTrace 0x00000200 /* Debug print SQL as it executes */
  10260. #define SQLITE_VdbeListing 0x00000400 /* Debug listings of VDBE programs */
  10261. #define SQLITE_WriteSchema 0x00000800 /* OK to update SQLITE_MASTER */
  10262. #define SQLITE_VdbeAddopTrace 0x00001000 /* Trace sqlite3VdbeAddOp() calls */
  10263. #define SQLITE_IgnoreChecks 0x00002000 /* Do not enforce check constraints */
  10264. #define SQLITE_ReadUncommitted 0x0004000 /* For shared-cache mode */
  10265. #define SQLITE_LegacyFileFmt 0x00008000 /* Create new databases in format 1 */
  10266. #define SQLITE_RecoveryMode 0x00010000 /* Ignore schema errors */
  10267. #define SQLITE_ReverseOrder 0x00020000 /* Reverse unordered SELECTs */
  10268. #define SQLITE_RecTriggers 0x00040000 /* Enable recursive triggers */
  10269. #define SQLITE_ForeignKeys 0x00080000 /* Enforce foreign key constraints */
  10270. #define SQLITE_AutoIndex 0x00100000 /* Enable automatic indexes */
  10271. #define SQLITE_PreferBuiltin 0x00200000 /* Preference to built-in funcs */
  10272. #define SQLITE_LoadExtension 0x00400000 /* Enable load_extension */
  10273. #define SQLITE_EnableTrigger 0x00800000 /* True to enable triggers */
  10274. #define SQLITE_DeferFKs 0x01000000 /* Defer all FK constraints */
  10275. #define SQLITE_QueryOnly 0x02000000 /* Disable database changes */
  10276. #define SQLITE_VdbeEQP 0x04000000 /* Debug EXPLAIN QUERY PLAN */
  10277. /*
  10278. ** Bits of the sqlite3.dbOptFlags field that are used by the
  10279. ** sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS,...) interface to
  10280. ** selectively disable various optimizations.
  10281. */
  10282. #define SQLITE_QueryFlattener 0x0001 /* Query flattening */
  10283. #define SQLITE_ColumnCache 0x0002 /* Column cache */
  10284. #define SQLITE_GroupByOrder 0x0004 /* GROUPBY cover of ORDERBY */
  10285. #define SQLITE_FactorOutConst 0x0008 /* Constant factoring */
  10286. /* not used 0x0010 // Was: SQLITE_IdxRealAsInt */
  10287. #define SQLITE_DistinctOpt 0x0020 /* DISTINCT using indexes */
  10288. #define SQLITE_CoverIdxScan 0x0040 /* Covering index scans */
  10289. #define SQLITE_OrderByIdxJoin 0x0080 /* ORDER BY of joins via index */
  10290. #define SQLITE_SubqCoroutine 0x0100 /* Evaluate subqueries as coroutines */
  10291. #define SQLITE_Transitive 0x0200 /* Transitive constraints */
  10292. #define SQLITE_OmitNoopJoin 0x0400 /* Omit unused tables in joins */
  10293. #define SQLITE_Stat3 0x0800 /* Use the SQLITE_STAT3 table */
  10294. #define SQLITE_AllOpts 0xffff /* All optimizations */
  10295. /*
  10296. ** Macros for testing whether or not optimizations are enabled or disabled.
  10297. */
  10298. #ifndef SQLITE_OMIT_BUILTIN_TEST
  10299. #define OptimizationDisabled(db, mask) (((db)->dbOptFlags&(mask))!=0)
  10300. #define OptimizationEnabled(db, mask) (((db)->dbOptFlags&(mask))==0)
  10301. #else
  10302. #define OptimizationDisabled(db, mask) 0
  10303. #define OptimizationEnabled(db, mask) 1
  10304. #endif
  10305. /*
  10306. ** Return true if it OK to factor constant expressions into the initialization
  10307. ** code. The argument is a Parse object for the code generator.
  10308. */
  10309. #define ConstFactorOk(P) ((P)->okConstFactor)
  10310. /*
  10311. ** Possible values for the sqlite.magic field.
  10312. ** The numbers are obtained at random and have no special meaning, other
  10313. ** than being distinct from one another.
  10314. */
  10315. #define SQLITE_MAGIC_OPEN 0xa029a697 /* Database is open */
  10316. #define SQLITE_MAGIC_CLOSED 0x9f3c2d33 /* Database is closed */
  10317. #define SQLITE_MAGIC_SICK 0x4b771290 /* Error and awaiting close */
  10318. #define SQLITE_MAGIC_BUSY 0xf03b7906 /* Database currently in use */
  10319. #define SQLITE_MAGIC_ERROR 0xb5357930 /* An SQLITE_MISUSE error occurred */
  10320. #define SQLITE_MAGIC_ZOMBIE 0x64cffc7f /* Close with last statement close */
  10321. /*
  10322. ** Each SQL function is defined by an instance of the following
  10323. ** structure. A pointer to this structure is stored in the sqlite.aFunc
  10324. ** hash table. When multiple functions have the same name, the hash table
  10325. ** points to a linked list of these structures.
  10326. */
  10327. struct FuncDef {
  10328. i16 nArg; /* Number of arguments. -1 means unlimited */
  10329. u16 funcFlags; /* Some combination of SQLITE_FUNC_* */
  10330. void *pUserData; /* User data parameter */
  10331. FuncDef *pNext; /* Next function with same name */
  10332. void (*xFunc)(sqlite3_context*,int,sqlite3_value**); /* Regular function */
  10333. void (*xStep)(sqlite3_context*,int,sqlite3_value**); /* Aggregate step */
  10334. void (*xFinalize)(sqlite3_context*); /* Aggregate finalizer */
  10335. char *zName; /* SQL name of the function. */
  10336. FuncDef *pHash; /* Next with a different name but the same hash */
  10337. FuncDestructor *pDestructor; /* Reference counted destructor function */
  10338. };
  10339. /*
  10340. ** This structure encapsulates a user-function destructor callback (as
  10341. ** configured using create_function_v2()) and a reference counter. When
  10342. ** create_function_v2() is called to create a function with a destructor,
  10343. ** a single object of this type is allocated. FuncDestructor.nRef is set to
  10344. ** the number of FuncDef objects created (either 1 or 3, depending on whether
  10345. ** or not the specified encoding is SQLITE_ANY). The FuncDef.pDestructor
  10346. ** member of each of the new FuncDef objects is set to point to the allocated
  10347. ** FuncDestructor.
  10348. **
  10349. ** Thereafter, when one of the FuncDef objects is deleted, the reference
  10350. ** count on this object is decremented. When it reaches 0, the destructor
  10351. ** is invoked and the FuncDestructor structure freed.
  10352. */
  10353. struct FuncDestructor {
  10354. int nRef;
  10355. void (*xDestroy)(void *);
  10356. void *pUserData;
  10357. };
  10358. /*
  10359. ** Possible values for FuncDef.flags. Note that the _LENGTH and _TYPEOF
  10360. ** values must correspond to OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG. There
  10361. ** are assert() statements in the code to verify this.
  10362. */
  10363. #define SQLITE_FUNC_ENCMASK 0x003 /* SQLITE_UTF8, SQLITE_UTF16BE or UTF16LE */
  10364. #define SQLITE_FUNC_LIKE 0x004 /* Candidate for the LIKE optimization */
  10365. #define SQLITE_FUNC_CASE 0x008 /* Case-sensitive LIKE-type function */
  10366. #define SQLITE_FUNC_EPHEM 0x010 /* Ephemeral. Delete with VDBE */
  10367. #define SQLITE_FUNC_NEEDCOLL 0x020 /* sqlite3GetFuncCollSeq() might be called */
  10368. #define SQLITE_FUNC_LENGTH 0x040 /* Built-in length() function */
  10369. #define SQLITE_FUNC_TYPEOF 0x080 /* Built-in typeof() function */
  10370. #define SQLITE_FUNC_COUNT 0x100 /* Built-in count(*) aggregate */
  10371. #define SQLITE_FUNC_COALESCE 0x200 /* Built-in coalesce() or ifnull() */
  10372. #define SQLITE_FUNC_UNLIKELY 0x400 /* Built-in unlikely() function */
  10373. #define SQLITE_FUNC_CONSTANT 0x800 /* Constant inputs give a constant output */
  10374. #define SQLITE_FUNC_MINMAX 0x1000 /* True for min() and max() aggregates */
  10375. /*
  10376. ** The following three macros, FUNCTION(), LIKEFUNC() and AGGREGATE() are
  10377. ** used to create the initializers for the FuncDef structures.
  10378. **
  10379. ** FUNCTION(zName, nArg, iArg, bNC, xFunc)
  10380. ** Used to create a scalar function definition of a function zName
  10381. ** implemented by C function xFunc that accepts nArg arguments. The
  10382. ** value passed as iArg is cast to a (void*) and made available
  10383. ** as the user-data (sqlite3_user_data()) for the function. If
  10384. ** argument bNC is true, then the SQLITE_FUNC_NEEDCOLL flag is set.
  10385. **
  10386. ** VFUNCTION(zName, nArg, iArg, bNC, xFunc)
  10387. ** Like FUNCTION except it omits the SQLITE_FUNC_CONSTANT flag.
  10388. **
  10389. ** AGGREGATE(zName, nArg, iArg, bNC, xStep, xFinal)
  10390. ** Used to create an aggregate function definition implemented by
  10391. ** the C functions xStep and xFinal. The first four parameters
  10392. ** are interpreted in the same way as the first 4 parameters to
  10393. ** FUNCTION().
  10394. **
  10395. ** LIKEFUNC(zName, nArg, pArg, flags)
  10396. ** Used to create a scalar function definition of a function zName
  10397. ** that accepts nArg arguments and is implemented by a call to C
  10398. ** function likeFunc. Argument pArg is cast to a (void *) and made
  10399. ** available as the function user-data (sqlite3_user_data()). The
  10400. ** FuncDef.flags variable is set to the value passed as the flags
  10401. ** parameter.
  10402. */
  10403. #define FUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10404. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10405. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10406. #define VFUNCTION(zName, nArg, iArg, bNC, xFunc) \
  10407. {nArg, SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10408. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10409. #define FUNCTION2(zName, nArg, iArg, bNC, xFunc, extraFlags) \
  10410. {nArg,SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL)|extraFlags,\
  10411. SQLITE_INT_TO_PTR(iArg), 0, xFunc, 0, 0, #zName, 0, 0}
  10412. #define STR_FUNCTION(zName, nArg, pArg, bNC, xFunc) \
  10413. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|(bNC*SQLITE_FUNC_NEEDCOLL), \
  10414. pArg, 0, xFunc, 0, 0, #zName, 0, 0}
  10415. #define LIKEFUNC(zName, nArg, arg, flags) \
  10416. {nArg, SQLITE_FUNC_CONSTANT|SQLITE_UTF8|flags, \
  10417. (void *)arg, 0, likeFunc, 0, 0, #zName, 0, 0}
  10418. #define AGGREGATE(zName, nArg, arg, nc, xStep, xFinal) \
  10419. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL), \
  10420. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10421. #define AGGREGATE2(zName, nArg, arg, nc, xStep, xFinal, extraFlags) \
  10422. {nArg, SQLITE_UTF8|(nc*SQLITE_FUNC_NEEDCOLL)|extraFlags, \
  10423. SQLITE_INT_TO_PTR(arg), 0, 0, xStep,xFinal,#zName,0,0}
  10424. /*
  10425. ** All current savepoints are stored in a linked list starting at
  10426. ** sqlite3.pSavepoint. The first element in the list is the most recently
  10427. ** opened savepoint. Savepoints are added to the list by the vdbe
  10428. ** OP_Savepoint instruction.
  10429. */
  10430. struct Savepoint {
  10431. char *zName; /* Savepoint name (nul-terminated) */
  10432. i64 nDeferredCons; /* Number of deferred fk violations */
  10433. i64 nDeferredImmCons; /* Number of deferred imm fk. */
  10434. Savepoint *pNext; /* Parent savepoint (if any) */
  10435. };
  10436. /*
  10437. ** The following are used as the second parameter to sqlite3Savepoint(),
  10438. ** and as the P1 argument to the OP_Savepoint instruction.
  10439. */
  10440. #define SAVEPOINT_BEGIN 0
  10441. #define SAVEPOINT_RELEASE 1
  10442. #define SAVEPOINT_ROLLBACK 2
  10443. /*
  10444. ** Each SQLite module (virtual table definition) is defined by an
  10445. ** instance of the following structure, stored in the sqlite3.aModule
  10446. ** hash table.
  10447. */
  10448. struct Module {
  10449. const sqlite3_module *pModule; /* Callback pointers */
  10450. const char *zName; /* Name passed to create_module() */
  10451. void *pAux; /* pAux passed to create_module() */
  10452. void (*xDestroy)(void *); /* Module destructor function */
  10453. };
  10454. /*
  10455. ** information about each column of an SQL table is held in an instance
  10456. ** of this structure.
  10457. */
  10458. struct Column {
  10459. char *zName; /* Name of this column */
  10460. Expr *pDflt; /* Default value of this column */
  10461. char *zDflt; /* Original text of the default value */
  10462. char *zType; /* Data type for this column */
  10463. char *zColl; /* Collating sequence. If NULL, use the default */
  10464. u8 notNull; /* An OE_ code for handling a NOT NULL constraint */
  10465. char affinity; /* One of the SQLITE_AFF_... values */
  10466. u8 szEst; /* Estimated size of this column. INT==1 */
  10467. u8 colFlags; /* Boolean properties. See COLFLAG_ defines below */
  10468. };
  10469. /* Allowed values for Column.colFlags:
  10470. */
  10471. #define COLFLAG_PRIMKEY 0x0001 /* Column is part of the primary key */
  10472. #define COLFLAG_HIDDEN 0x0002 /* A hidden column in a virtual table */
  10473. /*
  10474. ** A "Collating Sequence" is defined by an instance of the following
  10475. ** structure. Conceptually, a collating sequence consists of a name and
  10476. ** a comparison routine that defines the order of that sequence.
  10477. **
  10478. ** If CollSeq.xCmp is NULL, it means that the
  10479. ** collating sequence is undefined. Indices built on an undefined
  10480. ** collating sequence may not be read or written.
  10481. */
  10482. struct CollSeq {
  10483. char *zName; /* Name of the collating sequence, UTF-8 encoded */
  10484. u8 enc; /* Text encoding handled by xCmp() */
  10485. void *pUser; /* First argument to xCmp() */
  10486. int (*xCmp)(void*,int, const void*, int, const void*);
  10487. void (*xDel)(void*); /* Destructor for pUser */
  10488. };
  10489. /*
  10490. ** A sort order can be either ASC or DESC.
  10491. */
  10492. #define SQLITE_SO_ASC 0 /* Sort in ascending order */
  10493. #define SQLITE_SO_DESC 1 /* Sort in ascending order */
  10494. /*
  10495. ** Column affinity types.
  10496. **
  10497. ** These used to have mnemonic name like 'i' for SQLITE_AFF_INTEGER and
  10498. ** 't' for SQLITE_AFF_TEXT. But we can save a little space and improve
  10499. ** the speed a little by numbering the values consecutively.
  10500. **
  10501. ** But rather than start with 0 or 1, we begin with 'A'. That way,
  10502. ** when multiple affinity types are concatenated into a string and
  10503. ** used as the P4 operand, they will be more readable.
  10504. **
  10505. ** Note also that the numeric types are grouped together so that testing
  10506. ** for a numeric type is a single comparison. And the NONE type is first.
  10507. */
  10508. #define SQLITE_AFF_NONE 'A'
  10509. #define SQLITE_AFF_TEXT 'B'
  10510. #define SQLITE_AFF_NUMERIC 'C'
  10511. #define SQLITE_AFF_INTEGER 'D'
  10512. #define SQLITE_AFF_REAL 'E'
  10513. #define sqlite3IsNumericAffinity(X) ((X)>=SQLITE_AFF_NUMERIC)
  10514. /*
  10515. ** The SQLITE_AFF_MASK values masks off the significant bits of an
  10516. ** affinity value.
  10517. */
  10518. #define SQLITE_AFF_MASK 0x47
  10519. /*
  10520. ** Additional bit values that can be ORed with an affinity without
  10521. ** changing the affinity.
  10522. **
  10523. ** The SQLITE_NOTNULL flag is a combination of NULLEQ and JUMPIFNULL.
  10524. ** It causes an assert() to fire if either operand to a comparison
  10525. ** operator is NULL. It is added to certain comparison operators to
  10526. ** prove that the operands are always NOT NULL.
  10527. */
  10528. #define SQLITE_JUMPIFNULL 0x10 /* jumps if either operand is NULL */
  10529. #define SQLITE_STOREP2 0x20 /* Store result in reg[P2] rather than jump */
  10530. #define SQLITE_NULLEQ 0x80 /* NULL=NULL */
  10531. #define SQLITE_NOTNULL 0x90 /* Assert that operands are never NULL */
  10532. /*
  10533. ** An object of this type is created for each virtual table present in
  10534. ** the database schema.
  10535. **
  10536. ** If the database schema is shared, then there is one instance of this
  10537. ** structure for each database connection (sqlite3*) that uses the shared
  10538. ** schema. This is because each database connection requires its own unique
  10539. ** instance of the sqlite3_vtab* handle used to access the virtual table
  10540. ** implementation. sqlite3_vtab* handles can not be shared between
  10541. ** database connections, even when the rest of the in-memory database
  10542. ** schema is shared, as the implementation often stores the database
  10543. ** connection handle passed to it via the xConnect() or xCreate() method
  10544. ** during initialization internally. This database connection handle may
  10545. ** then be used by the virtual table implementation to access real tables
  10546. ** within the database. So that they appear as part of the callers
  10547. ** transaction, these accesses need to be made via the same database
  10548. ** connection as that used to execute SQL operations on the virtual table.
  10549. **
  10550. ** All VTable objects that correspond to a single table in a shared
  10551. ** database schema are initially stored in a linked-list pointed to by
  10552. ** the Table.pVTable member variable of the corresponding Table object.
  10553. ** When an sqlite3_prepare() operation is required to access the virtual
  10554. ** table, it searches the list for the VTable that corresponds to the
  10555. ** database connection doing the preparing so as to use the correct
  10556. ** sqlite3_vtab* handle in the compiled query.
  10557. **
  10558. ** When an in-memory Table object is deleted (for example when the
  10559. ** schema is being reloaded for some reason), the VTable objects are not
  10560. ** deleted and the sqlite3_vtab* handles are not xDisconnect()ed
  10561. ** immediately. Instead, they are moved from the Table.pVTable list to
  10562. ** another linked list headed by the sqlite3.pDisconnect member of the
  10563. ** corresponding sqlite3 structure. They are then deleted/xDisconnected
  10564. ** next time a statement is prepared using said sqlite3*. This is done
  10565. ** to avoid deadlock issues involving multiple sqlite3.mutex mutexes.
  10566. ** Refer to comments above function sqlite3VtabUnlockList() for an
  10567. ** explanation as to why it is safe to add an entry to an sqlite3.pDisconnect
  10568. ** list without holding the corresponding sqlite3.mutex mutex.
  10569. **
  10570. ** The memory for objects of this type is always allocated by
  10571. ** sqlite3DbMalloc(), using the connection handle stored in VTable.db as
  10572. ** the first argument.
  10573. */
  10574. struct VTable {
  10575. sqlite3 *db; /* Database connection associated with this table */
  10576. Module *pMod; /* Pointer to module implementation */
  10577. sqlite3_vtab *pVtab; /* Pointer to vtab instance */
  10578. int nRef; /* Number of pointers to this structure */
  10579. u8 bConstraint; /* True if constraints are supported */
  10580. int iSavepoint; /* Depth of the SAVEPOINT stack */
  10581. VTable *pNext; /* Next in linked list (see above) */
  10582. };
  10583. /*
  10584. ** Each SQL table is represented in memory by an instance of the
  10585. ** following structure.
  10586. **
  10587. ** Table.zName is the name of the table. The case of the original
  10588. ** CREATE TABLE statement is stored, but case is not significant for
  10589. ** comparisons.
  10590. **
  10591. ** Table.nCol is the number of columns in this table. Table.aCol is a
  10592. ** pointer to an array of Column structures, one for each column.
  10593. **
  10594. ** If the table has an INTEGER PRIMARY KEY, then Table.iPKey is the index of
  10595. ** the column that is that key. Otherwise Table.iPKey is negative. Note
  10596. ** that the datatype of the PRIMARY KEY must be INTEGER for this field to
  10597. ** be set. An INTEGER PRIMARY KEY is used as the rowid for each row of
  10598. ** the table. If a table has no INTEGER PRIMARY KEY, then a random rowid
  10599. ** is generated for each row of the table. TF_HasPrimaryKey is set if
  10600. ** the table has any PRIMARY KEY, INTEGER or otherwise.
  10601. **
  10602. ** Table.tnum is the page number for the root BTree page of the table in the
  10603. ** database file. If Table.iDb is the index of the database table backend
  10604. ** in sqlite.aDb[]. 0 is for the main database and 1 is for the file that
  10605. ** holds temporary tables and indices. If TF_Ephemeral is set
  10606. ** then the table is stored in a file that is automatically deleted
  10607. ** when the VDBE cursor to the table is closed. In this case Table.tnum
  10608. ** refers VDBE cursor number that holds the table open, not to the root
  10609. ** page number. Transient tables are used to hold the results of a
  10610. ** sub-query that appears instead of a real table name in the FROM clause
  10611. ** of a SELECT statement.
  10612. */
  10613. struct Table {
  10614. char *zName; /* Name of the table or view */
  10615. Column *aCol; /* Information about each column */
  10616. Index *pIndex; /* List of SQL indexes on this table. */
  10617. Select *pSelect; /* NULL for tables. Points to definition if a view. */
  10618. FKey *pFKey; /* Linked list of all foreign keys in this table */
  10619. char *zColAff; /* String defining the affinity of each column */
  10620. #ifndef SQLITE_OMIT_CHECK
  10621. ExprList *pCheck; /* All CHECK constraints */
  10622. #endif
  10623. LogEst nRowLogEst; /* Estimated rows in table - from sqlite_stat1 table */
  10624. int tnum; /* Root BTree node for this table (see note above) */
  10625. i16 iPKey; /* If not negative, use aCol[iPKey] as the primary key */
  10626. i16 nCol; /* Number of columns in this table */
  10627. u16 nRef; /* Number of pointers to this Table */
  10628. LogEst szTabRow; /* Estimated size of each table row in bytes */
  10629. #ifdef SQLITE_ENABLE_COSTMULT
  10630. LogEst costMult; /* Cost multiplier for using this table */
  10631. #endif
  10632. u8 tabFlags; /* Mask of TF_* values */
  10633. u8 keyConf; /* What to do in case of uniqueness conflict on iPKey */
  10634. #ifndef SQLITE_OMIT_ALTERTABLE
  10635. int addColOffset; /* Offset in CREATE TABLE stmt to add a new column */
  10636. #endif
  10637. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10638. int nModuleArg; /* Number of arguments to the module */
  10639. char **azModuleArg; /* Text of all module args. [0] is module name */
  10640. VTable *pVTable; /* List of VTable objects. */
  10641. #endif
  10642. Trigger *pTrigger; /* List of triggers stored in pSchema */
  10643. Schema *pSchema; /* Schema that contains this table */
  10644. Table *pNextZombie; /* Next on the Parse.pZombieTab list */
  10645. };
  10646. /*
  10647. ** Allowed values for Table.tabFlags.
  10648. */
  10649. #define TF_Readonly 0x01 /* Read-only system table */
  10650. #define TF_Ephemeral 0x02 /* An ephemeral table */
  10651. #define TF_HasPrimaryKey 0x04 /* Table has a primary key */
  10652. #define TF_Autoincrement 0x08 /* Integer primary key is autoincrement */
  10653. #define TF_Virtual 0x10 /* Is a virtual table */
  10654. #define TF_WithoutRowid 0x20 /* No rowid used. PRIMARY KEY is the key */
  10655. /*
  10656. ** Test to see whether or not a table is a virtual table. This is
  10657. ** done as a macro so that it will be optimized out when virtual
  10658. ** table support is omitted from the build.
  10659. */
  10660. #ifndef SQLITE_OMIT_VIRTUALTABLE
  10661. # define IsVirtual(X) (((X)->tabFlags & TF_Virtual)!=0)
  10662. # define IsHiddenColumn(X) (((X)->colFlags & COLFLAG_HIDDEN)!=0)
  10663. #else
  10664. # define IsVirtual(X) 0
  10665. # define IsHiddenColumn(X) 0
  10666. #endif
  10667. /* Does the table have a rowid */
  10668. #define HasRowid(X) (((X)->tabFlags & TF_WithoutRowid)==0)
  10669. /*
  10670. ** Each foreign key constraint is an instance of the following structure.
  10671. **
  10672. ** A foreign key is associated with two tables. The "from" table is
  10673. ** the table that contains the REFERENCES clause that creates the foreign
  10674. ** key. The "to" table is the table that is named in the REFERENCES clause.
  10675. ** Consider this example:
  10676. **
  10677. ** CREATE TABLE ex1(
  10678. ** a INTEGER PRIMARY KEY,
  10679. ** b INTEGER CONSTRAINT fk1 REFERENCES ex2(x)
  10680. ** );
  10681. **
  10682. ** For foreign key "fk1", the from-table is "ex1" and the to-table is "ex2".
  10683. ** Equivalent names:
  10684. **
  10685. ** from-table == child-table
  10686. ** to-table == parent-table
  10687. **
  10688. ** Each REFERENCES clause generates an instance of the following structure
  10689. ** which is attached to the from-table. The to-table need not exist when
  10690. ** the from-table is created. The existence of the to-table is not checked.
  10691. **
  10692. ** The list of all parents for child Table X is held at X.pFKey.
  10693. **
  10694. ** A list of all children for a table named Z (which might not even exist)
  10695. ** is held in Schema.fkeyHash with a hash key of Z.
  10696. */
  10697. struct FKey {
  10698. Table *pFrom; /* Table containing the REFERENCES clause (aka: Child) */
  10699. FKey *pNextFrom; /* Next FKey with the same in pFrom. Next parent of pFrom */
  10700. char *zTo; /* Name of table that the key points to (aka: Parent) */
  10701. FKey *pNextTo; /* Next with the same zTo. Next child of zTo. */
  10702. FKey *pPrevTo; /* Previous with the same zTo */
  10703. int nCol; /* Number of columns in this key */
  10704. /* EV: R-30323-21917 */
  10705. u8 isDeferred; /* True if constraint checking is deferred till COMMIT */
  10706. u8 aAction[2]; /* ON DELETE and ON UPDATE actions, respectively */
  10707. Trigger *apTrigger[2];/* Triggers for aAction[] actions */
  10708. struct sColMap { /* Mapping of columns in pFrom to columns in zTo */
  10709. int iFrom; /* Index of column in pFrom */
  10710. char *zCol; /* Name of column in zTo. If NULL use PRIMARY KEY */
  10711. } aCol[1]; /* One entry for each of nCol columns */
  10712. };
  10713. /*
  10714. ** SQLite supports many different ways to resolve a constraint
  10715. ** error. ROLLBACK processing means that a constraint violation
  10716. ** causes the operation in process to fail and for the current transaction
  10717. ** to be rolled back. ABORT processing means the operation in process
  10718. ** fails and any prior changes from that one operation are backed out,
  10719. ** but the transaction is not rolled back. FAIL processing means that
  10720. ** the operation in progress stops and returns an error code. But prior
  10721. ** changes due to the same operation are not backed out and no rollback
  10722. ** occurs. IGNORE means that the particular row that caused the constraint
  10723. ** error is not inserted or updated. Processing continues and no error
  10724. ** is returned. REPLACE means that preexisting database rows that caused
  10725. ** a UNIQUE constraint violation are removed so that the new insert or
  10726. ** update can proceed. Processing continues and no error is reported.
  10727. **
  10728. ** RESTRICT, SETNULL, and CASCADE actions apply only to foreign keys.
  10729. ** RESTRICT is the same as ABORT for IMMEDIATE foreign keys and the
  10730. ** same as ROLLBACK for DEFERRED keys. SETNULL means that the foreign
  10731. ** key is set to NULL. CASCADE means that a DELETE or UPDATE of the
  10732. ** referenced table row is propagated into the row that holds the
  10733. ** foreign key.
  10734. **
  10735. ** The following symbolic values are used to record which type
  10736. ** of action to take.
  10737. */
  10738. #define OE_None 0 /* There is no constraint to check */
  10739. #define OE_Rollback 1 /* Fail the operation and rollback the transaction */
  10740. #define OE_Abort 2 /* Back out changes but do no rollback transaction */
  10741. #define OE_Fail 3 /* Stop the operation but leave all prior changes */
  10742. #define OE_Ignore 4 /* Ignore the error. Do not do the INSERT or UPDATE */
  10743. #define OE_Replace 5 /* Delete existing record, then do INSERT or UPDATE */
  10744. #define OE_Restrict 6 /* OE_Abort for IMMEDIATE, OE_Rollback for DEFERRED */
  10745. #define OE_SetNull 7 /* Set the foreign key value to NULL */
  10746. #define OE_SetDflt 8 /* Set the foreign key value to its default */
  10747. #define OE_Cascade 9 /* Cascade the changes */
  10748. #define OE_Default 10 /* Do whatever the default action is */
  10749. /*
  10750. ** An instance of the following structure is passed as the first
  10751. ** argument to sqlite3VdbeKeyCompare and is used to control the
  10752. ** comparison of the two index keys.
  10753. **
  10754. ** Note that aSortOrder[] and aColl[] have nField+1 slots. There
  10755. ** are nField slots for the columns of an index then one extra slot
  10756. ** for the rowid at the end.
  10757. */
  10758. struct KeyInfo {
  10759. u32 nRef; /* Number of references to this KeyInfo object */
  10760. u8 enc; /* Text encoding - one of the SQLITE_UTF* values */
  10761. u16 nField; /* Number of key columns in the index */
  10762. u16 nXField; /* Number of columns beyond the key columns */
  10763. sqlite3 *db; /* The database connection */
  10764. u8 *aSortOrder; /* Sort order for each column. */
  10765. CollSeq *aColl[1]; /* Collating sequence for each term of the key */
  10766. };
  10767. /*
  10768. ** An instance of the following structure holds information about a
  10769. ** single index record that has already been parsed out into individual
  10770. ** values.
  10771. **
  10772. ** A record is an object that contains one or more fields of data.
  10773. ** Records are used to store the content of a table row and to store
  10774. ** the key of an index. A blob encoding of a record is created by
  10775. ** the OP_MakeRecord opcode of the VDBE and is disassembled by the
  10776. ** OP_Column opcode.
  10777. **
  10778. ** This structure holds a record that has already been disassembled
  10779. ** into its constituent fields.
  10780. **
  10781. ** The r1 and r2 member variables are only used by the optimized comparison
  10782. ** functions vdbeRecordCompareInt() and vdbeRecordCompareString().
  10783. */
  10784. struct UnpackedRecord {
  10785. KeyInfo *pKeyInfo; /* Collation and sort-order information */
  10786. u16 nField; /* Number of entries in apMem[] */
  10787. i8 default_rc; /* Comparison result if keys are equal */
  10788. u8 errCode; /* Error detected by xRecordCompare (CORRUPT or NOMEM) */
  10789. Mem *aMem; /* Values */
  10790. int r1; /* Value to return if (lhs > rhs) */
  10791. int r2; /* Value to return if (rhs < lhs) */
  10792. };
  10793. /*
  10794. ** Each SQL index is represented in memory by an
  10795. ** instance of the following structure.
  10796. **
  10797. ** The columns of the table that are to be indexed are described
  10798. ** by the aiColumn[] field of this structure. For example, suppose
  10799. ** we have the following table and index:
  10800. **
  10801. ** CREATE TABLE Ex1(c1 int, c2 int, c3 text);
  10802. ** CREATE INDEX Ex2 ON Ex1(c3,c1);
  10803. **
  10804. ** In the Table structure describing Ex1, nCol==3 because there are
  10805. ** three columns in the table. In the Index structure describing
  10806. ** Ex2, nColumn==2 since 2 of the 3 columns of Ex1 are indexed.
  10807. ** The value of aiColumn is {2, 0}. aiColumn[0]==2 because the
  10808. ** first column to be indexed (c3) has an index of 2 in Ex1.aCol[].
  10809. ** The second column to be indexed (c1) has an index of 0 in
  10810. ** Ex1.aCol[], hence Ex2.aiColumn[1]==0.
  10811. **
  10812. ** The Index.onError field determines whether or not the indexed columns
  10813. ** must be unique and what to do if they are not. When Index.onError=OE_None,
  10814. ** it means this is not a unique index. Otherwise it is a unique index
  10815. ** and the value of Index.onError indicate the which conflict resolution
  10816. ** algorithm to employ whenever an attempt is made to insert a non-unique
  10817. ** element.
  10818. */
  10819. struct Index {
  10820. char *zName; /* Name of this index */
  10821. i16 *aiColumn; /* Which columns are used by this index. 1st is 0 */
  10822. LogEst *aiRowLogEst; /* From ANALYZE: Est. rows selected by each column */
  10823. Table *pTable; /* The SQL table being indexed */
  10824. char *zColAff; /* String defining the affinity of each column */
  10825. Index *pNext; /* The next index associated with the same table */
  10826. Schema *pSchema; /* Schema containing this index */
  10827. u8 *aSortOrder; /* for each column: True==DESC, False==ASC */
  10828. char **azColl; /* Array of collation sequence names for index */
  10829. Expr *pPartIdxWhere; /* WHERE clause for partial indices */
  10830. KeyInfo *pKeyInfo; /* A KeyInfo object suitable for this index */
  10831. int tnum; /* DB Page containing root of this index */
  10832. LogEst szIdxRow; /* Estimated average row size in bytes */
  10833. u16 nKeyCol; /* Number of columns forming the key */
  10834. u16 nColumn; /* Number of columns stored in the index */
  10835. u8 onError; /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  10836. unsigned idxType:2; /* 1==UNIQUE, 2==PRIMARY KEY, 0==CREATE INDEX */
  10837. unsigned bUnordered:1; /* Use this index for == or IN queries only */
  10838. unsigned uniqNotNull:1; /* True if UNIQUE and NOT NULL for all columns */
  10839. unsigned isResized:1; /* True if resizeIndexObject() has been called */
  10840. unsigned isCovering:1; /* True if this is a covering index */
  10841. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  10842. int nSample; /* Number of elements in aSample[] */
  10843. int nSampleCol; /* Size of IndexSample.anEq[] and so on */
  10844. tRowcnt *aAvgEq; /* Average nEq values for keys not in aSample */
  10845. IndexSample *aSample; /* Samples of the left-most key */
  10846. tRowcnt *aiRowEst; /* Non-logarithmic stat1 data for this table */
  10847. #endif
  10848. };
  10849. /*
  10850. ** Allowed values for Index.idxType
  10851. */
  10852. #define SQLITE_IDXTYPE_APPDEF 0 /* Created using CREATE INDEX */
  10853. #define SQLITE_IDXTYPE_UNIQUE 1 /* Implements a UNIQUE constraint */
  10854. #define SQLITE_IDXTYPE_PRIMARYKEY 2 /* Is the PRIMARY KEY for the table */
  10855. /* Return true if index X is a PRIMARY KEY index */
  10856. #define IsPrimaryKeyIndex(X) ((X)->idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  10857. /* Return true if index X is a UNIQUE index */
  10858. #define IsUniqueIndex(X) ((X)->onError!=OE_None)
  10859. /*
  10860. ** Each sample stored in the sqlite_stat3 table is represented in memory
  10861. ** using a structure of this type. See documentation at the top of the
  10862. ** analyze.c source file for additional information.
  10863. */
  10864. struct IndexSample {
  10865. void *p; /* Pointer to sampled record */
  10866. int n; /* Size of record in bytes */
  10867. tRowcnt *anEq; /* Est. number of rows where the key equals this sample */
  10868. tRowcnt *anLt; /* Est. number of rows where key is less than this sample */
  10869. tRowcnt *anDLt; /* Est. number of distinct keys less than this sample */
  10870. };
  10871. /*
  10872. ** Each token coming out of the lexer is an instance of
  10873. ** this structure. Tokens are also used as part of an expression.
  10874. **
  10875. ** Note if Token.z==0 then Token.dyn and Token.n are undefined and
  10876. ** may contain random values. Do not make any assumptions about Token.dyn
  10877. ** and Token.n when Token.z==0.
  10878. */
  10879. struct Token {
  10880. const char *z; /* Text of the token. Not NULL-terminated! */
  10881. unsigned int n; /* Number of characters in this token */
  10882. };
  10883. /*
  10884. ** An instance of this structure contains information needed to generate
  10885. ** code for a SELECT that contains aggregate functions.
  10886. **
  10887. ** If Expr.op==TK_AGG_COLUMN or TK_AGG_FUNCTION then Expr.pAggInfo is a
  10888. ** pointer to this structure. The Expr.iColumn field is the index in
  10889. ** AggInfo.aCol[] or AggInfo.aFunc[] of information needed to generate
  10890. ** code for that node.
  10891. **
  10892. ** AggInfo.pGroupBy and AggInfo.aFunc.pExpr point to fields within the
  10893. ** original Select structure that describes the SELECT statement. These
  10894. ** fields do not need to be freed when deallocating the AggInfo structure.
  10895. */
  10896. struct AggInfo {
  10897. u8 directMode; /* Direct rendering mode means take data directly
  10898. ** from source tables rather than from accumulators */
  10899. u8 useSortingIdx; /* In direct mode, reference the sorting index rather
  10900. ** than the source table */
  10901. int sortingIdx; /* Cursor number of the sorting index */
  10902. int sortingIdxPTab; /* Cursor number of pseudo-table */
  10903. int nSortingColumn; /* Number of columns in the sorting index */
  10904. int mnReg, mxReg; /* Range of registers allocated for aCol and aFunc */
  10905. ExprList *pGroupBy; /* The group by clause */
  10906. struct AggInfo_col { /* For each column used in source tables */
  10907. Table *pTab; /* Source table */
  10908. int iTable; /* Cursor number of the source table */
  10909. int iColumn; /* Column number within the source table */
  10910. int iSorterColumn; /* Column number in the sorting index */
  10911. int iMem; /* Memory location that acts as accumulator */
  10912. Expr *pExpr; /* The original expression */
  10913. } *aCol;
  10914. int nColumn; /* Number of used entries in aCol[] */
  10915. int nAccumulator; /* Number of columns that show through to the output.
  10916. ** Additional columns are used only as parameters to
  10917. ** aggregate functions */
  10918. struct AggInfo_func { /* For each aggregate function */
  10919. Expr *pExpr; /* Expression encoding the function */
  10920. FuncDef *pFunc; /* The aggregate function implementation */
  10921. int iMem; /* Memory location that acts as accumulator */
  10922. int iDistinct; /* Ephemeral table used to enforce DISTINCT */
  10923. } *aFunc;
  10924. int nFunc; /* Number of entries in aFunc[] */
  10925. };
  10926. /*
  10927. ** The datatype ynVar is a signed integer, either 16-bit or 32-bit.
  10928. ** Usually it is 16-bits. But if SQLITE_MAX_VARIABLE_NUMBER is greater
  10929. ** than 32767 we have to make it 32-bit. 16-bit is preferred because
  10930. ** it uses less memory in the Expr object, which is a big memory user
  10931. ** in systems with lots of prepared statements. And few applications
  10932. ** need more than about 10 or 20 variables. But some extreme users want
  10933. ** to have prepared statements with over 32767 variables, and for them
  10934. ** the option is available (at compile-time).
  10935. */
  10936. #if SQLITE_MAX_VARIABLE_NUMBER<=32767
  10937. typedef i16 ynVar;
  10938. #else
  10939. typedef int ynVar;
  10940. #endif
  10941. /*
  10942. ** Each node of an expression in the parse tree is an instance
  10943. ** of this structure.
  10944. **
  10945. ** Expr.op is the opcode. The integer parser token codes are reused
  10946. ** as opcodes here. For example, the parser defines TK_GE to be an integer
  10947. ** code representing the ">=" operator. This same integer code is reused
  10948. ** to represent the greater-than-or-equal-to operator in the expression
  10949. ** tree.
  10950. **
  10951. ** If the expression is an SQL literal (TK_INTEGER, TK_FLOAT, TK_BLOB,
  10952. ** or TK_STRING), then Expr.token contains the text of the SQL literal. If
  10953. ** the expression is a variable (TK_VARIABLE), then Expr.token contains the
  10954. ** variable name. Finally, if the expression is an SQL function (TK_FUNCTION),
  10955. ** then Expr.token contains the name of the function.
  10956. **
  10957. ** Expr.pRight and Expr.pLeft are the left and right subexpressions of a
  10958. ** binary operator. Either or both may be NULL.
  10959. **
  10960. ** Expr.x.pList is a list of arguments if the expression is an SQL function,
  10961. ** a CASE expression or an IN expression of the form "<lhs> IN (<y>, <z>...)".
  10962. ** Expr.x.pSelect is used if the expression is a sub-select or an expression of
  10963. ** the form "<lhs> IN (SELECT ...)". If the EP_xIsSelect bit is set in the
  10964. ** Expr.flags mask, then Expr.x.pSelect is valid. Otherwise, Expr.x.pList is
  10965. ** valid.
  10966. **
  10967. ** An expression of the form ID or ID.ID refers to a column in a table.
  10968. ** For such expressions, Expr.op is set to TK_COLUMN and Expr.iTable is
  10969. ** the integer cursor number of a VDBE cursor pointing to that table and
  10970. ** Expr.iColumn is the column number for the specific column. If the
  10971. ** expression is used as a result in an aggregate SELECT, then the
  10972. ** value is also stored in the Expr.iAgg column in the aggregate so that
  10973. ** it can be accessed after all aggregates are computed.
  10974. **
  10975. ** If the expression is an unbound variable marker (a question mark
  10976. ** character '?' in the original SQL) then the Expr.iTable holds the index
  10977. ** number for that variable.
  10978. **
  10979. ** If the expression is a subquery then Expr.iColumn holds an integer
  10980. ** register number containing the result of the subquery. If the
  10981. ** subquery gives a constant result, then iTable is -1. If the subquery
  10982. ** gives a different answer at different times during statement processing
  10983. ** then iTable is the address of a subroutine that computes the subquery.
  10984. **
  10985. ** If the Expr is of type OP_Column, and the table it is selecting from
  10986. ** is a disk table or the "old.*" pseudo-table, then pTab points to the
  10987. ** corresponding table definition.
  10988. **
  10989. ** ALLOCATION NOTES:
  10990. **
  10991. ** Expr objects can use a lot of memory space in database schema. To
  10992. ** help reduce memory requirements, sometimes an Expr object will be
  10993. ** truncated. And to reduce the number of memory allocations, sometimes
  10994. ** two or more Expr objects will be stored in a single memory allocation,
  10995. ** together with Expr.zToken strings.
  10996. **
  10997. ** If the EP_Reduced and EP_TokenOnly flags are set when
  10998. ** an Expr object is truncated. When EP_Reduced is set, then all
  10999. ** the child Expr objects in the Expr.pLeft and Expr.pRight subtrees
  11000. ** are contained within the same memory allocation. Note, however, that
  11001. ** the subtrees in Expr.x.pList or Expr.x.pSelect are always separately
  11002. ** allocated, regardless of whether or not EP_Reduced is set.
  11003. */
  11004. struct Expr {
  11005. u8 op; /* Operation performed by this node */
  11006. char affinity; /* The affinity of the column or 0 if not a column */
  11007. u32 flags; /* Various flags. EP_* See below */
  11008. union {
  11009. char *zToken; /* Token value. Zero terminated and dequoted */
  11010. int iValue; /* Non-negative integer value if EP_IntValue */
  11011. } u;
  11012. /* If the EP_TokenOnly flag is set in the Expr.flags mask, then no
  11013. ** space is allocated for the fields below this point. An attempt to
  11014. ** access them will result in a segfault or malfunction.
  11015. *********************************************************************/
  11016. Expr *pLeft; /* Left subnode */
  11017. Expr *pRight; /* Right subnode */
  11018. union {
  11019. ExprList *pList; /* op = IN, EXISTS, SELECT, CASE, FUNCTION, BETWEEN */
  11020. Select *pSelect; /* EP_xIsSelect and op = IN, EXISTS, SELECT */
  11021. } x;
  11022. /* If the EP_Reduced flag is set in the Expr.flags mask, then no
  11023. ** space is allocated for the fields below this point. An attempt to
  11024. ** access them will result in a segfault or malfunction.
  11025. *********************************************************************/
  11026. #if SQLITE_MAX_EXPR_DEPTH>0
  11027. int nHeight; /* Height of the tree headed by this node */
  11028. #endif
  11029. int iTable; /* TK_COLUMN: cursor number of table holding column
  11030. ** TK_REGISTER: register number
  11031. ** TK_TRIGGER: 1 -> new, 0 -> old
  11032. ** EP_Unlikely: 1000 times likelihood */
  11033. ynVar iColumn; /* TK_COLUMN: column index. -1 for rowid.
  11034. ** TK_VARIABLE: variable number (always >= 1). */
  11035. i16 iAgg; /* Which entry in pAggInfo->aCol[] or ->aFunc[] */
  11036. i16 iRightJoinTable; /* If EP_FromJoin, the right table of the join */
  11037. u8 op2; /* TK_REGISTER: original value of Expr.op
  11038. ** TK_COLUMN: the value of p5 for OP_Column
  11039. ** TK_AGG_FUNCTION: nesting depth */
  11040. AggInfo *pAggInfo; /* Used by TK_AGG_COLUMN and TK_AGG_FUNCTION */
  11041. Table *pTab; /* Table for TK_COLUMN expressions. */
  11042. };
  11043. /*
  11044. ** The following are the meanings of bits in the Expr.flags field.
  11045. */
  11046. #define EP_FromJoin 0x000001 /* Originates in ON/USING clause of outer join */
  11047. #define EP_Agg 0x000002 /* Contains one or more aggregate functions */
  11048. #define EP_Resolved 0x000004 /* IDs have been resolved to COLUMNs */
  11049. #define EP_Error 0x000008 /* Expression contains one or more errors */
  11050. #define EP_Distinct 0x000010 /* Aggregate function with DISTINCT keyword */
  11051. #define EP_VarSelect 0x000020 /* pSelect is correlated, not constant */
  11052. #define EP_DblQuoted 0x000040 /* token.z was originally in "..." */
  11053. #define EP_InfixFunc 0x000080 /* True for an infix function: LIKE, GLOB, etc */
  11054. #define EP_Collate 0x000100 /* Tree contains a TK_COLLATE operator */
  11055. #define EP_Generic 0x000200 /* Ignore COLLATE or affinity on this tree */
  11056. #define EP_IntValue 0x000400 /* Integer value contained in u.iValue */
  11057. #define EP_xIsSelect 0x000800 /* x.pSelect is valid (otherwise x.pList is) */
  11058. #define EP_Skip 0x001000 /* COLLATE, AS, or UNLIKELY */
  11059. #define EP_Reduced 0x002000 /* Expr struct EXPR_REDUCEDSIZE bytes only */
  11060. #define EP_TokenOnly 0x004000 /* Expr struct EXPR_TOKENONLYSIZE bytes only */
  11061. #define EP_Static 0x008000 /* Held in memory not obtained from malloc() */
  11062. #define EP_MemToken 0x010000 /* Need to sqlite3DbFree() Expr.zToken */
  11063. #define EP_NoReduce 0x020000 /* Cannot EXPRDUP_REDUCE this Expr */
  11064. #define EP_Unlikely 0x040000 /* unlikely() or likelihood() function */
  11065. #define EP_Constant 0x080000 /* Node is a constant */
  11066. #define EP_CanBeNull 0x100000 /* Can be null despite NOT NULL constraint */
  11067. /*
  11068. ** These macros can be used to test, set, or clear bits in the
  11069. ** Expr.flags field.
  11070. */
  11071. #define ExprHasProperty(E,P) (((E)->flags&(P))!=0)
  11072. #define ExprHasAllProperty(E,P) (((E)->flags&(P))==(P))
  11073. #define ExprSetProperty(E,P) (E)->flags|=(P)
  11074. #define ExprClearProperty(E,P) (E)->flags&=~(P)
  11075. /* The ExprSetVVAProperty() macro is used for Verification, Validation,
  11076. ** and Accreditation only. It works like ExprSetProperty() during VVA
  11077. ** processes but is a no-op for delivery.
  11078. */
  11079. #ifdef SQLITE_DEBUG
  11080. # define ExprSetVVAProperty(E,P) (E)->flags|=(P)
  11081. #else
  11082. # define ExprSetVVAProperty(E,P)
  11083. #endif
  11084. /*
  11085. ** Macros to determine the number of bytes required by a normal Expr
  11086. ** struct, an Expr struct with the EP_Reduced flag set in Expr.flags
  11087. ** and an Expr struct with the EP_TokenOnly flag set.
  11088. */
  11089. #define EXPR_FULLSIZE sizeof(Expr) /* Full size */
  11090. #define EXPR_REDUCEDSIZE offsetof(Expr,iTable) /* Common features */
  11091. #define EXPR_TOKENONLYSIZE offsetof(Expr,pLeft) /* Fewer features */
  11092. /*
  11093. ** Flags passed to the sqlite3ExprDup() function. See the header comment
  11094. ** above sqlite3ExprDup() for details.
  11095. */
  11096. #define EXPRDUP_REDUCE 0x0001 /* Used reduced-size Expr nodes */
  11097. /*
  11098. ** A list of expressions. Each expression may optionally have a
  11099. ** name. An expr/name combination can be used in several ways, such
  11100. ** as the list of "expr AS ID" fields following a "SELECT" or in the
  11101. ** list of "ID = expr" items in an UPDATE. A list of expressions can
  11102. ** also be used as the argument to a function, in which case the a.zName
  11103. ** field is not used.
  11104. **
  11105. ** By default the Expr.zSpan field holds a human-readable description of
  11106. ** the expression that is used in the generation of error messages and
  11107. ** column labels. In this case, Expr.zSpan is typically the text of a
  11108. ** column expression as it exists in a SELECT statement. However, if
  11109. ** the bSpanIsTab flag is set, then zSpan is overloaded to mean the name
  11110. ** of the result column in the form: DATABASE.TABLE.COLUMN. This later
  11111. ** form is used for name resolution with nested FROM clauses.
  11112. */
  11113. struct ExprList {
  11114. int nExpr; /* Number of expressions on the list */
  11115. struct ExprList_item { /* For each expression in the list */
  11116. Expr *pExpr; /* The list of expressions */
  11117. char *zName; /* Token associated with this expression */
  11118. char *zSpan; /* Original text of the expression */
  11119. u8 sortOrder; /* 1 for DESC or 0 for ASC */
  11120. unsigned done :1; /* A flag to indicate when processing is finished */
  11121. unsigned bSpanIsTab :1; /* zSpan holds DB.TABLE.COLUMN */
  11122. unsigned reusable :1; /* Constant expression is reusable */
  11123. union {
  11124. struct {
  11125. u16 iOrderByCol; /* For ORDER BY, column number in result set */
  11126. u16 iAlias; /* Index into Parse.aAlias[] for zName */
  11127. } x;
  11128. int iConstExprReg; /* Register in which Expr value is cached */
  11129. } u;
  11130. } *a; /* Alloc a power of two greater or equal to nExpr */
  11131. };
  11132. /*
  11133. ** An instance of this structure is used by the parser to record both
  11134. ** the parse tree for an expression and the span of input text for an
  11135. ** expression.
  11136. */
  11137. struct ExprSpan {
  11138. Expr *pExpr; /* The expression parse tree */
  11139. const char *zStart; /* First character of input text */
  11140. const char *zEnd; /* One character past the end of input text */
  11141. };
  11142. /*
  11143. ** An instance of this structure can hold a simple list of identifiers,
  11144. ** such as the list "a,b,c" in the following statements:
  11145. **
  11146. ** INSERT INTO t(a,b,c) VALUES ...;
  11147. ** CREATE INDEX idx ON t(a,b,c);
  11148. ** CREATE TRIGGER trig BEFORE UPDATE ON t(a,b,c) ...;
  11149. **
  11150. ** The IdList.a.idx field is used when the IdList represents the list of
  11151. ** column names after a table name in an INSERT statement. In the statement
  11152. **
  11153. ** INSERT INTO t(a,b,c) ...
  11154. **
  11155. ** If "a" is the k-th column of table "t", then IdList.a[0].idx==k.
  11156. */
  11157. struct IdList {
  11158. struct IdList_item {
  11159. char *zName; /* Name of the identifier */
  11160. int idx; /* Index in some Table.aCol[] of a column named zName */
  11161. } *a;
  11162. int nId; /* Number of identifiers on the list */
  11163. };
  11164. /*
  11165. ** The bitmask datatype defined below is used for various optimizations.
  11166. **
  11167. ** Changing this from a 64-bit to a 32-bit type limits the number of
  11168. ** tables in a join to 32 instead of 64. But it also reduces the size
  11169. ** of the library by 738 bytes on ix86.
  11170. */
  11171. typedef u64 Bitmask;
  11172. /*
  11173. ** The number of bits in a Bitmask. "BMS" means "BitMask Size".
  11174. */
  11175. #define BMS ((int)(sizeof(Bitmask)*8))
  11176. /*
  11177. ** A bit in a Bitmask
  11178. */
  11179. #define MASKBIT(n) (((Bitmask)1)<<(n))
  11180. #define MASKBIT32(n) (((unsigned int)1)<<(n))
  11181. /*
  11182. ** The following structure describes the FROM clause of a SELECT statement.
  11183. ** Each table or subquery in the FROM clause is a separate element of
  11184. ** the SrcList.a[] array.
  11185. **
  11186. ** With the addition of multiple database support, the following structure
  11187. ** can also be used to describe a particular table such as the table that
  11188. ** is modified by an INSERT, DELETE, or UPDATE statement. In standard SQL,
  11189. ** such a table must be a simple name: ID. But in SQLite, the table can
  11190. ** now be identified by a database name, a dot, then the table name: ID.ID.
  11191. **
  11192. ** The jointype starts out showing the join type between the current table
  11193. ** and the next table on the list. The parser builds the list this way.
  11194. ** But sqlite3SrcListShiftJoinType() later shifts the jointypes so that each
  11195. ** jointype expresses the join between the table and the previous table.
  11196. **
  11197. ** In the colUsed field, the high-order bit (bit 63) is set if the table
  11198. ** contains more than 63 columns and the 64-th or later column is used.
  11199. */
  11200. struct SrcList {
  11201. int nSrc; /* Number of tables or subqueries in the FROM clause */
  11202. u32 nAlloc; /* Number of entries allocated in a[] below */
  11203. struct SrcList_item {
  11204. Schema *pSchema; /* Schema to which this item is fixed */
  11205. char *zDatabase; /* Name of database holding this table */
  11206. char *zName; /* Name of the table */
  11207. char *zAlias; /* The "B" part of a "A AS B" phrase. zName is the "A" */
  11208. Table *pTab; /* An SQL table corresponding to zName */
  11209. Select *pSelect; /* A SELECT statement used in place of a table name */
  11210. int addrFillSub; /* Address of subroutine to manifest a subquery */
  11211. int regReturn; /* Register holding return address of addrFillSub */
  11212. int regResult; /* Registers holding results of a co-routine */
  11213. u8 jointype; /* Type of join between this able and the previous */
  11214. unsigned notIndexed :1; /* True if there is a NOT INDEXED clause */
  11215. unsigned isCorrelated :1; /* True if sub-query is correlated */
  11216. unsigned viaCoroutine :1; /* Implemented as a co-routine */
  11217. unsigned isRecursive :1; /* True for recursive reference in WITH */
  11218. #ifndef SQLITE_OMIT_EXPLAIN
  11219. u8 iSelectId; /* If pSelect!=0, the id of the sub-select in EQP */
  11220. #endif
  11221. int iCursor; /* The VDBE cursor number used to access this table */
  11222. Expr *pOn; /* The ON clause of a join */
  11223. IdList *pUsing; /* The USING clause of a join */
  11224. Bitmask colUsed; /* Bit N (1<<N) set if column N of pTab is used */
  11225. char *zIndex; /* Identifier from "INDEXED BY <zIndex>" clause */
  11226. Index *pIndex; /* Index structure corresponding to zIndex, if any */
  11227. } a[1]; /* One entry for each identifier on the list */
  11228. };
  11229. /*
  11230. ** Permitted values of the SrcList.a.jointype field
  11231. */
  11232. #define JT_INNER 0x0001 /* Any kind of inner or cross join */
  11233. #define JT_CROSS 0x0002 /* Explicit use of the CROSS keyword */
  11234. #define JT_NATURAL 0x0004 /* True for a "natural" join */
  11235. #define JT_LEFT 0x0008 /* Left outer join */
  11236. #define JT_RIGHT 0x0010 /* Right outer join */
  11237. #define JT_OUTER 0x0020 /* The "OUTER" keyword is present */
  11238. #define JT_ERROR 0x0040 /* unknown or unsupported join type */
  11239. /*
  11240. ** Flags appropriate for the wctrlFlags parameter of sqlite3WhereBegin()
  11241. ** and the WhereInfo.wctrlFlags member.
  11242. */
  11243. #define WHERE_ORDERBY_NORMAL 0x0000 /* No-op */
  11244. #define WHERE_ORDERBY_MIN 0x0001 /* ORDER BY processing for min() func */
  11245. #define WHERE_ORDERBY_MAX 0x0002 /* ORDER BY processing for max() func */
  11246. #define WHERE_ONEPASS_DESIRED 0x0004 /* Want to do one-pass UPDATE/DELETE */
  11247. #define WHERE_DUPLICATES_OK 0x0008 /* Ok to return a row more than once */
  11248. #define WHERE_OMIT_OPEN_CLOSE 0x0010 /* Table cursors are already open */
  11249. #define WHERE_FORCE_TABLE 0x0020 /* Do not use an index-only search */
  11250. #define WHERE_ONETABLE_ONLY 0x0040 /* Only code the 1st table in pTabList */
  11251. /* 0x0080 // not currently used */
  11252. #define WHERE_GROUPBY 0x0100 /* pOrderBy is really a GROUP BY */
  11253. #define WHERE_DISTINCTBY 0x0200 /* pOrderby is really a DISTINCT clause */
  11254. #define WHERE_WANT_DISTINCT 0x0400 /* All output needs to be distinct */
  11255. #define WHERE_SORTBYGROUP 0x0800 /* Support sqlite3WhereIsSorted() */
  11256. #define WHERE_REOPEN_IDX 0x1000 /* Try to use OP_ReopenIdx */
  11257. /* Allowed return values from sqlite3WhereIsDistinct()
  11258. */
  11259. #define WHERE_DISTINCT_NOOP 0 /* DISTINCT keyword not used */
  11260. #define WHERE_DISTINCT_UNIQUE 1 /* No duplicates */
  11261. #define WHERE_DISTINCT_ORDERED 2 /* All duplicates are adjacent */
  11262. #define WHERE_DISTINCT_UNORDERED 3 /* Duplicates are scattered */
  11263. /*
  11264. ** A NameContext defines a context in which to resolve table and column
  11265. ** names. The context consists of a list of tables (the pSrcList) field and
  11266. ** a list of named expression (pEList). The named expression list may
  11267. ** be NULL. The pSrc corresponds to the FROM clause of a SELECT or
  11268. ** to the table being operated on by INSERT, UPDATE, or DELETE. The
  11269. ** pEList corresponds to the result set of a SELECT and is NULL for
  11270. ** other statements.
  11271. **
  11272. ** NameContexts can be nested. When resolving names, the inner-most
  11273. ** context is searched first. If no match is found, the next outer
  11274. ** context is checked. If there is still no match, the next context
  11275. ** is checked. This process continues until either a match is found
  11276. ** or all contexts are check. When a match is found, the nRef member of
  11277. ** the context containing the match is incremented.
  11278. **
  11279. ** Each subquery gets a new NameContext. The pNext field points to the
  11280. ** NameContext in the parent query. Thus the process of scanning the
  11281. ** NameContext list corresponds to searching through successively outer
  11282. ** subqueries looking for a match.
  11283. */
  11284. struct NameContext {
  11285. Parse *pParse; /* The parser */
  11286. SrcList *pSrcList; /* One or more tables used to resolve names */
  11287. ExprList *pEList; /* Optional list of result-set columns */
  11288. AggInfo *pAggInfo; /* Information about aggregates at this level */
  11289. NameContext *pNext; /* Next outer name context. NULL for outermost */
  11290. int nRef; /* Number of names resolved by this context */
  11291. int nErr; /* Number of errors encountered while resolving names */
  11292. u16 ncFlags; /* Zero or more NC_* flags defined below */
  11293. };
  11294. /*
  11295. ** Allowed values for the NameContext, ncFlags field.
  11296. **
  11297. ** Note: NC_MinMaxAgg must have the same value as SF_MinMaxAgg and
  11298. ** SQLITE_FUNC_MINMAX.
  11299. **
  11300. */
  11301. #define NC_AllowAgg 0x0001 /* Aggregate functions are allowed here */
  11302. #define NC_HasAgg 0x0002 /* One or more aggregate functions seen */
  11303. #define NC_IsCheck 0x0004 /* True if resolving names in a CHECK constraint */
  11304. #define NC_InAggFunc 0x0008 /* True if analyzing arguments to an agg func */
  11305. #define NC_PartIdx 0x0010 /* True if resolving a partial index WHERE */
  11306. #define NC_MinMaxAgg 0x1000 /* min/max aggregates seen. See note above */
  11307. /*
  11308. ** An instance of the following structure contains all information
  11309. ** needed to generate code for a single SELECT statement.
  11310. **
  11311. ** nLimit is set to -1 if there is no LIMIT clause. nOffset is set to 0.
  11312. ** If there is a LIMIT clause, the parser sets nLimit to the value of the
  11313. ** limit and nOffset to the value of the offset (or 0 if there is not
  11314. ** offset). But later on, nLimit and nOffset become the memory locations
  11315. ** in the VDBE that record the limit and offset counters.
  11316. **
  11317. ** addrOpenEphm[] entries contain the address of OP_OpenEphemeral opcodes.
  11318. ** These addresses must be stored so that we can go back and fill in
  11319. ** the P4_KEYINFO and P2 parameters later. Neither the KeyInfo nor
  11320. ** the number of columns in P2 can be computed at the same time
  11321. ** as the OP_OpenEphm instruction is coded because not
  11322. ** enough information about the compound query is known at that point.
  11323. ** The KeyInfo for addrOpenTran[0] and [1] contains collating sequences
  11324. ** for the result set. The KeyInfo for addrOpenEphm[2] contains collating
  11325. ** sequences for the ORDER BY clause.
  11326. */
  11327. struct Select {
  11328. ExprList *pEList; /* The fields of the result */
  11329. u8 op; /* One of: TK_UNION TK_ALL TK_INTERSECT TK_EXCEPT */
  11330. u16 selFlags; /* Various SF_* values */
  11331. int iLimit, iOffset; /* Memory registers holding LIMIT & OFFSET counters */
  11332. #if SELECTTRACE_ENABLED
  11333. char zSelName[12]; /* Symbolic name of this SELECT use for debugging */
  11334. #endif
  11335. int addrOpenEphm[2]; /* OP_OpenEphem opcodes related to this select */
  11336. u64 nSelectRow; /* Estimated number of result rows */
  11337. SrcList *pSrc; /* The FROM clause */
  11338. Expr *pWhere; /* The WHERE clause */
  11339. ExprList *pGroupBy; /* The GROUP BY clause */
  11340. Expr *pHaving; /* The HAVING clause */
  11341. ExprList *pOrderBy; /* The ORDER BY clause */
  11342. Select *pPrior; /* Prior select in a compound select statement */
  11343. Select *pNext; /* Next select to the left in a compound */
  11344. Expr *pLimit; /* LIMIT expression. NULL means not used. */
  11345. Expr *pOffset; /* OFFSET expression. NULL means not used. */
  11346. With *pWith; /* WITH clause attached to this select. Or NULL. */
  11347. };
  11348. /*
  11349. ** Allowed values for Select.selFlags. The "SF" prefix stands for
  11350. ** "Select Flag".
  11351. */
  11352. #define SF_Distinct 0x0001 /* Output should be DISTINCT */
  11353. #define SF_Resolved 0x0002 /* Identifiers have been resolved */
  11354. #define SF_Aggregate 0x0004 /* Contains aggregate functions */
  11355. #define SF_UsesEphemeral 0x0008 /* Uses the OpenEphemeral opcode */
  11356. #define SF_Expanded 0x0010 /* sqlite3SelectExpand() called on this */
  11357. #define SF_HasTypeInfo 0x0020 /* FROM subqueries have Table metadata */
  11358. #define SF_Compound 0x0040 /* Part of a compound query */
  11359. #define SF_Values 0x0080 /* Synthesized from VALUES clause */
  11360. /* 0x0100 NOT USED */
  11361. #define SF_NestedFrom 0x0200 /* Part of a parenthesized FROM clause */
  11362. #define SF_MaybeConvert 0x0400 /* Need convertCompoundSelectToSubquery() */
  11363. #define SF_Recursive 0x0800 /* The recursive part of a recursive CTE */
  11364. #define SF_MinMaxAgg 0x1000 /* Aggregate containing min() or max() */
  11365. /*
  11366. ** The results of a SELECT can be distributed in several ways, as defined
  11367. ** by one of the following macros. The "SRT" prefix means "SELECT Result
  11368. ** Type".
  11369. **
  11370. ** SRT_Union Store results as a key in a temporary index
  11371. ** identified by pDest->iSDParm.
  11372. **
  11373. ** SRT_Except Remove results from the temporary index pDest->iSDParm.
  11374. **
  11375. ** SRT_Exists Store a 1 in memory cell pDest->iSDParm if the result
  11376. ** set is not empty.
  11377. **
  11378. ** SRT_Discard Throw the results away. This is used by SELECT
  11379. ** statements within triggers whose only purpose is
  11380. ** the side-effects of functions.
  11381. **
  11382. ** All of the above are free to ignore their ORDER BY clause. Those that
  11383. ** follow must honor the ORDER BY clause.
  11384. **
  11385. ** SRT_Output Generate a row of output (using the OP_ResultRow
  11386. ** opcode) for each row in the result set.
  11387. **
  11388. ** SRT_Mem Only valid if the result is a single column.
  11389. ** Store the first column of the first result row
  11390. ** in register pDest->iSDParm then abandon the rest
  11391. ** of the query. This destination implies "LIMIT 1".
  11392. **
  11393. ** SRT_Set The result must be a single column. Store each
  11394. ** row of result as the key in table pDest->iSDParm.
  11395. ** Apply the affinity pDest->affSdst before storing
  11396. ** results. Used to implement "IN (SELECT ...)".
  11397. **
  11398. ** SRT_EphemTab Create an temporary table pDest->iSDParm and store
  11399. ** the result there. The cursor is left open after
  11400. ** returning. This is like SRT_Table except that
  11401. ** this destination uses OP_OpenEphemeral to create
  11402. ** the table first.
  11403. **
  11404. ** SRT_Coroutine Generate a co-routine that returns a new row of
  11405. ** results each time it is invoked. The entry point
  11406. ** of the co-routine is stored in register pDest->iSDParm
  11407. ** and the result row is stored in pDest->nDest registers
  11408. ** starting with pDest->iSdst.
  11409. **
  11410. ** SRT_Table Store results in temporary table pDest->iSDParm.
  11411. ** SRT_Fifo This is like SRT_EphemTab except that the table
  11412. ** is assumed to already be open. SRT_Fifo has
  11413. ** the additional property of being able to ignore
  11414. ** the ORDER BY clause.
  11415. **
  11416. ** SRT_DistFifo Store results in a temporary table pDest->iSDParm.
  11417. ** But also use temporary table pDest->iSDParm+1 as
  11418. ** a record of all prior results and ignore any duplicate
  11419. ** rows. Name means: "Distinct Fifo".
  11420. **
  11421. ** SRT_Queue Store results in priority queue pDest->iSDParm (really
  11422. ** an index). Append a sequence number so that all entries
  11423. ** are distinct.
  11424. **
  11425. ** SRT_DistQueue Store results in priority queue pDest->iSDParm only if
  11426. ** the same record has never been stored before. The
  11427. ** index at pDest->iSDParm+1 hold all prior stores.
  11428. */
  11429. #define SRT_Union 1 /* Store result as keys in an index */
  11430. #define SRT_Except 2 /* Remove result from a UNION index */
  11431. #define SRT_Exists 3 /* Store 1 if the result is not empty */
  11432. #define SRT_Discard 4 /* Do not save the results anywhere */
  11433. #define SRT_Fifo 5 /* Store result as data with an automatic rowid */
  11434. #define SRT_DistFifo 6 /* Like SRT_Fifo, but unique results only */
  11435. #define SRT_Queue 7 /* Store result in an queue */
  11436. #define SRT_DistQueue 8 /* Like SRT_Queue, but unique results only */
  11437. /* The ORDER BY clause is ignored for all of the above */
  11438. #define IgnorableOrderby(X) ((X->eDest)<=SRT_DistQueue)
  11439. #define SRT_Output 9 /* Output each row of result */
  11440. #define SRT_Mem 10 /* Store result in a memory cell */
  11441. #define SRT_Set 11 /* Store results as keys in an index */
  11442. #define SRT_EphemTab 12 /* Create transient tab and store like SRT_Table */
  11443. #define SRT_Coroutine 13 /* Generate a single row of result */
  11444. #define SRT_Table 14 /* Store result as data with an automatic rowid */
  11445. /*
  11446. ** An instance of this object describes where to put of the results of
  11447. ** a SELECT statement.
  11448. */
  11449. struct SelectDest {
  11450. u8 eDest; /* How to dispose of the results. On of SRT_* above. */
  11451. char affSdst; /* Affinity used when eDest==SRT_Set */
  11452. int iSDParm; /* A parameter used by the eDest disposal method */
  11453. int iSdst; /* Base register where results are written */
  11454. int nSdst; /* Number of registers allocated */
  11455. ExprList *pOrderBy; /* Key columns for SRT_Queue and SRT_DistQueue */
  11456. };
  11457. /*
  11458. ** During code generation of statements that do inserts into AUTOINCREMENT
  11459. ** tables, the following information is attached to the Table.u.autoInc.p
  11460. ** pointer of each autoincrement table to record some side information that
  11461. ** the code generator needs. We have to keep per-table autoincrement
  11462. ** information in case inserts are down within triggers. Triggers do not
  11463. ** normally coordinate their activities, but we do need to coordinate the
  11464. ** loading and saving of autoincrement information.
  11465. */
  11466. struct AutoincInfo {
  11467. AutoincInfo *pNext; /* Next info block in a list of them all */
  11468. Table *pTab; /* Table this info block refers to */
  11469. int iDb; /* Index in sqlite3.aDb[] of database holding pTab */
  11470. int regCtr; /* Memory register holding the rowid counter */
  11471. };
  11472. /*
  11473. ** Size of the column cache
  11474. */
  11475. #ifndef SQLITE_N_COLCACHE
  11476. # define SQLITE_N_COLCACHE 10
  11477. #endif
  11478. /*
  11479. ** At least one instance of the following structure is created for each
  11480. ** trigger that may be fired while parsing an INSERT, UPDATE or DELETE
  11481. ** statement. All such objects are stored in the linked list headed at
  11482. ** Parse.pTriggerPrg and deleted once statement compilation has been
  11483. ** completed.
  11484. **
  11485. ** A Vdbe sub-program that implements the body and WHEN clause of trigger
  11486. ** TriggerPrg.pTrigger, assuming a default ON CONFLICT clause of
  11487. ** TriggerPrg.orconf, is stored in the TriggerPrg.pProgram variable.
  11488. ** The Parse.pTriggerPrg list never contains two entries with the same
  11489. ** values for both pTrigger and orconf.
  11490. **
  11491. ** The TriggerPrg.aColmask[0] variable is set to a mask of old.* columns
  11492. ** accessed (or set to 0 for triggers fired as a result of INSERT
  11493. ** statements). Similarly, the TriggerPrg.aColmask[1] variable is set to
  11494. ** a mask of new.* columns used by the program.
  11495. */
  11496. struct TriggerPrg {
  11497. Trigger *pTrigger; /* Trigger this program was coded from */
  11498. TriggerPrg *pNext; /* Next entry in Parse.pTriggerPrg list */
  11499. SubProgram *pProgram; /* Program implementing pTrigger/orconf */
  11500. int orconf; /* Default ON CONFLICT policy */
  11501. u32 aColmask[2]; /* Masks of old.*, new.* columns accessed */
  11502. };
  11503. /*
  11504. ** The yDbMask datatype for the bitmask of all attached databases.
  11505. */
  11506. #if SQLITE_MAX_ATTACHED>30
  11507. typedef unsigned char yDbMask[(SQLITE_MAX_ATTACHED+9)/8];
  11508. # define DbMaskTest(M,I) (((M)[(I)/8]&(1<<((I)&7)))!=0)
  11509. # define DbMaskZero(M) memset((M),0,sizeof(M))
  11510. # define DbMaskSet(M,I) (M)[(I)/8]|=(1<<((I)&7))
  11511. # define DbMaskAllZero(M) sqlite3DbMaskAllZero(M)
  11512. # define DbMaskNonZero(M) (sqlite3DbMaskAllZero(M)==0)
  11513. #else
  11514. typedef unsigned int yDbMask;
  11515. # define DbMaskTest(M,I) (((M)&(((yDbMask)1)<<(I)))!=0)
  11516. # define DbMaskZero(M) (M)=0
  11517. # define DbMaskSet(M,I) (M)|=(((yDbMask)1)<<(I))
  11518. # define DbMaskAllZero(M) (M)==0
  11519. # define DbMaskNonZero(M) (M)!=0
  11520. #endif
  11521. /*
  11522. ** An SQL parser context. A copy of this structure is passed through
  11523. ** the parser and down into all the parser action routine in order to
  11524. ** carry around information that is global to the entire parse.
  11525. **
  11526. ** The structure is divided into two parts. When the parser and code
  11527. ** generate call themselves recursively, the first part of the structure
  11528. ** is constant but the second part is reset at the beginning and end of
  11529. ** each recursion.
  11530. **
  11531. ** The nTableLock and aTableLock variables are only used if the shared-cache
  11532. ** feature is enabled (if sqlite3Tsd()->useSharedData is true). They are
  11533. ** used to store the set of table-locks required by the statement being
  11534. ** compiled. Function sqlite3TableLock() is used to add entries to the
  11535. ** list.
  11536. */
  11537. struct Parse {
  11538. sqlite3 *db; /* The main database structure */
  11539. char *zErrMsg; /* An error message */
  11540. Vdbe *pVdbe; /* An engine for executing database bytecode */
  11541. int rc; /* Return code from execution */
  11542. u8 colNamesSet; /* TRUE after OP_ColumnName has been issued to pVdbe */
  11543. u8 checkSchema; /* Causes schema cookie check after an error */
  11544. u8 nested; /* Number of nested calls to the parser/code generator */
  11545. u8 nTempReg; /* Number of temporary registers in aTempReg[] */
  11546. u8 isMultiWrite; /* True if statement may modify/insert multiple rows */
  11547. u8 mayAbort; /* True if statement may throw an ABORT exception */
  11548. u8 hasCompound; /* Need to invoke convertCompoundSelectToSubquery() */
  11549. u8 okConstFactor; /* OK to factor out constants */
  11550. int aTempReg[8]; /* Holding area for temporary registers */
  11551. int nRangeReg; /* Size of the temporary register block */
  11552. int iRangeReg; /* First register in temporary register block */
  11553. int nErr; /* Number of errors seen */
  11554. int nTab; /* Number of previously allocated VDBE cursors */
  11555. int nMem; /* Number of memory cells used so far */
  11556. int nSet; /* Number of sets used so far */
  11557. int nOnce; /* Number of OP_Once instructions so far */
  11558. int nOpAlloc; /* Number of slots allocated for Vdbe.aOp[] */
  11559. int iFixedOp; /* Never back out opcodes iFixedOp-1 or earlier */
  11560. int ckBase; /* Base register of data during check constraints */
  11561. int iPartIdxTab; /* Table corresponding to a partial index */
  11562. int iCacheLevel; /* ColCache valid when aColCache[].iLevel<=iCacheLevel */
  11563. int iCacheCnt; /* Counter used to generate aColCache[].lru values */
  11564. int nLabel; /* Number of labels used */
  11565. int *aLabel; /* Space to hold the labels */
  11566. struct yColCache {
  11567. int iTable; /* Table cursor number */
  11568. i16 iColumn; /* Table column number */
  11569. u8 tempReg; /* iReg is a temp register that needs to be freed */
  11570. int iLevel; /* Nesting level */
  11571. int iReg; /* Reg with value of this column. 0 means none. */
  11572. int lru; /* Least recently used entry has the smallest value */
  11573. } aColCache[SQLITE_N_COLCACHE]; /* One for each column cache entry */
  11574. ExprList *pConstExpr;/* Constant expressions */
  11575. Token constraintName;/* Name of the constraint currently being parsed */
  11576. yDbMask writeMask; /* Start a write transaction on these databases */
  11577. yDbMask cookieMask; /* Bitmask of schema verified databases */
  11578. int cookieValue[SQLITE_MAX_ATTACHED+2]; /* Values of cookies to verify */
  11579. int regRowid; /* Register holding rowid of CREATE TABLE entry */
  11580. int regRoot; /* Register holding root page number for new objects */
  11581. int nMaxArg; /* Max args passed to user function by sub-program */
  11582. #if SELECTTRACE_ENABLED
  11583. int nSelect; /* Number of SELECT statements seen */
  11584. int nSelectIndent; /* How far to indent SELECTTRACE() output */
  11585. #endif
  11586. #ifndef SQLITE_OMIT_SHARED_CACHE
  11587. int nTableLock; /* Number of locks in aTableLock */
  11588. TableLock *aTableLock; /* Required table locks for shared-cache mode */
  11589. #endif
  11590. AutoincInfo *pAinc; /* Information about AUTOINCREMENT counters */
  11591. /* Information used while coding trigger programs. */
  11592. Parse *pToplevel; /* Parse structure for main program (or NULL) */
  11593. Table *pTriggerTab; /* Table triggers are being coded for */
  11594. int addrCrTab; /* Address of OP_CreateTable opcode on CREATE TABLE */
  11595. int addrSkipPK; /* Address of instruction to skip PRIMARY KEY index */
  11596. u32 nQueryLoop; /* Est number of iterations of a query (10*log2(N)) */
  11597. u32 oldmask; /* Mask of old.* columns referenced */
  11598. u32 newmask; /* Mask of new.* columns referenced */
  11599. u8 eTriggerOp; /* TK_UPDATE, TK_INSERT or TK_DELETE */
  11600. u8 eOrconf; /* Default ON CONFLICT policy for trigger steps */
  11601. u8 disableTriggers; /* True to disable triggers */
  11602. /************************************************************************
  11603. ** Above is constant between recursions. Below is reset before and after
  11604. ** each recursion. The boundary between these two regions is determined
  11605. ** using offsetof(Parse,nVar) so the nVar field must be the first field
  11606. ** in the recursive region.
  11607. ************************************************************************/
  11608. int nVar; /* Number of '?' variables seen in the SQL so far */
  11609. int nzVar; /* Number of available slots in azVar[] */
  11610. u8 iPkSortOrder; /* ASC or DESC for INTEGER PRIMARY KEY */
  11611. u8 bFreeWith; /* True if pWith should be freed with parser */
  11612. u8 explain; /* True if the EXPLAIN flag is found on the query */
  11613. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11614. u8 declareVtab; /* True if inside sqlite3_declare_vtab() */
  11615. int nVtabLock; /* Number of virtual tables to lock */
  11616. #endif
  11617. int nAlias; /* Number of aliased result set columns */
  11618. int nHeight; /* Expression tree height of current sub-select */
  11619. #ifndef SQLITE_OMIT_EXPLAIN
  11620. int iSelectId; /* ID of current select for EXPLAIN output */
  11621. int iNextSelectId; /* Next available select ID for EXPLAIN output */
  11622. #endif
  11623. char **azVar; /* Pointers to names of parameters */
  11624. Vdbe *pReprepare; /* VM being reprepared (sqlite3Reprepare()) */
  11625. const char *zTail; /* All SQL text past the last semicolon parsed */
  11626. Table *pNewTable; /* A table being constructed by CREATE TABLE */
  11627. Trigger *pNewTrigger; /* Trigger under construct by a CREATE TRIGGER */
  11628. const char *zAuthContext; /* The 6th parameter to db->xAuth callbacks */
  11629. Token sNameToken; /* Token with unqualified schema object name */
  11630. Token sLastToken; /* The last token parsed */
  11631. #ifndef SQLITE_OMIT_VIRTUALTABLE
  11632. Token sArg; /* Complete text of a module argument */
  11633. Table **apVtabLock; /* Pointer to virtual tables needing locking */
  11634. #endif
  11635. Table *pZombieTab; /* List of Table objects to delete after code gen */
  11636. TriggerPrg *pTriggerPrg; /* Linked list of coded triggers */
  11637. With *pWith; /* Current WITH clause, or NULL */
  11638. };
  11639. /*
  11640. ** Return true if currently inside an sqlite3_declare_vtab() call.
  11641. */
  11642. #ifdef SQLITE_OMIT_VIRTUALTABLE
  11643. #define IN_DECLARE_VTAB 0
  11644. #else
  11645. #define IN_DECLARE_VTAB (pParse->declareVtab)
  11646. #endif
  11647. /*
  11648. ** An instance of the following structure can be declared on a stack and used
  11649. ** to save the Parse.zAuthContext value so that it can be restored later.
  11650. */
  11651. struct AuthContext {
  11652. const char *zAuthContext; /* Put saved Parse.zAuthContext here */
  11653. Parse *pParse; /* The Parse structure */
  11654. };
  11655. /*
  11656. ** Bitfield flags for P5 value in various opcodes.
  11657. */
  11658. #define OPFLAG_NCHANGE 0x01 /* Set to update db->nChange */
  11659. #define OPFLAG_EPHEM 0x01 /* OP_Column: Ephemeral output is ok */
  11660. #define OPFLAG_LASTROWID 0x02 /* Set to update db->lastRowid */
  11661. #define OPFLAG_ISUPDATE 0x04 /* This OP_Insert is an sql UPDATE */
  11662. #define OPFLAG_APPEND 0x08 /* This is likely to be an append */
  11663. #define OPFLAG_USESEEKRESULT 0x10 /* Try to avoid a seek in BtreeInsert() */
  11664. #define OPFLAG_LENGTHARG 0x40 /* OP_Column only used for length() */
  11665. #define OPFLAG_TYPEOFARG 0x80 /* OP_Column only used for typeof() */
  11666. #define OPFLAG_BULKCSR 0x01 /* OP_Open** used to open bulk cursor */
  11667. #define OPFLAG_P2ISREG 0x02 /* P2 to OP_Open** is a register number */
  11668. #define OPFLAG_PERMUTE 0x01 /* OP_Compare: use the permutation */
  11669. /*
  11670. * Each trigger present in the database schema is stored as an instance of
  11671. * struct Trigger.
  11672. *
  11673. * Pointers to instances of struct Trigger are stored in two ways.
  11674. * 1. In the "trigHash" hash table (part of the sqlite3* that represents the
  11675. * database). This allows Trigger structures to be retrieved by name.
  11676. * 2. All triggers associated with a single table form a linked list, using the
  11677. * pNext member of struct Trigger. A pointer to the first element of the
  11678. * linked list is stored as the "pTrigger" member of the associated
  11679. * struct Table.
  11680. *
  11681. * The "step_list" member points to the first element of a linked list
  11682. * containing the SQL statements specified as the trigger program.
  11683. */
  11684. struct Trigger {
  11685. char *zName; /* The name of the trigger */
  11686. char *table; /* The table or view to which the trigger applies */
  11687. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT */
  11688. u8 tr_tm; /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  11689. Expr *pWhen; /* The WHEN clause of the expression (may be NULL) */
  11690. IdList *pColumns; /* If this is an UPDATE OF <column-list> trigger,
  11691. the <column-list> is stored here */
  11692. Schema *pSchema; /* Schema containing the trigger */
  11693. Schema *pTabSchema; /* Schema containing the table */
  11694. TriggerStep *step_list; /* Link list of trigger program steps */
  11695. Trigger *pNext; /* Next trigger associated with the table */
  11696. };
  11697. /*
  11698. ** A trigger is either a BEFORE or an AFTER trigger. The following constants
  11699. ** determine which.
  11700. **
  11701. ** If there are multiple triggers, you might of some BEFORE and some AFTER.
  11702. ** In that cases, the constants below can be ORed together.
  11703. */
  11704. #define TRIGGER_BEFORE 1
  11705. #define TRIGGER_AFTER 2
  11706. /*
  11707. * An instance of struct TriggerStep is used to store a single SQL statement
  11708. * that is a part of a trigger-program.
  11709. *
  11710. * Instances of struct TriggerStep are stored in a singly linked list (linked
  11711. * using the "pNext" member) referenced by the "step_list" member of the
  11712. * associated struct Trigger instance. The first element of the linked list is
  11713. * the first step of the trigger-program.
  11714. *
  11715. * The "op" member indicates whether this is a "DELETE", "INSERT", "UPDATE" or
  11716. * "SELECT" statement. The meanings of the other members is determined by the
  11717. * value of "op" as follows:
  11718. *
  11719. * (op == TK_INSERT)
  11720. * orconf -> stores the ON CONFLICT algorithm
  11721. * pSelect -> If this is an INSERT INTO ... SELECT ... statement, then
  11722. * this stores a pointer to the SELECT statement. Otherwise NULL.
  11723. * target -> A token holding the quoted name of the table to insert into.
  11724. * pExprList -> If this is an INSERT INTO ... VALUES ... statement, then
  11725. * this stores values to be inserted. Otherwise NULL.
  11726. * pIdList -> If this is an INSERT INTO ... (<column-names>) VALUES ...
  11727. * statement, then this stores the column-names to be
  11728. * inserted into.
  11729. *
  11730. * (op == TK_DELETE)
  11731. * target -> A token holding the quoted name of the table to delete from.
  11732. * pWhere -> The WHERE clause of the DELETE statement if one is specified.
  11733. * Otherwise NULL.
  11734. *
  11735. * (op == TK_UPDATE)
  11736. * target -> A token holding the quoted name of the table to update rows of.
  11737. * pWhere -> The WHERE clause of the UPDATE statement if one is specified.
  11738. * Otherwise NULL.
  11739. * pExprList -> A list of the columns to update and the expressions to update
  11740. * them to. See sqlite3Update() documentation of "pChanges"
  11741. * argument.
  11742. *
  11743. */
  11744. struct TriggerStep {
  11745. u8 op; /* One of TK_DELETE, TK_UPDATE, TK_INSERT, TK_SELECT */
  11746. u8 orconf; /* OE_Rollback etc. */
  11747. Trigger *pTrig; /* The trigger that this step is a part of */
  11748. Select *pSelect; /* SELECT statment or RHS of INSERT INTO .. SELECT ... */
  11749. Token target; /* Target table for DELETE, UPDATE, INSERT */
  11750. Expr *pWhere; /* The WHERE clause for DELETE or UPDATE steps */
  11751. ExprList *pExprList; /* SET clause for UPDATE. */
  11752. IdList *pIdList; /* Column names for INSERT */
  11753. TriggerStep *pNext; /* Next in the link-list */
  11754. TriggerStep *pLast; /* Last element in link-list. Valid for 1st elem only */
  11755. };
  11756. /*
  11757. ** The following structure contains information used by the sqliteFix...
  11758. ** routines as they walk the parse tree to make database references
  11759. ** explicit.
  11760. */
  11761. typedef struct DbFixer DbFixer;
  11762. struct DbFixer {
  11763. Parse *pParse; /* The parsing context. Error messages written here */
  11764. Schema *pSchema; /* Fix items to this schema */
  11765. int bVarOnly; /* Check for variable references only */
  11766. const char *zDb; /* Make sure all objects are contained in this database */
  11767. const char *zType; /* Type of the container - used for error messages */
  11768. const Token *pName; /* Name of the container - used for error messages */
  11769. };
  11770. /*
  11771. ** An objected used to accumulate the text of a string where we
  11772. ** do not necessarily know how big the string will be in the end.
  11773. */
  11774. struct StrAccum {
  11775. sqlite3 *db; /* Optional database for lookaside. Can be NULL */
  11776. char *zBase; /* A base allocation. Not from malloc. */
  11777. char *zText; /* The string collected so far */
  11778. int nChar; /* Length of the string so far */
  11779. int nAlloc; /* Amount of space allocated in zText */
  11780. int mxAlloc; /* Maximum allowed string length */
  11781. u8 useMalloc; /* 0: none, 1: sqlite3DbMalloc, 2: sqlite3_malloc */
  11782. u8 accError; /* STRACCUM_NOMEM or STRACCUM_TOOBIG */
  11783. };
  11784. #define STRACCUM_NOMEM 1
  11785. #define STRACCUM_TOOBIG 2
  11786. /*
  11787. ** A pointer to this structure is used to communicate information
  11788. ** from sqlite3Init and OP_ParseSchema into the sqlite3InitCallback.
  11789. */
  11790. typedef struct {
  11791. sqlite3 *db; /* The database being initialized */
  11792. char **pzErrMsg; /* Error message stored here */
  11793. int iDb; /* 0 for main database. 1 for TEMP, 2.. for ATTACHed */
  11794. int rc; /* Result code stored here */
  11795. } InitData;
  11796. /*
  11797. ** Structure containing global configuration data for the SQLite library.
  11798. **
  11799. ** This structure also contains some state information.
  11800. */
  11801. struct Sqlite3Config {
  11802. int bMemstat; /* True to enable memory status */
  11803. int bCoreMutex; /* True to enable core mutexing */
  11804. int bFullMutex; /* True to enable full mutexing */
  11805. int bOpenUri; /* True to interpret filenames as URIs */
  11806. int bUseCis; /* Use covering indices for full-scans */
  11807. int mxStrlen; /* Maximum string length */
  11808. int neverCorrupt; /* Database is always well-formed */
  11809. int szLookaside; /* Default lookaside buffer size */
  11810. int nLookaside; /* Default lookaside buffer count */
  11811. sqlite3_mem_methods m; /* Low-level memory allocation interface */
  11812. sqlite3_mutex_methods mutex; /* Low-level mutex interface */
  11813. sqlite3_pcache_methods2 pcache2; /* Low-level page-cache interface */
  11814. void *pHeap; /* Heap storage space */
  11815. int nHeap; /* Size of pHeap[] */
  11816. int mnReq, mxReq; /* Min and max heap requests sizes */
  11817. sqlite3_int64 szMmap; /* mmap() space per open file */
  11818. sqlite3_int64 mxMmap; /* Maximum value for szMmap */
  11819. void *pScratch; /* Scratch memory */
  11820. int szScratch; /* Size of each scratch buffer */
  11821. int nScratch; /* Number of scratch buffers */
  11822. void *pPage; /* Page cache memory */
  11823. int szPage; /* Size of each page in pPage[] */
  11824. int nPage; /* Number of pages in pPage[] */
  11825. int mxParserStack; /* maximum depth of the parser stack */
  11826. int sharedCacheEnabled; /* true if shared-cache mode enabled */
  11827. /* The above might be initialized to non-zero. The following need to always
  11828. ** initially be zero, however. */
  11829. int isInit; /* True after initialization has finished */
  11830. int inProgress; /* True while initialization in progress */
  11831. int isMutexInit; /* True after mutexes are initialized */
  11832. int isMallocInit; /* True after malloc is initialized */
  11833. int isPCacheInit; /* True after malloc is initialized */
  11834. int nRefInitMutex; /* Number of users of pInitMutex */
  11835. sqlite3_mutex *pInitMutex; /* Mutex used by sqlite3_initialize() */
  11836. void (*xLog)(void*,int,const char*); /* Function for logging */
  11837. void *pLogArg; /* First argument to xLog() */
  11838. #ifdef SQLITE_ENABLE_SQLLOG
  11839. void(*xSqllog)(void*,sqlite3*,const char*, int);
  11840. void *pSqllogArg;
  11841. #endif
  11842. #ifdef SQLITE_VDBE_COVERAGE
  11843. /* The following callback (if not NULL) is invoked on every VDBE branch
  11844. ** operation. Set the callback using SQLITE_TESTCTRL_VDBE_COVERAGE.
  11845. */
  11846. void (*xVdbeBranch)(void*,int iSrcLine,u8 eThis,u8 eMx); /* Callback */
  11847. void *pVdbeBranchArg; /* 1st argument */
  11848. #endif
  11849. #ifndef SQLITE_OMIT_BUILTIN_TEST
  11850. int (*xTestCallback)(int); /* Invoked by sqlite3FaultSim() */
  11851. #endif
  11852. int bLocaltimeFault; /* True to fail localtime() calls */
  11853. };
  11854. /*
  11855. ** This macro is used inside of assert() statements to indicate that
  11856. ** the assert is only valid on a well-formed database. Instead of:
  11857. **
  11858. ** assert( X );
  11859. **
  11860. ** One writes:
  11861. **
  11862. ** assert( X || CORRUPT_DB );
  11863. **
  11864. ** CORRUPT_DB is true during normal operation. CORRUPT_DB does not indicate
  11865. ** that the database is definitely corrupt, only that it might be corrupt.
  11866. ** For most test cases, CORRUPT_DB is set to false using a special
  11867. ** sqlite3_test_control(). This enables assert() statements to prove
  11868. ** things that are always true for well-formed databases.
  11869. */
  11870. #define CORRUPT_DB (sqlite3Config.neverCorrupt==0)
  11871. /*
  11872. ** Context pointer passed down through the tree-walk.
  11873. */
  11874. struct Walker {
  11875. int (*xExprCallback)(Walker*, Expr*); /* Callback for expressions */
  11876. int (*xSelectCallback)(Walker*,Select*); /* Callback for SELECTs */
  11877. void (*xSelectCallback2)(Walker*,Select*);/* Second callback for SELECTs */
  11878. Parse *pParse; /* Parser context. */
  11879. int walkerDepth; /* Number of subqueries */
  11880. union { /* Extra data for callback */
  11881. NameContext *pNC; /* Naming context */
  11882. int i; /* Integer value */
  11883. SrcList *pSrcList; /* FROM clause */
  11884. struct SrcCount *pSrcCount; /* Counting column references */
  11885. } u;
  11886. };
  11887. /* Forward declarations */
  11888. SQLITE_PRIVATE int sqlite3WalkExpr(Walker*, Expr*);
  11889. SQLITE_PRIVATE int sqlite3WalkExprList(Walker*, ExprList*);
  11890. SQLITE_PRIVATE int sqlite3WalkSelect(Walker*, Select*);
  11891. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker*, Select*);
  11892. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker*, Select*);
  11893. /*
  11894. ** Return code from the parse-tree walking primitives and their
  11895. ** callbacks.
  11896. */
  11897. #define WRC_Continue 0 /* Continue down into children */
  11898. #define WRC_Prune 1 /* Omit children but continue walking siblings */
  11899. #define WRC_Abort 2 /* Abandon the tree walk */
  11900. /*
  11901. ** An instance of this structure represents a set of one or more CTEs
  11902. ** (common table expressions) created by a single WITH clause.
  11903. */
  11904. struct With {
  11905. int nCte; /* Number of CTEs in the WITH clause */
  11906. With *pOuter; /* Containing WITH clause, or NULL */
  11907. struct Cte { /* For each CTE in the WITH clause.... */
  11908. char *zName; /* Name of this CTE */
  11909. ExprList *pCols; /* List of explicit column names, or NULL */
  11910. Select *pSelect; /* The definition of this CTE */
  11911. const char *zErr; /* Error message for circular references */
  11912. } a[1];
  11913. };
  11914. #ifdef SQLITE_DEBUG
  11915. /*
  11916. ** An instance of the TreeView object is used for printing the content of
  11917. ** data structures on sqlite3DebugPrintf() using a tree-like view.
  11918. */
  11919. struct TreeView {
  11920. int iLevel; /* Which level of the tree we are on */
  11921. u8 bLine[100]; /* Draw vertical in column i if bLine[i] is true */
  11922. };
  11923. #endif /* SQLITE_DEBUG */
  11924. /*
  11925. ** Assuming zIn points to the first byte of a UTF-8 character,
  11926. ** advance zIn to point to the first byte of the next UTF-8 character.
  11927. */
  11928. #define SQLITE_SKIP_UTF8(zIn) { \
  11929. if( (*(zIn++))>=0xc0 ){ \
  11930. while( (*zIn & 0xc0)==0x80 ){ zIn++; } \
  11931. } \
  11932. }
  11933. /*
  11934. ** The SQLITE_*_BKPT macros are substitutes for the error codes with
  11935. ** the same name but without the _BKPT suffix. These macros invoke
  11936. ** routines that report the line-number on which the error originated
  11937. ** using sqlite3_log(). The routines also provide a convenient place
  11938. ** to set a debugger breakpoint.
  11939. */
  11940. SQLITE_PRIVATE int sqlite3CorruptError(int);
  11941. SQLITE_PRIVATE int sqlite3MisuseError(int);
  11942. SQLITE_PRIVATE int sqlite3CantopenError(int);
  11943. #define SQLITE_CORRUPT_BKPT sqlite3CorruptError(__LINE__)
  11944. #define SQLITE_MISUSE_BKPT sqlite3MisuseError(__LINE__)
  11945. #define SQLITE_CANTOPEN_BKPT sqlite3CantopenError(__LINE__)
  11946. /*
  11947. ** FTS4 is really an extension for FTS3. It is enabled using the
  11948. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also call
  11949. ** the SQLITE_ENABLE_FTS4 macro to serve as an alias for SQLITE_ENABLE_FTS3.
  11950. */
  11951. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  11952. # define SQLITE_ENABLE_FTS3
  11953. #endif
  11954. /*
  11955. ** The ctype.h header is needed for non-ASCII systems. It is also
  11956. ** needed by FTS3 when FTS3 is included in the amalgamation.
  11957. */
  11958. #if !defined(SQLITE_ASCII) || \
  11959. (defined(SQLITE_ENABLE_FTS3) && defined(SQLITE_AMALGAMATION))
  11960. # include <ctype.h>
  11961. #endif
  11962. /*
  11963. ** The following macros mimic the standard library functions toupper(),
  11964. ** isspace(), isalnum(), isdigit() and isxdigit(), respectively. The
  11965. ** sqlite versions only work for ASCII characters, regardless of locale.
  11966. */
  11967. #ifdef SQLITE_ASCII
  11968. # define sqlite3Toupper(x) ((x)&~(sqlite3CtypeMap[(unsigned char)(x)]&0x20))
  11969. # define sqlite3Isspace(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x01)
  11970. # define sqlite3Isalnum(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x06)
  11971. # define sqlite3Isalpha(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x02)
  11972. # define sqlite3Isdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x04)
  11973. # define sqlite3Isxdigit(x) (sqlite3CtypeMap[(unsigned char)(x)]&0x08)
  11974. # define sqlite3Tolower(x) (sqlite3UpperToLower[(unsigned char)(x)])
  11975. #else
  11976. # define sqlite3Toupper(x) toupper((unsigned char)(x))
  11977. # define sqlite3Isspace(x) isspace((unsigned char)(x))
  11978. # define sqlite3Isalnum(x) isalnum((unsigned char)(x))
  11979. # define sqlite3Isalpha(x) isalpha((unsigned char)(x))
  11980. # define sqlite3Isdigit(x) isdigit((unsigned char)(x))
  11981. # define sqlite3Isxdigit(x) isxdigit((unsigned char)(x))
  11982. # define sqlite3Tolower(x) tolower((unsigned char)(x))
  11983. #endif
  11984. SQLITE_PRIVATE int sqlite3IsIdChar(u8);
  11985. /*
  11986. ** Internal function prototypes
  11987. */
  11988. #define sqlite3StrICmp sqlite3_stricmp
  11989. SQLITE_PRIVATE int sqlite3Strlen30(const char*);
  11990. #define sqlite3StrNICmp sqlite3_strnicmp
  11991. SQLITE_PRIVATE int sqlite3MallocInit(void);
  11992. SQLITE_PRIVATE void sqlite3MallocEnd(void);
  11993. SQLITE_PRIVATE void *sqlite3Malloc(u64);
  11994. SQLITE_PRIVATE void *sqlite3MallocZero(u64);
  11995. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3*, u64);
  11996. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3*, u64);
  11997. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3*,const char*);
  11998. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3*,const char*, u64);
  11999. SQLITE_PRIVATE void *sqlite3Realloc(void*, u64);
  12000. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *, void *, u64);
  12001. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *, void *, u64);
  12002. SQLITE_PRIVATE void sqlite3DbFree(sqlite3*, void*);
  12003. SQLITE_PRIVATE int sqlite3MallocSize(void*);
  12004. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3*, void*);
  12005. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int);
  12006. SQLITE_PRIVATE void sqlite3ScratchFree(void*);
  12007. SQLITE_PRIVATE void *sqlite3PageMalloc(int);
  12008. SQLITE_PRIVATE void sqlite3PageFree(void*);
  12009. SQLITE_PRIVATE void sqlite3MemSetDefault(void);
  12010. SQLITE_PRIVATE void sqlite3BenignMallocHooks(void (*)(void), void (*)(void));
  12011. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void);
  12012. /*
  12013. ** On systems with ample stack space and that support alloca(), make
  12014. ** use of alloca() to obtain space for large automatic objects. By default,
  12015. ** obtain space from malloc().
  12016. **
  12017. ** The alloca() routine never returns NULL. This will cause code paths
  12018. ** that deal with sqlite3StackAlloc() failures to be unreachable.
  12019. */
  12020. #ifdef SQLITE_USE_ALLOCA
  12021. # define sqlite3StackAllocRaw(D,N) alloca(N)
  12022. # define sqlite3StackAllocZero(D,N) memset(alloca(N), 0, N)
  12023. # define sqlite3StackFree(D,P)
  12024. #else
  12025. # define sqlite3StackAllocRaw(D,N) sqlite3DbMallocRaw(D,N)
  12026. # define sqlite3StackAllocZero(D,N) sqlite3DbMallocZero(D,N)
  12027. # define sqlite3StackFree(D,P) sqlite3DbFree(D,P)
  12028. #endif
  12029. #ifdef SQLITE_ENABLE_MEMSYS3
  12030. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void);
  12031. #endif
  12032. #ifdef SQLITE_ENABLE_MEMSYS5
  12033. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void);
  12034. #endif
  12035. #ifndef SQLITE_MUTEX_OMIT
  12036. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void);
  12037. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void);
  12038. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int);
  12039. SQLITE_PRIVATE int sqlite3MutexInit(void);
  12040. SQLITE_PRIVATE int sqlite3MutexEnd(void);
  12041. #endif
  12042. SQLITE_PRIVATE int sqlite3StatusValue(int);
  12043. SQLITE_PRIVATE void sqlite3StatusAdd(int, int);
  12044. SQLITE_PRIVATE void sqlite3StatusSet(int, int);
  12045. #ifndef SQLITE_OMIT_FLOATING_POINT
  12046. SQLITE_PRIVATE int sqlite3IsNaN(double);
  12047. #else
  12048. # define sqlite3IsNaN(X) 0
  12049. #endif
  12050. /*
  12051. ** An instance of the following structure holds information about SQL
  12052. ** functions arguments that are the parameters to the printf() function.
  12053. */
  12054. struct PrintfArguments {
  12055. int nArg; /* Total number of arguments */
  12056. int nUsed; /* Number of arguments used so far */
  12057. sqlite3_value **apArg; /* The argument values */
  12058. };
  12059. #define SQLITE_PRINTF_INTERNAL 0x01
  12060. #define SQLITE_PRINTF_SQLFUNC 0x02
  12061. SQLITE_PRIVATE void sqlite3VXPrintf(StrAccum*, u32, const char*, va_list);
  12062. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum*, u32, const char*, ...);
  12063. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3*,const char*, ...);
  12064. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3*,const char*, va_list);
  12065. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3*,char*,const char*,...);
  12066. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  12067. SQLITE_PRIVATE void sqlite3DebugPrintf(const char*, ...);
  12068. #endif
  12069. #if defined(SQLITE_TEST)
  12070. SQLITE_PRIVATE void *sqlite3TestTextToPtr(const char*);
  12071. #endif
  12072. #if defined(SQLITE_DEBUG)
  12073. SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView*,u8);
  12074. SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView*);
  12075. SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView*, const char*, ...);
  12076. SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView*, const char*, u8);
  12077. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView*, const Expr*, u8);
  12078. SQLITE_PRIVATE void sqlite3TreeViewExprList(TreeView*, const ExprList*, u8, const char*);
  12079. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView*, const Select*, u8);
  12080. #endif
  12081. SQLITE_PRIVATE void sqlite3SetString(char **, sqlite3*, const char*, ...);
  12082. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse*, const char*, ...);
  12083. SQLITE_PRIVATE int sqlite3Dequote(char*);
  12084. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char*, int);
  12085. SQLITE_PRIVATE int sqlite3RunParser(Parse*, const char*, char **);
  12086. SQLITE_PRIVATE void sqlite3FinishCoding(Parse*);
  12087. SQLITE_PRIVATE int sqlite3GetTempReg(Parse*);
  12088. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse*,int);
  12089. SQLITE_PRIVATE int sqlite3GetTempRange(Parse*,int);
  12090. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse*,int,int);
  12091. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse*);
  12092. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(sqlite3*,int,const Token*,int);
  12093. SQLITE_PRIVATE Expr *sqlite3Expr(sqlite3*,int,const char*);
  12094. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(sqlite3*,Expr*,Expr*,Expr*);
  12095. SQLITE_PRIVATE Expr *sqlite3PExpr(Parse*, int, Expr*, Expr*, const Token*);
  12096. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3*,Expr*, Expr*);
  12097. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse*,ExprList*, Token*);
  12098. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse*, Expr*);
  12099. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3*, Expr*);
  12100. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(Parse*,ExprList*,Expr*);
  12101. SQLITE_PRIVATE void sqlite3ExprListSetName(Parse*,ExprList*,Token*,int);
  12102. SQLITE_PRIVATE void sqlite3ExprListSetSpan(Parse*,ExprList*,ExprSpan*);
  12103. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3*, ExprList*);
  12104. SQLITE_PRIVATE int sqlite3Init(sqlite3*, char**);
  12105. SQLITE_PRIVATE int sqlite3InitCallback(void*, int, char**, char**);
  12106. SQLITE_PRIVATE void sqlite3Pragma(Parse*,Token*,Token*,Token*,int);
  12107. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3*);
  12108. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3*,int);
  12109. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3*);
  12110. SQLITE_PRIVATE void sqlite3BeginParse(Parse*,int);
  12111. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3*);
  12112. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse*,Select*);
  12113. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *, int);
  12114. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table*);
  12115. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index*, i16);
  12116. SQLITE_PRIVATE void sqlite3StartTable(Parse*,Token*,Token*,int,int,int,int);
  12117. SQLITE_PRIVATE void sqlite3AddColumn(Parse*,Token*);
  12118. SQLITE_PRIVATE void sqlite3AddNotNull(Parse*, int);
  12119. SQLITE_PRIVATE void sqlite3AddPrimaryKey(Parse*, ExprList*, int, int, int);
  12120. SQLITE_PRIVATE void sqlite3AddCheckConstraint(Parse*, Expr*);
  12121. SQLITE_PRIVATE void sqlite3AddColumnType(Parse*,Token*);
  12122. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse*,ExprSpan*);
  12123. SQLITE_PRIVATE void sqlite3AddCollateType(Parse*, Token*);
  12124. SQLITE_PRIVATE void sqlite3EndTable(Parse*,Token*,Token*,u8,Select*);
  12125. SQLITE_PRIVATE int sqlite3ParseUri(const char*,const char*,unsigned int*,
  12126. sqlite3_vfs**,char**,char **);
  12127. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3*,const char*);
  12128. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *);
  12129. #ifdef SQLITE_OMIT_BUILTIN_TEST
  12130. # define sqlite3FaultSim(X) SQLITE_OK
  12131. #else
  12132. SQLITE_PRIVATE int sqlite3FaultSim(int);
  12133. #endif
  12134. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32);
  12135. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec*, u32);
  12136. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec*, u32);
  12137. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec*, u32, void*);
  12138. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec*);
  12139. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec*);
  12140. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int,int*);
  12141. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3*, void*, unsigned int);
  12142. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet*);
  12143. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet*, i64);
  12144. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet*, int iBatch, i64);
  12145. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet*, i64*);
  12146. SQLITE_PRIVATE void sqlite3CreateView(Parse*,Token*,Token*,Token*,Select*,int,int);
  12147. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  12148. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse*,Table*);
  12149. #else
  12150. # define sqlite3ViewGetColumnNames(A,B) 0
  12151. #endif
  12152. #if SQLITE_MAX_ATTACHED>30
  12153. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask);
  12154. #endif
  12155. SQLITE_PRIVATE void sqlite3DropTable(Parse*, SrcList*, int, int);
  12156. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse*, Table*, int, int);
  12157. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3*, Table*);
  12158. #ifndef SQLITE_OMIT_AUTOINCREMENT
  12159. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse);
  12160. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse);
  12161. #else
  12162. # define sqlite3AutoincrementBegin(X)
  12163. # define sqlite3AutoincrementEnd(X)
  12164. #endif
  12165. SQLITE_PRIVATE void sqlite3Insert(Parse*, SrcList*, Select*, IdList*, int);
  12166. SQLITE_PRIVATE void *sqlite3ArrayAllocate(sqlite3*,void*,int,int*,int*);
  12167. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3*, IdList*, Token*);
  12168. SQLITE_PRIVATE int sqlite3IdListIndex(IdList*,const char*);
  12169. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(sqlite3*, SrcList*, int, int);
  12170. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(sqlite3*, SrcList*, Token*, Token*);
  12171. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(Parse*, SrcList*, Token*, Token*,
  12172. Token*, Select*, Expr*, IdList*);
  12173. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *, SrcList *, Token *);
  12174. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *, struct SrcList_item *);
  12175. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList*);
  12176. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse*, SrcList*);
  12177. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3*, IdList*);
  12178. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3*, SrcList*);
  12179. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(sqlite3*,i16,int,char**);
  12180. SQLITE_PRIVATE Index *sqlite3CreateIndex(Parse*,Token*,Token*,SrcList*,ExprList*,int,Token*,
  12181. Expr*, int, int);
  12182. SQLITE_PRIVATE void sqlite3DropIndex(Parse*, SrcList*, int);
  12183. SQLITE_PRIVATE int sqlite3Select(Parse*, Select*, SelectDest*);
  12184. SQLITE_PRIVATE Select *sqlite3SelectNew(Parse*,ExprList*,SrcList*,Expr*,ExprList*,
  12185. Expr*,ExprList*,u16,Expr*,Expr*);
  12186. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3*, Select*);
  12187. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse*, SrcList*);
  12188. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse*, Table*, int);
  12189. SQLITE_PRIVATE void sqlite3OpenTable(Parse*, int iCur, int iDb, Table*, int);
  12190. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  12191. SQLITE_PRIVATE Expr *sqlite3LimitWhere(Parse*,SrcList*,Expr*,ExprList*,Expr*,Expr*,char*);
  12192. #endif
  12193. SQLITE_PRIVATE void sqlite3DeleteFrom(Parse*, SrcList*, Expr*);
  12194. SQLITE_PRIVATE void sqlite3Update(Parse*, SrcList*, ExprList*, Expr*, int);
  12195. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(Parse*,SrcList*,Expr*,ExprList*,ExprList*,u16,int);
  12196. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo*);
  12197. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo*);
  12198. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo*);
  12199. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo*);
  12200. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo*);
  12201. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo*);
  12202. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo*);
  12203. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo*, int*);
  12204. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(Parse*, Table*, int, int, int, u8);
  12205. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(Vdbe*, Table*, int, int, int);
  12206. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse*, int, int, int);
  12207. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse*, int, int, int);
  12208. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse*);
  12209. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse*);
  12210. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse*, int, int);
  12211. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse*);
  12212. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse*, int, int);
  12213. SQLITE_PRIVATE void sqlite3ExprCode(Parse*, Expr*, int);
  12214. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse*, Expr*, int);
  12215. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(Parse*, Expr*, int, u8);
  12216. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse*, Expr*, int*);
  12217. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse*, Expr*, int);
  12218. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse*, Expr*, int);
  12219. SQLITE_PRIVATE int sqlite3ExprCodeExprList(Parse*, ExprList*, int, u8);
  12220. #define SQLITE_ECEL_DUP 0x01 /* Deep, not shallow copies */
  12221. #define SQLITE_ECEL_FACTOR 0x02 /* Factor out constant terms */
  12222. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse*, Expr*, int, int);
  12223. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse*, Expr*, int, int);
  12224. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3*,const char*, const char*);
  12225. SQLITE_PRIVATE Table *sqlite3LocateTable(Parse*,int isView,const char*, const char*);
  12226. SQLITE_PRIVATE Table *sqlite3LocateTableItem(Parse*,int isView,struct SrcList_item *);
  12227. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3*,const char*, const char*);
  12228. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3*,int,const char*);
  12229. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3*,int,const char*);
  12230. SQLITE_PRIVATE void sqlite3Vacuum(Parse*);
  12231. SQLITE_PRIVATE int sqlite3RunVacuum(char**, sqlite3*);
  12232. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3*, Token*);
  12233. SQLITE_PRIVATE int sqlite3ExprCompare(Expr*, Expr*, int);
  12234. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList*, ExprList*, int);
  12235. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr*, Expr*, int);
  12236. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext*, Expr*);
  12237. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext*,ExprList*);
  12238. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr*, SrcList*);
  12239. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse*);
  12240. SQLITE_PRIVATE void sqlite3PrngSaveState(void);
  12241. SQLITE_PRIVATE void sqlite3PrngRestoreState(void);
  12242. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3*,int);
  12243. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse*, int);
  12244. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse*, const char *zDb);
  12245. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse*, int);
  12246. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse*);
  12247. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse*);
  12248. SQLITE_PRIVATE void sqlite3Savepoint(Parse*, int, Token*);
  12249. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *);
  12250. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3*);
  12251. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr*);
  12252. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr*);
  12253. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr*, u8);
  12254. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr*, int*);
  12255. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr*);
  12256. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr*, char);
  12257. SQLITE_PRIVATE int sqlite3IsRowid(const char*);
  12258. SQLITE_PRIVATE void sqlite3GenerateRowDelete(Parse*,Table*,Trigger*,int,int,int,i16,u8,u8,u8);
  12259. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(Parse*, Table*, int, int, int*);
  12260. SQLITE_PRIVATE int sqlite3GenerateIndexKey(Parse*, Index*, int, int, int, int*,Index*,int);
  12261. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse*,int);
  12262. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(Parse*,Table*,int*,int,int,int,int,
  12263. u8,u8,int,int*);
  12264. SQLITE_PRIVATE void sqlite3CompleteInsertion(Parse*,Table*,int,int,int,int*,int,int,int);
  12265. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(Parse*, Table*, int, int, u8*, int*, int*);
  12266. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse*, int, int);
  12267. SQLITE_PRIVATE void sqlite3MultiWrite(Parse*);
  12268. SQLITE_PRIVATE void sqlite3MayAbort(Parse*);
  12269. SQLITE_PRIVATE void sqlite3HaltConstraint(Parse*, int, int, char*, i8, u8);
  12270. SQLITE_PRIVATE void sqlite3UniqueConstraint(Parse*, int, Index*);
  12271. SQLITE_PRIVATE void sqlite3RowidConstraint(Parse*, int, Table*);
  12272. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3*,Expr*,int);
  12273. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3*,ExprList*,int);
  12274. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3*,SrcList*,int);
  12275. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3*,IdList*);
  12276. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3*,Select*,int);
  12277. #if SELECTTRACE_ENABLED
  12278. SQLITE_PRIVATE void sqlite3SelectSetName(Select*,const char*);
  12279. #else
  12280. # define sqlite3SelectSetName(A,B)
  12281. #endif
  12282. SQLITE_PRIVATE void sqlite3FuncDefInsert(FuncDefHash*, FuncDef*);
  12283. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(sqlite3*,const char*,int,int,u8,u8);
  12284. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3*);
  12285. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void);
  12286. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void);
  12287. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3*);
  12288. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3*);
  12289. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse*, int);
  12290. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  12291. SQLITE_PRIVATE void sqlite3MaterializeView(Parse*, Table*, Expr*, int);
  12292. #endif
  12293. #ifndef SQLITE_OMIT_TRIGGER
  12294. SQLITE_PRIVATE void sqlite3BeginTrigger(Parse*, Token*,Token*,int,int,IdList*,SrcList*,
  12295. Expr*,int, int);
  12296. SQLITE_PRIVATE void sqlite3FinishTrigger(Parse*, TriggerStep*, Token*);
  12297. SQLITE_PRIVATE void sqlite3DropTrigger(Parse*, SrcList*, int);
  12298. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse*, Trigger*);
  12299. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(Parse *, Table*, int, ExprList*, int *pMask);
  12300. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *, Table *);
  12301. SQLITE_PRIVATE void sqlite3CodeRowTrigger(Parse*, Trigger *, int, ExprList*, int, Table *,
  12302. int, int, int);
  12303. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(Parse *, Trigger *, Table *, int, int, int);
  12304. void sqliteViewTriggers(Parse*, Table*, Expr*, int, ExprList*);
  12305. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3*, TriggerStep*);
  12306. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3*,Select*);
  12307. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(sqlite3*,Token*, IdList*,
  12308. Select*,u8);
  12309. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(sqlite3*,Token*,ExprList*, Expr*, u8);
  12310. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(sqlite3*,Token*, Expr*);
  12311. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3*, Trigger*);
  12312. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3*,int,const char*);
  12313. SQLITE_PRIVATE u32 sqlite3TriggerColmask(Parse*,Trigger*,ExprList*,int,int,Table*,int);
  12314. # define sqlite3ParseToplevel(p) ((p)->pToplevel ? (p)->pToplevel : (p))
  12315. #else
  12316. # define sqlite3TriggersExist(B,C,D,E,F) 0
  12317. # define sqlite3DeleteTrigger(A,B)
  12318. # define sqlite3DropTriggerPtr(A,B)
  12319. # define sqlite3UnlinkAndDeleteTrigger(A,B,C)
  12320. # define sqlite3CodeRowTrigger(A,B,C,D,E,F,G,H,I)
  12321. # define sqlite3CodeRowTriggerDirect(A,B,C,D,E,F)
  12322. # define sqlite3TriggerList(X, Y) 0
  12323. # define sqlite3ParseToplevel(p) p
  12324. # define sqlite3TriggerColmask(A,B,C,D,E,F,G) 0
  12325. #endif
  12326. SQLITE_PRIVATE int sqlite3JoinType(Parse*, Token*, Token*, Token*);
  12327. SQLITE_PRIVATE void sqlite3CreateForeignKey(Parse*, ExprList*, Token*, ExprList*, int);
  12328. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse*, int);
  12329. #ifndef SQLITE_OMIT_AUTHORIZATION
  12330. SQLITE_PRIVATE void sqlite3AuthRead(Parse*,Expr*,Schema*,SrcList*);
  12331. SQLITE_PRIVATE int sqlite3AuthCheck(Parse*,int, const char*, const char*, const char*);
  12332. SQLITE_PRIVATE void sqlite3AuthContextPush(Parse*, AuthContext*, const char*);
  12333. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext*);
  12334. SQLITE_PRIVATE int sqlite3AuthReadCol(Parse*, const char *, const char *, int);
  12335. #else
  12336. # define sqlite3AuthRead(a,b,c,d)
  12337. # define sqlite3AuthCheck(a,b,c,d,e) SQLITE_OK
  12338. # define sqlite3AuthContextPush(a,b,c)
  12339. # define sqlite3AuthContextPop(a) ((void)(a))
  12340. #endif
  12341. SQLITE_PRIVATE void sqlite3Attach(Parse*, Expr*, Expr*, Expr*);
  12342. SQLITE_PRIVATE void sqlite3Detach(Parse*, Expr*);
  12343. SQLITE_PRIVATE void sqlite3FixInit(DbFixer*, Parse*, int, const char*, const Token*);
  12344. SQLITE_PRIVATE int sqlite3FixSrcList(DbFixer*, SrcList*);
  12345. SQLITE_PRIVATE int sqlite3FixSelect(DbFixer*, Select*);
  12346. SQLITE_PRIVATE int sqlite3FixExpr(DbFixer*, Expr*);
  12347. SQLITE_PRIVATE int sqlite3FixExprList(DbFixer*, ExprList*);
  12348. SQLITE_PRIVATE int sqlite3FixTriggerStep(DbFixer*, TriggerStep*);
  12349. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double*, int, u8);
  12350. SQLITE_PRIVATE int sqlite3GetInt32(const char *, int*);
  12351. SQLITE_PRIVATE int sqlite3Atoi(const char*);
  12352. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *pData, int nChar);
  12353. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *pData, int nByte);
  12354. SQLITE_PRIVATE u32 sqlite3Utf8Read(const u8**);
  12355. SQLITE_PRIVATE LogEst sqlite3LogEst(u64);
  12356. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst,LogEst);
  12357. #ifndef SQLITE_OMIT_VIRTUALTABLE
  12358. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double);
  12359. #endif
  12360. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst);
  12361. /*
  12362. ** Routines to read and write variable-length integers. These used to
  12363. ** be defined locally, but now we use the varint routines in the util.c
  12364. ** file.
  12365. */
  12366. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char*, u64);
  12367. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *, u64 *);
  12368. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *, u32 *);
  12369. SQLITE_PRIVATE int sqlite3VarintLen(u64 v);
  12370. /*
  12371. ** The common case is for a varint to be a single byte. They following
  12372. ** macros handle the common case without a procedure call, but then call
  12373. ** the procedure for larger varints.
  12374. */
  12375. #define getVarint32(A,B) \
  12376. (u8)((*(A)<(u8)0x80)?((B)=(u32)*(A)),1:sqlite3GetVarint32((A),(u32 *)&(B)))
  12377. #define putVarint32(A,B) \
  12378. (u8)(((u32)(B)<(u32)0x80)?(*(A)=(unsigned char)(B)),1:\
  12379. sqlite3PutVarint((A),(B)))
  12380. #define getVarint sqlite3GetVarint
  12381. #define putVarint sqlite3PutVarint
  12382. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *, Index *);
  12383. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe*, Table*, int);
  12384. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2);
  12385. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity);
  12386. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr);
  12387. SQLITE_PRIVATE int sqlite3Atoi64(const char*, i64*, int, u8);
  12388. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char*, i64*);
  12389. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3*, int, const char*,...);
  12390. SQLITE_PRIVATE void sqlite3Error(sqlite3*,int);
  12391. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3*, const char *z, int n);
  12392. SQLITE_PRIVATE u8 sqlite3HexToInt(int h);
  12393. SQLITE_PRIVATE int sqlite3TwoPartName(Parse *, Token *, Token *, Token **);
  12394. #if defined(SQLITE_TEST)
  12395. SQLITE_PRIVATE const char *sqlite3ErrName(int);
  12396. #endif
  12397. SQLITE_PRIVATE const char *sqlite3ErrStr(int);
  12398. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse);
  12399. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(sqlite3*,u8 enc, const char*,int);
  12400. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char*zName);
  12401. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr);
  12402. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(Parse *pParse, Expr*, const Token*);
  12403. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse*,Expr*,const char*);
  12404. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr*);
  12405. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *, CollSeq *);
  12406. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *, const char *);
  12407. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *, int);
  12408. SQLITE_PRIVATE int sqlite3AddInt64(i64*,i64);
  12409. SQLITE_PRIVATE int sqlite3SubInt64(i64*,i64);
  12410. SQLITE_PRIVATE int sqlite3MulInt64(i64*,i64);
  12411. SQLITE_PRIVATE int sqlite3AbsInt32(int);
  12412. #ifdef SQLITE_ENABLE_8_3_NAMES
  12413. SQLITE_PRIVATE void sqlite3FileSuffix3(const char*, char*);
  12414. #else
  12415. # define sqlite3FileSuffix3(X,Y)
  12416. #endif
  12417. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z,u8);
  12418. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value*, u8);
  12419. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value*, u8);
  12420. SQLITE_PRIVATE void sqlite3ValueSetStr(sqlite3_value*, int, const void *,u8,
  12421. void(*)(void*));
  12422. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value*);
  12423. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value*);
  12424. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *);
  12425. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *, const void*, int, u8);
  12426. SQLITE_PRIVATE int sqlite3ValueFromExpr(sqlite3 *, Expr *, u8, u8, sqlite3_value **);
  12427. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(sqlite3_value *, u8, u8);
  12428. #ifndef SQLITE_AMALGAMATION
  12429. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[];
  12430. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[];
  12431. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[];
  12432. SQLITE_PRIVATE const Token sqlite3IntTokens[];
  12433. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config;
  12434. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12435. #ifndef SQLITE_OMIT_WSD
  12436. SQLITE_PRIVATE int sqlite3PendingByte;
  12437. #endif
  12438. #endif
  12439. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3*, int, int, int);
  12440. SQLITE_PRIVATE void sqlite3Reindex(Parse*, Token*, Token*);
  12441. SQLITE_PRIVATE void sqlite3AlterFunctions(void);
  12442. SQLITE_PRIVATE void sqlite3AlterRenameTable(Parse*, SrcList*, Token*);
  12443. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *, int *);
  12444. SQLITE_PRIVATE void sqlite3NestedParse(Parse*, const char*, ...);
  12445. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3*);
  12446. SQLITE_PRIVATE int sqlite3CodeSubselect(Parse *, Expr *, int, int);
  12447. SQLITE_PRIVATE void sqlite3SelectPrep(Parse*, Select*, NameContext*);
  12448. SQLITE_PRIVATE int sqlite3MatchSpanName(const char*, const char*, const char*, const char*);
  12449. SQLITE_PRIVATE int sqlite3ResolveExprNames(NameContext*, Expr*);
  12450. SQLITE_PRIVATE void sqlite3ResolveSelectNames(Parse*, Select*, NameContext*);
  12451. SQLITE_PRIVATE void sqlite3ResolveSelfReference(Parse*,Table*,int,Expr*,ExprList*);
  12452. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(Parse*, Select*, ExprList*, const char*);
  12453. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *, Table *, int, int);
  12454. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *, Token *);
  12455. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *, SrcList *);
  12456. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(Parse*, u8, CollSeq *, const char*);
  12457. SQLITE_PRIVATE char sqlite3AffinityType(const char*, u8*);
  12458. SQLITE_PRIVATE void sqlite3Analyze(Parse*, Token*, Token*);
  12459. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler*);
  12460. SQLITE_PRIVATE int sqlite3FindDb(sqlite3*, Token*);
  12461. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *, const char *);
  12462. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3*,int iDB);
  12463. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3*,Index*);
  12464. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index*);
  12465. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3*, int);
  12466. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3*,Expr*,int*,char*);
  12467. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse*, int, int);
  12468. SQLITE_PRIVATE void sqlite3SchemaClear(void *);
  12469. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *, Btree *);
  12470. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *);
  12471. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3*,int,int);
  12472. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo*);
  12473. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo*);
  12474. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse*, Index*);
  12475. #ifdef SQLITE_DEBUG
  12476. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo*);
  12477. #endif
  12478. SQLITE_PRIVATE int sqlite3CreateFunc(sqlite3 *, const char *, int, int, void *,
  12479. void (*)(sqlite3_context*,int,sqlite3_value **),
  12480. void (*)(sqlite3_context*,int,sqlite3_value **), void (*)(sqlite3_context*),
  12481. FuncDestructor *pDestructor
  12482. );
  12483. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3 *db, int);
  12484. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *);
  12485. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum*, char*, int, int);
  12486. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum*,const char*,int);
  12487. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum*,const char*);
  12488. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum*,int,char);
  12489. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum*);
  12490. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum*);
  12491. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest*,int,int);
  12492. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *, SrcList *, int, int);
  12493. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *);
  12494. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *, Pgno, const u8 *);
  12495. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  12496. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void);
  12497. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(Parse*,Index*,UnpackedRecord**,Expr*,u8,int,int*);
  12498. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(Parse*, Expr*, u8, sqlite3_value**);
  12499. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord*);
  12500. SQLITE_PRIVATE int sqlite3Stat4Column(sqlite3*, const void*, int, int, sqlite3_value**);
  12501. #endif
  12502. /*
  12503. ** The interface to the LEMON-generated parser
  12504. */
  12505. SQLITE_PRIVATE void *sqlite3ParserAlloc(void*(*)(u64));
  12506. SQLITE_PRIVATE void sqlite3ParserFree(void*, void(*)(void*));
  12507. SQLITE_PRIVATE void sqlite3Parser(void*, int, Token, Parse*);
  12508. #ifdef YYTRACKMAXSTACKDEPTH
  12509. SQLITE_PRIVATE int sqlite3ParserStackPeak(void*);
  12510. #endif
  12511. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3*);
  12512. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  12513. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3*);
  12514. #else
  12515. # define sqlite3CloseExtensions(X)
  12516. #endif
  12517. #ifndef SQLITE_OMIT_SHARED_CACHE
  12518. SQLITE_PRIVATE void sqlite3TableLock(Parse *, int, int, u8, const char *);
  12519. #else
  12520. #define sqlite3TableLock(v,w,x,y,z)
  12521. #endif
  12522. #ifdef SQLITE_TEST
  12523. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char*);
  12524. #endif
  12525. #ifdef SQLITE_OMIT_VIRTUALTABLE
  12526. # define sqlite3VtabClear(Y)
  12527. # define sqlite3VtabSync(X,Y) SQLITE_OK
  12528. # define sqlite3VtabRollback(X)
  12529. # define sqlite3VtabCommit(X)
  12530. # define sqlite3VtabInSync(db) 0
  12531. # define sqlite3VtabLock(X)
  12532. # define sqlite3VtabUnlock(X)
  12533. # define sqlite3VtabUnlockList(X)
  12534. # define sqlite3VtabSavepoint(X, Y, Z) SQLITE_OK
  12535. # define sqlite3GetVTable(X,Y) ((VTable*)0)
  12536. #else
  12537. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table*);
  12538. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p);
  12539. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe*);
  12540. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db);
  12541. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db);
  12542. SQLITE_PRIVATE void sqlite3VtabLock(VTable *);
  12543. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *);
  12544. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3*);
  12545. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *, int, int);
  12546. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe*, sqlite3_vtab*);
  12547. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3*, Table*);
  12548. # define sqlite3VtabInSync(db) ((db)->nVTrans>0 && (db)->aVTrans==0)
  12549. #endif
  12550. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse*,Table*);
  12551. SQLITE_PRIVATE void sqlite3VtabBeginParse(Parse*, Token*, Token*, Token*, int);
  12552. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse*, Token*);
  12553. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse*);
  12554. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse*, Token*);
  12555. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3*, int, const char *, char **);
  12556. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse*, Table*);
  12557. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3*, int, const char *);
  12558. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *, VTable *);
  12559. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(sqlite3 *,FuncDef*, int nArg, Expr*);
  12560. SQLITE_PRIVATE void sqlite3InvalidFunction(sqlite3_context*,int,sqlite3_value**);
  12561. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context*);
  12562. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe*, const char*, int);
  12563. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *, sqlite3_stmt *);
  12564. SQLITE_PRIVATE void sqlite3ParserReset(Parse*);
  12565. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe*);
  12566. SQLITE_PRIVATE void sqlite3ExprListCheckLength(Parse*, ExprList*, const char*);
  12567. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(Parse *, Expr *, Expr *);
  12568. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3*);
  12569. SQLITE_PRIVATE const char *sqlite3JournalModename(int);
  12570. #ifndef SQLITE_OMIT_WAL
  12571. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3*, int, int, int*, int*);
  12572. SQLITE_PRIVATE int sqlite3WalDefaultHook(void*,sqlite3*,const char*,int);
  12573. #endif
  12574. #ifndef SQLITE_OMIT_CTE
  12575. SQLITE_PRIVATE With *sqlite3WithAdd(Parse*,With*,Token*,ExprList*,Select*);
  12576. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3*,With*);
  12577. SQLITE_PRIVATE void sqlite3WithPush(Parse*, With*, u8);
  12578. #else
  12579. #define sqlite3WithPush(x,y,z)
  12580. #define sqlite3WithDelete(x,y)
  12581. #endif
  12582. /* Declarations for functions in fkey.c. All of these are replaced by
  12583. ** no-op macros if OMIT_FOREIGN_KEY is defined. In this case no foreign
  12584. ** key functionality is available. If OMIT_TRIGGER is defined but
  12585. ** OMIT_FOREIGN_KEY is not, only some of the functions are no-oped. In
  12586. ** this case foreign keys are parsed, but no other functionality is
  12587. ** provided (enforcement of FK constraints requires the triggers sub-system).
  12588. */
  12589. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  12590. SQLITE_PRIVATE void sqlite3FkCheck(Parse*, Table*, int, int, int*, int);
  12591. SQLITE_PRIVATE void sqlite3FkDropTable(Parse*, SrcList *, Table*);
  12592. SQLITE_PRIVATE void sqlite3FkActions(Parse*, Table*, ExprList*, int, int*, int);
  12593. SQLITE_PRIVATE int sqlite3FkRequired(Parse*, Table*, int*, int);
  12594. SQLITE_PRIVATE u32 sqlite3FkOldmask(Parse*, Table*);
  12595. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *);
  12596. #else
  12597. #define sqlite3FkActions(a,b,c,d,e,f)
  12598. #define sqlite3FkCheck(a,b,c,d,e,f)
  12599. #define sqlite3FkDropTable(a,b,c)
  12600. #define sqlite3FkOldmask(a,b) 0
  12601. #define sqlite3FkRequired(a,b,c,d) 0
  12602. #endif
  12603. #ifndef SQLITE_OMIT_FOREIGN_KEY
  12604. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *, Table*);
  12605. SQLITE_PRIVATE int sqlite3FkLocateIndex(Parse*,Table*,FKey*,Index**,int**);
  12606. #else
  12607. #define sqlite3FkDelete(a,b)
  12608. #define sqlite3FkLocateIndex(a,b,c,d,e)
  12609. #endif
  12610. /*
  12611. ** Available fault injectors. Should be numbered beginning with 0.
  12612. */
  12613. #define SQLITE_FAULTINJECTOR_MALLOC 0
  12614. #define SQLITE_FAULTINJECTOR_COUNT 1
  12615. /*
  12616. ** The interface to the code in fault.c used for identifying "benign"
  12617. ** malloc failures. This is only present if SQLITE_OMIT_BUILTIN_TEST
  12618. ** is not defined.
  12619. */
  12620. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12621. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void);
  12622. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void);
  12623. #else
  12624. #define sqlite3BeginBenignMalloc()
  12625. #define sqlite3EndBenignMalloc()
  12626. #endif
  12627. /*
  12628. ** Allowed return values from sqlite3FindInIndex()
  12629. */
  12630. #define IN_INDEX_ROWID 1 /* Search the rowid of the table */
  12631. #define IN_INDEX_EPH 2 /* Search an ephemeral b-tree */
  12632. #define IN_INDEX_INDEX_ASC 3 /* Existing index ASCENDING */
  12633. #define IN_INDEX_INDEX_DESC 4 /* Existing index DESCENDING */
  12634. #define IN_INDEX_NOOP 5 /* No table available. Use comparisons */
  12635. /*
  12636. ** Allowed flags for the 3rd parameter to sqlite3FindInIndex().
  12637. */
  12638. #define IN_INDEX_NOOP_OK 0x0001 /* OK to return IN_INDEX_NOOP */
  12639. #define IN_INDEX_MEMBERSHIP 0x0002 /* IN operator used for membership test */
  12640. #define IN_INDEX_LOOP 0x0004 /* IN operator used as a loop */
  12641. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *, Expr *, u32, int*);
  12642. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  12643. SQLITE_PRIVATE int sqlite3JournalOpen(sqlite3_vfs *, const char *, sqlite3_file *, int, int);
  12644. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *);
  12645. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *);
  12646. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p);
  12647. #else
  12648. #define sqlite3JournalSize(pVfs) ((pVfs)->szOsFile)
  12649. #define sqlite3JournalExists(p) 1
  12650. #endif
  12651. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *);
  12652. SQLITE_PRIVATE int sqlite3MemJournalSize(void);
  12653. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *);
  12654. #if SQLITE_MAX_EXPR_DEPTH>0
  12655. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p);
  12656. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *);
  12657. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse*, int);
  12658. #else
  12659. #define sqlite3ExprSetHeight(x,y)
  12660. #define sqlite3SelectExprHeight(x) 0
  12661. #define sqlite3ExprCheckHeight(x,y)
  12662. #endif
  12663. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8*);
  12664. SQLITE_PRIVATE void sqlite3Put4byte(u8*, u32);
  12665. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  12666. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *, sqlite3 *);
  12667. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db);
  12668. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db);
  12669. #else
  12670. #define sqlite3ConnectionBlocked(x,y)
  12671. #define sqlite3ConnectionUnlocked(x)
  12672. #define sqlite3ConnectionClosed(x)
  12673. #endif
  12674. #ifdef SQLITE_DEBUG
  12675. SQLITE_PRIVATE void sqlite3ParserTrace(FILE*, char *);
  12676. #endif
  12677. /*
  12678. ** If the SQLITE_ENABLE IOTRACE exists then the global variable
  12679. ** sqlite3IoTrace is a pointer to a printf-like routine used to
  12680. ** print I/O tracing messages.
  12681. */
  12682. #ifdef SQLITE_ENABLE_IOTRACE
  12683. # define IOTRACE(A) if( sqlite3IoTrace ){ sqlite3IoTrace A; }
  12684. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe*);
  12685. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*,...);
  12686. #else
  12687. # define IOTRACE(A)
  12688. # define sqlite3VdbeIOTraceSql(X)
  12689. #endif
  12690. /*
  12691. ** These routines are available for the mem2.c debugging memory allocator
  12692. ** only. They are used to verify that different "types" of memory
  12693. ** allocations are properly tracked by the system.
  12694. **
  12695. ** sqlite3MemdebugSetType() sets the "type" of an allocation to one of
  12696. ** the MEMTYPE_* macros defined below. The type must be a bitmask with
  12697. ** a single bit set.
  12698. **
  12699. ** sqlite3MemdebugHasType() returns true if any of the bits in its second
  12700. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12701. ** sqlite3MemdebugHasType() is intended for use inside assert() statements.
  12702. **
  12703. ** sqlite3MemdebugNoType() returns true if none of the bits in its second
  12704. ** argument match the type set by the previous sqlite3MemdebugSetType().
  12705. **
  12706. ** Perhaps the most important point is the difference between MEMTYPE_HEAP
  12707. ** and MEMTYPE_LOOKASIDE. If an allocation is MEMTYPE_LOOKASIDE, that means
  12708. ** it might have been allocated by lookaside, except the allocation was
  12709. ** too large or lookaside was already full. It is important to verify
  12710. ** that allocations that might have been satisfied by lookaside are not
  12711. ** passed back to non-lookaside free() routines. Asserts such as the
  12712. ** example above are placed on the non-lookaside free() routines to verify
  12713. ** this constraint.
  12714. **
  12715. ** All of this is no-op for a production build. It only comes into
  12716. ** play when the SQLITE_MEMDEBUG compile-time option is used.
  12717. */
  12718. #ifdef SQLITE_MEMDEBUG
  12719. SQLITE_PRIVATE void sqlite3MemdebugSetType(void*,u8);
  12720. SQLITE_PRIVATE int sqlite3MemdebugHasType(void*,u8);
  12721. SQLITE_PRIVATE int sqlite3MemdebugNoType(void*,u8);
  12722. #else
  12723. # define sqlite3MemdebugSetType(X,Y) /* no-op */
  12724. # define sqlite3MemdebugHasType(X,Y) 1
  12725. # define sqlite3MemdebugNoType(X,Y) 1
  12726. #endif
  12727. #define MEMTYPE_HEAP 0x01 /* General heap allocations */
  12728. #define MEMTYPE_LOOKASIDE 0x02 /* Heap that might have been lookaside */
  12729. #define MEMTYPE_SCRATCH 0x04 /* Scratch allocations */
  12730. #define MEMTYPE_PCACHE 0x08 /* Page cache allocations */
  12731. /*
  12732. ** Threading interface
  12733. */
  12734. #if SQLITE_MAX_WORKER_THREADS>0
  12735. SQLITE_PRIVATE int sqlite3ThreadCreate(SQLiteThread**,void*(*)(void*),void*);
  12736. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread*, void**);
  12737. #endif
  12738. #endif /* _SQLITEINT_H_ */
  12739. /************** End of sqliteInt.h *******************************************/
  12740. /************** Begin file global.c ******************************************/
  12741. /*
  12742. ** 2008 June 13
  12743. **
  12744. ** The author disclaims copyright to this source code. In place of
  12745. ** a legal notice, here is a blessing:
  12746. **
  12747. ** May you do good and not evil.
  12748. ** May you find forgiveness for yourself and forgive others.
  12749. ** May you share freely, never taking more than you give.
  12750. **
  12751. *************************************************************************
  12752. **
  12753. ** This file contains definitions of global variables and constants.
  12754. */
  12755. /* An array to map all upper-case characters into their corresponding
  12756. ** lower-case character.
  12757. **
  12758. ** SQLite only considers US-ASCII (or EBCDIC) characters. We do not
  12759. ** handle case conversions for the UTF character set since the tables
  12760. ** involved are nearly as big or bigger than SQLite itself.
  12761. */
  12762. SQLITE_PRIVATE const unsigned char sqlite3UpperToLower[] = {
  12763. #ifdef SQLITE_ASCII
  12764. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,
  12765. 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35,
  12766. 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
  12767. 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 97, 98, 99,100,101,102,103,
  12768. 104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,
  12769. 122, 91, 92, 93, 94, 95, 96, 97, 98, 99,100,101,102,103,104,105,106,107,
  12770. 108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,
  12771. 126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  12772. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,160,161,
  12773. 162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,
  12774. 180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,
  12775. 198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,
  12776. 216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,
  12777. 234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,
  12778. 252,253,254,255
  12779. #endif
  12780. #ifdef SQLITE_EBCDIC
  12781. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, /* 0x */
  12782. 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, /* 1x */
  12783. 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, /* 2x */
  12784. 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, /* 3x */
  12785. 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, /* 4x */
  12786. 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, /* 5x */
  12787. 96, 97, 66, 67, 68, 69, 70, 71, 72, 73,106,107,108,109,110,111, /* 6x */
  12788. 112, 81, 82, 83, 84, 85, 86, 87, 88, 89,122,123,124,125,126,127, /* 7x */
  12789. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143, /* 8x */
  12790. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,156,159, /* 9x */
  12791. 160,161,162,163,164,165,166,167,168,169,170,171,140,141,142,175, /* Ax */
  12792. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191, /* Bx */
  12793. 192,129,130,131,132,133,134,135,136,137,202,203,204,205,206,207, /* Cx */
  12794. 208,145,146,147,148,149,150,151,152,153,218,219,220,221,222,223, /* Dx */
  12795. 224,225,162,163,164,165,166,167,168,169,232,203,204,205,206,207, /* Ex */
  12796. 239,240,241,242,243,244,245,246,247,248,249,219,220,221,222,255, /* Fx */
  12797. #endif
  12798. };
  12799. /*
  12800. ** The following 256 byte lookup table is used to support SQLites built-in
  12801. ** equivalents to the following standard library functions:
  12802. **
  12803. ** isspace() 0x01
  12804. ** isalpha() 0x02
  12805. ** isdigit() 0x04
  12806. ** isalnum() 0x06
  12807. ** isxdigit() 0x08
  12808. ** toupper() 0x20
  12809. ** SQLite identifier character 0x40
  12810. **
  12811. ** Bit 0x20 is set if the mapped character requires translation to upper
  12812. ** case. i.e. if the character is a lower-case ASCII character.
  12813. ** If x is a lower-case ASCII character, then its upper-case equivalent
  12814. ** is (x - 0x20). Therefore toupper() can be implemented as:
  12815. **
  12816. ** (x & ~(map[x]&0x20))
  12817. **
  12818. ** Standard function tolower() is implemented using the sqlite3UpperToLower[]
  12819. ** array. tolower() is used more often than toupper() by SQLite.
  12820. **
  12821. ** Bit 0x40 is set if the character non-alphanumeric and can be used in an
  12822. ** SQLite identifier. Identifiers are alphanumerics, "_", "$", and any
  12823. ** non-ASCII UTF character. Hence the test for whether or not a character is
  12824. ** part of an identifier is 0x46.
  12825. **
  12826. ** SQLite's versions are identical to the standard versions assuming a
  12827. ** locale of "C". They are implemented as macros in sqliteInt.h.
  12828. */
  12829. #ifdef SQLITE_ASCII
  12830. SQLITE_PRIVATE const unsigned char sqlite3CtypeMap[256] = {
  12831. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 00..07 ........ */
  12832. 0x00, 0x01, 0x01, 0x01, 0x01, 0x01, 0x00, 0x00, /* 08..0f ........ */
  12833. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 10..17 ........ */
  12834. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 18..1f ........ */
  12835. 0x01, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, /* 20..27 !"#$%&' */
  12836. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 28..2f ()*+,-./ */
  12837. 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, /* 30..37 01234567 */
  12838. 0x0c, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* 38..3f 89:;<=>? */
  12839. 0x00, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x0a, 0x02, /* 40..47 @ABCDEFG */
  12840. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 48..4f HIJKLMNO */
  12841. 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, /* 50..57 PQRSTUVW */
  12842. 0x02, 0x02, 0x02, 0x00, 0x00, 0x00, 0x00, 0x40, /* 58..5f XYZ[\]^_ */
  12843. 0x00, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x2a, 0x22, /* 60..67 `abcdefg */
  12844. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 68..6f hijklmno */
  12845. 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, /* 70..77 pqrstuvw */
  12846. 0x22, 0x22, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, /* 78..7f xyz{|}~. */
  12847. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 80..87 ........ */
  12848. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 88..8f ........ */
  12849. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 90..97 ........ */
  12850. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* 98..9f ........ */
  12851. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a0..a7 ........ */
  12852. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* a8..af ........ */
  12853. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b0..b7 ........ */
  12854. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* b8..bf ........ */
  12855. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c0..c7 ........ */
  12856. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* c8..cf ........ */
  12857. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d0..d7 ........ */
  12858. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* d8..df ........ */
  12859. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e0..e7 ........ */
  12860. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* e8..ef ........ */
  12861. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, /* f0..f7 ........ */
  12862. 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40, 0x40 /* f8..ff ........ */
  12863. };
  12864. #endif
  12865. /* EVIDENCE-OF: R-02982-34736 In order to maintain full backwards
  12866. ** compatibility for legacy applications, the URI filename capability is
  12867. ** disabled by default.
  12868. **
  12869. ** EVIDENCE-OF: R-38799-08373 URI filenames can be enabled or disabled
  12870. ** using the SQLITE_USE_URI=1 or SQLITE_USE_URI=0 compile-time options.
  12871. */
  12872. #ifndef SQLITE_USE_URI
  12873. # define SQLITE_USE_URI 0
  12874. #endif
  12875. #ifndef SQLITE_ALLOW_COVERING_INDEX_SCAN
  12876. # define SQLITE_ALLOW_COVERING_INDEX_SCAN 1
  12877. #endif
  12878. /*
  12879. ** The following singleton contains the global configuration for
  12880. ** the SQLite library.
  12881. */
  12882. SQLITE_PRIVATE SQLITE_WSD struct Sqlite3Config sqlite3Config = {
  12883. SQLITE_DEFAULT_MEMSTATUS, /* bMemstat */
  12884. 1, /* bCoreMutex */
  12885. SQLITE_THREADSAFE==1, /* bFullMutex */
  12886. SQLITE_USE_URI, /* bOpenUri */
  12887. SQLITE_ALLOW_COVERING_INDEX_SCAN, /* bUseCis */
  12888. 0x7ffffffe, /* mxStrlen */
  12889. 0, /* neverCorrupt */
  12890. 128, /* szLookaside */
  12891. 500, /* nLookaside */
  12892. {0,0,0,0,0,0,0,0}, /* m */
  12893. {0,0,0,0,0,0,0,0,0}, /* mutex */
  12894. {0,0,0,0,0,0,0,0,0,0,0,0,0},/* pcache2 */
  12895. (void*)0, /* pHeap */
  12896. 0, /* nHeap */
  12897. 0, 0, /* mnHeap, mxHeap */
  12898. SQLITE_DEFAULT_MMAP_SIZE, /* szMmap */
  12899. SQLITE_MAX_MMAP_SIZE, /* mxMmap */
  12900. (void*)0, /* pScratch */
  12901. 0, /* szScratch */
  12902. 0, /* nScratch */
  12903. (void*)0, /* pPage */
  12904. 0, /* szPage */
  12905. 0, /* nPage */
  12906. 0, /* mxParserStack */
  12907. 0, /* sharedCacheEnabled */
  12908. /* All the rest should always be initialized to zero */
  12909. 0, /* isInit */
  12910. 0, /* inProgress */
  12911. 0, /* isMutexInit */
  12912. 0, /* isMallocInit */
  12913. 0, /* isPCacheInit */
  12914. 0, /* nRefInitMutex */
  12915. 0, /* pInitMutex */
  12916. 0, /* xLog */
  12917. 0, /* pLogArg */
  12918. #ifdef SQLITE_ENABLE_SQLLOG
  12919. 0, /* xSqllog */
  12920. 0, /* pSqllogArg */
  12921. #endif
  12922. #ifdef SQLITE_VDBE_COVERAGE
  12923. 0, /* xVdbeBranch */
  12924. 0, /* pVbeBranchArg */
  12925. #endif
  12926. #ifndef SQLITE_OMIT_BUILTIN_TEST
  12927. 0, /* xTestCallback */
  12928. #endif
  12929. 0 /* bLocaltimeFault */
  12930. };
  12931. /*
  12932. ** Hash table for global functions - functions common to all
  12933. ** database connections. After initialization, this table is
  12934. ** read-only.
  12935. */
  12936. SQLITE_PRIVATE SQLITE_WSD FuncDefHash sqlite3GlobalFunctions;
  12937. /*
  12938. ** Constant tokens for values 0 and 1.
  12939. */
  12940. SQLITE_PRIVATE const Token sqlite3IntTokens[] = {
  12941. { "0", 1 },
  12942. { "1", 1 }
  12943. };
  12944. /*
  12945. ** The value of the "pending" byte must be 0x40000000 (1 byte past the
  12946. ** 1-gibabyte boundary) in a compatible database. SQLite never uses
  12947. ** the database page that contains the pending byte. It never attempts
  12948. ** to read or write that page. The pending byte page is set assign
  12949. ** for use by the VFS layers as space for managing file locks.
  12950. **
  12951. ** During testing, it is often desirable to move the pending byte to
  12952. ** a different position in the file. This allows code that has to
  12953. ** deal with the pending byte to run on files that are much smaller
  12954. ** than 1 GiB. The sqlite3_test_control() interface can be used to
  12955. ** move the pending byte.
  12956. **
  12957. ** IMPORTANT: Changing the pending byte to any value other than
  12958. ** 0x40000000 results in an incompatible database file format!
  12959. ** Changing the pending byte during operating results in undefined
  12960. ** and dileterious behavior.
  12961. */
  12962. #ifndef SQLITE_OMIT_WSD
  12963. SQLITE_PRIVATE int sqlite3PendingByte = 0x40000000;
  12964. #endif
  12965. /*
  12966. ** Properties of opcodes. The OPFLG_INITIALIZER macro is
  12967. ** created by mkopcodeh.awk during compilation. Data is obtained
  12968. ** from the comments following the "case OP_xxxx:" statements in
  12969. ** the vdbe.c file.
  12970. */
  12971. SQLITE_PRIVATE const unsigned char sqlite3OpcodeProperty[] = OPFLG_INITIALIZER;
  12972. /************** End of global.c **********************************************/
  12973. /************** Begin file ctime.c *******************************************/
  12974. /*
  12975. ** 2010 February 23
  12976. **
  12977. ** The author disclaims copyright to this source code. In place of
  12978. ** a legal notice, here is a blessing:
  12979. **
  12980. ** May you do good and not evil.
  12981. ** May you find forgiveness for yourself and forgive others.
  12982. ** May you share freely, never taking more than you give.
  12983. **
  12984. *************************************************************************
  12985. **
  12986. ** This file implements routines used to report what compile-time options
  12987. ** SQLite was built with.
  12988. */
  12989. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  12990. /*
  12991. ** An array of names of all compile-time options. This array should
  12992. ** be sorted A-Z.
  12993. **
  12994. ** This array looks large, but in a typical installation actually uses
  12995. ** only a handful of compile-time options, so most times this array is usually
  12996. ** rather short and uses little memory space.
  12997. */
  12998. static const char * const azCompileOpt[] = {
  12999. /* These macros are provided to "stringify" the value of the define
  13000. ** for those options in which the value is meaningful. */
  13001. #define CTIMEOPT_VAL_(opt) #opt
  13002. #define CTIMEOPT_VAL(opt) CTIMEOPT_VAL_(opt)
  13003. #ifdef SQLITE_32BIT_ROWID
  13004. "32BIT_ROWID",
  13005. #endif
  13006. #ifdef SQLITE_4_BYTE_ALIGNED_MALLOC
  13007. "4_BYTE_ALIGNED_MALLOC",
  13008. #endif
  13009. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  13010. "CASE_SENSITIVE_LIKE",
  13011. #endif
  13012. #ifdef SQLITE_CHECK_PAGES
  13013. "CHECK_PAGES",
  13014. #endif
  13015. #ifdef SQLITE_COVERAGE_TEST
  13016. "COVERAGE_TEST",
  13017. #endif
  13018. #ifdef SQLITE_DEBUG
  13019. "DEBUG",
  13020. #endif
  13021. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  13022. "DEFAULT_LOCKING_MODE=" CTIMEOPT_VAL(SQLITE_DEFAULT_LOCKING_MODE),
  13023. #endif
  13024. #if defined(SQLITE_DEFAULT_MMAP_SIZE) && !defined(SQLITE_DEFAULT_MMAP_SIZE_xc)
  13025. "DEFAULT_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_DEFAULT_MMAP_SIZE),
  13026. #endif
  13027. #ifdef SQLITE_DISABLE_DIRSYNC
  13028. "DISABLE_DIRSYNC",
  13029. #endif
  13030. #ifdef SQLITE_DISABLE_LFS
  13031. "DISABLE_LFS",
  13032. #endif
  13033. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  13034. "ENABLE_ATOMIC_WRITE",
  13035. #endif
  13036. #ifdef SQLITE_ENABLE_CEROD
  13037. "ENABLE_CEROD",
  13038. #endif
  13039. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  13040. "ENABLE_COLUMN_METADATA",
  13041. #endif
  13042. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  13043. "ENABLE_EXPENSIVE_ASSERT",
  13044. #endif
  13045. #ifdef SQLITE_ENABLE_FTS1
  13046. "ENABLE_FTS1",
  13047. #endif
  13048. #ifdef SQLITE_ENABLE_FTS2
  13049. "ENABLE_FTS2",
  13050. #endif
  13051. #ifdef SQLITE_ENABLE_FTS3
  13052. "ENABLE_FTS3",
  13053. #endif
  13054. #ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  13055. "ENABLE_FTS3_PARENTHESIS",
  13056. #endif
  13057. #ifdef SQLITE_ENABLE_FTS4
  13058. "ENABLE_FTS4",
  13059. #endif
  13060. #ifdef SQLITE_ENABLE_ICU
  13061. "ENABLE_ICU",
  13062. #endif
  13063. #ifdef SQLITE_ENABLE_IOTRACE
  13064. "ENABLE_IOTRACE",
  13065. #endif
  13066. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  13067. "ENABLE_LOAD_EXTENSION",
  13068. #endif
  13069. #ifdef SQLITE_ENABLE_LOCKING_STYLE
  13070. "ENABLE_LOCKING_STYLE=" CTIMEOPT_VAL(SQLITE_ENABLE_LOCKING_STYLE),
  13071. #endif
  13072. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  13073. "ENABLE_MEMORY_MANAGEMENT",
  13074. #endif
  13075. #ifdef SQLITE_ENABLE_MEMSYS3
  13076. "ENABLE_MEMSYS3",
  13077. #endif
  13078. #ifdef SQLITE_ENABLE_MEMSYS5
  13079. "ENABLE_MEMSYS5",
  13080. #endif
  13081. #ifdef SQLITE_ENABLE_OVERSIZE_CELL_CHECK
  13082. "ENABLE_OVERSIZE_CELL_CHECK",
  13083. #endif
  13084. #ifdef SQLITE_ENABLE_RTREE
  13085. "ENABLE_RTREE",
  13086. #endif
  13087. #if defined(SQLITE_ENABLE_STAT4)
  13088. "ENABLE_STAT4",
  13089. #elif defined(SQLITE_ENABLE_STAT3)
  13090. "ENABLE_STAT3",
  13091. #endif
  13092. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  13093. "ENABLE_UNLOCK_NOTIFY",
  13094. #endif
  13095. #ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
  13096. "ENABLE_UPDATE_DELETE_LIMIT",
  13097. #endif
  13098. #ifdef SQLITE_HAS_CODEC
  13099. "HAS_CODEC",
  13100. #endif
  13101. #ifdef SQLITE_HAVE_ISNAN
  13102. "HAVE_ISNAN",
  13103. #endif
  13104. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  13105. "HOMEGROWN_RECURSIVE_MUTEX",
  13106. #endif
  13107. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  13108. "IGNORE_AFP_LOCK_ERRORS",
  13109. #endif
  13110. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  13111. "IGNORE_FLOCK_LOCK_ERRORS",
  13112. #endif
  13113. #ifdef SQLITE_INT64_TYPE
  13114. "INT64_TYPE",
  13115. #endif
  13116. #ifdef SQLITE_LOCK_TRACE
  13117. "LOCK_TRACE",
  13118. #endif
  13119. #if defined(SQLITE_MAX_MMAP_SIZE) && !defined(SQLITE_MAX_MMAP_SIZE_xc)
  13120. "MAX_MMAP_SIZE=" CTIMEOPT_VAL(SQLITE_MAX_MMAP_SIZE),
  13121. #endif
  13122. #ifdef SQLITE_MAX_SCHEMA_RETRY
  13123. "MAX_SCHEMA_RETRY=" CTIMEOPT_VAL(SQLITE_MAX_SCHEMA_RETRY),
  13124. #endif
  13125. #ifdef SQLITE_MEMDEBUG
  13126. "MEMDEBUG",
  13127. #endif
  13128. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  13129. "MIXED_ENDIAN_64BIT_FLOAT",
  13130. #endif
  13131. #ifdef SQLITE_NO_SYNC
  13132. "NO_SYNC",
  13133. #endif
  13134. #ifdef SQLITE_OMIT_ALTERTABLE
  13135. "OMIT_ALTERTABLE",
  13136. #endif
  13137. #ifdef SQLITE_OMIT_ANALYZE
  13138. "OMIT_ANALYZE",
  13139. #endif
  13140. #ifdef SQLITE_OMIT_ATTACH
  13141. "OMIT_ATTACH",
  13142. #endif
  13143. #ifdef SQLITE_OMIT_AUTHORIZATION
  13144. "OMIT_AUTHORIZATION",
  13145. #endif
  13146. #ifdef SQLITE_OMIT_AUTOINCREMENT
  13147. "OMIT_AUTOINCREMENT",
  13148. #endif
  13149. #ifdef SQLITE_OMIT_AUTOINIT
  13150. "OMIT_AUTOINIT",
  13151. #endif
  13152. #ifdef SQLITE_OMIT_AUTOMATIC_INDEX
  13153. "OMIT_AUTOMATIC_INDEX",
  13154. #endif
  13155. #ifdef SQLITE_OMIT_AUTORESET
  13156. "OMIT_AUTORESET",
  13157. #endif
  13158. #ifdef SQLITE_OMIT_AUTOVACUUM
  13159. "OMIT_AUTOVACUUM",
  13160. #endif
  13161. #ifdef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  13162. "OMIT_BETWEEN_OPTIMIZATION",
  13163. #endif
  13164. #ifdef SQLITE_OMIT_BLOB_LITERAL
  13165. "OMIT_BLOB_LITERAL",
  13166. #endif
  13167. #ifdef SQLITE_OMIT_BTREECOUNT
  13168. "OMIT_BTREECOUNT",
  13169. #endif
  13170. #ifdef SQLITE_OMIT_BUILTIN_TEST
  13171. "OMIT_BUILTIN_TEST",
  13172. #endif
  13173. #ifdef SQLITE_OMIT_CAST
  13174. "OMIT_CAST",
  13175. #endif
  13176. #ifdef SQLITE_OMIT_CHECK
  13177. "OMIT_CHECK",
  13178. #endif
  13179. #ifdef SQLITE_OMIT_COMPLETE
  13180. "OMIT_COMPLETE",
  13181. #endif
  13182. #ifdef SQLITE_OMIT_COMPOUND_SELECT
  13183. "OMIT_COMPOUND_SELECT",
  13184. #endif
  13185. #ifdef SQLITE_OMIT_CTE
  13186. "OMIT_CTE",
  13187. #endif
  13188. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  13189. "OMIT_DATETIME_FUNCS",
  13190. #endif
  13191. #ifdef SQLITE_OMIT_DECLTYPE
  13192. "OMIT_DECLTYPE",
  13193. #endif
  13194. #ifdef SQLITE_OMIT_DEPRECATED
  13195. "OMIT_DEPRECATED",
  13196. #endif
  13197. #ifdef SQLITE_OMIT_DISKIO
  13198. "OMIT_DISKIO",
  13199. #endif
  13200. #ifdef SQLITE_OMIT_EXPLAIN
  13201. "OMIT_EXPLAIN",
  13202. #endif
  13203. #ifdef SQLITE_OMIT_FLAG_PRAGMAS
  13204. "OMIT_FLAG_PRAGMAS",
  13205. #endif
  13206. #ifdef SQLITE_OMIT_FLOATING_POINT
  13207. "OMIT_FLOATING_POINT",
  13208. #endif
  13209. #ifdef SQLITE_OMIT_FOREIGN_KEY
  13210. "OMIT_FOREIGN_KEY",
  13211. #endif
  13212. #ifdef SQLITE_OMIT_GET_TABLE
  13213. "OMIT_GET_TABLE",
  13214. #endif
  13215. #ifdef SQLITE_OMIT_INCRBLOB
  13216. "OMIT_INCRBLOB",
  13217. #endif
  13218. #ifdef SQLITE_OMIT_INTEGRITY_CHECK
  13219. "OMIT_INTEGRITY_CHECK",
  13220. #endif
  13221. #ifdef SQLITE_OMIT_LIKE_OPTIMIZATION
  13222. "OMIT_LIKE_OPTIMIZATION",
  13223. #endif
  13224. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  13225. "OMIT_LOAD_EXTENSION",
  13226. #endif
  13227. #ifdef SQLITE_OMIT_LOCALTIME
  13228. "OMIT_LOCALTIME",
  13229. #endif
  13230. #ifdef SQLITE_OMIT_LOOKASIDE
  13231. "OMIT_LOOKASIDE",
  13232. #endif
  13233. #ifdef SQLITE_OMIT_MEMORYDB
  13234. "OMIT_MEMORYDB",
  13235. #endif
  13236. #ifdef SQLITE_OMIT_OR_OPTIMIZATION
  13237. "OMIT_OR_OPTIMIZATION",
  13238. #endif
  13239. #ifdef SQLITE_OMIT_PAGER_PRAGMAS
  13240. "OMIT_PAGER_PRAGMAS",
  13241. #endif
  13242. #ifdef SQLITE_OMIT_PRAGMA
  13243. "OMIT_PRAGMA",
  13244. #endif
  13245. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  13246. "OMIT_PROGRESS_CALLBACK",
  13247. #endif
  13248. #ifdef SQLITE_OMIT_QUICKBALANCE
  13249. "OMIT_QUICKBALANCE",
  13250. #endif
  13251. #ifdef SQLITE_OMIT_REINDEX
  13252. "OMIT_REINDEX",
  13253. #endif
  13254. #ifdef SQLITE_OMIT_SCHEMA_PRAGMAS
  13255. "OMIT_SCHEMA_PRAGMAS",
  13256. #endif
  13257. #ifdef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  13258. "OMIT_SCHEMA_VERSION_PRAGMAS",
  13259. #endif
  13260. #ifdef SQLITE_OMIT_SHARED_CACHE
  13261. "OMIT_SHARED_CACHE",
  13262. #endif
  13263. #ifdef SQLITE_OMIT_SUBQUERY
  13264. "OMIT_SUBQUERY",
  13265. #endif
  13266. #ifdef SQLITE_OMIT_TCL_VARIABLE
  13267. "OMIT_TCL_VARIABLE",
  13268. #endif
  13269. #ifdef SQLITE_OMIT_TEMPDB
  13270. "OMIT_TEMPDB",
  13271. #endif
  13272. #ifdef SQLITE_OMIT_TRACE
  13273. "OMIT_TRACE",
  13274. #endif
  13275. #ifdef SQLITE_OMIT_TRIGGER
  13276. "OMIT_TRIGGER",
  13277. #endif
  13278. #ifdef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  13279. "OMIT_TRUNCATE_OPTIMIZATION",
  13280. #endif
  13281. #ifdef SQLITE_OMIT_UTF16
  13282. "OMIT_UTF16",
  13283. #endif
  13284. #ifdef SQLITE_OMIT_VACUUM
  13285. "OMIT_VACUUM",
  13286. #endif
  13287. #ifdef SQLITE_OMIT_VIEW
  13288. "OMIT_VIEW",
  13289. #endif
  13290. #ifdef SQLITE_OMIT_VIRTUALTABLE
  13291. "OMIT_VIRTUALTABLE",
  13292. #endif
  13293. #ifdef SQLITE_OMIT_WAL
  13294. "OMIT_WAL",
  13295. #endif
  13296. #ifdef SQLITE_OMIT_WSD
  13297. "OMIT_WSD",
  13298. #endif
  13299. #ifdef SQLITE_OMIT_XFER_OPT
  13300. "OMIT_XFER_OPT",
  13301. #endif
  13302. #ifdef SQLITE_PERFORMANCE_TRACE
  13303. "PERFORMANCE_TRACE",
  13304. #endif
  13305. #ifdef SQLITE_PROXY_DEBUG
  13306. "PROXY_DEBUG",
  13307. #endif
  13308. #ifdef SQLITE_RTREE_INT_ONLY
  13309. "RTREE_INT_ONLY",
  13310. #endif
  13311. #ifdef SQLITE_SECURE_DELETE
  13312. "SECURE_DELETE",
  13313. #endif
  13314. #ifdef SQLITE_SMALL_STACK
  13315. "SMALL_STACK",
  13316. #endif
  13317. #ifdef SQLITE_SOUNDEX
  13318. "SOUNDEX",
  13319. #endif
  13320. #ifdef SQLITE_SYSTEM_MALLOC
  13321. "SYSTEM_MALLOC",
  13322. #endif
  13323. #ifdef SQLITE_TCL
  13324. "TCL",
  13325. #endif
  13326. #if defined(SQLITE_TEMP_STORE) && !defined(SQLITE_TEMP_STORE_xc)
  13327. "TEMP_STORE=" CTIMEOPT_VAL(SQLITE_TEMP_STORE),
  13328. #endif
  13329. #ifdef SQLITE_TEST
  13330. "TEST",
  13331. #endif
  13332. #if defined(SQLITE_THREADSAFE)
  13333. "THREADSAFE=" CTIMEOPT_VAL(SQLITE_THREADSAFE),
  13334. #endif
  13335. #ifdef SQLITE_USE_ALLOCA
  13336. "USE_ALLOCA",
  13337. #endif
  13338. #ifdef SQLITE_USER_AUTHENTICATION
  13339. "USER_AUTHENTICATION",
  13340. #endif
  13341. #ifdef SQLITE_WIN32_MALLOC
  13342. "WIN32_MALLOC",
  13343. #endif
  13344. #ifdef SQLITE_ZERO_MALLOC
  13345. "ZERO_MALLOC"
  13346. #endif
  13347. };
  13348. /*
  13349. ** Given the name of a compile-time option, return true if that option
  13350. ** was used and false if not.
  13351. **
  13352. ** The name can optionally begin with "SQLITE_" but the "SQLITE_" prefix
  13353. ** is not required for a match.
  13354. */
  13355. SQLITE_API int sqlite3_compileoption_used(const char *zOptName){
  13356. int i, n;
  13357. if( sqlite3StrNICmp(zOptName, "SQLITE_", 7)==0 ) zOptName += 7;
  13358. n = sqlite3Strlen30(zOptName);
  13359. /* Since ArraySize(azCompileOpt) is normally in single digits, a
  13360. ** linear search is adequate. No need for a binary search. */
  13361. for(i=0; i<ArraySize(azCompileOpt); i++){
  13362. if( sqlite3StrNICmp(zOptName, azCompileOpt[i], n)==0
  13363. && sqlite3IsIdChar((unsigned char)azCompileOpt[i][n])==0
  13364. ){
  13365. return 1;
  13366. }
  13367. }
  13368. return 0;
  13369. }
  13370. /*
  13371. ** Return the N-th compile-time option string. If N is out of range,
  13372. ** return a NULL pointer.
  13373. */
  13374. SQLITE_API const char *sqlite3_compileoption_get(int N){
  13375. if( N>=0 && N<ArraySize(azCompileOpt) ){
  13376. return azCompileOpt[N];
  13377. }
  13378. return 0;
  13379. }
  13380. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  13381. /************** End of ctime.c ***********************************************/
  13382. /************** Begin file status.c ******************************************/
  13383. /*
  13384. ** 2008 June 18
  13385. **
  13386. ** The author disclaims copyright to this source code. In place of
  13387. ** a legal notice, here is a blessing:
  13388. **
  13389. ** May you do good and not evil.
  13390. ** May you find forgiveness for yourself and forgive others.
  13391. ** May you share freely, never taking more than you give.
  13392. **
  13393. *************************************************************************
  13394. **
  13395. ** This module implements the sqlite3_status() interface and related
  13396. ** functionality.
  13397. */
  13398. /************** Include vdbeInt.h in the middle of status.c ******************/
  13399. /************** Begin file vdbeInt.h *****************************************/
  13400. /*
  13401. ** 2003 September 6
  13402. **
  13403. ** The author disclaims copyright to this source code. In place of
  13404. ** a legal notice, here is a blessing:
  13405. **
  13406. ** May you do good and not evil.
  13407. ** May you find forgiveness for yourself and forgive others.
  13408. ** May you share freely, never taking more than you give.
  13409. **
  13410. *************************************************************************
  13411. ** This is the header file for information that is private to the
  13412. ** VDBE. This information used to all be at the top of the single
  13413. ** source code file "vdbe.c". When that file became too big (over
  13414. ** 6000 lines long) it was split up into several smaller files and
  13415. ** this header information was factored out.
  13416. */
  13417. #ifndef _VDBEINT_H_
  13418. #define _VDBEINT_H_
  13419. /*
  13420. ** The maximum number of times that a statement will try to reparse
  13421. ** itself before giving up and returning SQLITE_SCHEMA.
  13422. */
  13423. #ifndef SQLITE_MAX_SCHEMA_RETRY
  13424. # define SQLITE_MAX_SCHEMA_RETRY 50
  13425. #endif
  13426. /*
  13427. ** SQL is translated into a sequence of instructions to be
  13428. ** executed by a virtual machine. Each instruction is an instance
  13429. ** of the following structure.
  13430. */
  13431. typedef struct VdbeOp Op;
  13432. /*
  13433. ** Boolean values
  13434. */
  13435. typedef unsigned Bool;
  13436. /* Opaque type used by code in vdbesort.c */
  13437. typedef struct VdbeSorter VdbeSorter;
  13438. /* Opaque type used by the explainer */
  13439. typedef struct Explain Explain;
  13440. /* Elements of the linked list at Vdbe.pAuxData */
  13441. typedef struct AuxData AuxData;
  13442. /*
  13443. ** A cursor is a pointer into a single BTree within a database file.
  13444. ** The cursor can seek to a BTree entry with a particular key, or
  13445. ** loop over all entries of the Btree. You can also insert new BTree
  13446. ** entries or retrieve the key or data from the entry that the cursor
  13447. ** is currently pointing to.
  13448. **
  13449. ** Cursors can also point to virtual tables, sorters, or "pseudo-tables".
  13450. ** A pseudo-table is a single-row table implemented by registers.
  13451. **
  13452. ** Every cursor that the virtual machine has open is represented by an
  13453. ** instance of the following structure.
  13454. */
  13455. struct VdbeCursor {
  13456. BtCursor *pCursor; /* The cursor structure of the backend */
  13457. Btree *pBt; /* Separate file holding temporary table */
  13458. KeyInfo *pKeyInfo; /* Info about index keys needed by index cursors */
  13459. int seekResult; /* Result of previous sqlite3BtreeMoveto() */
  13460. int pseudoTableReg; /* Register holding pseudotable content. */
  13461. i16 nField; /* Number of fields in the header */
  13462. u16 nHdrParsed; /* Number of header fields parsed so far */
  13463. #ifdef SQLITE_DEBUG
  13464. u8 seekOp; /* Most recent seek operation on this cursor */
  13465. #endif
  13466. i8 iDb; /* Index of cursor database in db->aDb[] (or -1) */
  13467. u8 nullRow; /* True if pointing to a row with no data */
  13468. u8 deferredMoveto; /* A call to sqlite3BtreeMoveto() is needed */
  13469. Bool isEphemeral:1; /* True for an ephemeral table */
  13470. Bool useRandomRowid:1;/* Generate new record numbers semi-randomly */
  13471. Bool isTable:1; /* True if a table requiring integer keys */
  13472. Bool isOrdered:1; /* True if the underlying table is BTREE_UNORDERED */
  13473. Pgno pgnoRoot; /* Root page of the open btree cursor */
  13474. sqlite3_vtab_cursor *pVtabCursor; /* The cursor for a virtual table */
  13475. i64 seqCount; /* Sequence counter */
  13476. i64 movetoTarget; /* Argument to the deferred sqlite3BtreeMoveto() */
  13477. VdbeSorter *pSorter; /* Sorter object for OP_SorterOpen cursors */
  13478. /* Cached information about the header for the data record that the
  13479. ** cursor is currently pointing to. Only valid if cacheStatus matches
  13480. ** Vdbe.cacheCtr. Vdbe.cacheCtr will never take on the value of
  13481. ** CACHE_STALE and so setting cacheStatus=CACHE_STALE guarantees that
  13482. ** the cache is out of date.
  13483. **
  13484. ** aRow might point to (ephemeral) data for the current row, or it might
  13485. ** be NULL.
  13486. */
  13487. u32 cacheStatus; /* Cache is valid if this matches Vdbe.cacheCtr */
  13488. u32 payloadSize; /* Total number of bytes in the record */
  13489. u32 szRow; /* Byte available in aRow */
  13490. u32 iHdrOffset; /* Offset to next unparsed byte of the header */
  13491. const u8 *aRow; /* Data for the current row, if all on one page */
  13492. u32 *aOffset; /* Pointer to aType[nField] */
  13493. u32 aType[1]; /* Type values for all entries in the record */
  13494. /* 2*nField extra array elements allocated for aType[], beyond the one
  13495. ** static element declared in the structure. nField total array slots for
  13496. ** aType[] and nField+1 array slots for aOffset[] */
  13497. };
  13498. typedef struct VdbeCursor VdbeCursor;
  13499. /*
  13500. ** When a sub-program is executed (OP_Program), a structure of this type
  13501. ** is allocated to store the current value of the program counter, as
  13502. ** well as the current memory cell array and various other frame specific
  13503. ** values stored in the Vdbe struct. When the sub-program is finished,
  13504. ** these values are copied back to the Vdbe from the VdbeFrame structure,
  13505. ** restoring the state of the VM to as it was before the sub-program
  13506. ** began executing.
  13507. **
  13508. ** The memory for a VdbeFrame object is allocated and managed by a memory
  13509. ** cell in the parent (calling) frame. When the memory cell is deleted or
  13510. ** overwritten, the VdbeFrame object is not freed immediately. Instead, it
  13511. ** is linked into the Vdbe.pDelFrame list. The contents of the Vdbe.pDelFrame
  13512. ** list is deleted when the VM is reset in VdbeHalt(). The reason for doing
  13513. ** this instead of deleting the VdbeFrame immediately is to avoid recursive
  13514. ** calls to sqlite3VdbeMemRelease() when the memory cells belonging to the
  13515. ** child frame are released.
  13516. **
  13517. ** The currently executing frame is stored in Vdbe.pFrame. Vdbe.pFrame is
  13518. ** set to NULL if the currently executing frame is the main program.
  13519. */
  13520. typedef struct VdbeFrame VdbeFrame;
  13521. struct VdbeFrame {
  13522. Vdbe *v; /* VM this frame belongs to */
  13523. VdbeFrame *pParent; /* Parent of this frame, or NULL if parent is main */
  13524. Op *aOp; /* Program instructions for parent frame */
  13525. Mem *aMem; /* Array of memory cells for parent frame */
  13526. u8 *aOnceFlag; /* Array of OP_Once flags for parent frame */
  13527. VdbeCursor **apCsr; /* Array of Vdbe cursors for parent frame */
  13528. void *token; /* Copy of SubProgram.token */
  13529. i64 lastRowid; /* Last insert rowid (sqlite3.lastRowid) */
  13530. int nCursor; /* Number of entries in apCsr */
  13531. int pc; /* Program Counter in parent (calling) frame */
  13532. int nOp; /* Size of aOp array */
  13533. int nMem; /* Number of entries in aMem */
  13534. int nOnceFlag; /* Number of entries in aOnceFlag */
  13535. int nChildMem; /* Number of memory cells for child frame */
  13536. int nChildCsr; /* Number of cursors for child frame */
  13537. int nChange; /* Statement changes (Vdbe.nChanges) */
  13538. };
  13539. #define VdbeFrameMem(p) ((Mem *)&((u8 *)p)[ROUND8(sizeof(VdbeFrame))])
  13540. /*
  13541. ** A value for VdbeCursor.cacheValid that means the cache is always invalid.
  13542. */
  13543. #define CACHE_STALE 0
  13544. /*
  13545. ** Internally, the vdbe manipulates nearly all SQL values as Mem
  13546. ** structures. Each Mem struct may cache multiple representations (string,
  13547. ** integer etc.) of the same value.
  13548. */
  13549. struct Mem {
  13550. union MemValue {
  13551. double r; /* Real value used when MEM_Real is set in flags */
  13552. i64 i; /* Integer value used when MEM_Int is set in flags */
  13553. int nZero; /* Used when bit MEM_Zero is set in flags */
  13554. FuncDef *pDef; /* Used only when flags==MEM_Agg */
  13555. RowSet *pRowSet; /* Used only when flags==MEM_RowSet */
  13556. VdbeFrame *pFrame; /* Used when flags==MEM_Frame */
  13557. } u;
  13558. u16 flags; /* Some combination of MEM_Null, MEM_Str, MEM_Dyn, etc. */
  13559. u8 enc; /* SQLITE_UTF8, SQLITE_UTF16BE, SQLITE_UTF16LE */
  13560. int n; /* Number of characters in string value, excluding '\0' */
  13561. char *z; /* String or BLOB value */
  13562. /* ShallowCopy only needs to copy the information above */
  13563. char *zMalloc; /* Space to hold MEM_Str or MEM_Blob if szMalloc>0 */
  13564. int szMalloc; /* Size of the zMalloc allocation */
  13565. u32 uTemp; /* Transient storage for serial_type in OP_MakeRecord */
  13566. sqlite3 *db; /* The associated database connection */
  13567. void (*xDel)(void*);/* Destructor for Mem.z - only valid if MEM_Dyn */
  13568. #ifdef SQLITE_DEBUG
  13569. Mem *pScopyFrom; /* This Mem is a shallow copy of pScopyFrom */
  13570. void *pFiller; /* So that sizeof(Mem) is a multiple of 8 */
  13571. #endif
  13572. };
  13573. /* One or more of the following flags are set to indicate the validOK
  13574. ** representations of the value stored in the Mem struct.
  13575. **
  13576. ** If the MEM_Null flag is set, then the value is an SQL NULL value.
  13577. ** No other flags may be set in this case.
  13578. **
  13579. ** If the MEM_Str flag is set then Mem.z points at a string representation.
  13580. ** Usually this is encoded in the same unicode encoding as the main
  13581. ** database (see below for exceptions). If the MEM_Term flag is also
  13582. ** set, then the string is nul terminated. The MEM_Int and MEM_Real
  13583. ** flags may coexist with the MEM_Str flag.
  13584. */
  13585. #define MEM_Null 0x0001 /* Value is NULL */
  13586. #define MEM_Str 0x0002 /* Value is a string */
  13587. #define MEM_Int 0x0004 /* Value is an integer */
  13588. #define MEM_Real 0x0008 /* Value is a real number */
  13589. #define MEM_Blob 0x0010 /* Value is a BLOB */
  13590. #define MEM_AffMask 0x001f /* Mask of affinity bits */
  13591. #define MEM_RowSet 0x0020 /* Value is a RowSet object */
  13592. #define MEM_Frame 0x0040 /* Value is a VdbeFrame object */
  13593. #define MEM_Undefined 0x0080 /* Value is undefined */
  13594. #define MEM_Cleared 0x0100 /* NULL set by OP_Null, not from data */
  13595. #define MEM_TypeMask 0x01ff /* Mask of type bits */
  13596. /* Whenever Mem contains a valid string or blob representation, one of
  13597. ** the following flags must be set to determine the memory management
  13598. ** policy for Mem.z. The MEM_Term flag tells us whether or not the
  13599. ** string is \000 or \u0000 terminated
  13600. */
  13601. #define MEM_Term 0x0200 /* String rep is nul terminated */
  13602. #define MEM_Dyn 0x0400 /* Need to call Mem.xDel() on Mem.z */
  13603. #define MEM_Static 0x0800 /* Mem.z points to a static string */
  13604. #define MEM_Ephem 0x1000 /* Mem.z points to an ephemeral string */
  13605. #define MEM_Agg 0x2000 /* Mem.z points to an agg function context */
  13606. #define MEM_Zero 0x4000 /* Mem.i contains count of 0s appended to blob */
  13607. #ifdef SQLITE_OMIT_INCRBLOB
  13608. #undef MEM_Zero
  13609. #define MEM_Zero 0x0000
  13610. #endif
  13611. /*
  13612. ** Clear any existing type flags from a Mem and replace them with f
  13613. */
  13614. #define MemSetTypeFlag(p, f) \
  13615. ((p)->flags = ((p)->flags&~(MEM_TypeMask|MEM_Zero))|f)
  13616. /*
  13617. ** Return true if a memory cell is not marked as invalid. This macro
  13618. ** is for use inside assert() statements only.
  13619. */
  13620. #ifdef SQLITE_DEBUG
  13621. #define memIsValid(M) ((M)->flags & MEM_Undefined)==0
  13622. #endif
  13623. /*
  13624. ** Each auxiliary data pointer stored by a user defined function
  13625. ** implementation calling sqlite3_set_auxdata() is stored in an instance
  13626. ** of this structure. All such structures associated with a single VM
  13627. ** are stored in a linked list headed at Vdbe.pAuxData. All are destroyed
  13628. ** when the VM is halted (if not before).
  13629. */
  13630. struct AuxData {
  13631. int iOp; /* Instruction number of OP_Function opcode */
  13632. int iArg; /* Index of function argument. */
  13633. void *pAux; /* Aux data pointer */
  13634. void (*xDelete)(void *); /* Destructor for the aux data */
  13635. AuxData *pNext; /* Next element in list */
  13636. };
  13637. /*
  13638. ** The "context" argument for an installable function. A pointer to an
  13639. ** instance of this structure is the first argument to the routines used
  13640. ** implement the SQL functions.
  13641. **
  13642. ** There is a typedef for this structure in sqlite.h. So all routines,
  13643. ** even the public interface to SQLite, can use a pointer to this structure.
  13644. ** But this file is the only place where the internal details of this
  13645. ** structure are known.
  13646. **
  13647. ** This structure is defined inside of vdbeInt.h because it uses substructures
  13648. ** (Mem) which are only defined there.
  13649. */
  13650. struct sqlite3_context {
  13651. Mem *pOut; /* The return value is stored here */
  13652. FuncDef *pFunc; /* Pointer to function information */
  13653. Mem *pMem; /* Memory cell used to store aggregate context */
  13654. Vdbe *pVdbe; /* The VM that owns this context */
  13655. int iOp; /* Instruction number of OP_Function */
  13656. int isError; /* Error code returned by the function. */
  13657. u8 skipFlag; /* Skip accumulator loading if true */
  13658. u8 fErrorOrAux; /* isError!=0 or pVdbe->pAuxData modified */
  13659. };
  13660. /*
  13661. ** An Explain object accumulates indented output which is helpful
  13662. ** in describing recursive data structures.
  13663. */
  13664. struct Explain {
  13665. Vdbe *pVdbe; /* Attach the explanation to this Vdbe */
  13666. StrAccum str; /* The string being accumulated */
  13667. int nIndent; /* Number of elements in aIndent */
  13668. u16 aIndent[100]; /* Levels of indentation */
  13669. char zBase[100]; /* Initial space */
  13670. };
  13671. /* A bitfield type for use inside of structures. Always follow with :N where
  13672. ** N is the number of bits.
  13673. */
  13674. typedef unsigned bft; /* Bit Field Type */
  13675. /*
  13676. ** An instance of the virtual machine. This structure contains the complete
  13677. ** state of the virtual machine.
  13678. **
  13679. ** The "sqlite3_stmt" structure pointer that is returned by sqlite3_prepare()
  13680. ** is really a pointer to an instance of this structure.
  13681. **
  13682. ** The Vdbe.inVtabMethod variable is set to non-zero for the duration of
  13683. ** any virtual table method invocations made by the vdbe program. It is
  13684. ** set to 2 for xDestroy method calls and 1 for all other methods. This
  13685. ** variable is used for two purposes: to allow xDestroy methods to execute
  13686. ** "DROP TABLE" statements and to prevent some nasty side effects of
  13687. ** malloc failure when SQLite is invoked recursively by a virtual table
  13688. ** method function.
  13689. */
  13690. struct Vdbe {
  13691. sqlite3 *db; /* The database connection that owns this statement */
  13692. Op *aOp; /* Space to hold the virtual machine's program */
  13693. Mem *aMem; /* The memory locations */
  13694. Mem **apArg; /* Arguments to currently executing user function */
  13695. Mem *aColName; /* Column names to return */
  13696. Mem *pResultSet; /* Pointer to an array of results */
  13697. Parse *pParse; /* Parsing context used to create this Vdbe */
  13698. int nMem; /* Number of memory locations currently allocated */
  13699. int nOp; /* Number of instructions in the program */
  13700. int nCursor; /* Number of slots in apCsr[] */
  13701. u32 magic; /* Magic number for sanity checking */
  13702. char *zErrMsg; /* Error message written here */
  13703. Vdbe *pPrev,*pNext; /* Linked list of VDBEs with the same Vdbe.db */
  13704. VdbeCursor **apCsr; /* One element of this array for each open cursor */
  13705. Mem *aVar; /* Values for the OP_Variable opcode. */
  13706. char **azVar; /* Name of variables */
  13707. ynVar nVar; /* Number of entries in aVar[] */
  13708. ynVar nzVar; /* Number of entries in azVar[] */
  13709. u32 cacheCtr; /* VdbeCursor row cache generation counter */
  13710. int pc; /* The program counter */
  13711. int rc; /* Value to return */
  13712. u16 nResColumn; /* Number of columns in one row of the result set */
  13713. u8 errorAction; /* Recovery action to do in case of an error */
  13714. u8 minWriteFileFormat; /* Minimum file format for writable database files */
  13715. bft explain:2; /* True if EXPLAIN present on SQL command */
  13716. bft inVtabMethod:2; /* See comments above */
  13717. bft changeCntOn:1; /* True to update the change-counter */
  13718. bft expired:1; /* True if the VM needs to be recompiled */
  13719. bft runOnlyOnce:1; /* Automatically expire on reset */
  13720. bft usesStmtJournal:1; /* True if uses a statement journal */
  13721. bft readOnly:1; /* True for statements that do not write */
  13722. bft bIsReader:1; /* True for statements that read */
  13723. bft isPrepareV2:1; /* True if prepared with prepare_v2() */
  13724. bft doingRerun:1; /* True if rerunning after an auto-reprepare */
  13725. int nChange; /* Number of db changes made since last reset */
  13726. yDbMask btreeMask; /* Bitmask of db->aDb[] entries referenced */
  13727. yDbMask lockMask; /* Subset of btreeMask that requires a lock */
  13728. int iStatement; /* Statement number (or 0 if has not opened stmt) */
  13729. u32 aCounter[5]; /* Counters used by sqlite3_stmt_status() */
  13730. #ifndef SQLITE_OMIT_TRACE
  13731. i64 startTime; /* Time when query started - used for profiling */
  13732. #endif
  13733. i64 iCurrentTime; /* Value of julianday('now') for this statement */
  13734. i64 nFkConstraint; /* Number of imm. FK constraints this VM */
  13735. i64 nStmtDefCons; /* Number of def. constraints when stmt started */
  13736. i64 nStmtDefImmCons; /* Number of def. imm constraints when stmt started */
  13737. char *zSql; /* Text of the SQL statement that generated this */
  13738. void *pFree; /* Free this when deleting the vdbe */
  13739. VdbeFrame *pFrame; /* Parent frame */
  13740. VdbeFrame *pDelFrame; /* List of frame objects to free on VM reset */
  13741. int nFrame; /* Number of frames in pFrame list */
  13742. u32 expmask; /* Binding to these vars invalidates VM */
  13743. SubProgram *pProgram; /* Linked list of all sub-programs used by VM */
  13744. int nOnceFlag; /* Size of array aOnceFlag[] */
  13745. u8 *aOnceFlag; /* Flags for OP_Once */
  13746. AuxData *pAuxData; /* Linked list of auxdata allocations */
  13747. };
  13748. /*
  13749. ** The following are allowed values for Vdbe.magic
  13750. */
  13751. #define VDBE_MAGIC_INIT 0x26bceaa5 /* Building a VDBE program */
  13752. #define VDBE_MAGIC_RUN 0xbdf20da3 /* VDBE is ready to execute */
  13753. #define VDBE_MAGIC_HALT 0x519c2973 /* VDBE has completed execution */
  13754. #define VDBE_MAGIC_DEAD 0xb606c3c8 /* The VDBE has been deallocated */
  13755. /*
  13756. ** Function prototypes
  13757. */
  13758. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *, VdbeCursor*);
  13759. void sqliteVdbePopStack(Vdbe*,int);
  13760. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor*);
  13761. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor*);
  13762. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  13763. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE*, int, Op*);
  13764. #endif
  13765. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32);
  13766. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem*, int);
  13767. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(unsigned char*, Mem*, u32);
  13768. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(const unsigned char*, u32, Mem*);
  13769. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe*, int, int);
  13770. int sqlite2BtreeKeyCompare(BtCursor *, const void *, int, int, int *);
  13771. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(sqlite3*,VdbeCursor*,UnpackedRecord*,int*);
  13772. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3*, BtCursor*, i64*);
  13773. SQLITE_PRIVATE int sqlite3VdbeExec(Vdbe*);
  13774. SQLITE_PRIVATE int sqlite3VdbeList(Vdbe*);
  13775. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe*);
  13776. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *, int);
  13777. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem*);
  13778. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem*, const Mem*);
  13779. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem*, const Mem*, int);
  13780. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem*, Mem*);
  13781. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem*);
  13782. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(Mem*, const char*, int, u8, void(*)(void*));
  13783. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem*, i64);
  13784. #ifdef SQLITE_OMIT_FLOATING_POINT
  13785. # define sqlite3VdbeMemSetDouble sqlite3VdbeMemSetInt64
  13786. #else
  13787. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem*, double);
  13788. #endif
  13789. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem*,sqlite3*,u16);
  13790. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem*);
  13791. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem*,int);
  13792. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem*);
  13793. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem*);
  13794. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem*, u8, u8);
  13795. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem*);
  13796. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem*);
  13797. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem*);
  13798. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem*);
  13799. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem*);
  13800. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem*);
  13801. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem*,u8,u8);
  13802. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(BtCursor*,u32,u32,int,Mem*);
  13803. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p);
  13804. #define VdbeMemDynamic(X) \
  13805. (((X)->flags&(MEM_Agg|MEM_Dyn|MEM_RowSet|MEM_Frame))!=0)
  13806. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem*, FuncDef*);
  13807. SQLITE_PRIVATE const char *sqlite3OpcodeName(int);
  13808. SQLITE_PRIVATE int sqlite3VdbeMemGrow(Mem *pMem, int n, int preserve);
  13809. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int n);
  13810. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *, int);
  13811. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame*);
  13812. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *);
  13813. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p);
  13814. SQLITE_PRIVATE int sqlite3VdbeSorterInit(sqlite3 *, int, VdbeCursor *);
  13815. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *, VdbeSorter *);
  13816. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *, VdbeCursor *);
  13817. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *, Mem *);
  13818. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *, const VdbeCursor *, int *);
  13819. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *, int *);
  13820. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(const VdbeCursor *, Mem *);
  13821. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(const VdbeCursor *, Mem *, int, int *);
  13822. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  13823. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe*);
  13824. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe*);
  13825. #else
  13826. # define sqlite3VdbeEnter(X)
  13827. # define sqlite3VdbeLeave(X)
  13828. #endif
  13829. #ifdef SQLITE_DEBUG
  13830. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe*,Mem*);
  13831. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem*);
  13832. #endif
  13833. #ifndef SQLITE_OMIT_FOREIGN_KEY
  13834. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *, int);
  13835. #else
  13836. # define sqlite3VdbeCheckFk(p,i) 0
  13837. #endif
  13838. SQLITE_PRIVATE int sqlite3VdbeMemTranslate(Mem*, u8);
  13839. #ifdef SQLITE_DEBUG
  13840. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe*);
  13841. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf);
  13842. #endif
  13843. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem);
  13844. #ifndef SQLITE_OMIT_INCRBLOB
  13845. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *);
  13846. #define ExpandBlob(P) (((P)->flags&MEM_Zero)?sqlite3VdbeMemExpandBlob(P):0)
  13847. #else
  13848. #define sqlite3VdbeMemExpandBlob(x) SQLITE_OK
  13849. #define ExpandBlob(P) SQLITE_OK
  13850. #endif
  13851. #endif /* !defined(_VDBEINT_H_) */
  13852. /************** End of vdbeInt.h *********************************************/
  13853. /************** Continuing where we left off in status.c *********************/
  13854. /*
  13855. ** Variables in which to record status information.
  13856. */
  13857. typedef struct sqlite3StatType sqlite3StatType;
  13858. static SQLITE_WSD struct sqlite3StatType {
  13859. int nowValue[10]; /* Current value */
  13860. int mxValue[10]; /* Maximum value */
  13861. } sqlite3Stat = { {0,}, {0,} };
  13862. /* The "wsdStat" macro will resolve to the status information
  13863. ** state vector. If writable static data is unsupported on the target,
  13864. ** we have to locate the state vector at run-time. In the more common
  13865. ** case where writable static data is supported, wsdStat can refer directly
  13866. ** to the "sqlite3Stat" state vector declared above.
  13867. */
  13868. #ifdef SQLITE_OMIT_WSD
  13869. # define wsdStatInit sqlite3StatType *x = &GLOBAL(sqlite3StatType,sqlite3Stat)
  13870. # define wsdStat x[0]
  13871. #else
  13872. # define wsdStatInit
  13873. # define wsdStat sqlite3Stat
  13874. #endif
  13875. /*
  13876. ** Return the current value of a status parameter.
  13877. */
  13878. SQLITE_PRIVATE int sqlite3StatusValue(int op){
  13879. wsdStatInit;
  13880. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13881. return wsdStat.nowValue[op];
  13882. }
  13883. /*
  13884. ** Add N to the value of a status record. It is assumed that the
  13885. ** caller holds appropriate locks.
  13886. */
  13887. SQLITE_PRIVATE void sqlite3StatusAdd(int op, int N){
  13888. wsdStatInit;
  13889. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13890. wsdStat.nowValue[op] += N;
  13891. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13892. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13893. }
  13894. }
  13895. /*
  13896. ** Set the value of a status to X.
  13897. */
  13898. SQLITE_PRIVATE void sqlite3StatusSet(int op, int X){
  13899. wsdStatInit;
  13900. assert( op>=0 && op<ArraySize(wsdStat.nowValue) );
  13901. wsdStat.nowValue[op] = X;
  13902. if( wsdStat.nowValue[op]>wsdStat.mxValue[op] ){
  13903. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13904. }
  13905. }
  13906. /*
  13907. ** Query status information.
  13908. **
  13909. ** This implementation assumes that reading or writing an aligned
  13910. ** 32-bit integer is an atomic operation. If that assumption is not true,
  13911. ** then this routine is not threadsafe.
  13912. */
  13913. SQLITE_API int sqlite3_status(int op, int *pCurrent, int *pHighwater, int resetFlag){
  13914. wsdStatInit;
  13915. if( op<0 || op>=ArraySize(wsdStat.nowValue) ){
  13916. return SQLITE_MISUSE_BKPT;
  13917. }
  13918. *pCurrent = wsdStat.nowValue[op];
  13919. *pHighwater = wsdStat.mxValue[op];
  13920. if( resetFlag ){
  13921. wsdStat.mxValue[op] = wsdStat.nowValue[op];
  13922. }
  13923. return SQLITE_OK;
  13924. }
  13925. /*
  13926. ** Query status information for a single database connection
  13927. */
  13928. SQLITE_API int sqlite3_db_status(
  13929. sqlite3 *db, /* The database connection whose status is desired */
  13930. int op, /* Status verb */
  13931. int *pCurrent, /* Write current value here */
  13932. int *pHighwater, /* Write high-water mark here */
  13933. int resetFlag /* Reset high-water mark if true */
  13934. ){
  13935. int rc = SQLITE_OK; /* Return code */
  13936. sqlite3_mutex_enter(db->mutex);
  13937. switch( op ){
  13938. case SQLITE_DBSTATUS_LOOKASIDE_USED: {
  13939. *pCurrent = db->lookaside.nOut;
  13940. *pHighwater = db->lookaside.mxOut;
  13941. if( resetFlag ){
  13942. db->lookaside.mxOut = db->lookaside.nOut;
  13943. }
  13944. break;
  13945. }
  13946. case SQLITE_DBSTATUS_LOOKASIDE_HIT:
  13947. case SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE:
  13948. case SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL: {
  13949. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_HIT );
  13950. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_SIZE );
  13951. testcase( op==SQLITE_DBSTATUS_LOOKASIDE_MISS_FULL );
  13952. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)>=0 );
  13953. assert( (op-SQLITE_DBSTATUS_LOOKASIDE_HIT)<3 );
  13954. *pCurrent = 0;
  13955. *pHighwater = db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT];
  13956. if( resetFlag ){
  13957. db->lookaside.anStat[op - SQLITE_DBSTATUS_LOOKASIDE_HIT] = 0;
  13958. }
  13959. break;
  13960. }
  13961. /*
  13962. ** Return an approximation for the amount of memory currently used
  13963. ** by all pagers associated with the given database connection. The
  13964. ** highwater mark is meaningless and is returned as zero.
  13965. */
  13966. case SQLITE_DBSTATUS_CACHE_USED: {
  13967. int totalUsed = 0;
  13968. int i;
  13969. sqlite3BtreeEnterAll(db);
  13970. for(i=0; i<db->nDb; i++){
  13971. Btree *pBt = db->aDb[i].pBt;
  13972. if( pBt ){
  13973. Pager *pPager = sqlite3BtreePager(pBt);
  13974. totalUsed += sqlite3PagerMemUsed(pPager);
  13975. }
  13976. }
  13977. sqlite3BtreeLeaveAll(db);
  13978. *pCurrent = totalUsed;
  13979. *pHighwater = 0;
  13980. break;
  13981. }
  13982. /*
  13983. ** *pCurrent gets an accurate estimate of the amount of memory used
  13984. ** to store the schema for all databases (main, temp, and any ATTACHed
  13985. ** databases. *pHighwater is set to zero.
  13986. */
  13987. case SQLITE_DBSTATUS_SCHEMA_USED: {
  13988. int i; /* Used to iterate through schemas */
  13989. int nByte = 0; /* Used to accumulate return value */
  13990. sqlite3BtreeEnterAll(db);
  13991. db->pnBytesFreed = &nByte;
  13992. for(i=0; i<db->nDb; i++){
  13993. Schema *pSchema = db->aDb[i].pSchema;
  13994. if( ALWAYS(pSchema!=0) ){
  13995. HashElem *p;
  13996. nByte += sqlite3GlobalConfig.m.xRoundup(sizeof(HashElem)) * (
  13997. pSchema->tblHash.count
  13998. + pSchema->trigHash.count
  13999. + pSchema->idxHash.count
  14000. + pSchema->fkeyHash.count
  14001. );
  14002. nByte += sqlite3MallocSize(pSchema->tblHash.ht);
  14003. nByte += sqlite3MallocSize(pSchema->trigHash.ht);
  14004. nByte += sqlite3MallocSize(pSchema->idxHash.ht);
  14005. nByte += sqlite3MallocSize(pSchema->fkeyHash.ht);
  14006. for(p=sqliteHashFirst(&pSchema->trigHash); p; p=sqliteHashNext(p)){
  14007. sqlite3DeleteTrigger(db, (Trigger*)sqliteHashData(p));
  14008. }
  14009. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  14010. sqlite3DeleteTable(db, (Table *)sqliteHashData(p));
  14011. }
  14012. }
  14013. }
  14014. db->pnBytesFreed = 0;
  14015. sqlite3BtreeLeaveAll(db);
  14016. *pHighwater = 0;
  14017. *pCurrent = nByte;
  14018. break;
  14019. }
  14020. /*
  14021. ** *pCurrent gets an accurate estimate of the amount of memory used
  14022. ** to store all prepared statements.
  14023. ** *pHighwater is set to zero.
  14024. */
  14025. case SQLITE_DBSTATUS_STMT_USED: {
  14026. struct Vdbe *pVdbe; /* Used to iterate through VMs */
  14027. int nByte = 0; /* Used to accumulate return value */
  14028. db->pnBytesFreed = &nByte;
  14029. for(pVdbe=db->pVdbe; pVdbe; pVdbe=pVdbe->pNext){
  14030. sqlite3VdbeClearObject(db, pVdbe);
  14031. sqlite3DbFree(db, pVdbe);
  14032. }
  14033. db->pnBytesFreed = 0;
  14034. *pHighwater = 0; /* IMP: R-64479-57858 */
  14035. *pCurrent = nByte;
  14036. break;
  14037. }
  14038. /*
  14039. ** Set *pCurrent to the total cache hits or misses encountered by all
  14040. ** pagers the database handle is connected to. *pHighwater is always set
  14041. ** to zero.
  14042. */
  14043. case SQLITE_DBSTATUS_CACHE_HIT:
  14044. case SQLITE_DBSTATUS_CACHE_MISS:
  14045. case SQLITE_DBSTATUS_CACHE_WRITE:{
  14046. int i;
  14047. int nRet = 0;
  14048. assert( SQLITE_DBSTATUS_CACHE_MISS==SQLITE_DBSTATUS_CACHE_HIT+1 );
  14049. assert( SQLITE_DBSTATUS_CACHE_WRITE==SQLITE_DBSTATUS_CACHE_HIT+2 );
  14050. for(i=0; i<db->nDb; i++){
  14051. if( db->aDb[i].pBt ){
  14052. Pager *pPager = sqlite3BtreePager(db->aDb[i].pBt);
  14053. sqlite3PagerCacheStat(pPager, op, resetFlag, &nRet);
  14054. }
  14055. }
  14056. *pHighwater = 0; /* IMP: R-42420-56072 */
  14057. /* IMP: R-54100-20147 */
  14058. /* IMP: R-29431-39229 */
  14059. *pCurrent = nRet;
  14060. break;
  14061. }
  14062. /* Set *pCurrent to non-zero if there are unresolved deferred foreign
  14063. ** key constraints. Set *pCurrent to zero if all foreign key constraints
  14064. ** have been satisfied. The *pHighwater is always set to zero.
  14065. */
  14066. case SQLITE_DBSTATUS_DEFERRED_FKS: {
  14067. *pHighwater = 0; /* IMP: R-11967-56545 */
  14068. *pCurrent = db->nDeferredImmCons>0 || db->nDeferredCons>0;
  14069. break;
  14070. }
  14071. default: {
  14072. rc = SQLITE_ERROR;
  14073. }
  14074. }
  14075. sqlite3_mutex_leave(db->mutex);
  14076. return rc;
  14077. }
  14078. /************** End of status.c **********************************************/
  14079. /************** Begin file date.c ********************************************/
  14080. /*
  14081. ** 2003 October 31
  14082. **
  14083. ** The author disclaims copyright to this source code. In place of
  14084. ** a legal notice, here is a blessing:
  14085. **
  14086. ** May you do good and not evil.
  14087. ** May you find forgiveness for yourself and forgive others.
  14088. ** May you share freely, never taking more than you give.
  14089. **
  14090. *************************************************************************
  14091. ** This file contains the C functions that implement date and time
  14092. ** functions for SQLite.
  14093. **
  14094. ** There is only one exported symbol in this file - the function
  14095. ** sqlite3RegisterDateTimeFunctions() found at the bottom of the file.
  14096. ** All other code has file scope.
  14097. **
  14098. ** SQLite processes all times and dates as Julian Day numbers. The
  14099. ** dates and times are stored as the number of days since noon
  14100. ** in Greenwich on November 24, 4714 B.C. according to the Gregorian
  14101. ** calendar system.
  14102. **
  14103. ** 1970-01-01 00:00:00 is JD 2440587.5
  14104. ** 2000-01-01 00:00:00 is JD 2451544.5
  14105. **
  14106. ** This implementation requires years to be expressed as a 4-digit number
  14107. ** which means that only dates between 0000-01-01 and 9999-12-31 can
  14108. ** be represented, even though julian day numbers allow a much wider
  14109. ** range of dates.
  14110. **
  14111. ** The Gregorian calendar system is used for all dates and times,
  14112. ** even those that predate the Gregorian calendar. Historians usually
  14113. ** use the Julian calendar for dates prior to 1582-10-15 and for some
  14114. ** dates afterwards, depending on locale. Beware of this difference.
  14115. **
  14116. ** The conversion algorithms are implemented based on descriptions
  14117. ** in the following text:
  14118. **
  14119. ** Jean Meeus
  14120. ** Astronomical Algorithms, 2nd Edition, 1998
  14121. ** ISBM 0-943396-61-1
  14122. ** Willmann-Bell, Inc
  14123. ** Richmond, Virginia (USA)
  14124. */
  14125. /* #include <stdlib.h> */
  14126. /* #include <assert.h> */
  14127. #include <time.h>
  14128. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  14129. /*
  14130. ** A structure for holding a single date and time.
  14131. */
  14132. typedef struct DateTime DateTime;
  14133. struct DateTime {
  14134. sqlite3_int64 iJD; /* The julian day number times 86400000 */
  14135. int Y, M, D; /* Year, month, and day */
  14136. int h, m; /* Hour and minutes */
  14137. int tz; /* Timezone offset in minutes */
  14138. double s; /* Seconds */
  14139. char validYMD; /* True (1) if Y,M,D are valid */
  14140. char validHMS; /* True (1) if h,m,s are valid */
  14141. char validJD; /* True (1) if iJD is valid */
  14142. char validTZ; /* True (1) if tz is valid */
  14143. };
  14144. /*
  14145. ** Convert zDate into one or more integers. Additional arguments
  14146. ** come in groups of 5 as follows:
  14147. **
  14148. ** N number of digits in the integer
  14149. ** min minimum allowed value of the integer
  14150. ** max maximum allowed value of the integer
  14151. ** nextC first character after the integer
  14152. ** pVal where to write the integers value.
  14153. **
  14154. ** Conversions continue until one with nextC==0 is encountered.
  14155. ** The function returns the number of successful conversions.
  14156. */
  14157. static int getDigits(const char *zDate, ...){
  14158. va_list ap;
  14159. int val;
  14160. int N;
  14161. int min;
  14162. int max;
  14163. int nextC;
  14164. int *pVal;
  14165. int cnt = 0;
  14166. va_start(ap, zDate);
  14167. do{
  14168. N = va_arg(ap, int);
  14169. min = va_arg(ap, int);
  14170. max = va_arg(ap, int);
  14171. nextC = va_arg(ap, int);
  14172. pVal = va_arg(ap, int*);
  14173. val = 0;
  14174. while( N-- ){
  14175. if( !sqlite3Isdigit(*zDate) ){
  14176. goto end_getDigits;
  14177. }
  14178. val = val*10 + *zDate - '0';
  14179. zDate++;
  14180. }
  14181. if( val<min || val>max || (nextC!=0 && nextC!=*zDate) ){
  14182. goto end_getDigits;
  14183. }
  14184. *pVal = val;
  14185. zDate++;
  14186. cnt++;
  14187. }while( nextC );
  14188. end_getDigits:
  14189. va_end(ap);
  14190. return cnt;
  14191. }
  14192. /*
  14193. ** Parse a timezone extension on the end of a date-time.
  14194. ** The extension is of the form:
  14195. **
  14196. ** (+/-)HH:MM
  14197. **
  14198. ** Or the "zulu" notation:
  14199. **
  14200. ** Z
  14201. **
  14202. ** If the parse is successful, write the number of minutes
  14203. ** of change in p->tz and return 0. If a parser error occurs,
  14204. ** return non-zero.
  14205. **
  14206. ** A missing specifier is not considered an error.
  14207. */
  14208. static int parseTimezone(const char *zDate, DateTime *p){
  14209. int sgn = 0;
  14210. int nHr, nMn;
  14211. int c;
  14212. while( sqlite3Isspace(*zDate) ){ zDate++; }
  14213. p->tz = 0;
  14214. c = *zDate;
  14215. if( c=='-' ){
  14216. sgn = -1;
  14217. }else if( c=='+' ){
  14218. sgn = +1;
  14219. }else if( c=='Z' || c=='z' ){
  14220. zDate++;
  14221. goto zulu_time;
  14222. }else{
  14223. return c!=0;
  14224. }
  14225. zDate++;
  14226. if( getDigits(zDate, 2, 0, 14, ':', &nHr, 2, 0, 59, 0, &nMn)!=2 ){
  14227. return 1;
  14228. }
  14229. zDate += 5;
  14230. p->tz = sgn*(nMn + nHr*60);
  14231. zulu_time:
  14232. while( sqlite3Isspace(*zDate) ){ zDate++; }
  14233. return *zDate!=0;
  14234. }
  14235. /*
  14236. ** Parse times of the form HH:MM or HH:MM:SS or HH:MM:SS.FFFF.
  14237. ** The HH, MM, and SS must each be exactly 2 digits. The
  14238. ** fractional seconds FFFF can be one or more digits.
  14239. **
  14240. ** Return 1 if there is a parsing error and 0 on success.
  14241. */
  14242. static int parseHhMmSs(const char *zDate, DateTime *p){
  14243. int h, m, s;
  14244. double ms = 0.0;
  14245. if( getDigits(zDate, 2, 0, 24, ':', &h, 2, 0, 59, 0, &m)!=2 ){
  14246. return 1;
  14247. }
  14248. zDate += 5;
  14249. if( *zDate==':' ){
  14250. zDate++;
  14251. if( getDigits(zDate, 2, 0, 59, 0, &s)!=1 ){
  14252. return 1;
  14253. }
  14254. zDate += 2;
  14255. if( *zDate=='.' && sqlite3Isdigit(zDate[1]) ){
  14256. double rScale = 1.0;
  14257. zDate++;
  14258. while( sqlite3Isdigit(*zDate) ){
  14259. ms = ms*10.0 + *zDate - '0';
  14260. rScale *= 10.0;
  14261. zDate++;
  14262. }
  14263. ms /= rScale;
  14264. }
  14265. }else{
  14266. s = 0;
  14267. }
  14268. p->validJD = 0;
  14269. p->validHMS = 1;
  14270. p->h = h;
  14271. p->m = m;
  14272. p->s = s + ms;
  14273. if( parseTimezone(zDate, p) ) return 1;
  14274. p->validTZ = (p->tz!=0)?1:0;
  14275. return 0;
  14276. }
  14277. /*
  14278. ** Convert from YYYY-MM-DD HH:MM:SS to julian day. We always assume
  14279. ** that the YYYY-MM-DD is according to the Gregorian calendar.
  14280. **
  14281. ** Reference: Meeus page 61
  14282. */
  14283. static void computeJD(DateTime *p){
  14284. int Y, M, D, A, B, X1, X2;
  14285. if( p->validJD ) return;
  14286. if( p->validYMD ){
  14287. Y = p->Y;
  14288. M = p->M;
  14289. D = p->D;
  14290. }else{
  14291. Y = 2000; /* If no YMD specified, assume 2000-Jan-01 */
  14292. M = 1;
  14293. D = 1;
  14294. }
  14295. if( M<=2 ){
  14296. Y--;
  14297. M += 12;
  14298. }
  14299. A = Y/100;
  14300. B = 2 - A + (A/4);
  14301. X1 = 36525*(Y+4716)/100;
  14302. X2 = 306001*(M+1)/10000;
  14303. p->iJD = (sqlite3_int64)((X1 + X2 + D + B - 1524.5 ) * 86400000);
  14304. p->validJD = 1;
  14305. if( p->validHMS ){
  14306. p->iJD += p->h*3600000 + p->m*60000 + (sqlite3_int64)(p->s*1000);
  14307. if( p->validTZ ){
  14308. p->iJD -= p->tz*60000;
  14309. p->validYMD = 0;
  14310. p->validHMS = 0;
  14311. p->validTZ = 0;
  14312. }
  14313. }
  14314. }
  14315. /*
  14316. ** Parse dates of the form
  14317. **
  14318. ** YYYY-MM-DD HH:MM:SS.FFF
  14319. ** YYYY-MM-DD HH:MM:SS
  14320. ** YYYY-MM-DD HH:MM
  14321. ** YYYY-MM-DD
  14322. **
  14323. ** Write the result into the DateTime structure and return 0
  14324. ** on success and 1 if the input string is not a well-formed
  14325. ** date.
  14326. */
  14327. static int parseYyyyMmDd(const char *zDate, DateTime *p){
  14328. int Y, M, D, neg;
  14329. if( zDate[0]=='-' ){
  14330. zDate++;
  14331. neg = 1;
  14332. }else{
  14333. neg = 0;
  14334. }
  14335. if( getDigits(zDate,4,0,9999,'-',&Y,2,1,12,'-',&M,2,1,31,0,&D)!=3 ){
  14336. return 1;
  14337. }
  14338. zDate += 10;
  14339. while( sqlite3Isspace(*zDate) || 'T'==*(u8*)zDate ){ zDate++; }
  14340. if( parseHhMmSs(zDate, p)==0 ){
  14341. /* We got the time */
  14342. }else if( *zDate==0 ){
  14343. p->validHMS = 0;
  14344. }else{
  14345. return 1;
  14346. }
  14347. p->validJD = 0;
  14348. p->validYMD = 1;
  14349. p->Y = neg ? -Y : Y;
  14350. p->M = M;
  14351. p->D = D;
  14352. if( p->validTZ ){
  14353. computeJD(p);
  14354. }
  14355. return 0;
  14356. }
  14357. /*
  14358. ** Set the time to the current time reported by the VFS.
  14359. **
  14360. ** Return the number of errors.
  14361. */
  14362. static int setDateTimeToCurrent(sqlite3_context *context, DateTime *p){
  14363. p->iJD = sqlite3StmtCurrentTime(context);
  14364. if( p->iJD>0 ){
  14365. p->validJD = 1;
  14366. return 0;
  14367. }else{
  14368. return 1;
  14369. }
  14370. }
  14371. /*
  14372. ** Attempt to parse the given string into a Julian Day Number. Return
  14373. ** the number of errors.
  14374. **
  14375. ** The following are acceptable forms for the input string:
  14376. **
  14377. ** YYYY-MM-DD HH:MM:SS.FFF +/-HH:MM
  14378. ** DDDD.DD
  14379. ** now
  14380. **
  14381. ** In the first form, the +/-HH:MM is always optional. The fractional
  14382. ** seconds extension (the ".FFF") is optional. The seconds portion
  14383. ** (":SS.FFF") is option. The year and date can be omitted as long
  14384. ** as there is a time string. The time string can be omitted as long
  14385. ** as there is a year and date.
  14386. */
  14387. static int parseDateOrTime(
  14388. sqlite3_context *context,
  14389. const char *zDate,
  14390. DateTime *p
  14391. ){
  14392. double r;
  14393. if( parseYyyyMmDd(zDate,p)==0 ){
  14394. return 0;
  14395. }else if( parseHhMmSs(zDate, p)==0 ){
  14396. return 0;
  14397. }else if( sqlite3StrICmp(zDate,"now")==0){
  14398. return setDateTimeToCurrent(context, p);
  14399. }else if( sqlite3AtoF(zDate, &r, sqlite3Strlen30(zDate), SQLITE_UTF8) ){
  14400. p->iJD = (sqlite3_int64)(r*86400000.0 + 0.5);
  14401. p->validJD = 1;
  14402. return 0;
  14403. }
  14404. return 1;
  14405. }
  14406. /*
  14407. ** Compute the Year, Month, and Day from the julian day number.
  14408. */
  14409. static void computeYMD(DateTime *p){
  14410. int Z, A, B, C, D, E, X1;
  14411. if( p->validYMD ) return;
  14412. if( !p->validJD ){
  14413. p->Y = 2000;
  14414. p->M = 1;
  14415. p->D = 1;
  14416. }else{
  14417. Z = (int)((p->iJD + 43200000)/86400000);
  14418. A = (int)((Z - 1867216.25)/36524.25);
  14419. A = Z + 1 + A - (A/4);
  14420. B = A + 1524;
  14421. C = (int)((B - 122.1)/365.25);
  14422. D = (36525*C)/100;
  14423. E = (int)((B-D)/30.6001);
  14424. X1 = (int)(30.6001*E);
  14425. p->D = B - D - X1;
  14426. p->M = E<14 ? E-1 : E-13;
  14427. p->Y = p->M>2 ? C - 4716 : C - 4715;
  14428. }
  14429. p->validYMD = 1;
  14430. }
  14431. /*
  14432. ** Compute the Hour, Minute, and Seconds from the julian day number.
  14433. */
  14434. static void computeHMS(DateTime *p){
  14435. int s;
  14436. if( p->validHMS ) return;
  14437. computeJD(p);
  14438. s = (int)((p->iJD + 43200000) % 86400000);
  14439. p->s = s/1000.0;
  14440. s = (int)p->s;
  14441. p->s -= s;
  14442. p->h = s/3600;
  14443. s -= p->h*3600;
  14444. p->m = s/60;
  14445. p->s += s - p->m*60;
  14446. p->validHMS = 1;
  14447. }
  14448. /*
  14449. ** Compute both YMD and HMS
  14450. */
  14451. static void computeYMD_HMS(DateTime *p){
  14452. computeYMD(p);
  14453. computeHMS(p);
  14454. }
  14455. /*
  14456. ** Clear the YMD and HMS and the TZ
  14457. */
  14458. static void clearYMD_HMS_TZ(DateTime *p){
  14459. p->validYMD = 0;
  14460. p->validHMS = 0;
  14461. p->validTZ = 0;
  14462. }
  14463. /*
  14464. ** On recent Windows platforms, the localtime_s() function is available
  14465. ** as part of the "Secure CRT". It is essentially equivalent to
  14466. ** localtime_r() available under most POSIX platforms, except that the
  14467. ** order of the parameters is reversed.
  14468. **
  14469. ** See http://msdn.microsoft.com/en-us/library/a442x3ye(VS.80).aspx.
  14470. **
  14471. ** If the user has not indicated to use localtime_r() or localtime_s()
  14472. ** already, check for an MSVC build environment that provides
  14473. ** localtime_s().
  14474. */
  14475. #if !defined(HAVE_LOCALTIME_R) && !defined(HAVE_LOCALTIME_S) && \
  14476. defined(_MSC_VER) && defined(_CRT_INSECURE_DEPRECATE)
  14477. #define HAVE_LOCALTIME_S 1
  14478. #endif
  14479. #ifndef SQLITE_OMIT_LOCALTIME
  14480. /*
  14481. ** The following routine implements the rough equivalent of localtime_r()
  14482. ** using whatever operating-system specific localtime facility that
  14483. ** is available. This routine returns 0 on success and
  14484. ** non-zero on any kind of error.
  14485. **
  14486. ** If the sqlite3GlobalConfig.bLocaltimeFault variable is true then this
  14487. ** routine will always fail.
  14488. **
  14489. ** EVIDENCE-OF: R-62172-00036 In this implementation, the standard C
  14490. ** library function localtime_r() is used to assist in the calculation of
  14491. ** local time.
  14492. */
  14493. static int osLocaltime(time_t *t, struct tm *pTm){
  14494. int rc;
  14495. #if (!defined(HAVE_LOCALTIME_R) || !HAVE_LOCALTIME_R) \
  14496. && (!defined(HAVE_LOCALTIME_S) || !HAVE_LOCALTIME_S)
  14497. struct tm *pX;
  14498. #if SQLITE_THREADSAFE>0
  14499. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  14500. #endif
  14501. sqlite3_mutex_enter(mutex);
  14502. pX = localtime(t);
  14503. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14504. if( sqlite3GlobalConfig.bLocaltimeFault ) pX = 0;
  14505. #endif
  14506. if( pX ) *pTm = *pX;
  14507. sqlite3_mutex_leave(mutex);
  14508. rc = pX==0;
  14509. #else
  14510. #ifndef SQLITE_OMIT_BUILTIN_TEST
  14511. if( sqlite3GlobalConfig.bLocaltimeFault ) return 1;
  14512. #endif
  14513. #if defined(HAVE_LOCALTIME_R) && HAVE_LOCALTIME_R
  14514. rc = localtime_r(t, pTm)==0;
  14515. #else
  14516. rc = localtime_s(pTm, t);
  14517. #endif /* HAVE_LOCALTIME_R */
  14518. #endif /* HAVE_LOCALTIME_R || HAVE_LOCALTIME_S */
  14519. return rc;
  14520. }
  14521. #endif /* SQLITE_OMIT_LOCALTIME */
  14522. #ifndef SQLITE_OMIT_LOCALTIME
  14523. /*
  14524. ** Compute the difference (in milliseconds) between localtime and UTC
  14525. ** (a.k.a. GMT) for the time value p where p is in UTC. If no error occurs,
  14526. ** return this value and set *pRc to SQLITE_OK.
  14527. **
  14528. ** Or, if an error does occur, set *pRc to SQLITE_ERROR. The returned value
  14529. ** is undefined in this case.
  14530. */
  14531. static sqlite3_int64 localtimeOffset(
  14532. DateTime *p, /* Date at which to calculate offset */
  14533. sqlite3_context *pCtx, /* Write error here if one occurs */
  14534. int *pRc /* OUT: Error code. SQLITE_OK or ERROR */
  14535. ){
  14536. DateTime x, y;
  14537. time_t t;
  14538. struct tm sLocal;
  14539. /* Initialize the contents of sLocal to avoid a compiler warning. */
  14540. memset(&sLocal, 0, sizeof(sLocal));
  14541. x = *p;
  14542. computeYMD_HMS(&x);
  14543. if( x.Y<1971 || x.Y>=2038 ){
  14544. /* EVIDENCE-OF: R-55269-29598 The localtime_r() C function normally only
  14545. ** works for years between 1970 and 2037. For dates outside this range,
  14546. ** SQLite attempts to map the year into an equivalent year within this
  14547. ** range, do the calculation, then map the year back.
  14548. */
  14549. x.Y = 2000;
  14550. x.M = 1;
  14551. x.D = 1;
  14552. x.h = 0;
  14553. x.m = 0;
  14554. x.s = 0.0;
  14555. } else {
  14556. int s = (int)(x.s + 0.5);
  14557. x.s = s;
  14558. }
  14559. x.tz = 0;
  14560. x.validJD = 0;
  14561. computeJD(&x);
  14562. t = (time_t)(x.iJD/1000 - 21086676*(i64)10000);
  14563. if( osLocaltime(&t, &sLocal) ){
  14564. sqlite3_result_error(pCtx, "local time unavailable", -1);
  14565. *pRc = SQLITE_ERROR;
  14566. return 0;
  14567. }
  14568. y.Y = sLocal.tm_year + 1900;
  14569. y.M = sLocal.tm_mon + 1;
  14570. y.D = sLocal.tm_mday;
  14571. y.h = sLocal.tm_hour;
  14572. y.m = sLocal.tm_min;
  14573. y.s = sLocal.tm_sec;
  14574. y.validYMD = 1;
  14575. y.validHMS = 1;
  14576. y.validJD = 0;
  14577. y.validTZ = 0;
  14578. computeJD(&y);
  14579. *pRc = SQLITE_OK;
  14580. return y.iJD - x.iJD;
  14581. }
  14582. #endif /* SQLITE_OMIT_LOCALTIME */
  14583. /*
  14584. ** Process a modifier to a date-time stamp. The modifiers are
  14585. ** as follows:
  14586. **
  14587. ** NNN days
  14588. ** NNN hours
  14589. ** NNN minutes
  14590. ** NNN.NNNN seconds
  14591. ** NNN months
  14592. ** NNN years
  14593. ** start of month
  14594. ** start of year
  14595. ** start of week
  14596. ** start of day
  14597. ** weekday N
  14598. ** unixepoch
  14599. ** localtime
  14600. ** utc
  14601. **
  14602. ** Return 0 on success and 1 if there is any kind of error. If the error
  14603. ** is in a system call (i.e. localtime()), then an error message is written
  14604. ** to context pCtx. If the error is an unrecognized modifier, no error is
  14605. ** written to pCtx.
  14606. */
  14607. static int parseModifier(sqlite3_context *pCtx, const char *zMod, DateTime *p){
  14608. int rc = 1;
  14609. int n;
  14610. double r;
  14611. char *z, zBuf[30];
  14612. z = zBuf;
  14613. for(n=0; n<ArraySize(zBuf)-1 && zMod[n]; n++){
  14614. z[n] = (char)sqlite3UpperToLower[(u8)zMod[n]];
  14615. }
  14616. z[n] = 0;
  14617. switch( z[0] ){
  14618. #ifndef SQLITE_OMIT_LOCALTIME
  14619. case 'l': {
  14620. /* localtime
  14621. **
  14622. ** Assuming the current time value is UTC (a.k.a. GMT), shift it to
  14623. ** show local time.
  14624. */
  14625. if( strcmp(z, "localtime")==0 ){
  14626. computeJD(p);
  14627. p->iJD += localtimeOffset(p, pCtx, &rc);
  14628. clearYMD_HMS_TZ(p);
  14629. }
  14630. break;
  14631. }
  14632. #endif
  14633. case 'u': {
  14634. /*
  14635. ** unixepoch
  14636. **
  14637. ** Treat the current value of p->iJD as the number of
  14638. ** seconds since 1970. Convert to a real julian day number.
  14639. */
  14640. if( strcmp(z, "unixepoch")==0 && p->validJD ){
  14641. p->iJD = (p->iJD + 43200)/86400 + 21086676*(i64)10000000;
  14642. clearYMD_HMS_TZ(p);
  14643. rc = 0;
  14644. }
  14645. #ifndef SQLITE_OMIT_LOCALTIME
  14646. else if( strcmp(z, "utc")==0 ){
  14647. sqlite3_int64 c1;
  14648. computeJD(p);
  14649. c1 = localtimeOffset(p, pCtx, &rc);
  14650. if( rc==SQLITE_OK ){
  14651. p->iJD -= c1;
  14652. clearYMD_HMS_TZ(p);
  14653. p->iJD += c1 - localtimeOffset(p, pCtx, &rc);
  14654. }
  14655. }
  14656. #endif
  14657. break;
  14658. }
  14659. case 'w': {
  14660. /*
  14661. ** weekday N
  14662. **
  14663. ** Move the date to the same time on the next occurrence of
  14664. ** weekday N where 0==Sunday, 1==Monday, and so forth. If the
  14665. ** date is already on the appropriate weekday, this is a no-op.
  14666. */
  14667. if( strncmp(z, "weekday ", 8)==0
  14668. && sqlite3AtoF(&z[8], &r, sqlite3Strlen30(&z[8]), SQLITE_UTF8)
  14669. && (n=(int)r)==r && n>=0 && r<7 ){
  14670. sqlite3_int64 Z;
  14671. computeYMD_HMS(p);
  14672. p->validTZ = 0;
  14673. p->validJD = 0;
  14674. computeJD(p);
  14675. Z = ((p->iJD + 129600000)/86400000) % 7;
  14676. if( Z>n ) Z -= 7;
  14677. p->iJD += (n - Z)*86400000;
  14678. clearYMD_HMS_TZ(p);
  14679. rc = 0;
  14680. }
  14681. break;
  14682. }
  14683. case 's': {
  14684. /*
  14685. ** start of TTTTT
  14686. **
  14687. ** Move the date backwards to the beginning of the current day,
  14688. ** or month or year.
  14689. */
  14690. if( strncmp(z, "start of ", 9)!=0 ) break;
  14691. z += 9;
  14692. computeYMD(p);
  14693. p->validHMS = 1;
  14694. p->h = p->m = 0;
  14695. p->s = 0.0;
  14696. p->validTZ = 0;
  14697. p->validJD = 0;
  14698. if( strcmp(z,"month")==0 ){
  14699. p->D = 1;
  14700. rc = 0;
  14701. }else if( strcmp(z,"year")==0 ){
  14702. computeYMD(p);
  14703. p->M = 1;
  14704. p->D = 1;
  14705. rc = 0;
  14706. }else if( strcmp(z,"day")==0 ){
  14707. rc = 0;
  14708. }
  14709. break;
  14710. }
  14711. case '+':
  14712. case '-':
  14713. case '0':
  14714. case '1':
  14715. case '2':
  14716. case '3':
  14717. case '4':
  14718. case '5':
  14719. case '6':
  14720. case '7':
  14721. case '8':
  14722. case '9': {
  14723. double rRounder;
  14724. for(n=1; z[n] && z[n]!=':' && !sqlite3Isspace(z[n]); n++){}
  14725. if( !sqlite3AtoF(z, &r, n, SQLITE_UTF8) ){
  14726. rc = 1;
  14727. break;
  14728. }
  14729. if( z[n]==':' ){
  14730. /* A modifier of the form (+|-)HH:MM:SS.FFF adds (or subtracts) the
  14731. ** specified number of hours, minutes, seconds, and fractional seconds
  14732. ** to the time. The ".FFF" may be omitted. The ":SS.FFF" may be
  14733. ** omitted.
  14734. */
  14735. const char *z2 = z;
  14736. DateTime tx;
  14737. sqlite3_int64 day;
  14738. if( !sqlite3Isdigit(*z2) ) z2++;
  14739. memset(&tx, 0, sizeof(tx));
  14740. if( parseHhMmSs(z2, &tx) ) break;
  14741. computeJD(&tx);
  14742. tx.iJD -= 43200000;
  14743. day = tx.iJD/86400000;
  14744. tx.iJD -= day*86400000;
  14745. if( z[0]=='-' ) tx.iJD = -tx.iJD;
  14746. computeJD(p);
  14747. clearYMD_HMS_TZ(p);
  14748. p->iJD += tx.iJD;
  14749. rc = 0;
  14750. break;
  14751. }
  14752. z += n;
  14753. while( sqlite3Isspace(*z) ) z++;
  14754. n = sqlite3Strlen30(z);
  14755. if( n>10 || n<3 ) break;
  14756. if( z[n-1]=='s' ){ z[n-1] = 0; n--; }
  14757. computeJD(p);
  14758. rc = 0;
  14759. rRounder = r<0 ? -0.5 : +0.5;
  14760. if( n==3 && strcmp(z,"day")==0 ){
  14761. p->iJD += (sqlite3_int64)(r*86400000.0 + rRounder);
  14762. }else if( n==4 && strcmp(z,"hour")==0 ){
  14763. p->iJD += (sqlite3_int64)(r*(86400000.0/24.0) + rRounder);
  14764. }else if( n==6 && strcmp(z,"minute")==0 ){
  14765. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0)) + rRounder);
  14766. }else if( n==6 && strcmp(z,"second")==0 ){
  14767. p->iJD += (sqlite3_int64)(r*(86400000.0/(24.0*60.0*60.0)) + rRounder);
  14768. }else if( n==5 && strcmp(z,"month")==0 ){
  14769. int x, y;
  14770. computeYMD_HMS(p);
  14771. p->M += (int)r;
  14772. x = p->M>0 ? (p->M-1)/12 : (p->M-12)/12;
  14773. p->Y += x;
  14774. p->M -= x*12;
  14775. p->validJD = 0;
  14776. computeJD(p);
  14777. y = (int)r;
  14778. if( y!=r ){
  14779. p->iJD += (sqlite3_int64)((r - y)*30.0*86400000.0 + rRounder);
  14780. }
  14781. }else if( n==4 && strcmp(z,"year")==0 ){
  14782. int y = (int)r;
  14783. computeYMD_HMS(p);
  14784. p->Y += y;
  14785. p->validJD = 0;
  14786. computeJD(p);
  14787. if( y!=r ){
  14788. p->iJD += (sqlite3_int64)((r - y)*365.0*86400000.0 + rRounder);
  14789. }
  14790. }else{
  14791. rc = 1;
  14792. }
  14793. clearYMD_HMS_TZ(p);
  14794. break;
  14795. }
  14796. default: {
  14797. break;
  14798. }
  14799. }
  14800. return rc;
  14801. }
  14802. /*
  14803. ** Process time function arguments. argv[0] is a date-time stamp.
  14804. ** argv[1] and following are modifiers. Parse them all and write
  14805. ** the resulting time into the DateTime structure p. Return 0
  14806. ** on success and 1 if there are any errors.
  14807. **
  14808. ** If there are zero parameters (if even argv[0] is undefined)
  14809. ** then assume a default value of "now" for argv[0].
  14810. */
  14811. static int isDate(
  14812. sqlite3_context *context,
  14813. int argc,
  14814. sqlite3_value **argv,
  14815. DateTime *p
  14816. ){
  14817. int i;
  14818. const unsigned char *z;
  14819. int eType;
  14820. memset(p, 0, sizeof(*p));
  14821. if( argc==0 ){
  14822. return setDateTimeToCurrent(context, p);
  14823. }
  14824. if( (eType = sqlite3_value_type(argv[0]))==SQLITE_FLOAT
  14825. || eType==SQLITE_INTEGER ){
  14826. p->iJD = (sqlite3_int64)(sqlite3_value_double(argv[0])*86400000.0 + 0.5);
  14827. p->validJD = 1;
  14828. }else{
  14829. z = sqlite3_value_text(argv[0]);
  14830. if( !z || parseDateOrTime(context, (char*)z, p) ){
  14831. return 1;
  14832. }
  14833. }
  14834. for(i=1; i<argc; i++){
  14835. z = sqlite3_value_text(argv[i]);
  14836. if( z==0 || parseModifier(context, (char*)z, p) ) return 1;
  14837. }
  14838. return 0;
  14839. }
  14840. /*
  14841. ** The following routines implement the various date and time functions
  14842. ** of SQLite.
  14843. */
  14844. /*
  14845. ** julianday( TIMESTRING, MOD, MOD, ...)
  14846. **
  14847. ** Return the julian day number of the date specified in the arguments
  14848. */
  14849. static void juliandayFunc(
  14850. sqlite3_context *context,
  14851. int argc,
  14852. sqlite3_value **argv
  14853. ){
  14854. DateTime x;
  14855. if( isDate(context, argc, argv, &x)==0 ){
  14856. computeJD(&x);
  14857. sqlite3_result_double(context, x.iJD/86400000.0);
  14858. }
  14859. }
  14860. /*
  14861. ** datetime( TIMESTRING, MOD, MOD, ...)
  14862. **
  14863. ** Return YYYY-MM-DD HH:MM:SS
  14864. */
  14865. static void datetimeFunc(
  14866. sqlite3_context *context,
  14867. int argc,
  14868. sqlite3_value **argv
  14869. ){
  14870. DateTime x;
  14871. if( isDate(context, argc, argv, &x)==0 ){
  14872. char zBuf[100];
  14873. computeYMD_HMS(&x);
  14874. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d %02d:%02d:%02d",
  14875. x.Y, x.M, x.D, x.h, x.m, (int)(x.s));
  14876. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14877. }
  14878. }
  14879. /*
  14880. ** time( TIMESTRING, MOD, MOD, ...)
  14881. **
  14882. ** Return HH:MM:SS
  14883. */
  14884. static void timeFunc(
  14885. sqlite3_context *context,
  14886. int argc,
  14887. sqlite3_value **argv
  14888. ){
  14889. DateTime x;
  14890. if( isDate(context, argc, argv, &x)==0 ){
  14891. char zBuf[100];
  14892. computeHMS(&x);
  14893. sqlite3_snprintf(sizeof(zBuf), zBuf, "%02d:%02d:%02d", x.h, x.m, (int)x.s);
  14894. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14895. }
  14896. }
  14897. /*
  14898. ** date( TIMESTRING, MOD, MOD, ...)
  14899. **
  14900. ** Return YYYY-MM-DD
  14901. */
  14902. static void dateFunc(
  14903. sqlite3_context *context,
  14904. int argc,
  14905. sqlite3_value **argv
  14906. ){
  14907. DateTime x;
  14908. if( isDate(context, argc, argv, &x)==0 ){
  14909. char zBuf[100];
  14910. computeYMD(&x);
  14911. sqlite3_snprintf(sizeof(zBuf), zBuf, "%04d-%02d-%02d", x.Y, x.M, x.D);
  14912. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  14913. }
  14914. }
  14915. /*
  14916. ** strftime( FORMAT, TIMESTRING, MOD, MOD, ...)
  14917. **
  14918. ** Return a string described by FORMAT. Conversions as follows:
  14919. **
  14920. ** %d day of month
  14921. ** %f ** fractional seconds SS.SSS
  14922. ** %H hour 00-24
  14923. ** %j day of year 000-366
  14924. ** %J ** Julian day number
  14925. ** %m month 01-12
  14926. ** %M minute 00-59
  14927. ** %s seconds since 1970-01-01
  14928. ** %S seconds 00-59
  14929. ** %w day of week 0-6 sunday==0
  14930. ** %W week of year 00-53
  14931. ** %Y year 0000-9999
  14932. ** %% %
  14933. */
  14934. static void strftimeFunc(
  14935. sqlite3_context *context,
  14936. int argc,
  14937. sqlite3_value **argv
  14938. ){
  14939. DateTime x;
  14940. u64 n;
  14941. size_t i,j;
  14942. char *z;
  14943. sqlite3 *db;
  14944. const char *zFmt = (const char*)sqlite3_value_text(argv[0]);
  14945. char zBuf[100];
  14946. if( zFmt==0 || isDate(context, argc-1, argv+1, &x) ) return;
  14947. db = sqlite3_context_db_handle(context);
  14948. for(i=0, n=1; zFmt[i]; i++, n++){
  14949. if( zFmt[i]=='%' ){
  14950. switch( zFmt[i+1] ){
  14951. case 'd':
  14952. case 'H':
  14953. case 'm':
  14954. case 'M':
  14955. case 'S':
  14956. case 'W':
  14957. n++;
  14958. /* fall thru */
  14959. case 'w':
  14960. case '%':
  14961. break;
  14962. case 'f':
  14963. n += 8;
  14964. break;
  14965. case 'j':
  14966. n += 3;
  14967. break;
  14968. case 'Y':
  14969. n += 8;
  14970. break;
  14971. case 's':
  14972. case 'J':
  14973. n += 50;
  14974. break;
  14975. default:
  14976. return; /* ERROR. return a NULL */
  14977. }
  14978. i++;
  14979. }
  14980. }
  14981. testcase( n==sizeof(zBuf)-1 );
  14982. testcase( n==sizeof(zBuf) );
  14983. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  14984. testcase( n==(u64)db->aLimit[SQLITE_LIMIT_LENGTH] );
  14985. if( n<sizeof(zBuf) ){
  14986. z = zBuf;
  14987. }else if( n>(u64)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  14988. sqlite3_result_error_toobig(context);
  14989. return;
  14990. }else{
  14991. z = sqlite3DbMallocRaw(db, (int)n);
  14992. if( z==0 ){
  14993. sqlite3_result_error_nomem(context);
  14994. return;
  14995. }
  14996. }
  14997. computeJD(&x);
  14998. computeYMD_HMS(&x);
  14999. for(i=j=0; zFmt[i]; i++){
  15000. if( zFmt[i]!='%' ){
  15001. z[j++] = zFmt[i];
  15002. }else{
  15003. i++;
  15004. switch( zFmt[i] ){
  15005. case 'd': sqlite3_snprintf(3, &z[j],"%02d",x.D); j+=2; break;
  15006. case 'f': {
  15007. double s = x.s;
  15008. if( s>59.999 ) s = 59.999;
  15009. sqlite3_snprintf(7, &z[j],"%06.3f", s);
  15010. j += sqlite3Strlen30(&z[j]);
  15011. break;
  15012. }
  15013. case 'H': sqlite3_snprintf(3, &z[j],"%02d",x.h); j+=2; break;
  15014. case 'W': /* Fall thru */
  15015. case 'j': {
  15016. int nDay; /* Number of days since 1st day of year */
  15017. DateTime y = x;
  15018. y.validJD = 0;
  15019. y.M = 1;
  15020. y.D = 1;
  15021. computeJD(&y);
  15022. nDay = (int)((x.iJD-y.iJD+43200000)/86400000);
  15023. if( zFmt[i]=='W' ){
  15024. int wd; /* 0=Monday, 1=Tuesday, ... 6=Sunday */
  15025. wd = (int)(((x.iJD+43200000)/86400000)%7);
  15026. sqlite3_snprintf(3, &z[j],"%02d",(nDay+7-wd)/7);
  15027. j += 2;
  15028. }else{
  15029. sqlite3_snprintf(4, &z[j],"%03d",nDay+1);
  15030. j += 3;
  15031. }
  15032. break;
  15033. }
  15034. case 'J': {
  15035. sqlite3_snprintf(20, &z[j],"%.16g",x.iJD/86400000.0);
  15036. j+=sqlite3Strlen30(&z[j]);
  15037. break;
  15038. }
  15039. case 'm': sqlite3_snprintf(3, &z[j],"%02d",x.M); j+=2; break;
  15040. case 'M': sqlite3_snprintf(3, &z[j],"%02d",x.m); j+=2; break;
  15041. case 's': {
  15042. sqlite3_snprintf(30,&z[j],"%lld",
  15043. (i64)(x.iJD/1000 - 21086676*(i64)10000));
  15044. j += sqlite3Strlen30(&z[j]);
  15045. break;
  15046. }
  15047. case 'S': sqlite3_snprintf(3,&z[j],"%02d",(int)x.s); j+=2; break;
  15048. case 'w': {
  15049. z[j++] = (char)(((x.iJD+129600000)/86400000) % 7) + '0';
  15050. break;
  15051. }
  15052. case 'Y': {
  15053. sqlite3_snprintf(5,&z[j],"%04d",x.Y); j+=sqlite3Strlen30(&z[j]);
  15054. break;
  15055. }
  15056. default: z[j++] = '%'; break;
  15057. }
  15058. }
  15059. }
  15060. z[j] = 0;
  15061. sqlite3_result_text(context, z, -1,
  15062. z==zBuf ? SQLITE_TRANSIENT : SQLITE_DYNAMIC);
  15063. }
  15064. /*
  15065. ** current_time()
  15066. **
  15067. ** This function returns the same value as time('now').
  15068. */
  15069. static void ctimeFunc(
  15070. sqlite3_context *context,
  15071. int NotUsed,
  15072. sqlite3_value **NotUsed2
  15073. ){
  15074. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15075. timeFunc(context, 0, 0);
  15076. }
  15077. /*
  15078. ** current_date()
  15079. **
  15080. ** This function returns the same value as date('now').
  15081. */
  15082. static void cdateFunc(
  15083. sqlite3_context *context,
  15084. int NotUsed,
  15085. sqlite3_value **NotUsed2
  15086. ){
  15087. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15088. dateFunc(context, 0, 0);
  15089. }
  15090. /*
  15091. ** current_timestamp()
  15092. **
  15093. ** This function returns the same value as datetime('now').
  15094. */
  15095. static void ctimestampFunc(
  15096. sqlite3_context *context,
  15097. int NotUsed,
  15098. sqlite3_value **NotUsed2
  15099. ){
  15100. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  15101. datetimeFunc(context, 0, 0);
  15102. }
  15103. #endif /* !defined(SQLITE_OMIT_DATETIME_FUNCS) */
  15104. #ifdef SQLITE_OMIT_DATETIME_FUNCS
  15105. /*
  15106. ** If the library is compiled to omit the full-scale date and time
  15107. ** handling (to get a smaller binary), the following minimal version
  15108. ** of the functions current_time(), current_date() and current_timestamp()
  15109. ** are included instead. This is to support column declarations that
  15110. ** include "DEFAULT CURRENT_TIME" etc.
  15111. **
  15112. ** This function uses the C-library functions time(), gmtime()
  15113. ** and strftime(). The format string to pass to strftime() is supplied
  15114. ** as the user-data for the function.
  15115. */
  15116. static void currentTimeFunc(
  15117. sqlite3_context *context,
  15118. int argc,
  15119. sqlite3_value **argv
  15120. ){
  15121. time_t t;
  15122. char *zFormat = (char *)sqlite3_user_data(context);
  15123. sqlite3 *db;
  15124. sqlite3_int64 iT;
  15125. struct tm *pTm;
  15126. struct tm sNow;
  15127. char zBuf[20];
  15128. UNUSED_PARAMETER(argc);
  15129. UNUSED_PARAMETER(argv);
  15130. iT = sqlite3StmtCurrentTime(context);
  15131. if( iT<=0 ) return;
  15132. t = iT/1000 - 10000*(sqlite3_int64)21086676;
  15133. #ifdef HAVE_GMTIME_R
  15134. pTm = gmtime_r(&t, &sNow);
  15135. #else
  15136. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  15137. pTm = gmtime(&t);
  15138. if( pTm ) memcpy(&sNow, pTm, sizeof(sNow));
  15139. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  15140. #endif
  15141. if( pTm ){
  15142. strftime(zBuf, 20, zFormat, &sNow);
  15143. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  15144. }
  15145. }
  15146. #endif
  15147. /*
  15148. ** This function registered all of the above C functions as SQL
  15149. ** functions. This should be the only routine in this file with
  15150. ** external linkage.
  15151. */
  15152. SQLITE_PRIVATE void sqlite3RegisterDateTimeFunctions(void){
  15153. static SQLITE_WSD FuncDef aDateTimeFuncs[] = {
  15154. #ifndef SQLITE_OMIT_DATETIME_FUNCS
  15155. FUNCTION(julianday, -1, 0, 0, juliandayFunc ),
  15156. FUNCTION(date, -1, 0, 0, dateFunc ),
  15157. FUNCTION(time, -1, 0, 0, timeFunc ),
  15158. FUNCTION(datetime, -1, 0, 0, datetimeFunc ),
  15159. FUNCTION(strftime, -1, 0, 0, strftimeFunc ),
  15160. FUNCTION(current_time, 0, 0, 0, ctimeFunc ),
  15161. FUNCTION(current_timestamp, 0, 0, 0, ctimestampFunc),
  15162. FUNCTION(current_date, 0, 0, 0, cdateFunc ),
  15163. #else
  15164. STR_FUNCTION(current_time, 0, "%H:%M:%S", 0, currentTimeFunc),
  15165. STR_FUNCTION(current_date, 0, "%Y-%m-%d", 0, currentTimeFunc),
  15166. STR_FUNCTION(current_timestamp, 0, "%Y-%m-%d %H:%M:%S", 0, currentTimeFunc),
  15167. #endif
  15168. };
  15169. int i;
  15170. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  15171. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aDateTimeFuncs);
  15172. for(i=0; i<ArraySize(aDateTimeFuncs); i++){
  15173. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  15174. }
  15175. }
  15176. /************** End of date.c ************************************************/
  15177. /************** Begin file os.c **********************************************/
  15178. /*
  15179. ** 2005 November 29
  15180. **
  15181. ** The author disclaims copyright to this source code. In place of
  15182. ** a legal notice, here is a blessing:
  15183. **
  15184. ** May you do good and not evil.
  15185. ** May you find forgiveness for yourself and forgive others.
  15186. ** May you share freely, never taking more than you give.
  15187. **
  15188. ******************************************************************************
  15189. **
  15190. ** This file contains OS interface code that is common to all
  15191. ** architectures.
  15192. */
  15193. #define _SQLITE_OS_C_ 1
  15194. #undef _SQLITE_OS_C_
  15195. /*
  15196. ** The default SQLite sqlite3_vfs implementations do not allocate
  15197. ** memory (actually, os_unix.c allocates a small amount of memory
  15198. ** from within OsOpen()), but some third-party implementations may.
  15199. ** So we test the effects of a malloc() failing and the sqlite3OsXXX()
  15200. ** function returning SQLITE_IOERR_NOMEM using the DO_OS_MALLOC_TEST macro.
  15201. **
  15202. ** The following functions are instrumented for malloc() failure
  15203. ** testing:
  15204. **
  15205. ** sqlite3OsRead()
  15206. ** sqlite3OsWrite()
  15207. ** sqlite3OsSync()
  15208. ** sqlite3OsFileSize()
  15209. ** sqlite3OsLock()
  15210. ** sqlite3OsCheckReservedLock()
  15211. ** sqlite3OsFileControl()
  15212. ** sqlite3OsShmMap()
  15213. ** sqlite3OsOpen()
  15214. ** sqlite3OsDelete()
  15215. ** sqlite3OsAccess()
  15216. ** sqlite3OsFullPathname()
  15217. **
  15218. */
  15219. #if defined(SQLITE_TEST)
  15220. SQLITE_API int sqlite3_memdebug_vfs_oom_test = 1;
  15221. #define DO_OS_MALLOC_TEST(x) \
  15222. if (sqlite3_memdebug_vfs_oom_test && (!x || !sqlite3IsMemJournal(x))) { \
  15223. void *pTstAlloc = sqlite3Malloc(10); \
  15224. if (!pTstAlloc) return SQLITE_IOERR_NOMEM; \
  15225. sqlite3_free(pTstAlloc); \
  15226. }
  15227. #else
  15228. #define DO_OS_MALLOC_TEST(x)
  15229. #endif
  15230. /*
  15231. ** The following routines are convenience wrappers around methods
  15232. ** of the sqlite3_file object. This is mostly just syntactic sugar. All
  15233. ** of this would be completely automatic if SQLite were coded using
  15234. ** C++ instead of plain old C.
  15235. */
  15236. SQLITE_PRIVATE int sqlite3OsClose(sqlite3_file *pId){
  15237. int rc = SQLITE_OK;
  15238. if( pId->pMethods ){
  15239. rc = pId->pMethods->xClose(pId);
  15240. pId->pMethods = 0;
  15241. }
  15242. return rc;
  15243. }
  15244. SQLITE_PRIVATE int sqlite3OsRead(sqlite3_file *id, void *pBuf, int amt, i64 offset){
  15245. DO_OS_MALLOC_TEST(id);
  15246. return id->pMethods->xRead(id, pBuf, amt, offset);
  15247. }
  15248. SQLITE_PRIVATE int sqlite3OsWrite(sqlite3_file *id, const void *pBuf, int amt, i64 offset){
  15249. DO_OS_MALLOC_TEST(id);
  15250. return id->pMethods->xWrite(id, pBuf, amt, offset);
  15251. }
  15252. SQLITE_PRIVATE int sqlite3OsTruncate(sqlite3_file *id, i64 size){
  15253. return id->pMethods->xTruncate(id, size);
  15254. }
  15255. SQLITE_PRIVATE int sqlite3OsSync(sqlite3_file *id, int flags){
  15256. DO_OS_MALLOC_TEST(id);
  15257. return id->pMethods->xSync(id, flags);
  15258. }
  15259. SQLITE_PRIVATE int sqlite3OsFileSize(sqlite3_file *id, i64 *pSize){
  15260. DO_OS_MALLOC_TEST(id);
  15261. return id->pMethods->xFileSize(id, pSize);
  15262. }
  15263. SQLITE_PRIVATE int sqlite3OsLock(sqlite3_file *id, int lockType){
  15264. DO_OS_MALLOC_TEST(id);
  15265. return id->pMethods->xLock(id, lockType);
  15266. }
  15267. SQLITE_PRIVATE int sqlite3OsUnlock(sqlite3_file *id, int lockType){
  15268. return id->pMethods->xUnlock(id, lockType);
  15269. }
  15270. SQLITE_PRIVATE int sqlite3OsCheckReservedLock(sqlite3_file *id, int *pResOut){
  15271. DO_OS_MALLOC_TEST(id);
  15272. return id->pMethods->xCheckReservedLock(id, pResOut);
  15273. }
  15274. /*
  15275. ** Use sqlite3OsFileControl() when we are doing something that might fail
  15276. ** and we need to know about the failures. Use sqlite3OsFileControlHint()
  15277. ** when simply tossing information over the wall to the VFS and we do not
  15278. ** really care if the VFS receives and understands the information since it
  15279. ** is only a hint and can be safely ignored. The sqlite3OsFileControlHint()
  15280. ** routine has no return value since the return value would be meaningless.
  15281. */
  15282. SQLITE_PRIVATE int sqlite3OsFileControl(sqlite3_file *id, int op, void *pArg){
  15283. #ifdef SQLITE_TEST
  15284. if( op!=SQLITE_FCNTL_COMMIT_PHASETWO ){
  15285. /* Faults are not injected into COMMIT_PHASETWO because, assuming SQLite
  15286. ** is using a regular VFS, it is called after the corresponding
  15287. ** transaction has been committed. Injecting a fault at this point
  15288. ** confuses the test scripts - the COMMIT comand returns SQLITE_NOMEM
  15289. ** but the transaction is committed anyway.
  15290. **
  15291. ** The core must call OsFileControl() though, not OsFileControlHint(),
  15292. ** as if a custom VFS (e.g. zipvfs) returns an error here, it probably
  15293. ** means the commit really has failed and an error should be returned
  15294. ** to the user. */
  15295. DO_OS_MALLOC_TEST(id);
  15296. }
  15297. #endif
  15298. return id->pMethods->xFileControl(id, op, pArg);
  15299. }
  15300. SQLITE_PRIVATE void sqlite3OsFileControlHint(sqlite3_file *id, int op, void *pArg){
  15301. (void)id->pMethods->xFileControl(id, op, pArg);
  15302. }
  15303. SQLITE_PRIVATE int sqlite3OsSectorSize(sqlite3_file *id){
  15304. int (*xSectorSize)(sqlite3_file*) = id->pMethods->xSectorSize;
  15305. return (xSectorSize ? xSectorSize(id) : SQLITE_DEFAULT_SECTOR_SIZE);
  15306. }
  15307. SQLITE_PRIVATE int sqlite3OsDeviceCharacteristics(sqlite3_file *id){
  15308. return id->pMethods->xDeviceCharacteristics(id);
  15309. }
  15310. SQLITE_PRIVATE int sqlite3OsShmLock(sqlite3_file *id, int offset, int n, int flags){
  15311. return id->pMethods->xShmLock(id, offset, n, flags);
  15312. }
  15313. SQLITE_PRIVATE void sqlite3OsShmBarrier(sqlite3_file *id){
  15314. id->pMethods->xShmBarrier(id);
  15315. }
  15316. SQLITE_PRIVATE int sqlite3OsShmUnmap(sqlite3_file *id, int deleteFlag){
  15317. return id->pMethods->xShmUnmap(id, deleteFlag);
  15318. }
  15319. SQLITE_PRIVATE int sqlite3OsShmMap(
  15320. sqlite3_file *id, /* Database file handle */
  15321. int iPage,
  15322. int pgsz,
  15323. int bExtend, /* True to extend file if necessary */
  15324. void volatile **pp /* OUT: Pointer to mapping */
  15325. ){
  15326. DO_OS_MALLOC_TEST(id);
  15327. return id->pMethods->xShmMap(id, iPage, pgsz, bExtend, pp);
  15328. }
  15329. #if SQLITE_MAX_MMAP_SIZE>0
  15330. /* The real implementation of xFetch and xUnfetch */
  15331. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  15332. DO_OS_MALLOC_TEST(id);
  15333. return id->pMethods->xFetch(id, iOff, iAmt, pp);
  15334. }
  15335. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  15336. return id->pMethods->xUnfetch(id, iOff, p);
  15337. }
  15338. #else
  15339. /* No-op stubs to use when memory-mapped I/O is disabled */
  15340. SQLITE_PRIVATE int sqlite3OsFetch(sqlite3_file *id, i64 iOff, int iAmt, void **pp){
  15341. *pp = 0;
  15342. return SQLITE_OK;
  15343. }
  15344. SQLITE_PRIVATE int sqlite3OsUnfetch(sqlite3_file *id, i64 iOff, void *p){
  15345. return SQLITE_OK;
  15346. }
  15347. #endif
  15348. /*
  15349. ** The next group of routines are convenience wrappers around the
  15350. ** VFS methods.
  15351. */
  15352. SQLITE_PRIVATE int sqlite3OsOpen(
  15353. sqlite3_vfs *pVfs,
  15354. const char *zPath,
  15355. sqlite3_file *pFile,
  15356. int flags,
  15357. int *pFlagsOut
  15358. ){
  15359. int rc;
  15360. DO_OS_MALLOC_TEST(0);
  15361. /* 0x87f7f is a mask of SQLITE_OPEN_ flags that are valid to be passed
  15362. ** down into the VFS layer. Some SQLITE_OPEN_ flags (for example,
  15363. ** SQLITE_OPEN_FULLMUTEX or SQLITE_OPEN_SHAREDCACHE) are blocked before
  15364. ** reaching the VFS. */
  15365. rc = pVfs->xOpen(pVfs, zPath, pFile, flags & 0x87f7f, pFlagsOut);
  15366. assert( rc==SQLITE_OK || pFile->pMethods==0 );
  15367. return rc;
  15368. }
  15369. SQLITE_PRIVATE int sqlite3OsDelete(sqlite3_vfs *pVfs, const char *zPath, int dirSync){
  15370. DO_OS_MALLOC_TEST(0);
  15371. assert( dirSync==0 || dirSync==1 );
  15372. return pVfs->xDelete(pVfs, zPath, dirSync);
  15373. }
  15374. SQLITE_PRIVATE int sqlite3OsAccess(
  15375. sqlite3_vfs *pVfs,
  15376. const char *zPath,
  15377. int flags,
  15378. int *pResOut
  15379. ){
  15380. DO_OS_MALLOC_TEST(0);
  15381. return pVfs->xAccess(pVfs, zPath, flags, pResOut);
  15382. }
  15383. SQLITE_PRIVATE int sqlite3OsFullPathname(
  15384. sqlite3_vfs *pVfs,
  15385. const char *zPath,
  15386. int nPathOut,
  15387. char *zPathOut
  15388. ){
  15389. DO_OS_MALLOC_TEST(0);
  15390. zPathOut[0] = 0;
  15391. return pVfs->xFullPathname(pVfs, zPath, nPathOut, zPathOut);
  15392. }
  15393. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  15394. SQLITE_PRIVATE void *sqlite3OsDlOpen(sqlite3_vfs *pVfs, const char *zPath){
  15395. return pVfs->xDlOpen(pVfs, zPath);
  15396. }
  15397. SQLITE_PRIVATE void sqlite3OsDlError(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  15398. pVfs->xDlError(pVfs, nByte, zBufOut);
  15399. }
  15400. SQLITE_PRIVATE void (*sqlite3OsDlSym(sqlite3_vfs *pVfs, void *pHdle, const char *zSym))(void){
  15401. return pVfs->xDlSym(pVfs, pHdle, zSym);
  15402. }
  15403. SQLITE_PRIVATE void sqlite3OsDlClose(sqlite3_vfs *pVfs, void *pHandle){
  15404. pVfs->xDlClose(pVfs, pHandle);
  15405. }
  15406. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  15407. SQLITE_PRIVATE int sqlite3OsRandomness(sqlite3_vfs *pVfs, int nByte, char *zBufOut){
  15408. return pVfs->xRandomness(pVfs, nByte, zBufOut);
  15409. }
  15410. SQLITE_PRIVATE int sqlite3OsSleep(sqlite3_vfs *pVfs, int nMicro){
  15411. return pVfs->xSleep(pVfs, nMicro);
  15412. }
  15413. SQLITE_PRIVATE int sqlite3OsCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *pTimeOut){
  15414. int rc;
  15415. /* IMPLEMENTATION-OF: R-49045-42493 SQLite will use the xCurrentTimeInt64()
  15416. ** method to get the current date and time if that method is available
  15417. ** (if iVersion is 2 or greater and the function pointer is not NULL) and
  15418. ** will fall back to xCurrentTime() if xCurrentTimeInt64() is
  15419. ** unavailable.
  15420. */
  15421. if( pVfs->iVersion>=2 && pVfs->xCurrentTimeInt64 ){
  15422. rc = pVfs->xCurrentTimeInt64(pVfs, pTimeOut);
  15423. }else{
  15424. double r;
  15425. rc = pVfs->xCurrentTime(pVfs, &r);
  15426. *pTimeOut = (sqlite3_int64)(r*86400000.0);
  15427. }
  15428. return rc;
  15429. }
  15430. SQLITE_PRIVATE int sqlite3OsOpenMalloc(
  15431. sqlite3_vfs *pVfs,
  15432. const char *zFile,
  15433. sqlite3_file **ppFile,
  15434. int flags,
  15435. int *pOutFlags
  15436. ){
  15437. int rc = SQLITE_NOMEM;
  15438. sqlite3_file *pFile;
  15439. pFile = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile);
  15440. if( pFile ){
  15441. rc = sqlite3OsOpen(pVfs, zFile, pFile, flags, pOutFlags);
  15442. if( rc!=SQLITE_OK ){
  15443. sqlite3_free(pFile);
  15444. }else{
  15445. *ppFile = pFile;
  15446. }
  15447. }
  15448. return rc;
  15449. }
  15450. SQLITE_PRIVATE int sqlite3OsCloseFree(sqlite3_file *pFile){
  15451. int rc = SQLITE_OK;
  15452. assert( pFile );
  15453. rc = sqlite3OsClose(pFile);
  15454. sqlite3_free(pFile);
  15455. return rc;
  15456. }
  15457. /*
  15458. ** This function is a wrapper around the OS specific implementation of
  15459. ** sqlite3_os_init(). The purpose of the wrapper is to provide the
  15460. ** ability to simulate a malloc failure, so that the handling of an
  15461. ** error in sqlite3_os_init() by the upper layers can be tested.
  15462. */
  15463. SQLITE_PRIVATE int sqlite3OsInit(void){
  15464. void *p = sqlite3_malloc(10);
  15465. if( p==0 ) return SQLITE_NOMEM;
  15466. sqlite3_free(p);
  15467. return sqlite3_os_init();
  15468. }
  15469. /*
  15470. ** The list of all registered VFS implementations.
  15471. */
  15472. static sqlite3_vfs * SQLITE_WSD vfsList = 0;
  15473. #define vfsList GLOBAL(sqlite3_vfs *, vfsList)
  15474. /*
  15475. ** Locate a VFS by name. If no name is given, simply return the
  15476. ** first VFS on the list.
  15477. */
  15478. SQLITE_API sqlite3_vfs *sqlite3_vfs_find(const char *zVfs){
  15479. sqlite3_vfs *pVfs = 0;
  15480. #if SQLITE_THREADSAFE
  15481. sqlite3_mutex *mutex;
  15482. #endif
  15483. #ifndef SQLITE_OMIT_AUTOINIT
  15484. int rc = sqlite3_initialize();
  15485. if( rc ) return 0;
  15486. #endif
  15487. #if SQLITE_THREADSAFE
  15488. mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  15489. #endif
  15490. sqlite3_mutex_enter(mutex);
  15491. for(pVfs = vfsList; pVfs; pVfs=pVfs->pNext){
  15492. if( zVfs==0 ) break;
  15493. if( strcmp(zVfs, pVfs->zName)==0 ) break;
  15494. }
  15495. sqlite3_mutex_leave(mutex);
  15496. return pVfs;
  15497. }
  15498. /*
  15499. ** Unlink a VFS from the linked list
  15500. */
  15501. static void vfsUnlink(sqlite3_vfs *pVfs){
  15502. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) );
  15503. if( pVfs==0 ){
  15504. /* No-op */
  15505. }else if( vfsList==pVfs ){
  15506. vfsList = pVfs->pNext;
  15507. }else if( vfsList ){
  15508. sqlite3_vfs *p = vfsList;
  15509. while( p->pNext && p->pNext!=pVfs ){
  15510. p = p->pNext;
  15511. }
  15512. if( p->pNext==pVfs ){
  15513. p->pNext = pVfs->pNext;
  15514. }
  15515. }
  15516. }
  15517. /*
  15518. ** Register a VFS with the system. It is harmless to register the same
  15519. ** VFS multiple times. The new VFS becomes the default if makeDflt is
  15520. ** true.
  15521. */
  15522. SQLITE_API int sqlite3_vfs_register(sqlite3_vfs *pVfs, int makeDflt){
  15523. MUTEX_LOGIC(sqlite3_mutex *mutex;)
  15524. #ifndef SQLITE_OMIT_AUTOINIT
  15525. int rc = sqlite3_initialize();
  15526. if( rc ) return rc;
  15527. #endif
  15528. MUTEX_LOGIC( mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  15529. sqlite3_mutex_enter(mutex);
  15530. vfsUnlink(pVfs);
  15531. if( makeDflt || vfsList==0 ){
  15532. pVfs->pNext = vfsList;
  15533. vfsList = pVfs;
  15534. }else{
  15535. pVfs->pNext = vfsList->pNext;
  15536. vfsList->pNext = pVfs;
  15537. }
  15538. assert(vfsList);
  15539. sqlite3_mutex_leave(mutex);
  15540. return SQLITE_OK;
  15541. }
  15542. /*
  15543. ** Unregister a VFS so that it is no longer accessible.
  15544. */
  15545. SQLITE_API int sqlite3_vfs_unregister(sqlite3_vfs *pVfs){
  15546. #if SQLITE_THREADSAFE
  15547. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  15548. #endif
  15549. sqlite3_mutex_enter(mutex);
  15550. vfsUnlink(pVfs);
  15551. sqlite3_mutex_leave(mutex);
  15552. return SQLITE_OK;
  15553. }
  15554. /************** End of os.c **************************************************/
  15555. /************** Begin file fault.c *******************************************/
  15556. /*
  15557. ** 2008 Jan 22
  15558. **
  15559. ** The author disclaims copyright to this source code. In place of
  15560. ** a legal notice, here is a blessing:
  15561. **
  15562. ** May you do good and not evil.
  15563. ** May you find forgiveness for yourself and forgive others.
  15564. ** May you share freely, never taking more than you give.
  15565. **
  15566. *************************************************************************
  15567. **
  15568. ** This file contains code to support the concept of "benign"
  15569. ** malloc failures (when the xMalloc() or xRealloc() method of the
  15570. ** sqlite3_mem_methods structure fails to allocate a block of memory
  15571. ** and returns 0).
  15572. **
  15573. ** Most malloc failures are non-benign. After they occur, SQLite
  15574. ** abandons the current operation and returns an error code (usually
  15575. ** SQLITE_NOMEM) to the user. However, sometimes a fault is not necessarily
  15576. ** fatal. For example, if a malloc fails while resizing a hash table, this
  15577. ** is completely recoverable simply by not carrying out the resize. The
  15578. ** hash table will continue to function normally. So a malloc failure
  15579. ** during a hash table resize is a benign fault.
  15580. */
  15581. #ifndef SQLITE_OMIT_BUILTIN_TEST
  15582. /*
  15583. ** Global variables.
  15584. */
  15585. typedef struct BenignMallocHooks BenignMallocHooks;
  15586. static SQLITE_WSD struct BenignMallocHooks {
  15587. void (*xBenignBegin)(void);
  15588. void (*xBenignEnd)(void);
  15589. } sqlite3Hooks = { 0, 0 };
  15590. /* The "wsdHooks" macro will resolve to the appropriate BenignMallocHooks
  15591. ** structure. If writable static data is unsupported on the target,
  15592. ** we have to locate the state vector at run-time. In the more common
  15593. ** case where writable static data is supported, wsdHooks can refer directly
  15594. ** to the "sqlite3Hooks" state vector declared above.
  15595. */
  15596. #ifdef SQLITE_OMIT_WSD
  15597. # define wsdHooksInit \
  15598. BenignMallocHooks *x = &GLOBAL(BenignMallocHooks,sqlite3Hooks)
  15599. # define wsdHooks x[0]
  15600. #else
  15601. # define wsdHooksInit
  15602. # define wsdHooks sqlite3Hooks
  15603. #endif
  15604. /*
  15605. ** Register hooks to call when sqlite3BeginBenignMalloc() and
  15606. ** sqlite3EndBenignMalloc() are called, respectively.
  15607. */
  15608. SQLITE_PRIVATE void sqlite3BenignMallocHooks(
  15609. void (*xBenignBegin)(void),
  15610. void (*xBenignEnd)(void)
  15611. ){
  15612. wsdHooksInit;
  15613. wsdHooks.xBenignBegin = xBenignBegin;
  15614. wsdHooks.xBenignEnd = xBenignEnd;
  15615. }
  15616. /*
  15617. ** This (sqlite3EndBenignMalloc()) is called by SQLite code to indicate that
  15618. ** subsequent malloc failures are benign. A call to sqlite3EndBenignMalloc()
  15619. ** indicates that subsequent malloc failures are non-benign.
  15620. */
  15621. SQLITE_PRIVATE void sqlite3BeginBenignMalloc(void){
  15622. wsdHooksInit;
  15623. if( wsdHooks.xBenignBegin ){
  15624. wsdHooks.xBenignBegin();
  15625. }
  15626. }
  15627. SQLITE_PRIVATE void sqlite3EndBenignMalloc(void){
  15628. wsdHooksInit;
  15629. if( wsdHooks.xBenignEnd ){
  15630. wsdHooks.xBenignEnd();
  15631. }
  15632. }
  15633. #endif /* #ifndef SQLITE_OMIT_BUILTIN_TEST */
  15634. /************** End of fault.c ***********************************************/
  15635. /************** Begin file mem0.c ********************************************/
  15636. /*
  15637. ** 2008 October 28
  15638. **
  15639. ** The author disclaims copyright to this source code. In place of
  15640. ** a legal notice, here is a blessing:
  15641. **
  15642. ** May you do good and not evil.
  15643. ** May you find forgiveness for yourself and forgive others.
  15644. ** May you share freely, never taking more than you give.
  15645. **
  15646. *************************************************************************
  15647. **
  15648. ** This file contains a no-op memory allocation drivers for use when
  15649. ** SQLITE_ZERO_MALLOC is defined. The allocation drivers implemented
  15650. ** here always fail. SQLite will not operate with these drivers. These
  15651. ** are merely placeholders. Real drivers must be substituted using
  15652. ** sqlite3_config() before SQLite will operate.
  15653. */
  15654. /*
  15655. ** This version of the memory allocator is the default. It is
  15656. ** used when no other memory allocator is specified using compile-time
  15657. ** macros.
  15658. */
  15659. #ifdef SQLITE_ZERO_MALLOC
  15660. /*
  15661. ** No-op versions of all memory allocation routines
  15662. */
  15663. static void *sqlite3MemMalloc(int nByte){ return 0; }
  15664. static void sqlite3MemFree(void *pPrior){ return; }
  15665. static void *sqlite3MemRealloc(void *pPrior, int nByte){ return 0; }
  15666. static int sqlite3MemSize(void *pPrior){ return 0; }
  15667. static int sqlite3MemRoundup(int n){ return n; }
  15668. static int sqlite3MemInit(void *NotUsed){ return SQLITE_OK; }
  15669. static void sqlite3MemShutdown(void *NotUsed){ return; }
  15670. /*
  15671. ** This routine is the only routine in this file with external linkage.
  15672. **
  15673. ** Populate the low-level memory allocation function pointers in
  15674. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15675. */
  15676. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15677. static const sqlite3_mem_methods defaultMethods = {
  15678. sqlite3MemMalloc,
  15679. sqlite3MemFree,
  15680. sqlite3MemRealloc,
  15681. sqlite3MemSize,
  15682. sqlite3MemRoundup,
  15683. sqlite3MemInit,
  15684. sqlite3MemShutdown,
  15685. 0
  15686. };
  15687. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15688. }
  15689. #endif /* SQLITE_ZERO_MALLOC */
  15690. /************** End of mem0.c ************************************************/
  15691. /************** Begin file mem1.c ********************************************/
  15692. /*
  15693. ** 2007 August 14
  15694. **
  15695. ** The author disclaims copyright to this source code. In place of
  15696. ** a legal notice, here is a blessing:
  15697. **
  15698. ** May you do good and not evil.
  15699. ** May you find forgiveness for yourself and forgive others.
  15700. ** May you share freely, never taking more than you give.
  15701. **
  15702. *************************************************************************
  15703. **
  15704. ** This file contains low-level memory allocation drivers for when
  15705. ** SQLite will use the standard C-library malloc/realloc/free interface
  15706. ** to obtain the memory it needs.
  15707. **
  15708. ** This file contains implementations of the low-level memory allocation
  15709. ** routines specified in the sqlite3_mem_methods object. The content of
  15710. ** this file is only used if SQLITE_SYSTEM_MALLOC is defined. The
  15711. ** SQLITE_SYSTEM_MALLOC macro is defined automatically if neither the
  15712. ** SQLITE_MEMDEBUG nor the SQLITE_WIN32_MALLOC macros are defined. The
  15713. ** default configuration is to use memory allocation routines in this
  15714. ** file.
  15715. **
  15716. ** C-preprocessor macro summary:
  15717. **
  15718. ** HAVE_MALLOC_USABLE_SIZE The configure script sets this symbol if
  15719. ** the malloc_usable_size() interface exists
  15720. ** on the target platform. Or, this symbol
  15721. ** can be set manually, if desired.
  15722. ** If an equivalent interface exists by
  15723. ** a different name, using a separate -D
  15724. ** option to rename it.
  15725. **
  15726. ** SQLITE_WITHOUT_ZONEMALLOC Some older macs lack support for the zone
  15727. ** memory allocator. Set this symbol to enable
  15728. ** building on older macs.
  15729. **
  15730. ** SQLITE_WITHOUT_MSIZE Set this symbol to disable the use of
  15731. ** _msize() on windows systems. This might
  15732. ** be necessary when compiling for Delphi,
  15733. ** for example.
  15734. */
  15735. /*
  15736. ** This version of the memory allocator is the default. It is
  15737. ** used when no other memory allocator is specified using compile-time
  15738. ** macros.
  15739. */
  15740. #ifdef SQLITE_SYSTEM_MALLOC
  15741. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15742. /*
  15743. ** Use the zone allocator available on apple products unless the
  15744. ** SQLITE_WITHOUT_ZONEMALLOC symbol is defined.
  15745. */
  15746. #include <sys/sysctl.h>
  15747. #include <malloc/malloc.h>
  15748. #include <libkern/OSAtomic.h>
  15749. static malloc_zone_t* _sqliteZone_;
  15750. #define SQLITE_MALLOC(x) malloc_zone_malloc(_sqliteZone_, (x))
  15751. #define SQLITE_FREE(x) malloc_zone_free(_sqliteZone_, (x));
  15752. #define SQLITE_REALLOC(x,y) malloc_zone_realloc(_sqliteZone_, (x), (y))
  15753. #define SQLITE_MALLOCSIZE(x) \
  15754. (_sqliteZone_ ? _sqliteZone_->size(_sqliteZone_,x) : malloc_size(x))
  15755. #else /* if not __APPLE__ */
  15756. /*
  15757. ** Use standard C library malloc and free on non-Apple systems.
  15758. ** Also used by Apple systems if SQLITE_WITHOUT_ZONEMALLOC is defined.
  15759. */
  15760. #define SQLITE_MALLOC(x) malloc(x)
  15761. #define SQLITE_FREE(x) free(x)
  15762. #define SQLITE_REALLOC(x,y) realloc((x),(y))
  15763. /*
  15764. ** The malloc.h header file is needed for malloc_usable_size() function
  15765. ** on some systems (e.g. Linux).
  15766. */
  15767. #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLOC_USABLE_SIZE)
  15768. # define SQLITE_USE_MALLOC_H
  15769. # define SQLITE_USE_MALLOC_USABLE_SIZE
  15770. /*
  15771. ** The MSVCRT has malloc_usable_size(), but it is called _msize(). The
  15772. ** use of _msize() is automatic, but can be disabled by compiling with
  15773. ** -DSQLITE_WITHOUT_MSIZE. Using the _msize() function also requires
  15774. ** the malloc.h header file.
  15775. */
  15776. #elif defined(_MSC_VER) && !defined(SQLITE_WITHOUT_MSIZE)
  15777. # define SQLITE_USE_MALLOC_H
  15778. # define SQLITE_USE_MSIZE
  15779. #endif
  15780. /*
  15781. ** Include the malloc.h header file, if necessary. Also set define macro
  15782. ** SQLITE_MALLOCSIZE to the appropriate function name, which is _msize()
  15783. ** for MSVC and malloc_usable_size() for most other systems (e.g. Linux).
  15784. ** The memory size function can always be overridden manually by defining
  15785. ** the macro SQLITE_MALLOCSIZE to the desired function name.
  15786. */
  15787. #if defined(SQLITE_USE_MALLOC_H)
  15788. # include <malloc.h>
  15789. # if defined(SQLITE_USE_MALLOC_USABLE_SIZE)
  15790. # if !defined(SQLITE_MALLOCSIZE)
  15791. # define SQLITE_MALLOCSIZE(x) malloc_usable_size(x)
  15792. # endif
  15793. # elif defined(SQLITE_USE_MSIZE)
  15794. # if !defined(SQLITE_MALLOCSIZE)
  15795. # define SQLITE_MALLOCSIZE _msize
  15796. # endif
  15797. # endif
  15798. #endif /* defined(SQLITE_USE_MALLOC_H) */
  15799. #endif /* __APPLE__ or not __APPLE__ */
  15800. /*
  15801. ** Like malloc(), but remember the size of the allocation
  15802. ** so that we can find it later using sqlite3MemSize().
  15803. **
  15804. ** For this low-level routine, we are guaranteed that nByte>0 because
  15805. ** cases of nByte<=0 will be intercepted and dealt with by higher level
  15806. ** routines.
  15807. */
  15808. static void *sqlite3MemMalloc(int nByte){
  15809. #ifdef SQLITE_MALLOCSIZE
  15810. void *p = SQLITE_MALLOC( nByte );
  15811. if( p==0 ){
  15812. testcase( sqlite3GlobalConfig.xLog!=0 );
  15813. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15814. }
  15815. return p;
  15816. #else
  15817. sqlite3_int64 *p;
  15818. assert( nByte>0 );
  15819. nByte = ROUND8(nByte);
  15820. p = SQLITE_MALLOC( nByte+8 );
  15821. if( p ){
  15822. p[0] = nByte;
  15823. p++;
  15824. }else{
  15825. testcase( sqlite3GlobalConfig.xLog!=0 );
  15826. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes of memory", nByte);
  15827. }
  15828. return (void *)p;
  15829. #endif
  15830. }
  15831. /*
  15832. ** Like free() but works for allocations obtained from sqlite3MemMalloc()
  15833. ** or sqlite3MemRealloc().
  15834. **
  15835. ** For this low-level routine, we already know that pPrior!=0 since
  15836. ** cases where pPrior==0 will have been intecepted and dealt with
  15837. ** by higher-level routines.
  15838. */
  15839. static void sqlite3MemFree(void *pPrior){
  15840. #ifdef SQLITE_MALLOCSIZE
  15841. SQLITE_FREE(pPrior);
  15842. #else
  15843. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15844. assert( pPrior!=0 );
  15845. p--;
  15846. SQLITE_FREE(p);
  15847. #endif
  15848. }
  15849. /*
  15850. ** Report the allocated size of a prior return from xMalloc()
  15851. ** or xRealloc().
  15852. */
  15853. static int sqlite3MemSize(void *pPrior){
  15854. #ifdef SQLITE_MALLOCSIZE
  15855. return pPrior ? (int)SQLITE_MALLOCSIZE(pPrior) : 0;
  15856. #else
  15857. sqlite3_int64 *p;
  15858. if( pPrior==0 ) return 0;
  15859. p = (sqlite3_int64*)pPrior;
  15860. p--;
  15861. return (int)p[0];
  15862. #endif
  15863. }
  15864. /*
  15865. ** Like realloc(). Resize an allocation previously obtained from
  15866. ** sqlite3MemMalloc().
  15867. **
  15868. ** For this low-level interface, we know that pPrior!=0. Cases where
  15869. ** pPrior==0 while have been intercepted by higher-level routine and
  15870. ** redirected to xMalloc. Similarly, we know that nByte>0 because
  15871. ** cases where nByte<=0 will have been intercepted by higher-level
  15872. ** routines and redirected to xFree.
  15873. */
  15874. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  15875. #ifdef SQLITE_MALLOCSIZE
  15876. void *p = SQLITE_REALLOC(pPrior, nByte);
  15877. if( p==0 ){
  15878. testcase( sqlite3GlobalConfig.xLog!=0 );
  15879. sqlite3_log(SQLITE_NOMEM,
  15880. "failed memory resize %u to %u bytes",
  15881. SQLITE_MALLOCSIZE(pPrior), nByte);
  15882. }
  15883. return p;
  15884. #else
  15885. sqlite3_int64 *p = (sqlite3_int64*)pPrior;
  15886. assert( pPrior!=0 && nByte>0 );
  15887. assert( nByte==ROUND8(nByte) ); /* EV: R-46199-30249 */
  15888. p--;
  15889. p = SQLITE_REALLOC(p, nByte+8 );
  15890. if( p ){
  15891. p[0] = nByte;
  15892. p++;
  15893. }else{
  15894. testcase( sqlite3GlobalConfig.xLog!=0 );
  15895. sqlite3_log(SQLITE_NOMEM,
  15896. "failed memory resize %u to %u bytes",
  15897. sqlite3MemSize(pPrior), nByte);
  15898. }
  15899. return (void*)p;
  15900. #endif
  15901. }
  15902. /*
  15903. ** Round up a request size to the next valid allocation size.
  15904. */
  15905. static int sqlite3MemRoundup(int n){
  15906. return ROUND8(n);
  15907. }
  15908. /*
  15909. ** Initialize this module.
  15910. */
  15911. static int sqlite3MemInit(void *NotUsed){
  15912. #if defined(__APPLE__) && !defined(SQLITE_WITHOUT_ZONEMALLOC)
  15913. int cpuCount;
  15914. size_t len;
  15915. if( _sqliteZone_ ){
  15916. return SQLITE_OK;
  15917. }
  15918. len = sizeof(cpuCount);
  15919. /* One usually wants to use hw.acctivecpu for MT decisions, but not here */
  15920. sysctlbyname("hw.ncpu", &cpuCount, &len, NULL, 0);
  15921. if( cpuCount>1 ){
  15922. /* defer MT decisions to system malloc */
  15923. _sqliteZone_ = malloc_default_zone();
  15924. }else{
  15925. /* only 1 core, use our own zone to contention over global locks,
  15926. ** e.g. we have our own dedicated locks */
  15927. bool success;
  15928. malloc_zone_t* newzone = malloc_create_zone(4096, 0);
  15929. malloc_set_zone_name(newzone, "Sqlite_Heap");
  15930. do{
  15931. success = OSAtomicCompareAndSwapPtrBarrier(NULL, newzone,
  15932. (void * volatile *)&_sqliteZone_);
  15933. }while(!_sqliteZone_);
  15934. if( !success ){
  15935. /* somebody registered a zone first */
  15936. malloc_destroy_zone(newzone);
  15937. }
  15938. }
  15939. #endif
  15940. UNUSED_PARAMETER(NotUsed);
  15941. return SQLITE_OK;
  15942. }
  15943. /*
  15944. ** Deinitialize this module.
  15945. */
  15946. static void sqlite3MemShutdown(void *NotUsed){
  15947. UNUSED_PARAMETER(NotUsed);
  15948. return;
  15949. }
  15950. /*
  15951. ** This routine is the only routine in this file with external linkage.
  15952. **
  15953. ** Populate the low-level memory allocation function pointers in
  15954. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  15955. */
  15956. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  15957. static const sqlite3_mem_methods defaultMethods = {
  15958. sqlite3MemMalloc,
  15959. sqlite3MemFree,
  15960. sqlite3MemRealloc,
  15961. sqlite3MemSize,
  15962. sqlite3MemRoundup,
  15963. sqlite3MemInit,
  15964. sqlite3MemShutdown,
  15965. 0
  15966. };
  15967. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  15968. }
  15969. #endif /* SQLITE_SYSTEM_MALLOC */
  15970. /************** End of mem1.c ************************************************/
  15971. /************** Begin file mem2.c ********************************************/
  15972. /*
  15973. ** 2007 August 15
  15974. **
  15975. ** The author disclaims copyright to this source code. In place of
  15976. ** a legal notice, here is a blessing:
  15977. **
  15978. ** May you do good and not evil.
  15979. ** May you find forgiveness for yourself and forgive others.
  15980. ** May you share freely, never taking more than you give.
  15981. **
  15982. *************************************************************************
  15983. **
  15984. ** This file contains low-level memory allocation drivers for when
  15985. ** SQLite will use the standard C-library malloc/realloc/free interface
  15986. ** to obtain the memory it needs while adding lots of additional debugging
  15987. ** information to each allocation in order to help detect and fix memory
  15988. ** leaks and memory usage errors.
  15989. **
  15990. ** This file contains implementations of the low-level memory allocation
  15991. ** routines specified in the sqlite3_mem_methods object.
  15992. */
  15993. /*
  15994. ** This version of the memory allocator is used only if the
  15995. ** SQLITE_MEMDEBUG macro is defined
  15996. */
  15997. #ifdef SQLITE_MEMDEBUG
  15998. /*
  15999. ** The backtrace functionality is only available with GLIBC
  16000. */
  16001. #ifdef __GLIBC__
  16002. extern int backtrace(void**,int);
  16003. extern void backtrace_symbols_fd(void*const*,int,int);
  16004. #else
  16005. # define backtrace(A,B) 1
  16006. # define backtrace_symbols_fd(A,B,C)
  16007. #endif
  16008. /* #include <stdio.h> */
  16009. /*
  16010. ** Each memory allocation looks like this:
  16011. **
  16012. ** ------------------------------------------------------------------------
  16013. ** | Title | backtrace pointers | MemBlockHdr | allocation | EndGuard |
  16014. ** ------------------------------------------------------------------------
  16015. **
  16016. ** The application code sees only a pointer to the allocation. We have
  16017. ** to back up from the allocation pointer to find the MemBlockHdr. The
  16018. ** MemBlockHdr tells us the size of the allocation and the number of
  16019. ** backtrace pointers. There is also a guard word at the end of the
  16020. ** MemBlockHdr.
  16021. */
  16022. struct MemBlockHdr {
  16023. i64 iSize; /* Size of this allocation */
  16024. struct MemBlockHdr *pNext, *pPrev; /* Linked list of all unfreed memory */
  16025. char nBacktrace; /* Number of backtraces on this alloc */
  16026. char nBacktraceSlots; /* Available backtrace slots */
  16027. u8 nTitle; /* Bytes of title; includes '\0' */
  16028. u8 eType; /* Allocation type code */
  16029. int iForeGuard; /* Guard word for sanity */
  16030. };
  16031. /*
  16032. ** Guard words
  16033. */
  16034. #define FOREGUARD 0x80F5E153
  16035. #define REARGUARD 0xE4676B53
  16036. /*
  16037. ** Number of malloc size increments to track.
  16038. */
  16039. #define NCSIZE 1000
  16040. /*
  16041. ** All of the static variables used by this module are collected
  16042. ** into a single structure named "mem". This is to keep the
  16043. ** static variables organized and to reduce namespace pollution
  16044. ** when this module is combined with other in the amalgamation.
  16045. */
  16046. static struct {
  16047. /*
  16048. ** Mutex to control access to the memory allocation subsystem.
  16049. */
  16050. sqlite3_mutex *mutex;
  16051. /*
  16052. ** Head and tail of a linked list of all outstanding allocations
  16053. */
  16054. struct MemBlockHdr *pFirst;
  16055. struct MemBlockHdr *pLast;
  16056. /*
  16057. ** The number of levels of backtrace to save in new allocations.
  16058. */
  16059. int nBacktrace;
  16060. void (*xBacktrace)(int, int, void **);
  16061. /*
  16062. ** Title text to insert in front of each block
  16063. */
  16064. int nTitle; /* Bytes of zTitle to save. Includes '\0' and padding */
  16065. char zTitle[100]; /* The title text */
  16066. /*
  16067. ** sqlite3MallocDisallow() increments the following counter.
  16068. ** sqlite3MallocAllow() decrements it.
  16069. */
  16070. int disallow; /* Do not allow memory allocation */
  16071. /*
  16072. ** Gather statistics on the sizes of memory allocations.
  16073. ** nAlloc[i] is the number of allocation attempts of i*8
  16074. ** bytes. i==NCSIZE is the number of allocation attempts for
  16075. ** sizes more than NCSIZE*8 bytes.
  16076. */
  16077. int nAlloc[NCSIZE]; /* Total number of allocations */
  16078. int nCurrent[NCSIZE]; /* Current number of allocations */
  16079. int mxCurrent[NCSIZE]; /* Highwater mark for nCurrent */
  16080. } mem;
  16081. /*
  16082. ** Adjust memory usage statistics
  16083. */
  16084. static void adjustStats(int iSize, int increment){
  16085. int i = ROUND8(iSize)/8;
  16086. if( i>NCSIZE-1 ){
  16087. i = NCSIZE - 1;
  16088. }
  16089. if( increment>0 ){
  16090. mem.nAlloc[i]++;
  16091. mem.nCurrent[i]++;
  16092. if( mem.nCurrent[i]>mem.mxCurrent[i] ){
  16093. mem.mxCurrent[i] = mem.nCurrent[i];
  16094. }
  16095. }else{
  16096. mem.nCurrent[i]--;
  16097. assert( mem.nCurrent[i]>=0 );
  16098. }
  16099. }
  16100. /*
  16101. ** Given an allocation, find the MemBlockHdr for that allocation.
  16102. **
  16103. ** This routine checks the guards at either end of the allocation and
  16104. ** if they are incorrect it asserts.
  16105. */
  16106. static struct MemBlockHdr *sqlite3MemsysGetHeader(void *pAllocation){
  16107. struct MemBlockHdr *p;
  16108. int *pInt;
  16109. u8 *pU8;
  16110. int nReserve;
  16111. p = (struct MemBlockHdr*)pAllocation;
  16112. p--;
  16113. assert( p->iForeGuard==(int)FOREGUARD );
  16114. nReserve = ROUND8(p->iSize);
  16115. pInt = (int*)pAllocation;
  16116. pU8 = (u8*)pAllocation;
  16117. assert( pInt[nReserve/sizeof(int)]==(int)REARGUARD );
  16118. /* This checks any of the "extra" bytes allocated due
  16119. ** to rounding up to an 8 byte boundary to ensure
  16120. ** they haven't been overwritten.
  16121. */
  16122. while( nReserve-- > p->iSize ) assert( pU8[nReserve]==0x65 );
  16123. return p;
  16124. }
  16125. /*
  16126. ** Return the number of bytes currently allocated at address p.
  16127. */
  16128. static int sqlite3MemSize(void *p){
  16129. struct MemBlockHdr *pHdr;
  16130. if( !p ){
  16131. return 0;
  16132. }
  16133. pHdr = sqlite3MemsysGetHeader(p);
  16134. return (int)pHdr->iSize;
  16135. }
  16136. /*
  16137. ** Initialize the memory allocation subsystem.
  16138. */
  16139. static int sqlite3MemInit(void *NotUsed){
  16140. UNUSED_PARAMETER(NotUsed);
  16141. assert( (sizeof(struct MemBlockHdr)&7) == 0 );
  16142. if( !sqlite3GlobalConfig.bMemstat ){
  16143. /* If memory status is enabled, then the malloc.c wrapper will already
  16144. ** hold the STATIC_MEM mutex when the routines here are invoked. */
  16145. mem.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16146. }
  16147. return SQLITE_OK;
  16148. }
  16149. /*
  16150. ** Deinitialize the memory allocation subsystem.
  16151. */
  16152. static void sqlite3MemShutdown(void *NotUsed){
  16153. UNUSED_PARAMETER(NotUsed);
  16154. mem.mutex = 0;
  16155. }
  16156. /*
  16157. ** Round up a request size to the next valid allocation size.
  16158. */
  16159. static int sqlite3MemRoundup(int n){
  16160. return ROUND8(n);
  16161. }
  16162. /*
  16163. ** Fill a buffer with pseudo-random bytes. This is used to preset
  16164. ** the content of a new memory allocation to unpredictable values and
  16165. ** to clear the content of a freed allocation to unpredictable values.
  16166. */
  16167. static void randomFill(char *pBuf, int nByte){
  16168. unsigned int x, y, r;
  16169. x = SQLITE_PTR_TO_INT(pBuf);
  16170. y = nByte | 1;
  16171. while( nByte >= 4 ){
  16172. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  16173. y = y*1103515245 + 12345;
  16174. r = x ^ y;
  16175. *(int*)pBuf = r;
  16176. pBuf += 4;
  16177. nByte -= 4;
  16178. }
  16179. while( nByte-- > 0 ){
  16180. x = (x>>1) ^ (-(int)(x&1) & 0xd0000001);
  16181. y = y*1103515245 + 12345;
  16182. r = x ^ y;
  16183. *(pBuf++) = r & 0xff;
  16184. }
  16185. }
  16186. /*
  16187. ** Allocate nByte bytes of memory.
  16188. */
  16189. static void *sqlite3MemMalloc(int nByte){
  16190. struct MemBlockHdr *pHdr;
  16191. void **pBt;
  16192. char *z;
  16193. int *pInt;
  16194. void *p = 0;
  16195. int totalSize;
  16196. int nReserve;
  16197. sqlite3_mutex_enter(mem.mutex);
  16198. assert( mem.disallow==0 );
  16199. nReserve = ROUND8(nByte);
  16200. totalSize = nReserve + sizeof(*pHdr) + sizeof(int) +
  16201. mem.nBacktrace*sizeof(void*) + mem.nTitle;
  16202. p = malloc(totalSize);
  16203. if( p ){
  16204. z = p;
  16205. pBt = (void**)&z[mem.nTitle];
  16206. pHdr = (struct MemBlockHdr*)&pBt[mem.nBacktrace];
  16207. pHdr->pNext = 0;
  16208. pHdr->pPrev = mem.pLast;
  16209. if( mem.pLast ){
  16210. mem.pLast->pNext = pHdr;
  16211. }else{
  16212. mem.pFirst = pHdr;
  16213. }
  16214. mem.pLast = pHdr;
  16215. pHdr->iForeGuard = FOREGUARD;
  16216. pHdr->eType = MEMTYPE_HEAP;
  16217. pHdr->nBacktraceSlots = mem.nBacktrace;
  16218. pHdr->nTitle = mem.nTitle;
  16219. if( mem.nBacktrace ){
  16220. void *aAddr[40];
  16221. pHdr->nBacktrace = backtrace(aAddr, mem.nBacktrace+1)-1;
  16222. memcpy(pBt, &aAddr[1], pHdr->nBacktrace*sizeof(void*));
  16223. assert(pBt[0]);
  16224. if( mem.xBacktrace ){
  16225. mem.xBacktrace(nByte, pHdr->nBacktrace-1, &aAddr[1]);
  16226. }
  16227. }else{
  16228. pHdr->nBacktrace = 0;
  16229. }
  16230. if( mem.nTitle ){
  16231. memcpy(z, mem.zTitle, mem.nTitle);
  16232. }
  16233. pHdr->iSize = nByte;
  16234. adjustStats(nByte, +1);
  16235. pInt = (int*)&pHdr[1];
  16236. pInt[nReserve/sizeof(int)] = REARGUARD;
  16237. randomFill((char*)pInt, nByte);
  16238. memset(((char*)pInt)+nByte, 0x65, nReserve-nByte);
  16239. p = (void*)pInt;
  16240. }
  16241. sqlite3_mutex_leave(mem.mutex);
  16242. return p;
  16243. }
  16244. /*
  16245. ** Free memory.
  16246. */
  16247. static void sqlite3MemFree(void *pPrior){
  16248. struct MemBlockHdr *pHdr;
  16249. void **pBt;
  16250. char *z;
  16251. assert( sqlite3GlobalConfig.bMemstat || sqlite3GlobalConfig.bCoreMutex==0
  16252. || mem.mutex!=0 );
  16253. pHdr = sqlite3MemsysGetHeader(pPrior);
  16254. pBt = (void**)pHdr;
  16255. pBt -= pHdr->nBacktraceSlots;
  16256. sqlite3_mutex_enter(mem.mutex);
  16257. if( pHdr->pPrev ){
  16258. assert( pHdr->pPrev->pNext==pHdr );
  16259. pHdr->pPrev->pNext = pHdr->pNext;
  16260. }else{
  16261. assert( mem.pFirst==pHdr );
  16262. mem.pFirst = pHdr->pNext;
  16263. }
  16264. if( pHdr->pNext ){
  16265. assert( pHdr->pNext->pPrev==pHdr );
  16266. pHdr->pNext->pPrev = pHdr->pPrev;
  16267. }else{
  16268. assert( mem.pLast==pHdr );
  16269. mem.pLast = pHdr->pPrev;
  16270. }
  16271. z = (char*)pBt;
  16272. z -= pHdr->nTitle;
  16273. adjustStats((int)pHdr->iSize, -1);
  16274. randomFill(z, sizeof(void*)*pHdr->nBacktraceSlots + sizeof(*pHdr) +
  16275. (int)pHdr->iSize + sizeof(int) + pHdr->nTitle);
  16276. free(z);
  16277. sqlite3_mutex_leave(mem.mutex);
  16278. }
  16279. /*
  16280. ** Change the size of an existing memory allocation.
  16281. **
  16282. ** For this debugging implementation, we *always* make a copy of the
  16283. ** allocation into a new place in memory. In this way, if the
  16284. ** higher level code is using pointer to the old allocation, it is
  16285. ** much more likely to break and we are much more liking to find
  16286. ** the error.
  16287. */
  16288. static void *sqlite3MemRealloc(void *pPrior, int nByte){
  16289. struct MemBlockHdr *pOldHdr;
  16290. void *pNew;
  16291. assert( mem.disallow==0 );
  16292. assert( (nByte & 7)==0 ); /* EV: R-46199-30249 */
  16293. pOldHdr = sqlite3MemsysGetHeader(pPrior);
  16294. pNew = sqlite3MemMalloc(nByte);
  16295. if( pNew ){
  16296. memcpy(pNew, pPrior, (int)(nByte<pOldHdr->iSize ? nByte : pOldHdr->iSize));
  16297. if( nByte>pOldHdr->iSize ){
  16298. randomFill(&((char*)pNew)[pOldHdr->iSize], nByte - (int)pOldHdr->iSize);
  16299. }
  16300. sqlite3MemFree(pPrior);
  16301. }
  16302. return pNew;
  16303. }
  16304. /*
  16305. ** Populate the low-level memory allocation function pointers in
  16306. ** sqlite3GlobalConfig.m with pointers to the routines in this file.
  16307. */
  16308. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  16309. static const sqlite3_mem_methods defaultMethods = {
  16310. sqlite3MemMalloc,
  16311. sqlite3MemFree,
  16312. sqlite3MemRealloc,
  16313. sqlite3MemSize,
  16314. sqlite3MemRoundup,
  16315. sqlite3MemInit,
  16316. sqlite3MemShutdown,
  16317. 0
  16318. };
  16319. sqlite3_config(SQLITE_CONFIG_MALLOC, &defaultMethods);
  16320. }
  16321. /*
  16322. ** Set the "type" of an allocation.
  16323. */
  16324. SQLITE_PRIVATE void sqlite3MemdebugSetType(void *p, u8 eType){
  16325. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16326. struct MemBlockHdr *pHdr;
  16327. pHdr = sqlite3MemsysGetHeader(p);
  16328. assert( pHdr->iForeGuard==FOREGUARD );
  16329. pHdr->eType = eType;
  16330. }
  16331. }
  16332. /*
  16333. ** Return TRUE if the mask of type in eType matches the type of the
  16334. ** allocation p. Also return true if p==NULL.
  16335. **
  16336. ** This routine is designed for use within an assert() statement, to
  16337. ** verify the type of an allocation. For example:
  16338. **
  16339. ** assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  16340. */
  16341. SQLITE_PRIVATE int sqlite3MemdebugHasType(void *p, u8 eType){
  16342. int rc = 1;
  16343. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16344. struct MemBlockHdr *pHdr;
  16345. pHdr = sqlite3MemsysGetHeader(p);
  16346. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  16347. if( (pHdr->eType&eType)==0 ){
  16348. rc = 0;
  16349. }
  16350. }
  16351. return rc;
  16352. }
  16353. /*
  16354. ** Return TRUE if the mask of type in eType matches no bits of the type of the
  16355. ** allocation p. Also return true if p==NULL.
  16356. **
  16357. ** This routine is designed for use within an assert() statement, to
  16358. ** verify the type of an allocation. For example:
  16359. **
  16360. ** assert( sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  16361. */
  16362. SQLITE_PRIVATE int sqlite3MemdebugNoType(void *p, u8 eType){
  16363. int rc = 1;
  16364. if( p && sqlite3GlobalConfig.m.xMalloc==sqlite3MemMalloc ){
  16365. struct MemBlockHdr *pHdr;
  16366. pHdr = sqlite3MemsysGetHeader(p);
  16367. assert( pHdr->iForeGuard==FOREGUARD ); /* Allocation is valid */
  16368. if( (pHdr->eType&eType)!=0 ){
  16369. rc = 0;
  16370. }
  16371. }
  16372. return rc;
  16373. }
  16374. /*
  16375. ** Set the number of backtrace levels kept for each allocation.
  16376. ** A value of zero turns off backtracing. The number is always rounded
  16377. ** up to a multiple of 2.
  16378. */
  16379. SQLITE_PRIVATE void sqlite3MemdebugBacktrace(int depth){
  16380. if( depth<0 ){ depth = 0; }
  16381. if( depth>20 ){ depth = 20; }
  16382. depth = (depth+1)&0xfe;
  16383. mem.nBacktrace = depth;
  16384. }
  16385. SQLITE_PRIVATE void sqlite3MemdebugBacktraceCallback(void (*xBacktrace)(int, int, void **)){
  16386. mem.xBacktrace = xBacktrace;
  16387. }
  16388. /*
  16389. ** Set the title string for subsequent allocations.
  16390. */
  16391. SQLITE_PRIVATE void sqlite3MemdebugSettitle(const char *zTitle){
  16392. unsigned int n = sqlite3Strlen30(zTitle) + 1;
  16393. sqlite3_mutex_enter(mem.mutex);
  16394. if( n>=sizeof(mem.zTitle) ) n = sizeof(mem.zTitle)-1;
  16395. memcpy(mem.zTitle, zTitle, n);
  16396. mem.zTitle[n] = 0;
  16397. mem.nTitle = ROUND8(n);
  16398. sqlite3_mutex_leave(mem.mutex);
  16399. }
  16400. SQLITE_PRIVATE void sqlite3MemdebugSync(){
  16401. struct MemBlockHdr *pHdr;
  16402. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  16403. void **pBt = (void**)pHdr;
  16404. pBt -= pHdr->nBacktraceSlots;
  16405. mem.xBacktrace((int)pHdr->iSize, pHdr->nBacktrace-1, &pBt[1]);
  16406. }
  16407. }
  16408. /*
  16409. ** Open the file indicated and write a log of all unfreed memory
  16410. ** allocations into that log.
  16411. */
  16412. SQLITE_PRIVATE void sqlite3MemdebugDump(const char *zFilename){
  16413. FILE *out;
  16414. struct MemBlockHdr *pHdr;
  16415. void **pBt;
  16416. int i;
  16417. out = fopen(zFilename, "w");
  16418. if( out==0 ){
  16419. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  16420. zFilename);
  16421. return;
  16422. }
  16423. for(pHdr=mem.pFirst; pHdr; pHdr=pHdr->pNext){
  16424. char *z = (char*)pHdr;
  16425. z -= pHdr->nBacktraceSlots*sizeof(void*) + pHdr->nTitle;
  16426. fprintf(out, "**** %lld bytes at %p from %s ****\n",
  16427. pHdr->iSize, &pHdr[1], pHdr->nTitle ? z : "???");
  16428. if( pHdr->nBacktrace ){
  16429. fflush(out);
  16430. pBt = (void**)pHdr;
  16431. pBt -= pHdr->nBacktraceSlots;
  16432. backtrace_symbols_fd(pBt, pHdr->nBacktrace, fileno(out));
  16433. fprintf(out, "\n");
  16434. }
  16435. }
  16436. fprintf(out, "COUNTS:\n");
  16437. for(i=0; i<NCSIZE-1; i++){
  16438. if( mem.nAlloc[i] ){
  16439. fprintf(out, " %5d: %10d %10d %10d\n",
  16440. i*8, mem.nAlloc[i], mem.nCurrent[i], mem.mxCurrent[i]);
  16441. }
  16442. }
  16443. if( mem.nAlloc[NCSIZE-1] ){
  16444. fprintf(out, " %5d: %10d %10d %10d\n",
  16445. NCSIZE*8-8, mem.nAlloc[NCSIZE-1],
  16446. mem.nCurrent[NCSIZE-1], mem.mxCurrent[NCSIZE-1]);
  16447. }
  16448. fclose(out);
  16449. }
  16450. /*
  16451. ** Return the number of times sqlite3MemMalloc() has been called.
  16452. */
  16453. SQLITE_PRIVATE int sqlite3MemdebugMallocCount(){
  16454. int i;
  16455. int nTotal = 0;
  16456. for(i=0; i<NCSIZE; i++){
  16457. nTotal += mem.nAlloc[i];
  16458. }
  16459. return nTotal;
  16460. }
  16461. #endif /* SQLITE_MEMDEBUG */
  16462. /************** End of mem2.c ************************************************/
  16463. /************** Begin file mem3.c ********************************************/
  16464. /*
  16465. ** 2007 October 14
  16466. **
  16467. ** The author disclaims copyright to this source code. In place of
  16468. ** a legal notice, here is a blessing:
  16469. **
  16470. ** May you do good and not evil.
  16471. ** May you find forgiveness for yourself and forgive others.
  16472. ** May you share freely, never taking more than you give.
  16473. **
  16474. *************************************************************************
  16475. ** This file contains the C functions that implement a memory
  16476. ** allocation subsystem for use by SQLite.
  16477. **
  16478. ** This version of the memory allocation subsystem omits all
  16479. ** use of malloc(). The SQLite user supplies a block of memory
  16480. ** before calling sqlite3_initialize() from which allocations
  16481. ** are made and returned by the xMalloc() and xRealloc()
  16482. ** implementations. Once sqlite3_initialize() has been called,
  16483. ** the amount of memory available to SQLite is fixed and cannot
  16484. ** be changed.
  16485. **
  16486. ** This version of the memory allocation subsystem is included
  16487. ** in the build only if SQLITE_ENABLE_MEMSYS3 is defined.
  16488. */
  16489. /*
  16490. ** This version of the memory allocator is only built into the library
  16491. ** SQLITE_ENABLE_MEMSYS3 is defined. Defining this symbol does not
  16492. ** mean that the library will use a memory-pool by default, just that
  16493. ** it is available. The mempool allocator is activated by calling
  16494. ** sqlite3_config().
  16495. */
  16496. #ifdef SQLITE_ENABLE_MEMSYS3
  16497. /*
  16498. ** Maximum size (in Mem3Blocks) of a "small" chunk.
  16499. */
  16500. #define MX_SMALL 10
  16501. /*
  16502. ** Number of freelist hash slots
  16503. */
  16504. #define N_HASH 61
  16505. /*
  16506. ** A memory allocation (also called a "chunk") consists of two or
  16507. ** more blocks where each block is 8 bytes. The first 8 bytes are
  16508. ** a header that is not returned to the user.
  16509. **
  16510. ** A chunk is two or more blocks that is either checked out or
  16511. ** free. The first block has format u.hdr. u.hdr.size4x is 4 times the
  16512. ** size of the allocation in blocks if the allocation is free.
  16513. ** The u.hdr.size4x&1 bit is true if the chunk is checked out and
  16514. ** false if the chunk is on the freelist. The u.hdr.size4x&2 bit
  16515. ** is true if the previous chunk is checked out and false if the
  16516. ** previous chunk is free. The u.hdr.prevSize field is the size of
  16517. ** the previous chunk in blocks if the previous chunk is on the
  16518. ** freelist. If the previous chunk is checked out, then
  16519. ** u.hdr.prevSize can be part of the data for that chunk and should
  16520. ** not be read or written.
  16521. **
  16522. ** We often identify a chunk by its index in mem3.aPool[]. When
  16523. ** this is done, the chunk index refers to the second block of
  16524. ** the chunk. In this way, the first chunk has an index of 1.
  16525. ** A chunk index of 0 means "no such chunk" and is the equivalent
  16526. ** of a NULL pointer.
  16527. **
  16528. ** The second block of free chunks is of the form u.list. The
  16529. ** two fields form a double-linked list of chunks of related sizes.
  16530. ** Pointers to the head of the list are stored in mem3.aiSmall[]
  16531. ** for smaller chunks and mem3.aiHash[] for larger chunks.
  16532. **
  16533. ** The second block of a chunk is user data if the chunk is checked
  16534. ** out. If a chunk is checked out, the user data may extend into
  16535. ** the u.hdr.prevSize value of the following chunk.
  16536. */
  16537. typedef struct Mem3Block Mem3Block;
  16538. struct Mem3Block {
  16539. union {
  16540. struct {
  16541. u32 prevSize; /* Size of previous chunk in Mem3Block elements */
  16542. u32 size4x; /* 4x the size of current chunk in Mem3Block elements */
  16543. } hdr;
  16544. struct {
  16545. u32 next; /* Index in mem3.aPool[] of next free chunk */
  16546. u32 prev; /* Index in mem3.aPool[] of previous free chunk */
  16547. } list;
  16548. } u;
  16549. };
  16550. /*
  16551. ** All of the static variables used by this module are collected
  16552. ** into a single structure named "mem3". This is to keep the
  16553. ** static variables organized and to reduce namespace pollution
  16554. ** when this module is combined with other in the amalgamation.
  16555. */
  16556. static SQLITE_WSD struct Mem3Global {
  16557. /*
  16558. ** Memory available for allocation. nPool is the size of the array
  16559. ** (in Mem3Blocks) pointed to by aPool less 2.
  16560. */
  16561. u32 nPool;
  16562. Mem3Block *aPool;
  16563. /*
  16564. ** True if we are evaluating an out-of-memory callback.
  16565. */
  16566. int alarmBusy;
  16567. /*
  16568. ** Mutex to control access to the memory allocation subsystem.
  16569. */
  16570. sqlite3_mutex *mutex;
  16571. /*
  16572. ** The minimum amount of free space that we have seen.
  16573. */
  16574. u32 mnMaster;
  16575. /*
  16576. ** iMaster is the index of the master chunk. Most new allocations
  16577. ** occur off of this chunk. szMaster is the size (in Mem3Blocks)
  16578. ** of the current master. iMaster is 0 if there is not master chunk.
  16579. ** The master chunk is not in either the aiHash[] or aiSmall[].
  16580. */
  16581. u32 iMaster;
  16582. u32 szMaster;
  16583. /*
  16584. ** Array of lists of free blocks according to the block size
  16585. ** for smaller chunks, or a hash on the block size for larger
  16586. ** chunks.
  16587. */
  16588. u32 aiSmall[MX_SMALL-1]; /* For sizes 2 through MX_SMALL, inclusive */
  16589. u32 aiHash[N_HASH]; /* For sizes MX_SMALL+1 and larger */
  16590. } mem3 = { 97535575 };
  16591. #define mem3 GLOBAL(struct Mem3Global, mem3)
  16592. /*
  16593. ** Unlink the chunk at mem3.aPool[i] from list it is currently
  16594. ** on. *pRoot is the list that i is a member of.
  16595. */
  16596. static void memsys3UnlinkFromList(u32 i, u32 *pRoot){
  16597. u32 next = mem3.aPool[i].u.list.next;
  16598. u32 prev = mem3.aPool[i].u.list.prev;
  16599. assert( sqlite3_mutex_held(mem3.mutex) );
  16600. if( prev==0 ){
  16601. *pRoot = next;
  16602. }else{
  16603. mem3.aPool[prev].u.list.next = next;
  16604. }
  16605. if( next ){
  16606. mem3.aPool[next].u.list.prev = prev;
  16607. }
  16608. mem3.aPool[i].u.list.next = 0;
  16609. mem3.aPool[i].u.list.prev = 0;
  16610. }
  16611. /*
  16612. ** Unlink the chunk at index i from
  16613. ** whatever list is currently a member of.
  16614. */
  16615. static void memsys3Unlink(u32 i){
  16616. u32 size, hash;
  16617. assert( sqlite3_mutex_held(mem3.mutex) );
  16618. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  16619. assert( i>=1 );
  16620. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16621. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  16622. assert( size>=2 );
  16623. if( size <= MX_SMALL ){
  16624. memsys3UnlinkFromList(i, &mem3.aiSmall[size-2]);
  16625. }else{
  16626. hash = size % N_HASH;
  16627. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16628. }
  16629. }
  16630. /*
  16631. ** Link the chunk at mem3.aPool[i] so that is on the list rooted
  16632. ** at *pRoot.
  16633. */
  16634. static void memsys3LinkIntoList(u32 i, u32 *pRoot){
  16635. assert( sqlite3_mutex_held(mem3.mutex) );
  16636. mem3.aPool[i].u.list.next = *pRoot;
  16637. mem3.aPool[i].u.list.prev = 0;
  16638. if( *pRoot ){
  16639. mem3.aPool[*pRoot].u.list.prev = i;
  16640. }
  16641. *pRoot = i;
  16642. }
  16643. /*
  16644. ** Link the chunk at index i into either the appropriate
  16645. ** small chunk list, or into the large chunk hash table.
  16646. */
  16647. static void memsys3Link(u32 i){
  16648. u32 size, hash;
  16649. assert( sqlite3_mutex_held(mem3.mutex) );
  16650. assert( i>=1 );
  16651. assert( (mem3.aPool[i-1].u.hdr.size4x & 1)==0 );
  16652. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16653. assert( size==mem3.aPool[i+size-1].u.hdr.prevSize );
  16654. assert( size>=2 );
  16655. if( size <= MX_SMALL ){
  16656. memsys3LinkIntoList(i, &mem3.aiSmall[size-2]);
  16657. }else{
  16658. hash = size % N_HASH;
  16659. memsys3LinkIntoList(i, &mem3.aiHash[hash]);
  16660. }
  16661. }
  16662. /*
  16663. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  16664. ** will already be held (obtained by code in malloc.c) if
  16665. ** sqlite3GlobalConfig.bMemStat is true.
  16666. */
  16667. static void memsys3Enter(void){
  16668. if( sqlite3GlobalConfig.bMemstat==0 && mem3.mutex==0 ){
  16669. mem3.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  16670. }
  16671. sqlite3_mutex_enter(mem3.mutex);
  16672. }
  16673. static void memsys3Leave(void){
  16674. sqlite3_mutex_leave(mem3.mutex);
  16675. }
  16676. /*
  16677. ** Called when we are unable to satisfy an allocation of nBytes.
  16678. */
  16679. static void memsys3OutOfMemory(int nByte){
  16680. if( !mem3.alarmBusy ){
  16681. mem3.alarmBusy = 1;
  16682. assert( sqlite3_mutex_held(mem3.mutex) );
  16683. sqlite3_mutex_leave(mem3.mutex);
  16684. sqlite3_release_memory(nByte);
  16685. sqlite3_mutex_enter(mem3.mutex);
  16686. mem3.alarmBusy = 0;
  16687. }
  16688. }
  16689. /*
  16690. ** Chunk i is a free chunk that has been unlinked. Adjust its
  16691. ** size parameters for check-out and return a pointer to the
  16692. ** user portion of the chunk.
  16693. */
  16694. static void *memsys3Checkout(u32 i, u32 nBlock){
  16695. u32 x;
  16696. assert( sqlite3_mutex_held(mem3.mutex) );
  16697. assert( i>=1 );
  16698. assert( mem3.aPool[i-1].u.hdr.size4x/4==nBlock );
  16699. assert( mem3.aPool[i+nBlock-1].u.hdr.prevSize==nBlock );
  16700. x = mem3.aPool[i-1].u.hdr.size4x;
  16701. mem3.aPool[i-1].u.hdr.size4x = nBlock*4 | 1 | (x&2);
  16702. mem3.aPool[i+nBlock-1].u.hdr.prevSize = nBlock;
  16703. mem3.aPool[i+nBlock-1].u.hdr.size4x |= 2;
  16704. return &mem3.aPool[i];
  16705. }
  16706. /*
  16707. ** Carve a piece off of the end of the mem3.iMaster free chunk.
  16708. ** Return a pointer to the new allocation. Or, if the master chunk
  16709. ** is not large enough, return 0.
  16710. */
  16711. static void *memsys3FromMaster(u32 nBlock){
  16712. assert( sqlite3_mutex_held(mem3.mutex) );
  16713. assert( mem3.szMaster>=nBlock );
  16714. if( nBlock>=mem3.szMaster-1 ){
  16715. /* Use the entire master */
  16716. void *p = memsys3Checkout(mem3.iMaster, mem3.szMaster);
  16717. mem3.iMaster = 0;
  16718. mem3.szMaster = 0;
  16719. mem3.mnMaster = 0;
  16720. return p;
  16721. }else{
  16722. /* Split the master block. Return the tail. */
  16723. u32 newi, x;
  16724. newi = mem3.iMaster + mem3.szMaster - nBlock;
  16725. assert( newi > mem3.iMaster+1 );
  16726. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = nBlock;
  16727. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x |= 2;
  16728. mem3.aPool[newi-1].u.hdr.size4x = nBlock*4 + 1;
  16729. mem3.szMaster -= nBlock;
  16730. mem3.aPool[newi-1].u.hdr.prevSize = mem3.szMaster;
  16731. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16732. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16733. if( mem3.szMaster < mem3.mnMaster ){
  16734. mem3.mnMaster = mem3.szMaster;
  16735. }
  16736. return (void*)&mem3.aPool[newi];
  16737. }
  16738. }
  16739. /*
  16740. ** *pRoot is the head of a list of free chunks of the same size
  16741. ** or same size hash. In other words, *pRoot is an entry in either
  16742. ** mem3.aiSmall[] or mem3.aiHash[].
  16743. **
  16744. ** This routine examines all entries on the given list and tries
  16745. ** to coalesce each entries with adjacent free chunks.
  16746. **
  16747. ** If it sees a chunk that is larger than mem3.iMaster, it replaces
  16748. ** the current mem3.iMaster with the new larger chunk. In order for
  16749. ** this mem3.iMaster replacement to work, the master chunk must be
  16750. ** linked into the hash tables. That is not the normal state of
  16751. ** affairs, of course. The calling routine must link the master
  16752. ** chunk before invoking this routine, then must unlink the (possibly
  16753. ** changed) master chunk once this routine has finished.
  16754. */
  16755. static void memsys3Merge(u32 *pRoot){
  16756. u32 iNext, prev, size, i, x;
  16757. assert( sqlite3_mutex_held(mem3.mutex) );
  16758. for(i=*pRoot; i>0; i=iNext){
  16759. iNext = mem3.aPool[i].u.list.next;
  16760. size = mem3.aPool[i-1].u.hdr.size4x;
  16761. assert( (size&1)==0 );
  16762. if( (size&2)==0 ){
  16763. memsys3UnlinkFromList(i, pRoot);
  16764. assert( i > mem3.aPool[i-1].u.hdr.prevSize );
  16765. prev = i - mem3.aPool[i-1].u.hdr.prevSize;
  16766. if( prev==iNext ){
  16767. iNext = mem3.aPool[prev].u.list.next;
  16768. }
  16769. memsys3Unlink(prev);
  16770. size = i + size/4 - prev;
  16771. x = mem3.aPool[prev-1].u.hdr.size4x & 2;
  16772. mem3.aPool[prev-1].u.hdr.size4x = size*4 | x;
  16773. mem3.aPool[prev+size-1].u.hdr.prevSize = size;
  16774. memsys3Link(prev);
  16775. i = prev;
  16776. }else{
  16777. size /= 4;
  16778. }
  16779. if( size>mem3.szMaster ){
  16780. mem3.iMaster = i;
  16781. mem3.szMaster = size;
  16782. }
  16783. }
  16784. }
  16785. /*
  16786. ** Return a block of memory of at least nBytes in size.
  16787. ** Return NULL if unable.
  16788. **
  16789. ** This function assumes that the necessary mutexes, if any, are
  16790. ** already held by the caller. Hence "Unsafe".
  16791. */
  16792. static void *memsys3MallocUnsafe(int nByte){
  16793. u32 i;
  16794. u32 nBlock;
  16795. u32 toFree;
  16796. assert( sqlite3_mutex_held(mem3.mutex) );
  16797. assert( sizeof(Mem3Block)==8 );
  16798. if( nByte<=12 ){
  16799. nBlock = 2;
  16800. }else{
  16801. nBlock = (nByte + 11)/8;
  16802. }
  16803. assert( nBlock>=2 );
  16804. /* STEP 1:
  16805. ** Look for an entry of the correct size in either the small
  16806. ** chunk table or in the large chunk hash table. This is
  16807. ** successful most of the time (about 9 times out of 10).
  16808. */
  16809. if( nBlock <= MX_SMALL ){
  16810. i = mem3.aiSmall[nBlock-2];
  16811. if( i>0 ){
  16812. memsys3UnlinkFromList(i, &mem3.aiSmall[nBlock-2]);
  16813. return memsys3Checkout(i, nBlock);
  16814. }
  16815. }else{
  16816. int hash = nBlock % N_HASH;
  16817. for(i=mem3.aiHash[hash]; i>0; i=mem3.aPool[i].u.list.next){
  16818. if( mem3.aPool[i-1].u.hdr.size4x/4==nBlock ){
  16819. memsys3UnlinkFromList(i, &mem3.aiHash[hash]);
  16820. return memsys3Checkout(i, nBlock);
  16821. }
  16822. }
  16823. }
  16824. /* STEP 2:
  16825. ** Try to satisfy the allocation by carving a piece off of the end
  16826. ** of the master chunk. This step usually works if step 1 fails.
  16827. */
  16828. if( mem3.szMaster>=nBlock ){
  16829. return memsys3FromMaster(nBlock);
  16830. }
  16831. /* STEP 3:
  16832. ** Loop through the entire memory pool. Coalesce adjacent free
  16833. ** chunks. Recompute the master chunk as the largest free chunk.
  16834. ** Then try again to satisfy the allocation by carving a piece off
  16835. ** of the end of the master chunk. This step happens very
  16836. ** rarely (we hope!)
  16837. */
  16838. for(toFree=nBlock*16; toFree<(mem3.nPool*16); toFree *= 2){
  16839. memsys3OutOfMemory(toFree);
  16840. if( mem3.iMaster ){
  16841. memsys3Link(mem3.iMaster);
  16842. mem3.iMaster = 0;
  16843. mem3.szMaster = 0;
  16844. }
  16845. for(i=0; i<N_HASH; i++){
  16846. memsys3Merge(&mem3.aiHash[i]);
  16847. }
  16848. for(i=0; i<MX_SMALL-1; i++){
  16849. memsys3Merge(&mem3.aiSmall[i]);
  16850. }
  16851. if( mem3.szMaster ){
  16852. memsys3Unlink(mem3.iMaster);
  16853. if( mem3.szMaster>=nBlock ){
  16854. return memsys3FromMaster(nBlock);
  16855. }
  16856. }
  16857. }
  16858. /* If none of the above worked, then we fail. */
  16859. return 0;
  16860. }
  16861. /*
  16862. ** Free an outstanding memory allocation.
  16863. **
  16864. ** This function assumes that the necessary mutexes, if any, are
  16865. ** already held by the caller. Hence "Unsafe".
  16866. */
  16867. static void memsys3FreeUnsafe(void *pOld){
  16868. Mem3Block *p = (Mem3Block*)pOld;
  16869. int i;
  16870. u32 size, x;
  16871. assert( sqlite3_mutex_held(mem3.mutex) );
  16872. assert( p>mem3.aPool && p<&mem3.aPool[mem3.nPool] );
  16873. i = p - mem3.aPool;
  16874. assert( (mem3.aPool[i-1].u.hdr.size4x&1)==1 );
  16875. size = mem3.aPool[i-1].u.hdr.size4x/4;
  16876. assert( i+size<=mem3.nPool+1 );
  16877. mem3.aPool[i-1].u.hdr.size4x &= ~1;
  16878. mem3.aPool[i+size-1].u.hdr.prevSize = size;
  16879. mem3.aPool[i+size-1].u.hdr.size4x &= ~2;
  16880. memsys3Link(i);
  16881. /* Try to expand the master using the newly freed chunk */
  16882. if( mem3.iMaster ){
  16883. while( (mem3.aPool[mem3.iMaster-1].u.hdr.size4x&2)==0 ){
  16884. size = mem3.aPool[mem3.iMaster-1].u.hdr.prevSize;
  16885. mem3.iMaster -= size;
  16886. mem3.szMaster += size;
  16887. memsys3Unlink(mem3.iMaster);
  16888. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16889. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16890. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16891. }
  16892. x = mem3.aPool[mem3.iMaster-1].u.hdr.size4x & 2;
  16893. while( (mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x&1)==0 ){
  16894. memsys3Unlink(mem3.iMaster+mem3.szMaster);
  16895. mem3.szMaster += mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.size4x/4;
  16896. mem3.aPool[mem3.iMaster-1].u.hdr.size4x = mem3.szMaster*4 | x;
  16897. mem3.aPool[mem3.iMaster+mem3.szMaster-1].u.hdr.prevSize = mem3.szMaster;
  16898. }
  16899. }
  16900. }
  16901. /*
  16902. ** Return the size of an outstanding allocation, in bytes. The
  16903. ** size returned omits the 8-byte header overhead. This only
  16904. ** works for chunks that are currently checked out.
  16905. */
  16906. static int memsys3Size(void *p){
  16907. Mem3Block *pBlock;
  16908. if( p==0 ) return 0;
  16909. pBlock = (Mem3Block*)p;
  16910. assert( (pBlock[-1].u.hdr.size4x&1)!=0 );
  16911. return (pBlock[-1].u.hdr.size4x&~3)*2 - 4;
  16912. }
  16913. /*
  16914. ** Round up a request size to the next valid allocation size.
  16915. */
  16916. static int memsys3Roundup(int n){
  16917. if( n<=12 ){
  16918. return 12;
  16919. }else{
  16920. return ((n+11)&~7) - 4;
  16921. }
  16922. }
  16923. /*
  16924. ** Allocate nBytes of memory.
  16925. */
  16926. static void *memsys3Malloc(int nBytes){
  16927. sqlite3_int64 *p;
  16928. assert( nBytes>0 ); /* malloc.c filters out 0 byte requests */
  16929. memsys3Enter();
  16930. p = memsys3MallocUnsafe(nBytes);
  16931. memsys3Leave();
  16932. return (void*)p;
  16933. }
  16934. /*
  16935. ** Free memory.
  16936. */
  16937. static void memsys3Free(void *pPrior){
  16938. assert( pPrior );
  16939. memsys3Enter();
  16940. memsys3FreeUnsafe(pPrior);
  16941. memsys3Leave();
  16942. }
  16943. /*
  16944. ** Change the size of an existing memory allocation
  16945. */
  16946. static void *memsys3Realloc(void *pPrior, int nBytes){
  16947. int nOld;
  16948. void *p;
  16949. if( pPrior==0 ){
  16950. return sqlite3_malloc(nBytes);
  16951. }
  16952. if( nBytes<=0 ){
  16953. sqlite3_free(pPrior);
  16954. return 0;
  16955. }
  16956. nOld = memsys3Size(pPrior);
  16957. if( nBytes<=nOld && nBytes>=nOld-128 ){
  16958. return pPrior;
  16959. }
  16960. memsys3Enter();
  16961. p = memsys3MallocUnsafe(nBytes);
  16962. if( p ){
  16963. if( nOld<nBytes ){
  16964. memcpy(p, pPrior, nOld);
  16965. }else{
  16966. memcpy(p, pPrior, nBytes);
  16967. }
  16968. memsys3FreeUnsafe(pPrior);
  16969. }
  16970. memsys3Leave();
  16971. return p;
  16972. }
  16973. /*
  16974. ** Initialize this module.
  16975. */
  16976. static int memsys3Init(void *NotUsed){
  16977. UNUSED_PARAMETER(NotUsed);
  16978. if( !sqlite3GlobalConfig.pHeap ){
  16979. return SQLITE_ERROR;
  16980. }
  16981. /* Store a pointer to the memory block in global structure mem3. */
  16982. assert( sizeof(Mem3Block)==8 );
  16983. mem3.aPool = (Mem3Block *)sqlite3GlobalConfig.pHeap;
  16984. mem3.nPool = (sqlite3GlobalConfig.nHeap / sizeof(Mem3Block)) - 2;
  16985. /* Initialize the master block. */
  16986. mem3.szMaster = mem3.nPool;
  16987. mem3.mnMaster = mem3.szMaster;
  16988. mem3.iMaster = 1;
  16989. mem3.aPool[0].u.hdr.size4x = (mem3.szMaster<<2) + 2;
  16990. mem3.aPool[mem3.nPool].u.hdr.prevSize = mem3.nPool;
  16991. mem3.aPool[mem3.nPool].u.hdr.size4x = 1;
  16992. return SQLITE_OK;
  16993. }
  16994. /*
  16995. ** Deinitialize this module.
  16996. */
  16997. static void memsys3Shutdown(void *NotUsed){
  16998. UNUSED_PARAMETER(NotUsed);
  16999. mem3.mutex = 0;
  17000. return;
  17001. }
  17002. /*
  17003. ** Open the file indicated and write a log of all unfreed memory
  17004. ** allocations into that log.
  17005. */
  17006. SQLITE_PRIVATE void sqlite3Memsys3Dump(const char *zFilename){
  17007. #ifdef SQLITE_DEBUG
  17008. FILE *out;
  17009. u32 i, j;
  17010. u32 size;
  17011. if( zFilename==0 || zFilename[0]==0 ){
  17012. out = stdout;
  17013. }else{
  17014. out = fopen(zFilename, "w");
  17015. if( out==0 ){
  17016. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  17017. zFilename);
  17018. return;
  17019. }
  17020. }
  17021. memsys3Enter();
  17022. fprintf(out, "CHUNKS:\n");
  17023. for(i=1; i<=mem3.nPool; i+=size/4){
  17024. size = mem3.aPool[i-1].u.hdr.size4x;
  17025. if( size/4<=1 ){
  17026. fprintf(out, "%p size error\n", &mem3.aPool[i]);
  17027. assert( 0 );
  17028. break;
  17029. }
  17030. if( (size&1)==0 && mem3.aPool[i+size/4-1].u.hdr.prevSize!=size/4 ){
  17031. fprintf(out, "%p tail size does not match\n", &mem3.aPool[i]);
  17032. assert( 0 );
  17033. break;
  17034. }
  17035. if( ((mem3.aPool[i+size/4-1].u.hdr.size4x&2)>>1)!=(size&1) ){
  17036. fprintf(out, "%p tail checkout bit is incorrect\n", &mem3.aPool[i]);
  17037. assert( 0 );
  17038. break;
  17039. }
  17040. if( size&1 ){
  17041. fprintf(out, "%p %6d bytes checked out\n", &mem3.aPool[i], (size/4)*8-8);
  17042. }else{
  17043. fprintf(out, "%p %6d bytes free%s\n", &mem3.aPool[i], (size/4)*8-8,
  17044. i==mem3.iMaster ? " **master**" : "");
  17045. }
  17046. }
  17047. for(i=0; i<MX_SMALL-1; i++){
  17048. if( mem3.aiSmall[i]==0 ) continue;
  17049. fprintf(out, "small(%2d):", i);
  17050. for(j = mem3.aiSmall[i]; j>0; j=mem3.aPool[j].u.list.next){
  17051. fprintf(out, " %p(%d)", &mem3.aPool[j],
  17052. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  17053. }
  17054. fprintf(out, "\n");
  17055. }
  17056. for(i=0; i<N_HASH; i++){
  17057. if( mem3.aiHash[i]==0 ) continue;
  17058. fprintf(out, "hash(%2d):", i);
  17059. for(j = mem3.aiHash[i]; j>0; j=mem3.aPool[j].u.list.next){
  17060. fprintf(out, " %p(%d)", &mem3.aPool[j],
  17061. (mem3.aPool[j-1].u.hdr.size4x/4)*8-8);
  17062. }
  17063. fprintf(out, "\n");
  17064. }
  17065. fprintf(out, "master=%d\n", mem3.iMaster);
  17066. fprintf(out, "nowUsed=%d\n", mem3.nPool*8 - mem3.szMaster*8);
  17067. fprintf(out, "mxUsed=%d\n", mem3.nPool*8 - mem3.mnMaster*8);
  17068. sqlite3_mutex_leave(mem3.mutex);
  17069. if( out==stdout ){
  17070. fflush(stdout);
  17071. }else{
  17072. fclose(out);
  17073. }
  17074. #else
  17075. UNUSED_PARAMETER(zFilename);
  17076. #endif
  17077. }
  17078. /*
  17079. ** This routine is the only routine in this file with external
  17080. ** linkage.
  17081. **
  17082. ** Populate the low-level memory allocation function pointers in
  17083. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  17084. ** arguments specify the block of memory to manage.
  17085. **
  17086. ** This routine is only called by sqlite3_config(), and therefore
  17087. ** is not required to be threadsafe (it is not).
  17088. */
  17089. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys3(void){
  17090. static const sqlite3_mem_methods mempoolMethods = {
  17091. memsys3Malloc,
  17092. memsys3Free,
  17093. memsys3Realloc,
  17094. memsys3Size,
  17095. memsys3Roundup,
  17096. memsys3Init,
  17097. memsys3Shutdown,
  17098. 0
  17099. };
  17100. return &mempoolMethods;
  17101. }
  17102. #endif /* SQLITE_ENABLE_MEMSYS3 */
  17103. /************** End of mem3.c ************************************************/
  17104. /************** Begin file mem5.c ********************************************/
  17105. /*
  17106. ** 2007 October 14
  17107. **
  17108. ** The author disclaims copyright to this source code. In place of
  17109. ** a legal notice, here is a blessing:
  17110. **
  17111. ** May you do good and not evil.
  17112. ** May you find forgiveness for yourself and forgive others.
  17113. ** May you share freely, never taking more than you give.
  17114. **
  17115. *************************************************************************
  17116. ** This file contains the C functions that implement a memory
  17117. ** allocation subsystem for use by SQLite.
  17118. **
  17119. ** This version of the memory allocation subsystem omits all
  17120. ** use of malloc(). The application gives SQLite a block of memory
  17121. ** before calling sqlite3_initialize() from which allocations
  17122. ** are made and returned by the xMalloc() and xRealloc()
  17123. ** implementations. Once sqlite3_initialize() has been called,
  17124. ** the amount of memory available to SQLite is fixed and cannot
  17125. ** be changed.
  17126. **
  17127. ** This version of the memory allocation subsystem is included
  17128. ** in the build only if SQLITE_ENABLE_MEMSYS5 is defined.
  17129. **
  17130. ** This memory allocator uses the following algorithm:
  17131. **
  17132. ** 1. All memory allocations sizes are rounded up to a power of 2.
  17133. **
  17134. ** 2. If two adjacent free blocks are the halves of a larger block,
  17135. ** then the two blocks are coalesced into the single larger block.
  17136. **
  17137. ** 3. New memory is allocated from the first available free block.
  17138. **
  17139. ** This algorithm is described in: J. M. Robson. "Bounds for Some Functions
  17140. ** Concerning Dynamic Storage Allocation". Journal of the Association for
  17141. ** Computing Machinery, Volume 21, Number 8, July 1974, pages 491-499.
  17142. **
  17143. ** Let n be the size of the largest allocation divided by the minimum
  17144. ** allocation size (after rounding all sizes up to a power of 2.) Let M
  17145. ** be the maximum amount of memory ever outstanding at one time. Let
  17146. ** N be the total amount of memory available for allocation. Robson
  17147. ** proved that this memory allocator will never breakdown due to
  17148. ** fragmentation as long as the following constraint holds:
  17149. **
  17150. ** N >= M*(1 + log2(n)/2) - n + 1
  17151. **
  17152. ** The sqlite3_status() logic tracks the maximum values of n and M so
  17153. ** that an application can, at any time, verify this constraint.
  17154. */
  17155. /*
  17156. ** This version of the memory allocator is used only when
  17157. ** SQLITE_ENABLE_MEMSYS5 is defined.
  17158. */
  17159. #ifdef SQLITE_ENABLE_MEMSYS5
  17160. /*
  17161. ** A minimum allocation is an instance of the following structure.
  17162. ** Larger allocations are an array of these structures where the
  17163. ** size of the array is a power of 2.
  17164. **
  17165. ** The size of this object must be a power of two. That fact is
  17166. ** verified in memsys5Init().
  17167. */
  17168. typedef struct Mem5Link Mem5Link;
  17169. struct Mem5Link {
  17170. int next; /* Index of next free chunk */
  17171. int prev; /* Index of previous free chunk */
  17172. };
  17173. /*
  17174. ** Maximum size of any allocation is ((1<<LOGMAX)*mem5.szAtom). Since
  17175. ** mem5.szAtom is always at least 8 and 32-bit integers are used,
  17176. ** it is not actually possible to reach this limit.
  17177. */
  17178. #define LOGMAX 30
  17179. /*
  17180. ** Masks used for mem5.aCtrl[] elements.
  17181. */
  17182. #define CTRL_LOGSIZE 0x1f /* Log2 Size of this block */
  17183. #define CTRL_FREE 0x20 /* True if not checked out */
  17184. /*
  17185. ** All of the static variables used by this module are collected
  17186. ** into a single structure named "mem5". This is to keep the
  17187. ** static variables organized and to reduce namespace pollution
  17188. ** when this module is combined with other in the amalgamation.
  17189. */
  17190. static SQLITE_WSD struct Mem5Global {
  17191. /*
  17192. ** Memory available for allocation
  17193. */
  17194. int szAtom; /* Smallest possible allocation in bytes */
  17195. int nBlock; /* Number of szAtom sized blocks in zPool */
  17196. u8 *zPool; /* Memory available to be allocated */
  17197. /*
  17198. ** Mutex to control access to the memory allocation subsystem.
  17199. */
  17200. sqlite3_mutex *mutex;
  17201. /*
  17202. ** Performance statistics
  17203. */
  17204. u64 nAlloc; /* Total number of calls to malloc */
  17205. u64 totalAlloc; /* Total of all malloc calls - includes internal frag */
  17206. u64 totalExcess; /* Total internal fragmentation */
  17207. u32 currentOut; /* Current checkout, including internal fragmentation */
  17208. u32 currentCount; /* Current number of distinct checkouts */
  17209. u32 maxOut; /* Maximum instantaneous currentOut */
  17210. u32 maxCount; /* Maximum instantaneous currentCount */
  17211. u32 maxRequest; /* Largest allocation (exclusive of internal frag) */
  17212. /*
  17213. ** Lists of free blocks. aiFreelist[0] is a list of free blocks of
  17214. ** size mem5.szAtom. aiFreelist[1] holds blocks of size szAtom*2.
  17215. ** and so forth.
  17216. */
  17217. int aiFreelist[LOGMAX+1];
  17218. /*
  17219. ** Space for tracking which blocks are checked out and the size
  17220. ** of each block. One byte per block.
  17221. */
  17222. u8 *aCtrl;
  17223. } mem5;
  17224. /*
  17225. ** Access the static variable through a macro for SQLITE_OMIT_WSD.
  17226. */
  17227. #define mem5 GLOBAL(struct Mem5Global, mem5)
  17228. /*
  17229. ** Assuming mem5.zPool is divided up into an array of Mem5Link
  17230. ** structures, return a pointer to the idx-th such link.
  17231. */
  17232. #define MEM5LINK(idx) ((Mem5Link *)(&mem5.zPool[(idx)*mem5.szAtom]))
  17233. /*
  17234. ** Unlink the chunk at mem5.aPool[i] from list it is currently
  17235. ** on. It should be found on mem5.aiFreelist[iLogsize].
  17236. */
  17237. static void memsys5Unlink(int i, int iLogsize){
  17238. int next, prev;
  17239. assert( i>=0 && i<mem5.nBlock );
  17240. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  17241. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  17242. next = MEM5LINK(i)->next;
  17243. prev = MEM5LINK(i)->prev;
  17244. if( prev<0 ){
  17245. mem5.aiFreelist[iLogsize] = next;
  17246. }else{
  17247. MEM5LINK(prev)->next = next;
  17248. }
  17249. if( next>=0 ){
  17250. MEM5LINK(next)->prev = prev;
  17251. }
  17252. }
  17253. /*
  17254. ** Link the chunk at mem5.aPool[i] so that is on the iLogsize
  17255. ** free list.
  17256. */
  17257. static void memsys5Link(int i, int iLogsize){
  17258. int x;
  17259. assert( sqlite3_mutex_held(mem5.mutex) );
  17260. assert( i>=0 && i<mem5.nBlock );
  17261. assert( iLogsize>=0 && iLogsize<=LOGMAX );
  17262. assert( (mem5.aCtrl[i] & CTRL_LOGSIZE)==iLogsize );
  17263. x = MEM5LINK(i)->next = mem5.aiFreelist[iLogsize];
  17264. MEM5LINK(i)->prev = -1;
  17265. if( x>=0 ){
  17266. assert( x<mem5.nBlock );
  17267. MEM5LINK(x)->prev = i;
  17268. }
  17269. mem5.aiFreelist[iLogsize] = i;
  17270. }
  17271. /*
  17272. ** If the STATIC_MEM mutex is not already held, obtain it now. The mutex
  17273. ** will already be held (obtained by code in malloc.c) if
  17274. ** sqlite3GlobalConfig.bMemStat is true.
  17275. */
  17276. static void memsys5Enter(void){
  17277. sqlite3_mutex_enter(mem5.mutex);
  17278. }
  17279. static void memsys5Leave(void){
  17280. sqlite3_mutex_leave(mem5.mutex);
  17281. }
  17282. /*
  17283. ** Return the size of an outstanding allocation, in bytes. The
  17284. ** size returned omits the 8-byte header overhead. This only
  17285. ** works for chunks that are currently checked out.
  17286. */
  17287. static int memsys5Size(void *p){
  17288. int iSize = 0;
  17289. if( p ){
  17290. int i = (int)(((u8 *)p-mem5.zPool)/mem5.szAtom);
  17291. assert( i>=0 && i<mem5.nBlock );
  17292. iSize = mem5.szAtom * (1 << (mem5.aCtrl[i]&CTRL_LOGSIZE));
  17293. }
  17294. return iSize;
  17295. }
  17296. /*
  17297. ** Return a block of memory of at least nBytes in size.
  17298. ** Return NULL if unable. Return NULL if nBytes==0.
  17299. **
  17300. ** The caller guarantees that nByte is positive.
  17301. **
  17302. ** The caller has obtained a mutex prior to invoking this
  17303. ** routine so there is never any chance that two or more
  17304. ** threads can be in this routine at the same time.
  17305. */
  17306. static void *memsys5MallocUnsafe(int nByte){
  17307. int i; /* Index of a mem5.aPool[] slot */
  17308. int iBin; /* Index into mem5.aiFreelist[] */
  17309. int iFullSz; /* Size of allocation rounded up to power of 2 */
  17310. int iLogsize; /* Log2 of iFullSz/POW2_MIN */
  17311. /* nByte must be a positive */
  17312. assert( nByte>0 );
  17313. /* Keep track of the maximum allocation request. Even unfulfilled
  17314. ** requests are counted */
  17315. if( (u32)nByte>mem5.maxRequest ){
  17316. mem5.maxRequest = nByte;
  17317. }
  17318. /* Abort if the requested allocation size is larger than the largest
  17319. ** power of two that we can represent using 32-bit signed integers.
  17320. */
  17321. if( nByte > 0x40000000 ){
  17322. return 0;
  17323. }
  17324. /* Round nByte up to the next valid power of two */
  17325. for(iFullSz=mem5.szAtom, iLogsize=0; iFullSz<nByte; iFullSz *= 2, iLogsize++){}
  17326. /* Make sure mem5.aiFreelist[iLogsize] contains at least one free
  17327. ** block. If not, then split a block of the next larger power of
  17328. ** two in order to create a new free block of size iLogsize.
  17329. */
  17330. for(iBin=iLogsize; iBin<=LOGMAX && mem5.aiFreelist[iBin]<0; iBin++){}
  17331. if( iBin>LOGMAX ){
  17332. testcase( sqlite3GlobalConfig.xLog!=0 );
  17333. sqlite3_log(SQLITE_NOMEM, "failed to allocate %u bytes", nByte);
  17334. return 0;
  17335. }
  17336. i = mem5.aiFreelist[iBin];
  17337. memsys5Unlink(i, iBin);
  17338. while( iBin>iLogsize ){
  17339. int newSize;
  17340. iBin--;
  17341. newSize = 1 << iBin;
  17342. mem5.aCtrl[i+newSize] = CTRL_FREE | iBin;
  17343. memsys5Link(i+newSize, iBin);
  17344. }
  17345. mem5.aCtrl[i] = iLogsize;
  17346. /* Update allocator performance statistics. */
  17347. mem5.nAlloc++;
  17348. mem5.totalAlloc += iFullSz;
  17349. mem5.totalExcess += iFullSz - nByte;
  17350. mem5.currentCount++;
  17351. mem5.currentOut += iFullSz;
  17352. if( mem5.maxCount<mem5.currentCount ) mem5.maxCount = mem5.currentCount;
  17353. if( mem5.maxOut<mem5.currentOut ) mem5.maxOut = mem5.currentOut;
  17354. #ifdef SQLITE_DEBUG
  17355. /* Make sure the allocated memory does not assume that it is set to zero
  17356. ** or retains a value from a previous allocation */
  17357. memset(&mem5.zPool[i*mem5.szAtom], 0xAA, iFullSz);
  17358. #endif
  17359. /* Return a pointer to the allocated memory. */
  17360. return (void*)&mem5.zPool[i*mem5.szAtom];
  17361. }
  17362. /*
  17363. ** Free an outstanding memory allocation.
  17364. */
  17365. static void memsys5FreeUnsafe(void *pOld){
  17366. u32 size, iLogsize;
  17367. int iBlock;
  17368. /* Set iBlock to the index of the block pointed to by pOld in
  17369. ** the array of mem5.szAtom byte blocks pointed to by mem5.zPool.
  17370. */
  17371. iBlock = (int)(((u8 *)pOld-mem5.zPool)/mem5.szAtom);
  17372. /* Check that the pointer pOld points to a valid, non-free block. */
  17373. assert( iBlock>=0 && iBlock<mem5.nBlock );
  17374. assert( ((u8 *)pOld-mem5.zPool)%mem5.szAtom==0 );
  17375. assert( (mem5.aCtrl[iBlock] & CTRL_FREE)==0 );
  17376. iLogsize = mem5.aCtrl[iBlock] & CTRL_LOGSIZE;
  17377. size = 1<<iLogsize;
  17378. assert( iBlock+size-1<(u32)mem5.nBlock );
  17379. mem5.aCtrl[iBlock] |= CTRL_FREE;
  17380. mem5.aCtrl[iBlock+size-1] |= CTRL_FREE;
  17381. assert( mem5.currentCount>0 );
  17382. assert( mem5.currentOut>=(size*mem5.szAtom) );
  17383. mem5.currentCount--;
  17384. mem5.currentOut -= size*mem5.szAtom;
  17385. assert( mem5.currentOut>0 || mem5.currentCount==0 );
  17386. assert( mem5.currentCount>0 || mem5.currentOut==0 );
  17387. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  17388. while( ALWAYS(iLogsize<LOGMAX) ){
  17389. int iBuddy;
  17390. if( (iBlock>>iLogsize) & 1 ){
  17391. iBuddy = iBlock - size;
  17392. }else{
  17393. iBuddy = iBlock + size;
  17394. }
  17395. assert( iBuddy>=0 );
  17396. if( (iBuddy+(1<<iLogsize))>mem5.nBlock ) break;
  17397. if( mem5.aCtrl[iBuddy]!=(CTRL_FREE | iLogsize) ) break;
  17398. memsys5Unlink(iBuddy, iLogsize);
  17399. iLogsize++;
  17400. if( iBuddy<iBlock ){
  17401. mem5.aCtrl[iBuddy] = CTRL_FREE | iLogsize;
  17402. mem5.aCtrl[iBlock] = 0;
  17403. iBlock = iBuddy;
  17404. }else{
  17405. mem5.aCtrl[iBlock] = CTRL_FREE | iLogsize;
  17406. mem5.aCtrl[iBuddy] = 0;
  17407. }
  17408. size *= 2;
  17409. }
  17410. #ifdef SQLITE_DEBUG
  17411. /* Overwrite freed memory with the 0x55 bit pattern to verify that it is
  17412. ** not used after being freed */
  17413. memset(&mem5.zPool[iBlock*mem5.szAtom], 0x55, size);
  17414. #endif
  17415. memsys5Link(iBlock, iLogsize);
  17416. }
  17417. /*
  17418. ** Allocate nBytes of memory.
  17419. */
  17420. static void *memsys5Malloc(int nBytes){
  17421. sqlite3_int64 *p = 0;
  17422. if( nBytes>0 ){
  17423. memsys5Enter();
  17424. p = memsys5MallocUnsafe(nBytes);
  17425. memsys5Leave();
  17426. }
  17427. return (void*)p;
  17428. }
  17429. /*
  17430. ** Free memory.
  17431. **
  17432. ** The outer layer memory allocator prevents this routine from
  17433. ** being called with pPrior==0.
  17434. */
  17435. static void memsys5Free(void *pPrior){
  17436. assert( pPrior!=0 );
  17437. memsys5Enter();
  17438. memsys5FreeUnsafe(pPrior);
  17439. memsys5Leave();
  17440. }
  17441. /*
  17442. ** Change the size of an existing memory allocation.
  17443. **
  17444. ** The outer layer memory allocator prevents this routine from
  17445. ** being called with pPrior==0.
  17446. **
  17447. ** nBytes is always a value obtained from a prior call to
  17448. ** memsys5Round(). Hence nBytes is always a non-negative power
  17449. ** of two. If nBytes==0 that means that an oversize allocation
  17450. ** (an allocation larger than 0x40000000) was requested and this
  17451. ** routine should return 0 without freeing pPrior.
  17452. */
  17453. static void *memsys5Realloc(void *pPrior, int nBytes){
  17454. int nOld;
  17455. void *p;
  17456. assert( pPrior!=0 );
  17457. assert( (nBytes&(nBytes-1))==0 ); /* EV: R-46199-30249 */
  17458. assert( nBytes>=0 );
  17459. if( nBytes==0 ){
  17460. return 0;
  17461. }
  17462. nOld = memsys5Size(pPrior);
  17463. if( nBytes<=nOld ){
  17464. return pPrior;
  17465. }
  17466. memsys5Enter();
  17467. p = memsys5MallocUnsafe(nBytes);
  17468. if( p ){
  17469. memcpy(p, pPrior, nOld);
  17470. memsys5FreeUnsafe(pPrior);
  17471. }
  17472. memsys5Leave();
  17473. return p;
  17474. }
  17475. /*
  17476. ** Round up a request size to the next valid allocation size. If
  17477. ** the allocation is too large to be handled by this allocation system,
  17478. ** return 0.
  17479. **
  17480. ** All allocations must be a power of two and must be expressed by a
  17481. ** 32-bit signed integer. Hence the largest allocation is 0x40000000
  17482. ** or 1073741824 bytes.
  17483. */
  17484. static int memsys5Roundup(int n){
  17485. int iFullSz;
  17486. if( n > 0x40000000 ) return 0;
  17487. for(iFullSz=mem5.szAtom; iFullSz<n; iFullSz *= 2);
  17488. return iFullSz;
  17489. }
  17490. /*
  17491. ** Return the ceiling of the logarithm base 2 of iValue.
  17492. **
  17493. ** Examples: memsys5Log(1) -> 0
  17494. ** memsys5Log(2) -> 1
  17495. ** memsys5Log(4) -> 2
  17496. ** memsys5Log(5) -> 3
  17497. ** memsys5Log(8) -> 3
  17498. ** memsys5Log(9) -> 4
  17499. */
  17500. static int memsys5Log(int iValue){
  17501. int iLog;
  17502. for(iLog=0; (iLog<(int)((sizeof(int)*8)-1)) && (1<<iLog)<iValue; iLog++);
  17503. return iLog;
  17504. }
  17505. /*
  17506. ** Initialize the memory allocator.
  17507. **
  17508. ** This routine is not threadsafe. The caller must be holding a mutex
  17509. ** to prevent multiple threads from entering at the same time.
  17510. */
  17511. static int memsys5Init(void *NotUsed){
  17512. int ii; /* Loop counter */
  17513. int nByte; /* Number of bytes of memory available to this allocator */
  17514. u8 *zByte; /* Memory usable by this allocator */
  17515. int nMinLog; /* Log base 2 of minimum allocation size in bytes */
  17516. int iOffset; /* An offset into mem5.aCtrl[] */
  17517. UNUSED_PARAMETER(NotUsed);
  17518. /* For the purposes of this routine, disable the mutex */
  17519. mem5.mutex = 0;
  17520. /* The size of a Mem5Link object must be a power of two. Verify that
  17521. ** this is case.
  17522. */
  17523. assert( (sizeof(Mem5Link)&(sizeof(Mem5Link)-1))==0 );
  17524. nByte = sqlite3GlobalConfig.nHeap;
  17525. zByte = (u8*)sqlite3GlobalConfig.pHeap;
  17526. assert( zByte!=0 ); /* sqlite3_config() does not allow otherwise */
  17527. /* boundaries on sqlite3GlobalConfig.mnReq are enforced in sqlite3_config() */
  17528. nMinLog = memsys5Log(sqlite3GlobalConfig.mnReq);
  17529. mem5.szAtom = (1<<nMinLog);
  17530. while( (int)sizeof(Mem5Link)>mem5.szAtom ){
  17531. mem5.szAtom = mem5.szAtom << 1;
  17532. }
  17533. mem5.nBlock = (nByte / (mem5.szAtom+sizeof(u8)));
  17534. mem5.zPool = zByte;
  17535. mem5.aCtrl = (u8 *)&mem5.zPool[mem5.nBlock*mem5.szAtom];
  17536. for(ii=0; ii<=LOGMAX; ii++){
  17537. mem5.aiFreelist[ii] = -1;
  17538. }
  17539. iOffset = 0;
  17540. for(ii=LOGMAX; ii>=0; ii--){
  17541. int nAlloc = (1<<ii);
  17542. if( (iOffset+nAlloc)<=mem5.nBlock ){
  17543. mem5.aCtrl[iOffset] = ii | CTRL_FREE;
  17544. memsys5Link(iOffset, ii);
  17545. iOffset += nAlloc;
  17546. }
  17547. assert((iOffset+nAlloc)>mem5.nBlock);
  17548. }
  17549. /* If a mutex is required for normal operation, allocate one */
  17550. if( sqlite3GlobalConfig.bMemstat==0 ){
  17551. mem5.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  17552. }
  17553. return SQLITE_OK;
  17554. }
  17555. /*
  17556. ** Deinitialize this module.
  17557. */
  17558. static void memsys5Shutdown(void *NotUsed){
  17559. UNUSED_PARAMETER(NotUsed);
  17560. mem5.mutex = 0;
  17561. return;
  17562. }
  17563. #ifdef SQLITE_TEST
  17564. /*
  17565. ** Open the file indicated and write a log of all unfreed memory
  17566. ** allocations into that log.
  17567. */
  17568. SQLITE_PRIVATE void sqlite3Memsys5Dump(const char *zFilename){
  17569. FILE *out;
  17570. int i, j, n;
  17571. int nMinLog;
  17572. if( zFilename==0 || zFilename[0]==0 ){
  17573. out = stdout;
  17574. }else{
  17575. out = fopen(zFilename, "w");
  17576. if( out==0 ){
  17577. fprintf(stderr, "** Unable to output memory debug output log: %s **\n",
  17578. zFilename);
  17579. return;
  17580. }
  17581. }
  17582. memsys5Enter();
  17583. nMinLog = memsys5Log(mem5.szAtom);
  17584. for(i=0; i<=LOGMAX && i+nMinLog<32; i++){
  17585. for(n=0, j=mem5.aiFreelist[i]; j>=0; j = MEM5LINK(j)->next, n++){}
  17586. fprintf(out, "freelist items of size %d: %d\n", mem5.szAtom << i, n);
  17587. }
  17588. fprintf(out, "mem5.nAlloc = %llu\n", mem5.nAlloc);
  17589. fprintf(out, "mem5.totalAlloc = %llu\n", mem5.totalAlloc);
  17590. fprintf(out, "mem5.totalExcess = %llu\n", mem5.totalExcess);
  17591. fprintf(out, "mem5.currentOut = %u\n", mem5.currentOut);
  17592. fprintf(out, "mem5.currentCount = %u\n", mem5.currentCount);
  17593. fprintf(out, "mem5.maxOut = %u\n", mem5.maxOut);
  17594. fprintf(out, "mem5.maxCount = %u\n", mem5.maxCount);
  17595. fprintf(out, "mem5.maxRequest = %u\n", mem5.maxRequest);
  17596. memsys5Leave();
  17597. if( out==stdout ){
  17598. fflush(stdout);
  17599. }else{
  17600. fclose(out);
  17601. }
  17602. }
  17603. #endif
  17604. /*
  17605. ** This routine is the only routine in this file with external
  17606. ** linkage. It returns a pointer to a static sqlite3_mem_methods
  17607. ** struct populated with the memsys5 methods.
  17608. */
  17609. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetMemsys5(void){
  17610. static const sqlite3_mem_methods memsys5Methods = {
  17611. memsys5Malloc,
  17612. memsys5Free,
  17613. memsys5Realloc,
  17614. memsys5Size,
  17615. memsys5Roundup,
  17616. memsys5Init,
  17617. memsys5Shutdown,
  17618. 0
  17619. };
  17620. return &memsys5Methods;
  17621. }
  17622. #endif /* SQLITE_ENABLE_MEMSYS5 */
  17623. /************** End of mem5.c ************************************************/
  17624. /************** Begin file mutex.c *******************************************/
  17625. /*
  17626. ** 2007 August 14
  17627. **
  17628. ** The author disclaims copyright to this source code. In place of
  17629. ** a legal notice, here is a blessing:
  17630. **
  17631. ** May you do good and not evil.
  17632. ** May you find forgiveness for yourself and forgive others.
  17633. ** May you share freely, never taking more than you give.
  17634. **
  17635. *************************************************************************
  17636. ** This file contains the C functions that implement mutexes.
  17637. **
  17638. ** This file contains code that is common across all mutex implementations.
  17639. */
  17640. #if defined(SQLITE_DEBUG) && !defined(SQLITE_MUTEX_OMIT)
  17641. /*
  17642. ** For debugging purposes, record when the mutex subsystem is initialized
  17643. ** and uninitialized so that we can assert() if there is an attempt to
  17644. ** allocate a mutex while the system is uninitialized.
  17645. */
  17646. static SQLITE_WSD int mutexIsInit = 0;
  17647. #endif /* SQLITE_DEBUG */
  17648. #ifndef SQLITE_MUTEX_OMIT
  17649. /*
  17650. ** Initialize the mutex system.
  17651. */
  17652. SQLITE_PRIVATE int sqlite3MutexInit(void){
  17653. int rc = SQLITE_OK;
  17654. if( !sqlite3GlobalConfig.mutex.xMutexAlloc ){
  17655. /* If the xMutexAlloc method has not been set, then the user did not
  17656. ** install a mutex implementation via sqlite3_config() prior to
  17657. ** sqlite3_initialize() being called. This block copies pointers to
  17658. ** the default implementation into the sqlite3GlobalConfig structure.
  17659. */
  17660. sqlite3_mutex_methods const *pFrom;
  17661. sqlite3_mutex_methods *pTo = &sqlite3GlobalConfig.mutex;
  17662. if( sqlite3GlobalConfig.bCoreMutex ){
  17663. pFrom = sqlite3DefaultMutex();
  17664. }else{
  17665. pFrom = sqlite3NoopMutex();
  17666. }
  17667. memcpy(pTo, pFrom, offsetof(sqlite3_mutex_methods, xMutexAlloc));
  17668. memcpy(&pTo->xMutexFree, &pFrom->xMutexFree,
  17669. sizeof(*pTo) - offsetof(sqlite3_mutex_methods, xMutexFree));
  17670. pTo->xMutexAlloc = pFrom->xMutexAlloc;
  17671. }
  17672. rc = sqlite3GlobalConfig.mutex.xMutexInit();
  17673. #ifdef SQLITE_DEBUG
  17674. GLOBAL(int, mutexIsInit) = 1;
  17675. #endif
  17676. return rc;
  17677. }
  17678. /*
  17679. ** Shutdown the mutex system. This call frees resources allocated by
  17680. ** sqlite3MutexInit().
  17681. */
  17682. SQLITE_PRIVATE int sqlite3MutexEnd(void){
  17683. int rc = SQLITE_OK;
  17684. if( sqlite3GlobalConfig.mutex.xMutexEnd ){
  17685. rc = sqlite3GlobalConfig.mutex.xMutexEnd();
  17686. }
  17687. #ifdef SQLITE_DEBUG
  17688. GLOBAL(int, mutexIsInit) = 0;
  17689. #endif
  17690. return rc;
  17691. }
  17692. /*
  17693. ** Retrieve a pointer to a static mutex or allocate a new dynamic one.
  17694. */
  17695. SQLITE_API sqlite3_mutex *sqlite3_mutex_alloc(int id){
  17696. #ifndef SQLITE_OMIT_AUTOINIT
  17697. if( id<=SQLITE_MUTEX_RECURSIVE && sqlite3_initialize() ) return 0;
  17698. #endif
  17699. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  17700. }
  17701. SQLITE_PRIVATE sqlite3_mutex *sqlite3MutexAlloc(int id){
  17702. if( !sqlite3GlobalConfig.bCoreMutex ){
  17703. return 0;
  17704. }
  17705. assert( GLOBAL(int, mutexIsInit) );
  17706. return sqlite3GlobalConfig.mutex.xMutexAlloc(id);
  17707. }
  17708. /*
  17709. ** Free a dynamic mutex.
  17710. */
  17711. SQLITE_API void sqlite3_mutex_free(sqlite3_mutex *p){
  17712. if( p ){
  17713. sqlite3GlobalConfig.mutex.xMutexFree(p);
  17714. }
  17715. }
  17716. /*
  17717. ** Obtain the mutex p. If some other thread already has the mutex, block
  17718. ** until it can be obtained.
  17719. */
  17720. SQLITE_API void sqlite3_mutex_enter(sqlite3_mutex *p){
  17721. if( p ){
  17722. sqlite3GlobalConfig.mutex.xMutexEnter(p);
  17723. }
  17724. }
  17725. /*
  17726. ** Obtain the mutex p. If successful, return SQLITE_OK. Otherwise, if another
  17727. ** thread holds the mutex and it cannot be obtained, return SQLITE_BUSY.
  17728. */
  17729. SQLITE_API int sqlite3_mutex_try(sqlite3_mutex *p){
  17730. int rc = SQLITE_OK;
  17731. if( p ){
  17732. return sqlite3GlobalConfig.mutex.xMutexTry(p);
  17733. }
  17734. return rc;
  17735. }
  17736. /*
  17737. ** The sqlite3_mutex_leave() routine exits a mutex that was previously
  17738. ** entered by the same thread. The behavior is undefined if the mutex
  17739. ** is not currently entered. If a NULL pointer is passed as an argument
  17740. ** this function is a no-op.
  17741. */
  17742. SQLITE_API void sqlite3_mutex_leave(sqlite3_mutex *p){
  17743. if( p ){
  17744. sqlite3GlobalConfig.mutex.xMutexLeave(p);
  17745. }
  17746. }
  17747. #ifndef NDEBUG
  17748. /*
  17749. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17750. ** intended for use inside assert() statements.
  17751. */
  17752. SQLITE_API int sqlite3_mutex_held(sqlite3_mutex *p){
  17753. return p==0 || sqlite3GlobalConfig.mutex.xMutexHeld(p);
  17754. }
  17755. SQLITE_API int sqlite3_mutex_notheld(sqlite3_mutex *p){
  17756. return p==0 || sqlite3GlobalConfig.mutex.xMutexNotheld(p);
  17757. }
  17758. #endif
  17759. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17760. /************** End of mutex.c ***********************************************/
  17761. /************** Begin file mutex_noop.c **************************************/
  17762. /*
  17763. ** 2008 October 07
  17764. **
  17765. ** The author disclaims copyright to this source code. In place of
  17766. ** a legal notice, here is a blessing:
  17767. **
  17768. ** May you do good and not evil.
  17769. ** May you find forgiveness for yourself and forgive others.
  17770. ** May you share freely, never taking more than you give.
  17771. **
  17772. *************************************************************************
  17773. ** This file contains the C functions that implement mutexes.
  17774. **
  17775. ** This implementation in this file does not provide any mutual
  17776. ** exclusion and is thus suitable for use only in applications
  17777. ** that use SQLite in a single thread. The routines defined
  17778. ** here are place-holders. Applications can substitute working
  17779. ** mutex routines at start-time using the
  17780. **
  17781. ** sqlite3_config(SQLITE_CONFIG_MUTEX,...)
  17782. **
  17783. ** interface.
  17784. **
  17785. ** If compiled with SQLITE_DEBUG, then additional logic is inserted
  17786. ** that does error checking on mutexes to make sure they are being
  17787. ** called correctly.
  17788. */
  17789. #ifndef SQLITE_MUTEX_OMIT
  17790. #ifndef SQLITE_DEBUG
  17791. /*
  17792. ** Stub routines for all mutex methods.
  17793. **
  17794. ** This routines provide no mutual exclusion or error checking.
  17795. */
  17796. static int noopMutexInit(void){ return SQLITE_OK; }
  17797. static int noopMutexEnd(void){ return SQLITE_OK; }
  17798. static sqlite3_mutex *noopMutexAlloc(int id){
  17799. UNUSED_PARAMETER(id);
  17800. return (sqlite3_mutex*)8;
  17801. }
  17802. static void noopMutexFree(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17803. static void noopMutexEnter(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17804. static int noopMutexTry(sqlite3_mutex *p){
  17805. UNUSED_PARAMETER(p);
  17806. return SQLITE_OK;
  17807. }
  17808. static void noopMutexLeave(sqlite3_mutex *p){ UNUSED_PARAMETER(p); return; }
  17809. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17810. static const sqlite3_mutex_methods sMutex = {
  17811. noopMutexInit,
  17812. noopMutexEnd,
  17813. noopMutexAlloc,
  17814. noopMutexFree,
  17815. noopMutexEnter,
  17816. noopMutexTry,
  17817. noopMutexLeave,
  17818. 0,
  17819. 0,
  17820. };
  17821. return &sMutex;
  17822. }
  17823. #endif /* !SQLITE_DEBUG */
  17824. #ifdef SQLITE_DEBUG
  17825. /*
  17826. ** In this implementation, error checking is provided for testing
  17827. ** and debugging purposes. The mutexes still do not provide any
  17828. ** mutual exclusion.
  17829. */
  17830. /*
  17831. ** The mutex object
  17832. */
  17833. typedef struct sqlite3_debug_mutex {
  17834. int id; /* The mutex type */
  17835. int cnt; /* Number of entries without a matching leave */
  17836. } sqlite3_debug_mutex;
  17837. /*
  17838. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  17839. ** intended for use inside assert() statements.
  17840. */
  17841. static int debugMutexHeld(sqlite3_mutex *pX){
  17842. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17843. return p==0 || p->cnt>0;
  17844. }
  17845. static int debugMutexNotheld(sqlite3_mutex *pX){
  17846. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17847. return p==0 || p->cnt==0;
  17848. }
  17849. /*
  17850. ** Initialize and deinitialize the mutex subsystem.
  17851. */
  17852. static int debugMutexInit(void){ return SQLITE_OK; }
  17853. static int debugMutexEnd(void){ return SQLITE_OK; }
  17854. /*
  17855. ** The sqlite3_mutex_alloc() routine allocates a new
  17856. ** mutex and returns a pointer to it. If it returns NULL
  17857. ** that means that a mutex could not be allocated.
  17858. */
  17859. static sqlite3_mutex *debugMutexAlloc(int id){
  17860. static sqlite3_debug_mutex aStatic[SQLITE_MUTEX_STATIC_APP3 - 1];
  17861. sqlite3_debug_mutex *pNew = 0;
  17862. switch( id ){
  17863. case SQLITE_MUTEX_FAST:
  17864. case SQLITE_MUTEX_RECURSIVE: {
  17865. pNew = sqlite3Malloc(sizeof(*pNew));
  17866. if( pNew ){
  17867. pNew->id = id;
  17868. pNew->cnt = 0;
  17869. }
  17870. break;
  17871. }
  17872. default: {
  17873. assert( id-2 >= 0 );
  17874. assert( id-2 < (int)(sizeof(aStatic)/sizeof(aStatic[0])) );
  17875. pNew = &aStatic[id-2];
  17876. pNew->id = id;
  17877. break;
  17878. }
  17879. }
  17880. return (sqlite3_mutex*)pNew;
  17881. }
  17882. /*
  17883. ** This routine deallocates a previously allocated mutex.
  17884. */
  17885. static void debugMutexFree(sqlite3_mutex *pX){
  17886. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17887. assert( p->cnt==0 );
  17888. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  17889. sqlite3_free(p);
  17890. }
  17891. /*
  17892. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  17893. ** to enter a mutex. If another thread is already within the mutex,
  17894. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  17895. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  17896. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  17897. ** be entered multiple times by the same thread. In such cases the,
  17898. ** mutex must be exited an equal number of times before another thread
  17899. ** can enter. If the same thread tries to enter any other kind of mutex
  17900. ** more than once, the behavior is undefined.
  17901. */
  17902. static void debugMutexEnter(sqlite3_mutex *pX){
  17903. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17904. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17905. p->cnt++;
  17906. }
  17907. static int debugMutexTry(sqlite3_mutex *pX){
  17908. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17909. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17910. p->cnt++;
  17911. return SQLITE_OK;
  17912. }
  17913. /*
  17914. ** The sqlite3_mutex_leave() routine exits a mutex that was
  17915. ** previously entered by the same thread. The behavior
  17916. ** is undefined if the mutex is not currently entered or
  17917. ** is not currently allocated. SQLite will never do either.
  17918. */
  17919. static void debugMutexLeave(sqlite3_mutex *pX){
  17920. sqlite3_debug_mutex *p = (sqlite3_debug_mutex*)pX;
  17921. assert( debugMutexHeld(pX) );
  17922. p->cnt--;
  17923. assert( p->id==SQLITE_MUTEX_RECURSIVE || debugMutexNotheld(pX) );
  17924. }
  17925. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3NoopMutex(void){
  17926. static const sqlite3_mutex_methods sMutex = {
  17927. debugMutexInit,
  17928. debugMutexEnd,
  17929. debugMutexAlloc,
  17930. debugMutexFree,
  17931. debugMutexEnter,
  17932. debugMutexTry,
  17933. debugMutexLeave,
  17934. debugMutexHeld,
  17935. debugMutexNotheld
  17936. };
  17937. return &sMutex;
  17938. }
  17939. #endif /* SQLITE_DEBUG */
  17940. /*
  17941. ** If compiled with SQLITE_MUTEX_NOOP, then the no-op mutex implementation
  17942. ** is used regardless of the run-time threadsafety setting.
  17943. */
  17944. #ifdef SQLITE_MUTEX_NOOP
  17945. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  17946. return sqlite3NoopMutex();
  17947. }
  17948. #endif /* defined(SQLITE_MUTEX_NOOP) */
  17949. #endif /* !defined(SQLITE_MUTEX_OMIT) */
  17950. /************** End of mutex_noop.c ******************************************/
  17951. /************** Begin file mutex_unix.c **************************************/
  17952. /*
  17953. ** 2007 August 28
  17954. **
  17955. ** The author disclaims copyright to this source code. In place of
  17956. ** a legal notice, here is a blessing:
  17957. **
  17958. ** May you do good and not evil.
  17959. ** May you find forgiveness for yourself and forgive others.
  17960. ** May you share freely, never taking more than you give.
  17961. **
  17962. *************************************************************************
  17963. ** This file contains the C functions that implement mutexes for pthreads
  17964. */
  17965. /*
  17966. ** The code in this file is only used if we are compiling threadsafe
  17967. ** under unix with pthreads.
  17968. **
  17969. ** Note that this implementation requires a version of pthreads that
  17970. ** supports recursive mutexes.
  17971. */
  17972. #ifdef SQLITE_MUTEX_PTHREADS
  17973. #include <pthread.h>
  17974. /*
  17975. ** The sqlite3_mutex.id, sqlite3_mutex.nRef, and sqlite3_mutex.owner fields
  17976. ** are necessary under two condidtions: (1) Debug builds and (2) using
  17977. ** home-grown mutexes. Encapsulate these conditions into a single #define.
  17978. */
  17979. #if defined(SQLITE_DEBUG) || defined(SQLITE_HOMEGROWN_RECURSIVE_MUTEX)
  17980. # define SQLITE_MUTEX_NREF 1
  17981. #else
  17982. # define SQLITE_MUTEX_NREF 0
  17983. #endif
  17984. /*
  17985. ** Each recursive mutex is an instance of the following structure.
  17986. */
  17987. struct sqlite3_mutex {
  17988. pthread_mutex_t mutex; /* Mutex controlling the lock */
  17989. #if SQLITE_MUTEX_NREF
  17990. int id; /* Mutex type */
  17991. volatile int nRef; /* Number of entrances */
  17992. volatile pthread_t owner; /* Thread that is within this mutex */
  17993. int trace; /* True to trace changes */
  17994. #endif
  17995. };
  17996. #if SQLITE_MUTEX_NREF
  17997. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER, 0, 0, (pthread_t)0, 0 }
  17998. #else
  17999. #define SQLITE3_MUTEX_INITIALIZER { PTHREAD_MUTEX_INITIALIZER }
  18000. #endif
  18001. /*
  18002. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18003. ** intended for use only inside assert() statements. On some platforms,
  18004. ** there might be race conditions that can cause these routines to
  18005. ** deliver incorrect results. In particular, if pthread_equal() is
  18006. ** not an atomic operation, then these routines might delivery
  18007. ** incorrect results. On most platforms, pthread_equal() is a
  18008. ** comparison of two integers and is therefore atomic. But we are
  18009. ** told that HPUX is not such a platform. If so, then these routines
  18010. ** will not always work correctly on HPUX.
  18011. **
  18012. ** On those platforms where pthread_equal() is not atomic, SQLite
  18013. ** should be compiled without -DSQLITE_DEBUG and with -DNDEBUG to
  18014. ** make sure no assert() statements are evaluated and hence these
  18015. ** routines are never called.
  18016. */
  18017. #if !defined(NDEBUG) || defined(SQLITE_DEBUG)
  18018. static int pthreadMutexHeld(sqlite3_mutex *p){
  18019. return (p->nRef!=0 && pthread_equal(p->owner, pthread_self()));
  18020. }
  18021. static int pthreadMutexNotheld(sqlite3_mutex *p){
  18022. return p->nRef==0 || pthread_equal(p->owner, pthread_self())==0;
  18023. }
  18024. #endif
  18025. /*
  18026. ** Initialize and deinitialize the mutex subsystem.
  18027. */
  18028. static int pthreadMutexInit(void){ return SQLITE_OK; }
  18029. static int pthreadMutexEnd(void){ return SQLITE_OK; }
  18030. /*
  18031. ** The sqlite3_mutex_alloc() routine allocates a new
  18032. ** mutex and returns a pointer to it. If it returns NULL
  18033. ** that means that a mutex could not be allocated. SQLite
  18034. ** will unwind its stack and return an error. The argument
  18035. ** to sqlite3_mutex_alloc() is one of these integer constants:
  18036. **
  18037. ** <ul>
  18038. ** <li> SQLITE_MUTEX_FAST
  18039. ** <li> SQLITE_MUTEX_RECURSIVE
  18040. ** <li> SQLITE_MUTEX_STATIC_MASTER
  18041. ** <li> SQLITE_MUTEX_STATIC_MEM
  18042. ** <li> SQLITE_MUTEX_STATIC_OPEN
  18043. ** <li> SQLITE_MUTEX_STATIC_PRNG
  18044. ** <li> SQLITE_MUTEX_STATIC_LRU
  18045. ** <li> SQLITE_MUTEX_STATIC_PMEM
  18046. ** <li> SQLITE_MUTEX_STATIC_APP1
  18047. ** <li> SQLITE_MUTEX_STATIC_APP2
  18048. ** <li> SQLITE_MUTEX_STATIC_APP3
  18049. ** </ul>
  18050. **
  18051. ** The first two constants cause sqlite3_mutex_alloc() to create
  18052. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  18053. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  18054. ** The mutex implementation does not need to make a distinction
  18055. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  18056. ** not want to. But SQLite will only request a recursive mutex in
  18057. ** cases where it really needs one. If a faster non-recursive mutex
  18058. ** implementation is available on the host platform, the mutex subsystem
  18059. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  18060. **
  18061. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  18062. ** a pointer to a static preexisting mutex. Six static mutexes are
  18063. ** used by the current version of SQLite. Future versions of SQLite
  18064. ** may add additional static mutexes. Static mutexes are for internal
  18065. ** use by SQLite only. Applications that use SQLite mutexes should
  18066. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  18067. ** SQLITE_MUTEX_RECURSIVE.
  18068. **
  18069. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  18070. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  18071. ** returns a different mutex on every call. But for the static
  18072. ** mutex types, the same mutex is returned on every call that has
  18073. ** the same type number.
  18074. */
  18075. static sqlite3_mutex *pthreadMutexAlloc(int iType){
  18076. static sqlite3_mutex staticMutexes[] = {
  18077. SQLITE3_MUTEX_INITIALIZER,
  18078. SQLITE3_MUTEX_INITIALIZER,
  18079. SQLITE3_MUTEX_INITIALIZER,
  18080. SQLITE3_MUTEX_INITIALIZER,
  18081. SQLITE3_MUTEX_INITIALIZER,
  18082. SQLITE3_MUTEX_INITIALIZER,
  18083. SQLITE3_MUTEX_INITIALIZER,
  18084. SQLITE3_MUTEX_INITIALIZER,
  18085. SQLITE3_MUTEX_INITIALIZER
  18086. };
  18087. sqlite3_mutex *p;
  18088. switch( iType ){
  18089. case SQLITE_MUTEX_RECURSIVE: {
  18090. p = sqlite3MallocZero( sizeof(*p) );
  18091. if( p ){
  18092. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18093. /* If recursive mutexes are not available, we will have to
  18094. ** build our own. See below. */
  18095. pthread_mutex_init(&p->mutex, 0);
  18096. #else
  18097. /* Use a recursive mutex if it is available */
  18098. pthread_mutexattr_t recursiveAttr;
  18099. pthread_mutexattr_init(&recursiveAttr);
  18100. pthread_mutexattr_settype(&recursiveAttr, PTHREAD_MUTEX_RECURSIVE);
  18101. pthread_mutex_init(&p->mutex, &recursiveAttr);
  18102. pthread_mutexattr_destroy(&recursiveAttr);
  18103. #endif
  18104. #if SQLITE_MUTEX_NREF
  18105. p->id = iType;
  18106. #endif
  18107. }
  18108. break;
  18109. }
  18110. case SQLITE_MUTEX_FAST: {
  18111. p = sqlite3MallocZero( sizeof(*p) );
  18112. if( p ){
  18113. #if SQLITE_MUTEX_NREF
  18114. p->id = iType;
  18115. #endif
  18116. pthread_mutex_init(&p->mutex, 0);
  18117. }
  18118. break;
  18119. }
  18120. default: {
  18121. assert( iType-2 >= 0 );
  18122. assert( iType-2 < ArraySize(staticMutexes) );
  18123. p = &staticMutexes[iType-2];
  18124. #if SQLITE_MUTEX_NREF
  18125. p->id = iType;
  18126. #endif
  18127. break;
  18128. }
  18129. }
  18130. return p;
  18131. }
  18132. /*
  18133. ** This routine deallocates a previously
  18134. ** allocated mutex. SQLite is careful to deallocate every
  18135. ** mutex that it allocates.
  18136. */
  18137. static void pthreadMutexFree(sqlite3_mutex *p){
  18138. assert( p->nRef==0 );
  18139. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  18140. pthread_mutex_destroy(&p->mutex);
  18141. sqlite3_free(p);
  18142. }
  18143. /*
  18144. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18145. ** to enter a mutex. If another thread is already within the mutex,
  18146. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18147. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18148. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18149. ** be entered multiple times by the same thread. In such cases the,
  18150. ** mutex must be exited an equal number of times before another thread
  18151. ** can enter. If the same thread tries to enter any other kind of mutex
  18152. ** more than once, the behavior is undefined.
  18153. */
  18154. static void pthreadMutexEnter(sqlite3_mutex *p){
  18155. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  18156. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18157. /* If recursive mutexes are not available, then we have to grow
  18158. ** our own. This implementation assumes that pthread_equal()
  18159. ** is atomic - that it cannot be deceived into thinking self
  18160. ** and p->owner are equal if p->owner changes between two values
  18161. ** that are not equal to self while the comparison is taking place.
  18162. ** This implementation also assumes a coherent cache - that
  18163. ** separate processes cannot read different values from the same
  18164. ** address at the same time. If either of these two conditions
  18165. ** are not met, then the mutexes will fail and problems will result.
  18166. */
  18167. {
  18168. pthread_t self = pthread_self();
  18169. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  18170. p->nRef++;
  18171. }else{
  18172. pthread_mutex_lock(&p->mutex);
  18173. assert( p->nRef==0 );
  18174. p->owner = self;
  18175. p->nRef = 1;
  18176. }
  18177. }
  18178. #else
  18179. /* Use the built-in recursive mutexes if they are available.
  18180. */
  18181. pthread_mutex_lock(&p->mutex);
  18182. #if SQLITE_MUTEX_NREF
  18183. assert( p->nRef>0 || p->owner==0 );
  18184. p->owner = pthread_self();
  18185. p->nRef++;
  18186. #endif
  18187. #endif
  18188. #ifdef SQLITE_DEBUG
  18189. if( p->trace ){
  18190. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18191. }
  18192. #endif
  18193. }
  18194. static int pthreadMutexTry(sqlite3_mutex *p){
  18195. int rc;
  18196. assert( p->id==SQLITE_MUTEX_RECURSIVE || pthreadMutexNotheld(p) );
  18197. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18198. /* If recursive mutexes are not available, then we have to grow
  18199. ** our own. This implementation assumes that pthread_equal()
  18200. ** is atomic - that it cannot be deceived into thinking self
  18201. ** and p->owner are equal if p->owner changes between two values
  18202. ** that are not equal to self while the comparison is taking place.
  18203. ** This implementation also assumes a coherent cache - that
  18204. ** separate processes cannot read different values from the same
  18205. ** address at the same time. If either of these two conditions
  18206. ** are not met, then the mutexes will fail and problems will result.
  18207. */
  18208. {
  18209. pthread_t self = pthread_self();
  18210. if( p->nRef>0 && pthread_equal(p->owner, self) ){
  18211. p->nRef++;
  18212. rc = SQLITE_OK;
  18213. }else if( pthread_mutex_trylock(&p->mutex)==0 ){
  18214. assert( p->nRef==0 );
  18215. p->owner = self;
  18216. p->nRef = 1;
  18217. rc = SQLITE_OK;
  18218. }else{
  18219. rc = SQLITE_BUSY;
  18220. }
  18221. }
  18222. #else
  18223. /* Use the built-in recursive mutexes if they are available.
  18224. */
  18225. if( pthread_mutex_trylock(&p->mutex)==0 ){
  18226. #if SQLITE_MUTEX_NREF
  18227. p->owner = pthread_self();
  18228. p->nRef++;
  18229. #endif
  18230. rc = SQLITE_OK;
  18231. }else{
  18232. rc = SQLITE_BUSY;
  18233. }
  18234. #endif
  18235. #ifdef SQLITE_DEBUG
  18236. if( rc==SQLITE_OK && p->trace ){
  18237. printf("enter mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18238. }
  18239. #endif
  18240. return rc;
  18241. }
  18242. /*
  18243. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18244. ** previously entered by the same thread. The behavior
  18245. ** is undefined if the mutex is not currently entered or
  18246. ** is not currently allocated. SQLite will never do either.
  18247. */
  18248. static void pthreadMutexLeave(sqlite3_mutex *p){
  18249. assert( pthreadMutexHeld(p) );
  18250. #if SQLITE_MUTEX_NREF
  18251. p->nRef--;
  18252. if( p->nRef==0 ) p->owner = 0;
  18253. #endif
  18254. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  18255. #ifdef SQLITE_HOMEGROWN_RECURSIVE_MUTEX
  18256. if( p->nRef==0 ){
  18257. pthread_mutex_unlock(&p->mutex);
  18258. }
  18259. #else
  18260. pthread_mutex_unlock(&p->mutex);
  18261. #endif
  18262. #ifdef SQLITE_DEBUG
  18263. if( p->trace ){
  18264. printf("leave mutex %p (%d) with nRef=%d\n", p, p->trace, p->nRef);
  18265. }
  18266. #endif
  18267. }
  18268. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18269. static const sqlite3_mutex_methods sMutex = {
  18270. pthreadMutexInit,
  18271. pthreadMutexEnd,
  18272. pthreadMutexAlloc,
  18273. pthreadMutexFree,
  18274. pthreadMutexEnter,
  18275. pthreadMutexTry,
  18276. pthreadMutexLeave,
  18277. #ifdef SQLITE_DEBUG
  18278. pthreadMutexHeld,
  18279. pthreadMutexNotheld
  18280. #else
  18281. 0,
  18282. 0
  18283. #endif
  18284. };
  18285. return &sMutex;
  18286. }
  18287. #endif /* SQLITE_MUTEX_PTHREADS */
  18288. /************** End of mutex_unix.c ******************************************/
  18289. /************** Begin file mutex_w32.c ***************************************/
  18290. /*
  18291. ** 2007 August 14
  18292. **
  18293. ** The author disclaims copyright to this source code. In place of
  18294. ** a legal notice, here is a blessing:
  18295. **
  18296. ** May you do good and not evil.
  18297. ** May you find forgiveness for yourself and forgive others.
  18298. ** May you share freely, never taking more than you give.
  18299. **
  18300. *************************************************************************
  18301. ** This file contains the C functions that implement mutexes for Win32.
  18302. */
  18303. #if SQLITE_OS_WIN
  18304. /*
  18305. ** Include code that is common to all os_*.c files
  18306. */
  18307. /************** Include os_common.h in the middle of mutex_w32.c *************/
  18308. /************** Begin file os_common.h ***************************************/
  18309. /*
  18310. ** 2004 May 22
  18311. **
  18312. ** The author disclaims copyright to this source code. In place of
  18313. ** a legal notice, here is a blessing:
  18314. **
  18315. ** May you do good and not evil.
  18316. ** May you find forgiveness for yourself and forgive others.
  18317. ** May you share freely, never taking more than you give.
  18318. **
  18319. ******************************************************************************
  18320. **
  18321. ** This file contains macros and a little bit of code that is common to
  18322. ** all of the platform-specific files (os_*.c) and is #included into those
  18323. ** files.
  18324. **
  18325. ** This file should be #included by the os_*.c files only. It is not a
  18326. ** general purpose header file.
  18327. */
  18328. #ifndef _OS_COMMON_H_
  18329. #define _OS_COMMON_H_
  18330. /*
  18331. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  18332. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  18333. ** switch. The following code should catch this problem at compile-time.
  18334. */
  18335. #ifdef MEMORY_DEBUG
  18336. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  18337. #endif
  18338. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  18339. # ifndef SQLITE_DEBUG_OS_TRACE
  18340. # define SQLITE_DEBUG_OS_TRACE 0
  18341. # endif
  18342. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  18343. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  18344. #else
  18345. # define OSTRACE(X)
  18346. #endif
  18347. /*
  18348. ** Macros for performance tracing. Normally turned off. Only works
  18349. ** on i486 hardware.
  18350. */
  18351. #ifdef SQLITE_PERFORMANCE_TRACE
  18352. /*
  18353. ** hwtime.h contains inline assembler code for implementing
  18354. ** high-performance timing routines.
  18355. */
  18356. /************** Include hwtime.h in the middle of os_common.h ****************/
  18357. /************** Begin file hwtime.h ******************************************/
  18358. /*
  18359. ** 2008 May 27
  18360. **
  18361. ** The author disclaims copyright to this source code. In place of
  18362. ** a legal notice, here is a blessing:
  18363. **
  18364. ** May you do good and not evil.
  18365. ** May you find forgiveness for yourself and forgive others.
  18366. ** May you share freely, never taking more than you give.
  18367. **
  18368. ******************************************************************************
  18369. **
  18370. ** This file contains inline asm code for retrieving "high-performance"
  18371. ** counters for x86 class CPUs.
  18372. */
  18373. #ifndef _HWTIME_H_
  18374. #define _HWTIME_H_
  18375. /*
  18376. ** The following routine only works on pentium-class (or newer) processors.
  18377. ** It uses the RDTSC opcode to read the cycle count value out of the
  18378. ** processor and returns that value. This can be used for high-res
  18379. ** profiling.
  18380. */
  18381. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  18382. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  18383. #if defined(__GNUC__)
  18384. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18385. unsigned int lo, hi;
  18386. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  18387. return (sqlite_uint64)hi << 32 | lo;
  18388. }
  18389. #elif defined(_MSC_VER)
  18390. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  18391. __asm {
  18392. rdtsc
  18393. ret ; return value at EDX:EAX
  18394. }
  18395. }
  18396. #endif
  18397. #elif (defined(__GNUC__) && defined(__x86_64__))
  18398. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18399. unsigned long val;
  18400. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  18401. return val;
  18402. }
  18403. #elif (defined(__GNUC__) && defined(__ppc__))
  18404. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  18405. unsigned long long retval;
  18406. unsigned long junk;
  18407. __asm__ __volatile__ ("\n\
  18408. 1: mftbu %1\n\
  18409. mftb %L0\n\
  18410. mftbu %0\n\
  18411. cmpw %0,%1\n\
  18412. bne 1b"
  18413. : "=r" (retval), "=r" (junk));
  18414. return retval;
  18415. }
  18416. #else
  18417. #error Need implementation of sqlite3Hwtime() for your platform.
  18418. /*
  18419. ** To compile without implementing sqlite3Hwtime() for your platform,
  18420. ** you can remove the above #error and use the following
  18421. ** stub function. You will lose timing support for many
  18422. ** of the debugging and testing utilities, but it should at
  18423. ** least compile and run.
  18424. */
  18425. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  18426. #endif
  18427. #endif /* !defined(_HWTIME_H_) */
  18428. /************** End of hwtime.h **********************************************/
  18429. /************** Continuing where we left off in os_common.h ******************/
  18430. static sqlite_uint64 g_start;
  18431. static sqlite_uint64 g_elapsed;
  18432. #define TIMER_START g_start=sqlite3Hwtime()
  18433. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  18434. #define TIMER_ELAPSED g_elapsed
  18435. #else
  18436. #define TIMER_START
  18437. #define TIMER_END
  18438. #define TIMER_ELAPSED ((sqlite_uint64)0)
  18439. #endif
  18440. /*
  18441. ** If we compile with the SQLITE_TEST macro set, then the following block
  18442. ** of code will give us the ability to simulate a disk I/O error. This
  18443. ** is used for testing the I/O recovery logic.
  18444. */
  18445. #ifdef SQLITE_TEST
  18446. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  18447. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  18448. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  18449. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  18450. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  18451. SQLITE_API int sqlite3_diskfull_pending = 0;
  18452. SQLITE_API int sqlite3_diskfull = 0;
  18453. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  18454. #define SimulateIOError(CODE) \
  18455. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  18456. || sqlite3_io_error_pending-- == 1 ) \
  18457. { local_ioerr(); CODE; }
  18458. static void local_ioerr(){
  18459. IOTRACE(("IOERR\n"));
  18460. sqlite3_io_error_hit++;
  18461. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  18462. }
  18463. #define SimulateDiskfullError(CODE) \
  18464. if( sqlite3_diskfull_pending ){ \
  18465. if( sqlite3_diskfull_pending == 1 ){ \
  18466. local_ioerr(); \
  18467. sqlite3_diskfull = 1; \
  18468. sqlite3_io_error_hit = 1; \
  18469. CODE; \
  18470. }else{ \
  18471. sqlite3_diskfull_pending--; \
  18472. } \
  18473. }
  18474. #else
  18475. #define SimulateIOErrorBenign(X)
  18476. #define SimulateIOError(A)
  18477. #define SimulateDiskfullError(A)
  18478. #endif
  18479. /*
  18480. ** When testing, keep a count of the number of open files.
  18481. */
  18482. #ifdef SQLITE_TEST
  18483. SQLITE_API int sqlite3_open_file_count = 0;
  18484. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  18485. #else
  18486. #define OpenCounter(X)
  18487. #endif
  18488. #endif /* !defined(_OS_COMMON_H_) */
  18489. /************** End of os_common.h *******************************************/
  18490. /************** Continuing where we left off in mutex_w32.c ******************/
  18491. /*
  18492. ** Include the header file for the Windows VFS.
  18493. */
  18494. /************** Include os_win.h in the middle of mutex_w32.c ****************/
  18495. /************** Begin file os_win.h ******************************************/
  18496. /*
  18497. ** 2013 November 25
  18498. **
  18499. ** The author disclaims copyright to this source code. In place of
  18500. ** a legal notice, here is a blessing:
  18501. **
  18502. ** May you do good and not evil.
  18503. ** May you find forgiveness for yourself and forgive others.
  18504. ** May you share freely, never taking more than you give.
  18505. **
  18506. ******************************************************************************
  18507. **
  18508. ** This file contains code that is specific to Windows.
  18509. */
  18510. #ifndef _OS_WIN_H_
  18511. #define _OS_WIN_H_
  18512. /*
  18513. ** Include the primary Windows SDK header file.
  18514. */
  18515. #include "windows.h"
  18516. #ifdef __CYGWIN__
  18517. # include <sys/cygwin.h>
  18518. # include <errno.h> /* amalgamator: dontcache */
  18519. #endif
  18520. /*
  18521. ** Determine if we are dealing with Windows NT.
  18522. **
  18523. ** We ought to be able to determine if we are compiling for Windows 9x or
  18524. ** Windows NT using the _WIN32_WINNT macro as follows:
  18525. **
  18526. ** #if defined(_WIN32_WINNT)
  18527. ** # define SQLITE_OS_WINNT 1
  18528. ** #else
  18529. ** # define SQLITE_OS_WINNT 0
  18530. ** #endif
  18531. **
  18532. ** However, Visual Studio 2005 does not set _WIN32_WINNT by default, as
  18533. ** it ought to, so the above test does not work. We'll just assume that
  18534. ** everything is Windows NT unless the programmer explicitly says otherwise
  18535. ** by setting SQLITE_OS_WINNT to 0.
  18536. */
  18537. #if SQLITE_OS_WIN && !defined(SQLITE_OS_WINNT)
  18538. # define SQLITE_OS_WINNT 1
  18539. #endif
  18540. /*
  18541. ** Determine if we are dealing with Windows CE - which has a much reduced
  18542. ** API.
  18543. */
  18544. #if defined(_WIN32_WCE)
  18545. # define SQLITE_OS_WINCE 1
  18546. #else
  18547. # define SQLITE_OS_WINCE 0
  18548. #endif
  18549. /*
  18550. ** Determine if we are dealing with WinRT, which provides only a subset of
  18551. ** the full Win32 API.
  18552. */
  18553. #if !defined(SQLITE_OS_WINRT)
  18554. # define SQLITE_OS_WINRT 0
  18555. #endif
  18556. /*
  18557. ** For WinCE, some API function parameters do not appear to be declared as
  18558. ** volatile.
  18559. */
  18560. #if SQLITE_OS_WINCE
  18561. # define SQLITE_WIN32_VOLATILE
  18562. #else
  18563. # define SQLITE_WIN32_VOLATILE volatile
  18564. #endif
  18565. #endif /* _OS_WIN_H_ */
  18566. /************** End of os_win.h **********************************************/
  18567. /************** Continuing where we left off in mutex_w32.c ******************/
  18568. #endif
  18569. /*
  18570. ** The code in this file is only used if we are compiling multithreaded
  18571. ** on a Win32 system.
  18572. */
  18573. #ifdef SQLITE_MUTEX_W32
  18574. /*
  18575. ** Each recursive mutex is an instance of the following structure.
  18576. */
  18577. struct sqlite3_mutex {
  18578. CRITICAL_SECTION mutex; /* Mutex controlling the lock */
  18579. int id; /* Mutex type */
  18580. #ifdef SQLITE_DEBUG
  18581. volatile int nRef; /* Number of enterances */
  18582. volatile DWORD owner; /* Thread holding this mutex */
  18583. volatile int trace; /* True to trace changes */
  18584. #endif
  18585. };
  18586. /*
  18587. ** These are the initializer values used when declaring a "static" mutex
  18588. ** on Win32. It should be noted that all mutexes require initialization
  18589. ** on the Win32 platform.
  18590. */
  18591. #define SQLITE_W32_MUTEX_INITIALIZER { 0 }
  18592. #ifdef SQLITE_DEBUG
  18593. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0, \
  18594. 0L, (DWORD)0, 0 }
  18595. #else
  18596. #define SQLITE3_MUTEX_INITIALIZER { SQLITE_W32_MUTEX_INITIALIZER, 0 }
  18597. #endif
  18598. #ifdef SQLITE_DEBUG
  18599. /*
  18600. ** The sqlite3_mutex_held() and sqlite3_mutex_notheld() routine are
  18601. ** intended for use only inside assert() statements.
  18602. */
  18603. static int winMutexHeld(sqlite3_mutex *p){
  18604. return p->nRef!=0 && p->owner==GetCurrentThreadId();
  18605. }
  18606. static int winMutexNotheld2(sqlite3_mutex *p, DWORD tid){
  18607. return p->nRef==0 || p->owner!=tid;
  18608. }
  18609. static int winMutexNotheld(sqlite3_mutex *p){
  18610. DWORD tid = GetCurrentThreadId();
  18611. return winMutexNotheld2(p, tid);
  18612. }
  18613. #endif
  18614. /*
  18615. ** Initialize and deinitialize the mutex subsystem.
  18616. */
  18617. static sqlite3_mutex winMutex_staticMutexes[] = {
  18618. SQLITE3_MUTEX_INITIALIZER,
  18619. SQLITE3_MUTEX_INITIALIZER,
  18620. SQLITE3_MUTEX_INITIALIZER,
  18621. SQLITE3_MUTEX_INITIALIZER,
  18622. SQLITE3_MUTEX_INITIALIZER,
  18623. SQLITE3_MUTEX_INITIALIZER,
  18624. SQLITE3_MUTEX_INITIALIZER,
  18625. SQLITE3_MUTEX_INITIALIZER,
  18626. SQLITE3_MUTEX_INITIALIZER
  18627. };
  18628. static int winMutex_isInit = 0;
  18629. static int winMutex_isNt = -1; /* <0 means "need to query" */
  18630. /* As the winMutexInit() and winMutexEnd() functions are called as part
  18631. ** of the sqlite3_initialize() and sqlite3_shutdown() processing, the
  18632. ** "interlocked" magic used here is probably not strictly necessary.
  18633. */
  18634. static LONG SQLITE_WIN32_VOLATILE winMutex_lock = 0;
  18635. SQLITE_API int sqlite3_win32_is_nt(void); /* os_win.c */
  18636. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds); /* os_win.c */
  18637. static int winMutexInit(void){
  18638. /* The first to increment to 1 does actual initialization */
  18639. if( InterlockedCompareExchange(&winMutex_lock, 1, 0)==0 ){
  18640. int i;
  18641. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  18642. #if SQLITE_OS_WINRT
  18643. InitializeCriticalSectionEx(&winMutex_staticMutexes[i].mutex, 0, 0);
  18644. #else
  18645. InitializeCriticalSection(&winMutex_staticMutexes[i].mutex);
  18646. #endif
  18647. }
  18648. winMutex_isInit = 1;
  18649. }else{
  18650. /* Another thread is (in the process of) initializing the static
  18651. ** mutexes */
  18652. while( !winMutex_isInit ){
  18653. sqlite3_win32_sleep(1);
  18654. }
  18655. }
  18656. return SQLITE_OK;
  18657. }
  18658. static int winMutexEnd(void){
  18659. /* The first to decrement to 0 does actual shutdown
  18660. ** (which should be the last to shutdown.) */
  18661. if( InterlockedCompareExchange(&winMutex_lock, 0, 1)==1 ){
  18662. if( winMutex_isInit==1 ){
  18663. int i;
  18664. for(i=0; i<ArraySize(winMutex_staticMutexes); i++){
  18665. DeleteCriticalSection(&winMutex_staticMutexes[i].mutex);
  18666. }
  18667. winMutex_isInit = 0;
  18668. }
  18669. }
  18670. return SQLITE_OK;
  18671. }
  18672. /*
  18673. ** The sqlite3_mutex_alloc() routine allocates a new
  18674. ** mutex and returns a pointer to it. If it returns NULL
  18675. ** that means that a mutex could not be allocated. SQLite
  18676. ** will unwind its stack and return an error. The argument
  18677. ** to sqlite3_mutex_alloc() is one of these integer constants:
  18678. **
  18679. ** <ul>
  18680. ** <li> SQLITE_MUTEX_FAST
  18681. ** <li> SQLITE_MUTEX_RECURSIVE
  18682. ** <li> SQLITE_MUTEX_STATIC_MASTER
  18683. ** <li> SQLITE_MUTEX_STATIC_MEM
  18684. ** <li> SQLITE_MUTEX_STATIC_OPEN
  18685. ** <li> SQLITE_MUTEX_STATIC_PRNG
  18686. ** <li> SQLITE_MUTEX_STATIC_LRU
  18687. ** <li> SQLITE_MUTEX_STATIC_PMEM
  18688. ** <li> SQLITE_MUTEX_STATIC_APP1
  18689. ** <li> SQLITE_MUTEX_STATIC_APP2
  18690. ** <li> SQLITE_MUTEX_STATIC_APP3
  18691. ** </ul>
  18692. **
  18693. ** The first two constants cause sqlite3_mutex_alloc() to create
  18694. ** a new mutex. The new mutex is recursive when SQLITE_MUTEX_RECURSIVE
  18695. ** is used but not necessarily so when SQLITE_MUTEX_FAST is used.
  18696. ** The mutex implementation does not need to make a distinction
  18697. ** between SQLITE_MUTEX_RECURSIVE and SQLITE_MUTEX_FAST if it does
  18698. ** not want to. But SQLite will only request a recursive mutex in
  18699. ** cases where it really needs one. If a faster non-recursive mutex
  18700. ** implementation is available on the host platform, the mutex subsystem
  18701. ** might return such a mutex in response to SQLITE_MUTEX_FAST.
  18702. **
  18703. ** The other allowed parameters to sqlite3_mutex_alloc() each return
  18704. ** a pointer to a static preexisting mutex. Six static mutexes are
  18705. ** used by the current version of SQLite. Future versions of SQLite
  18706. ** may add additional static mutexes. Static mutexes are for internal
  18707. ** use by SQLite only. Applications that use SQLite mutexes should
  18708. ** use only the dynamic mutexes returned by SQLITE_MUTEX_FAST or
  18709. ** SQLITE_MUTEX_RECURSIVE.
  18710. **
  18711. ** Note that if one of the dynamic mutex parameters (SQLITE_MUTEX_FAST
  18712. ** or SQLITE_MUTEX_RECURSIVE) is used then sqlite3_mutex_alloc()
  18713. ** returns a different mutex on every call. But for the static
  18714. ** mutex types, the same mutex is returned on every call that has
  18715. ** the same type number.
  18716. */
  18717. static sqlite3_mutex *winMutexAlloc(int iType){
  18718. sqlite3_mutex *p;
  18719. switch( iType ){
  18720. case SQLITE_MUTEX_FAST:
  18721. case SQLITE_MUTEX_RECURSIVE: {
  18722. p = sqlite3MallocZero( sizeof(*p) );
  18723. if( p ){
  18724. #ifdef SQLITE_DEBUG
  18725. p->id = iType;
  18726. #ifdef SQLITE_WIN32_MUTEX_TRACE_DYNAMIC
  18727. p->trace = 1;
  18728. #endif
  18729. #endif
  18730. #if SQLITE_OS_WINRT
  18731. InitializeCriticalSectionEx(&p->mutex, 0, 0);
  18732. #else
  18733. InitializeCriticalSection(&p->mutex);
  18734. #endif
  18735. }
  18736. break;
  18737. }
  18738. default: {
  18739. assert( iType-2 >= 0 );
  18740. assert( iType-2 < ArraySize(winMutex_staticMutexes) );
  18741. assert( winMutex_isInit==1 );
  18742. p = &winMutex_staticMutexes[iType-2];
  18743. #ifdef SQLITE_DEBUG
  18744. p->id = iType;
  18745. #ifdef SQLITE_WIN32_MUTEX_TRACE_STATIC
  18746. p->trace = 1;
  18747. #endif
  18748. #endif
  18749. break;
  18750. }
  18751. }
  18752. return p;
  18753. }
  18754. /*
  18755. ** This routine deallocates a previously
  18756. ** allocated mutex. SQLite is careful to deallocate every
  18757. ** mutex that it allocates.
  18758. */
  18759. static void winMutexFree(sqlite3_mutex *p){
  18760. assert( p );
  18761. #ifdef SQLITE_DEBUG
  18762. assert( p->nRef==0 && p->owner==0 );
  18763. assert( p->id==SQLITE_MUTEX_FAST || p->id==SQLITE_MUTEX_RECURSIVE );
  18764. #endif
  18765. assert( winMutex_isInit==1 );
  18766. DeleteCriticalSection(&p->mutex);
  18767. sqlite3_free(p);
  18768. }
  18769. /*
  18770. ** The sqlite3_mutex_enter() and sqlite3_mutex_try() routines attempt
  18771. ** to enter a mutex. If another thread is already within the mutex,
  18772. ** sqlite3_mutex_enter() will block and sqlite3_mutex_try() will return
  18773. ** SQLITE_BUSY. The sqlite3_mutex_try() interface returns SQLITE_OK
  18774. ** upon successful entry. Mutexes created using SQLITE_MUTEX_RECURSIVE can
  18775. ** be entered multiple times by the same thread. In such cases the,
  18776. ** mutex must be exited an equal number of times before another thread
  18777. ** can enter. If the same thread tries to enter any other kind of mutex
  18778. ** more than once, the behavior is undefined.
  18779. */
  18780. static void winMutexEnter(sqlite3_mutex *p){
  18781. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  18782. DWORD tid = GetCurrentThreadId();
  18783. #endif
  18784. #ifdef SQLITE_DEBUG
  18785. assert( p );
  18786. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  18787. #else
  18788. assert( p );
  18789. #endif
  18790. assert( winMutex_isInit==1 );
  18791. EnterCriticalSection(&p->mutex);
  18792. #ifdef SQLITE_DEBUG
  18793. assert( p->nRef>0 || p->owner==0 );
  18794. p->owner = tid;
  18795. p->nRef++;
  18796. if( p->trace ){
  18797. OSTRACE(("ENTER-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  18798. tid, p, p->trace, p->nRef));
  18799. }
  18800. #endif
  18801. }
  18802. static int winMutexTry(sqlite3_mutex *p){
  18803. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  18804. DWORD tid = GetCurrentThreadId();
  18805. #endif
  18806. int rc = SQLITE_BUSY;
  18807. assert( p );
  18808. assert( p->id==SQLITE_MUTEX_RECURSIVE || winMutexNotheld2(p, tid) );
  18809. /*
  18810. ** The sqlite3_mutex_try() routine is very rarely used, and when it
  18811. ** is used it is merely an optimization. So it is OK for it to always
  18812. ** fail.
  18813. **
  18814. ** The TryEnterCriticalSection() interface is only available on WinNT.
  18815. ** And some windows compilers complain if you try to use it without
  18816. ** first doing some #defines that prevent SQLite from building on Win98.
  18817. ** For that reason, we will omit this optimization for now. See
  18818. ** ticket #2685.
  18819. */
  18820. #if defined(_WIN32_WINNT) && _WIN32_WINNT >= 0x0400
  18821. assert( winMutex_isInit==1 );
  18822. assert( winMutex_isNt>=-1 && winMutex_isNt<=1 );
  18823. if( winMutex_isNt<0 ){
  18824. winMutex_isNt = sqlite3_win32_is_nt();
  18825. }
  18826. assert( winMutex_isNt==0 || winMutex_isNt==1 );
  18827. if( winMutex_isNt && TryEnterCriticalSection(&p->mutex) ){
  18828. #ifdef SQLITE_DEBUG
  18829. p->owner = tid;
  18830. p->nRef++;
  18831. #endif
  18832. rc = SQLITE_OK;
  18833. }
  18834. #else
  18835. UNUSED_PARAMETER(p);
  18836. #endif
  18837. #ifdef SQLITE_DEBUG
  18838. if( p->trace ){
  18839. OSTRACE(("TRY-MUTEX tid=%lu, mutex=%p (%d), owner=%lu, nRef=%d, rc=%s\n",
  18840. tid, p, p->trace, p->owner, p->nRef, sqlite3ErrName(rc)));
  18841. }
  18842. #endif
  18843. return rc;
  18844. }
  18845. /*
  18846. ** The sqlite3_mutex_leave() routine exits a mutex that was
  18847. ** previously entered by the same thread. The behavior
  18848. ** is undefined if the mutex is not currently entered or
  18849. ** is not currently allocated. SQLite will never do either.
  18850. */
  18851. static void winMutexLeave(sqlite3_mutex *p){
  18852. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  18853. DWORD tid = GetCurrentThreadId();
  18854. #endif
  18855. assert( p );
  18856. #ifdef SQLITE_DEBUG
  18857. assert( p->nRef>0 );
  18858. assert( p->owner==tid );
  18859. p->nRef--;
  18860. if( p->nRef==0 ) p->owner = 0;
  18861. assert( p->nRef==0 || p->id==SQLITE_MUTEX_RECURSIVE );
  18862. #endif
  18863. assert( winMutex_isInit==1 );
  18864. LeaveCriticalSection(&p->mutex);
  18865. #ifdef SQLITE_DEBUG
  18866. if( p->trace ){
  18867. OSTRACE(("LEAVE-MUTEX tid=%lu, mutex=%p (%d), nRef=%d\n",
  18868. tid, p, p->trace, p->nRef));
  18869. }
  18870. #endif
  18871. }
  18872. SQLITE_PRIVATE sqlite3_mutex_methods const *sqlite3DefaultMutex(void){
  18873. static const sqlite3_mutex_methods sMutex = {
  18874. winMutexInit,
  18875. winMutexEnd,
  18876. winMutexAlloc,
  18877. winMutexFree,
  18878. winMutexEnter,
  18879. winMutexTry,
  18880. winMutexLeave,
  18881. #ifdef SQLITE_DEBUG
  18882. winMutexHeld,
  18883. winMutexNotheld
  18884. #else
  18885. 0,
  18886. 0
  18887. #endif
  18888. };
  18889. return &sMutex;
  18890. }
  18891. #endif /* SQLITE_MUTEX_W32 */
  18892. /************** End of mutex_w32.c *******************************************/
  18893. /************** Begin file malloc.c ******************************************/
  18894. /*
  18895. ** 2001 September 15
  18896. **
  18897. ** The author disclaims copyright to this source code. In place of
  18898. ** a legal notice, here is a blessing:
  18899. **
  18900. ** May you do good and not evil.
  18901. ** May you find forgiveness for yourself and forgive others.
  18902. ** May you share freely, never taking more than you give.
  18903. **
  18904. *************************************************************************
  18905. **
  18906. ** Memory allocation functions used throughout sqlite.
  18907. */
  18908. /* #include <stdarg.h> */
  18909. /*
  18910. ** Attempt to release up to n bytes of non-essential memory currently
  18911. ** held by SQLite. An example of non-essential memory is memory used to
  18912. ** cache database pages that are not currently in use.
  18913. */
  18914. SQLITE_API int sqlite3_release_memory(int n){
  18915. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  18916. return sqlite3PcacheReleaseMemory(n);
  18917. #else
  18918. /* IMPLEMENTATION-OF: R-34391-24921 The sqlite3_release_memory() routine
  18919. ** is a no-op returning zero if SQLite is not compiled with
  18920. ** SQLITE_ENABLE_MEMORY_MANAGEMENT. */
  18921. UNUSED_PARAMETER(n);
  18922. return 0;
  18923. #endif
  18924. }
  18925. /*
  18926. ** An instance of the following object records the location of
  18927. ** each unused scratch buffer.
  18928. */
  18929. typedef struct ScratchFreeslot {
  18930. struct ScratchFreeslot *pNext; /* Next unused scratch buffer */
  18931. } ScratchFreeslot;
  18932. /*
  18933. ** State information local to the memory allocation subsystem.
  18934. */
  18935. static SQLITE_WSD struct Mem0Global {
  18936. sqlite3_mutex *mutex; /* Mutex to serialize access */
  18937. /*
  18938. ** The alarm callback and its arguments. The mem0.mutex lock will
  18939. ** be held while the callback is running. Recursive calls into
  18940. ** the memory subsystem are allowed, but no new callbacks will be
  18941. ** issued.
  18942. */
  18943. sqlite3_int64 alarmThreshold;
  18944. void (*alarmCallback)(void*, sqlite3_int64,int);
  18945. void *alarmArg;
  18946. /*
  18947. ** Pointers to the end of sqlite3GlobalConfig.pScratch memory
  18948. ** (so that a range test can be used to determine if an allocation
  18949. ** being freed came from pScratch) and a pointer to the list of
  18950. ** unused scratch allocations.
  18951. */
  18952. void *pScratchEnd;
  18953. ScratchFreeslot *pScratchFree;
  18954. u32 nScratchFree;
  18955. /*
  18956. ** True if heap is nearly "full" where "full" is defined by the
  18957. ** sqlite3_soft_heap_limit() setting.
  18958. */
  18959. int nearlyFull;
  18960. } mem0 = { 0, 0, 0, 0, 0, 0, 0, 0 };
  18961. #define mem0 GLOBAL(struct Mem0Global, mem0)
  18962. /*
  18963. ** This routine runs when the memory allocator sees that the
  18964. ** total memory allocation is about to exceed the soft heap
  18965. ** limit.
  18966. */
  18967. static void softHeapLimitEnforcer(
  18968. void *NotUsed,
  18969. sqlite3_int64 NotUsed2,
  18970. int allocSize
  18971. ){
  18972. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  18973. sqlite3_release_memory(allocSize);
  18974. }
  18975. /*
  18976. ** Change the alarm callback
  18977. */
  18978. static int sqlite3MemoryAlarm(
  18979. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  18980. void *pArg,
  18981. sqlite3_int64 iThreshold
  18982. ){
  18983. int nUsed;
  18984. sqlite3_mutex_enter(mem0.mutex);
  18985. mem0.alarmCallback = xCallback;
  18986. mem0.alarmArg = pArg;
  18987. mem0.alarmThreshold = iThreshold;
  18988. nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  18989. mem0.nearlyFull = (iThreshold>0 && iThreshold<=nUsed);
  18990. sqlite3_mutex_leave(mem0.mutex);
  18991. return SQLITE_OK;
  18992. }
  18993. #ifndef SQLITE_OMIT_DEPRECATED
  18994. /*
  18995. ** Deprecated external interface. Internal/core SQLite code
  18996. ** should call sqlite3MemoryAlarm.
  18997. */
  18998. SQLITE_API int sqlite3_memory_alarm(
  18999. void(*xCallback)(void *pArg, sqlite3_int64 used,int N),
  19000. void *pArg,
  19001. sqlite3_int64 iThreshold
  19002. ){
  19003. return sqlite3MemoryAlarm(xCallback, pArg, iThreshold);
  19004. }
  19005. #endif
  19006. /*
  19007. ** Set the soft heap-size limit for the library. Passing a zero or
  19008. ** negative value indicates no limit.
  19009. */
  19010. SQLITE_API sqlite3_int64 sqlite3_soft_heap_limit64(sqlite3_int64 n){
  19011. sqlite3_int64 priorLimit;
  19012. sqlite3_int64 excess;
  19013. #ifndef SQLITE_OMIT_AUTOINIT
  19014. int rc = sqlite3_initialize();
  19015. if( rc ) return -1;
  19016. #endif
  19017. sqlite3_mutex_enter(mem0.mutex);
  19018. priorLimit = mem0.alarmThreshold;
  19019. sqlite3_mutex_leave(mem0.mutex);
  19020. if( n<0 ) return priorLimit;
  19021. if( n>0 ){
  19022. sqlite3MemoryAlarm(softHeapLimitEnforcer, 0, n);
  19023. }else{
  19024. sqlite3MemoryAlarm(0, 0, 0);
  19025. }
  19026. excess = sqlite3_memory_used() - n;
  19027. if( excess>0 ) sqlite3_release_memory((int)(excess & 0x7fffffff));
  19028. return priorLimit;
  19029. }
  19030. SQLITE_API void sqlite3_soft_heap_limit(int n){
  19031. if( n<0 ) n = 0;
  19032. sqlite3_soft_heap_limit64(n);
  19033. }
  19034. /*
  19035. ** Initialize the memory allocation subsystem.
  19036. */
  19037. SQLITE_PRIVATE int sqlite3MallocInit(void){
  19038. if( sqlite3GlobalConfig.m.xMalloc==0 ){
  19039. sqlite3MemSetDefault();
  19040. }
  19041. memset(&mem0, 0, sizeof(mem0));
  19042. if( sqlite3GlobalConfig.bCoreMutex ){
  19043. mem0.mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM);
  19044. }
  19045. if( sqlite3GlobalConfig.pScratch && sqlite3GlobalConfig.szScratch>=100
  19046. && sqlite3GlobalConfig.nScratch>0 ){
  19047. int i, n, sz;
  19048. ScratchFreeslot *pSlot;
  19049. sz = ROUNDDOWN8(sqlite3GlobalConfig.szScratch);
  19050. sqlite3GlobalConfig.szScratch = sz;
  19051. pSlot = (ScratchFreeslot*)sqlite3GlobalConfig.pScratch;
  19052. n = sqlite3GlobalConfig.nScratch;
  19053. mem0.pScratchFree = pSlot;
  19054. mem0.nScratchFree = n;
  19055. for(i=0; i<n-1; i++){
  19056. pSlot->pNext = (ScratchFreeslot*)(sz+(char*)pSlot);
  19057. pSlot = pSlot->pNext;
  19058. }
  19059. pSlot->pNext = 0;
  19060. mem0.pScratchEnd = (void*)&pSlot[1];
  19061. }else{
  19062. mem0.pScratchEnd = 0;
  19063. sqlite3GlobalConfig.pScratch = 0;
  19064. sqlite3GlobalConfig.szScratch = 0;
  19065. sqlite3GlobalConfig.nScratch = 0;
  19066. }
  19067. if( sqlite3GlobalConfig.pPage==0 || sqlite3GlobalConfig.szPage<512
  19068. || sqlite3GlobalConfig.nPage<1 ){
  19069. sqlite3GlobalConfig.pPage = 0;
  19070. sqlite3GlobalConfig.szPage = 0;
  19071. sqlite3GlobalConfig.nPage = 0;
  19072. }
  19073. return sqlite3GlobalConfig.m.xInit(sqlite3GlobalConfig.m.pAppData);
  19074. }
  19075. /*
  19076. ** Return true if the heap is currently under memory pressure - in other
  19077. ** words if the amount of heap used is close to the limit set by
  19078. ** sqlite3_soft_heap_limit().
  19079. */
  19080. SQLITE_PRIVATE int sqlite3HeapNearlyFull(void){
  19081. return mem0.nearlyFull;
  19082. }
  19083. /*
  19084. ** Deinitialize the memory allocation subsystem.
  19085. */
  19086. SQLITE_PRIVATE void sqlite3MallocEnd(void){
  19087. if( sqlite3GlobalConfig.m.xShutdown ){
  19088. sqlite3GlobalConfig.m.xShutdown(sqlite3GlobalConfig.m.pAppData);
  19089. }
  19090. memset(&mem0, 0, sizeof(mem0));
  19091. }
  19092. /*
  19093. ** Return the amount of memory currently checked out.
  19094. */
  19095. SQLITE_API sqlite3_int64 sqlite3_memory_used(void){
  19096. int n, mx;
  19097. sqlite3_int64 res;
  19098. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, 0);
  19099. res = (sqlite3_int64)n; /* Work around bug in Borland C. Ticket #3216 */
  19100. return res;
  19101. }
  19102. /*
  19103. ** Return the maximum amount of memory that has ever been
  19104. ** checked out since either the beginning of this process
  19105. ** or since the most recent reset.
  19106. */
  19107. SQLITE_API sqlite3_int64 sqlite3_memory_highwater(int resetFlag){
  19108. int n, mx;
  19109. sqlite3_int64 res;
  19110. sqlite3_status(SQLITE_STATUS_MEMORY_USED, &n, &mx, resetFlag);
  19111. res = (sqlite3_int64)mx; /* Work around bug in Borland C. Ticket #3216 */
  19112. return res;
  19113. }
  19114. /*
  19115. ** Trigger the alarm
  19116. */
  19117. static void sqlite3MallocAlarm(int nByte){
  19118. void (*xCallback)(void*,sqlite3_int64,int);
  19119. sqlite3_int64 nowUsed;
  19120. void *pArg;
  19121. if( mem0.alarmCallback==0 ) return;
  19122. xCallback = mem0.alarmCallback;
  19123. nowUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19124. pArg = mem0.alarmArg;
  19125. mem0.alarmCallback = 0;
  19126. sqlite3_mutex_leave(mem0.mutex);
  19127. xCallback(pArg, nowUsed, nByte);
  19128. sqlite3_mutex_enter(mem0.mutex);
  19129. mem0.alarmCallback = xCallback;
  19130. mem0.alarmArg = pArg;
  19131. }
  19132. /*
  19133. ** Do a memory allocation with statistics and alarms. Assume the
  19134. ** lock is already held.
  19135. */
  19136. static int mallocWithAlarm(int n, void **pp){
  19137. int nFull;
  19138. void *p;
  19139. assert( sqlite3_mutex_held(mem0.mutex) );
  19140. nFull = sqlite3GlobalConfig.m.xRoundup(n);
  19141. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, n);
  19142. if( mem0.alarmCallback!=0 ){
  19143. int nUsed = sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED);
  19144. if( nUsed >= mem0.alarmThreshold - nFull ){
  19145. mem0.nearlyFull = 1;
  19146. sqlite3MallocAlarm(nFull);
  19147. }else{
  19148. mem0.nearlyFull = 0;
  19149. }
  19150. }
  19151. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  19152. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  19153. if( p==0 && mem0.alarmCallback ){
  19154. sqlite3MallocAlarm(nFull);
  19155. p = sqlite3GlobalConfig.m.xMalloc(nFull);
  19156. }
  19157. #endif
  19158. if( p ){
  19159. nFull = sqlite3MallocSize(p);
  19160. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nFull);
  19161. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, 1);
  19162. }
  19163. *pp = p;
  19164. return nFull;
  19165. }
  19166. /*
  19167. ** Allocate memory. This routine is like sqlite3_malloc() except that it
  19168. ** assumes the memory subsystem has already been initialized.
  19169. */
  19170. SQLITE_PRIVATE void *sqlite3Malloc(u64 n){
  19171. void *p;
  19172. if( n==0 || n>=0x7fffff00 ){
  19173. /* A memory allocation of a number of bytes which is near the maximum
  19174. ** signed integer value might cause an integer overflow inside of the
  19175. ** xMalloc(). Hence we limit the maximum size to 0x7fffff00, giving
  19176. ** 255 bytes of overhead. SQLite itself will never use anything near
  19177. ** this amount. The only way to reach the limit is with sqlite3_malloc() */
  19178. p = 0;
  19179. }else if( sqlite3GlobalConfig.bMemstat ){
  19180. sqlite3_mutex_enter(mem0.mutex);
  19181. mallocWithAlarm((int)n, &p);
  19182. sqlite3_mutex_leave(mem0.mutex);
  19183. }else{
  19184. p = sqlite3GlobalConfig.m.xMalloc((int)n);
  19185. }
  19186. assert( EIGHT_BYTE_ALIGNMENT(p) ); /* IMP: R-11148-40995 */
  19187. return p;
  19188. }
  19189. /*
  19190. ** This version of the memory allocation is for use by the application.
  19191. ** First make sure the memory subsystem is initialized, then do the
  19192. ** allocation.
  19193. */
  19194. SQLITE_API void *sqlite3_malloc(int n){
  19195. #ifndef SQLITE_OMIT_AUTOINIT
  19196. if( sqlite3_initialize() ) return 0;
  19197. #endif
  19198. return n<=0 ? 0 : sqlite3Malloc(n);
  19199. }
  19200. SQLITE_API void *sqlite3_malloc64(sqlite3_uint64 n){
  19201. #ifndef SQLITE_OMIT_AUTOINIT
  19202. if( sqlite3_initialize() ) return 0;
  19203. #endif
  19204. return sqlite3Malloc(n);
  19205. }
  19206. /*
  19207. ** Each thread may only have a single outstanding allocation from
  19208. ** xScratchMalloc(). We verify this constraint in the single-threaded
  19209. ** case by setting scratchAllocOut to 1 when an allocation
  19210. ** is outstanding clearing it when the allocation is freed.
  19211. */
  19212. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19213. static int scratchAllocOut = 0;
  19214. #endif
  19215. /*
  19216. ** Allocate memory that is to be used and released right away.
  19217. ** This routine is similar to alloca() in that it is not intended
  19218. ** for situations where the memory might be held long-term. This
  19219. ** routine is intended to get memory to old large transient data
  19220. ** structures that would not normally fit on the stack of an
  19221. ** embedded processor.
  19222. */
  19223. SQLITE_PRIVATE void *sqlite3ScratchMalloc(int n){
  19224. void *p;
  19225. assert( n>0 );
  19226. sqlite3_mutex_enter(mem0.mutex);
  19227. sqlite3StatusSet(SQLITE_STATUS_SCRATCH_SIZE, n);
  19228. if( mem0.nScratchFree && sqlite3GlobalConfig.szScratch>=n ){
  19229. p = mem0.pScratchFree;
  19230. mem0.pScratchFree = mem0.pScratchFree->pNext;
  19231. mem0.nScratchFree--;
  19232. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, 1);
  19233. sqlite3_mutex_leave(mem0.mutex);
  19234. }else{
  19235. sqlite3_mutex_leave(mem0.mutex);
  19236. p = sqlite3Malloc(n);
  19237. if( sqlite3GlobalConfig.bMemstat && p ){
  19238. sqlite3_mutex_enter(mem0.mutex);
  19239. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, sqlite3MallocSize(p));
  19240. sqlite3_mutex_leave(mem0.mutex);
  19241. }
  19242. sqlite3MemdebugSetType(p, MEMTYPE_SCRATCH);
  19243. }
  19244. assert( sqlite3_mutex_notheld(mem0.mutex) );
  19245. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19246. /* Verify that no more than two scratch allocations per thread
  19247. ** are outstanding at one time. (This is only checked in the
  19248. ** single-threaded case since checking in the multi-threaded case
  19249. ** would be much more complicated.) */
  19250. assert( scratchAllocOut<=1 );
  19251. if( p ) scratchAllocOut++;
  19252. #endif
  19253. return p;
  19254. }
  19255. SQLITE_PRIVATE void sqlite3ScratchFree(void *p){
  19256. if( p ){
  19257. #if SQLITE_THREADSAFE==0 && !defined(NDEBUG)
  19258. /* Verify that no more than two scratch allocation per thread
  19259. ** is outstanding at one time. (This is only checked in the
  19260. ** single-threaded case since checking in the multi-threaded case
  19261. ** would be much more complicated.) */
  19262. assert( scratchAllocOut>=1 && scratchAllocOut<=2 );
  19263. scratchAllocOut--;
  19264. #endif
  19265. if( p>=sqlite3GlobalConfig.pScratch && p<mem0.pScratchEnd ){
  19266. /* Release memory from the SQLITE_CONFIG_SCRATCH allocation */
  19267. ScratchFreeslot *pSlot;
  19268. pSlot = (ScratchFreeslot*)p;
  19269. sqlite3_mutex_enter(mem0.mutex);
  19270. pSlot->pNext = mem0.pScratchFree;
  19271. mem0.pScratchFree = pSlot;
  19272. mem0.nScratchFree++;
  19273. assert( mem0.nScratchFree <= (u32)sqlite3GlobalConfig.nScratch );
  19274. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_USED, -1);
  19275. sqlite3_mutex_leave(mem0.mutex);
  19276. }else{
  19277. /* Release memory back to the heap */
  19278. assert( sqlite3MemdebugHasType(p, MEMTYPE_SCRATCH) );
  19279. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_SCRATCH) );
  19280. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19281. if( sqlite3GlobalConfig.bMemstat ){
  19282. int iSize = sqlite3MallocSize(p);
  19283. sqlite3_mutex_enter(mem0.mutex);
  19284. sqlite3StatusAdd(SQLITE_STATUS_SCRATCH_OVERFLOW, -iSize);
  19285. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -iSize);
  19286. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  19287. sqlite3GlobalConfig.m.xFree(p);
  19288. sqlite3_mutex_leave(mem0.mutex);
  19289. }else{
  19290. sqlite3GlobalConfig.m.xFree(p);
  19291. }
  19292. }
  19293. }
  19294. }
  19295. /*
  19296. ** TRUE if p is a lookaside memory allocation from db
  19297. */
  19298. #ifndef SQLITE_OMIT_LOOKASIDE
  19299. static int isLookaside(sqlite3 *db, void *p){
  19300. return p>=db->lookaside.pStart && p<db->lookaside.pEnd;
  19301. }
  19302. #else
  19303. #define isLookaside(A,B) 0
  19304. #endif
  19305. /*
  19306. ** Return the size of a memory allocation previously obtained from
  19307. ** sqlite3Malloc() or sqlite3_malloc().
  19308. */
  19309. SQLITE_PRIVATE int sqlite3MallocSize(void *p){
  19310. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19311. return sqlite3GlobalConfig.m.xSize(p);
  19312. }
  19313. SQLITE_PRIVATE int sqlite3DbMallocSize(sqlite3 *db, void *p){
  19314. if( db==0 ){
  19315. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
  19316. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19317. return sqlite3MallocSize(p);
  19318. }else{
  19319. assert( sqlite3_mutex_held(db->mutex) );
  19320. if( isLookaside(db, p) ){
  19321. return db->lookaside.sz;
  19322. }else{
  19323. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19324. assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19325. return sqlite3GlobalConfig.m.xSize(p);
  19326. }
  19327. }
  19328. }
  19329. SQLITE_API sqlite3_uint64 sqlite3_msize(void *p){
  19330. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
  19331. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19332. return (sqlite3_uint64)sqlite3GlobalConfig.m.xSize(p);
  19333. }
  19334. /*
  19335. ** Free memory previously obtained from sqlite3Malloc().
  19336. */
  19337. SQLITE_API void sqlite3_free(void *p){
  19338. if( p==0 ) return; /* IMP: R-49053-54554 */
  19339. assert( sqlite3MemdebugHasType(p, MEMTYPE_HEAP) );
  19340. assert( sqlite3MemdebugNoType(p, ~MEMTYPE_HEAP) );
  19341. if( sqlite3GlobalConfig.bMemstat ){
  19342. sqlite3_mutex_enter(mem0.mutex);
  19343. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, -sqlite3MallocSize(p));
  19344. sqlite3StatusAdd(SQLITE_STATUS_MALLOC_COUNT, -1);
  19345. sqlite3GlobalConfig.m.xFree(p);
  19346. sqlite3_mutex_leave(mem0.mutex);
  19347. }else{
  19348. sqlite3GlobalConfig.m.xFree(p);
  19349. }
  19350. }
  19351. /*
  19352. ** Add the size of memory allocation "p" to the count in
  19353. ** *db->pnBytesFreed.
  19354. */
  19355. static SQLITE_NOINLINE void measureAllocationSize(sqlite3 *db, void *p){
  19356. *db->pnBytesFreed += sqlite3DbMallocSize(db,p);
  19357. }
  19358. /*
  19359. ** Free memory that might be associated with a particular database
  19360. ** connection.
  19361. */
  19362. SQLITE_PRIVATE void sqlite3DbFree(sqlite3 *db, void *p){
  19363. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  19364. if( p==0 ) return;
  19365. if( db ){
  19366. if( db->pnBytesFreed ){
  19367. measureAllocationSize(db, p);
  19368. return;
  19369. }
  19370. if( isLookaside(db, p) ){
  19371. LookasideSlot *pBuf = (LookasideSlot*)p;
  19372. #if SQLITE_DEBUG
  19373. /* Trash all content in the buffer being freed */
  19374. memset(p, 0xaa, db->lookaside.sz);
  19375. #endif
  19376. pBuf->pNext = db->lookaside.pFree;
  19377. db->lookaside.pFree = pBuf;
  19378. db->lookaside.nOut--;
  19379. return;
  19380. }
  19381. }
  19382. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19383. assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19384. assert( db!=0 || sqlite3MemdebugNoType(p, MEMTYPE_LOOKASIDE) );
  19385. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19386. sqlite3_free(p);
  19387. }
  19388. /*
  19389. ** Change the size of an existing memory allocation
  19390. */
  19391. SQLITE_PRIVATE void *sqlite3Realloc(void *pOld, u64 nBytes){
  19392. int nOld, nNew, nDiff;
  19393. void *pNew;
  19394. assert( sqlite3MemdebugHasType(pOld, MEMTYPE_HEAP) );
  19395. assert( sqlite3MemdebugNoType(pOld, ~MEMTYPE_HEAP) );
  19396. if( pOld==0 ){
  19397. return sqlite3Malloc(nBytes); /* IMP: R-04300-56712 */
  19398. }
  19399. if( nBytes==0 ){
  19400. sqlite3_free(pOld); /* IMP: R-26507-47431 */
  19401. return 0;
  19402. }
  19403. if( nBytes>=0x7fffff00 ){
  19404. /* The 0x7ffff00 limit term is explained in comments on sqlite3Malloc() */
  19405. return 0;
  19406. }
  19407. nOld = sqlite3MallocSize(pOld);
  19408. /* IMPLEMENTATION-OF: R-46199-30249 SQLite guarantees that the second
  19409. ** argument to xRealloc is always a value returned by a prior call to
  19410. ** xRoundup. */
  19411. nNew = sqlite3GlobalConfig.m.xRoundup((int)nBytes);
  19412. if( nOld==nNew ){
  19413. pNew = pOld;
  19414. }else if( sqlite3GlobalConfig.bMemstat ){
  19415. sqlite3_mutex_enter(mem0.mutex);
  19416. sqlite3StatusSet(SQLITE_STATUS_MALLOC_SIZE, (int)nBytes);
  19417. nDiff = nNew - nOld;
  19418. if( sqlite3StatusValue(SQLITE_STATUS_MEMORY_USED) >=
  19419. mem0.alarmThreshold-nDiff ){
  19420. sqlite3MallocAlarm(nDiff);
  19421. }
  19422. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  19423. if( pNew==0 && mem0.alarmCallback ){
  19424. sqlite3MallocAlarm((int)nBytes);
  19425. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  19426. }
  19427. if( pNew ){
  19428. nNew = sqlite3MallocSize(pNew);
  19429. sqlite3StatusAdd(SQLITE_STATUS_MEMORY_USED, nNew-nOld);
  19430. }
  19431. sqlite3_mutex_leave(mem0.mutex);
  19432. }else{
  19433. pNew = sqlite3GlobalConfig.m.xRealloc(pOld, nNew);
  19434. }
  19435. assert( EIGHT_BYTE_ALIGNMENT(pNew) ); /* IMP: R-11148-40995 */
  19436. return pNew;
  19437. }
  19438. /*
  19439. ** The public interface to sqlite3Realloc. Make sure that the memory
  19440. ** subsystem is initialized prior to invoking sqliteRealloc.
  19441. */
  19442. SQLITE_API void *sqlite3_realloc(void *pOld, int n){
  19443. #ifndef SQLITE_OMIT_AUTOINIT
  19444. if( sqlite3_initialize() ) return 0;
  19445. #endif
  19446. if( n<0 ) n = 0; /* IMP: R-26507-47431 */
  19447. return sqlite3Realloc(pOld, n);
  19448. }
  19449. SQLITE_API void *sqlite3_realloc64(void *pOld, sqlite3_uint64 n){
  19450. #ifndef SQLITE_OMIT_AUTOINIT
  19451. if( sqlite3_initialize() ) return 0;
  19452. #endif
  19453. return sqlite3Realloc(pOld, n);
  19454. }
  19455. /*
  19456. ** Allocate and zero memory.
  19457. */
  19458. SQLITE_PRIVATE void *sqlite3MallocZero(u64 n){
  19459. void *p = sqlite3Malloc(n);
  19460. if( p ){
  19461. memset(p, 0, (size_t)n);
  19462. }
  19463. return p;
  19464. }
  19465. /*
  19466. ** Allocate and zero memory. If the allocation fails, make
  19467. ** the mallocFailed flag in the connection pointer.
  19468. */
  19469. SQLITE_PRIVATE void *sqlite3DbMallocZero(sqlite3 *db, u64 n){
  19470. void *p = sqlite3DbMallocRaw(db, n);
  19471. if( p ){
  19472. memset(p, 0, (size_t)n);
  19473. }
  19474. return p;
  19475. }
  19476. /*
  19477. ** Allocate and zero memory. If the allocation fails, make
  19478. ** the mallocFailed flag in the connection pointer.
  19479. **
  19480. ** If db!=0 and db->mallocFailed is true (indicating a prior malloc
  19481. ** failure on the same database connection) then always return 0.
  19482. ** Hence for a particular database connection, once malloc starts
  19483. ** failing, it fails consistently until mallocFailed is reset.
  19484. ** This is an important assumption. There are many places in the
  19485. ** code that do things like this:
  19486. **
  19487. ** int *a = (int*)sqlite3DbMallocRaw(db, 100);
  19488. ** int *b = (int*)sqlite3DbMallocRaw(db, 200);
  19489. ** if( b ) a[10] = 9;
  19490. **
  19491. ** In other words, if a subsequent malloc (ex: "b") worked, it is assumed
  19492. ** that all prior mallocs (ex: "a") worked too.
  19493. */
  19494. SQLITE_PRIVATE void *sqlite3DbMallocRaw(sqlite3 *db, u64 n){
  19495. void *p;
  19496. assert( db==0 || sqlite3_mutex_held(db->mutex) );
  19497. assert( db==0 || db->pnBytesFreed==0 );
  19498. #ifndef SQLITE_OMIT_LOOKASIDE
  19499. if( db ){
  19500. LookasideSlot *pBuf;
  19501. if( db->mallocFailed ){
  19502. return 0;
  19503. }
  19504. if( db->lookaside.bEnabled ){
  19505. if( n>db->lookaside.sz ){
  19506. db->lookaside.anStat[1]++;
  19507. }else if( (pBuf = db->lookaside.pFree)==0 ){
  19508. db->lookaside.anStat[2]++;
  19509. }else{
  19510. db->lookaside.pFree = pBuf->pNext;
  19511. db->lookaside.nOut++;
  19512. db->lookaside.anStat[0]++;
  19513. if( db->lookaside.nOut>db->lookaside.mxOut ){
  19514. db->lookaside.mxOut = db->lookaside.nOut;
  19515. }
  19516. return (void*)pBuf;
  19517. }
  19518. }
  19519. }
  19520. #else
  19521. if( db && db->mallocFailed ){
  19522. return 0;
  19523. }
  19524. #endif
  19525. p = sqlite3Malloc(n);
  19526. if( !p && db ){
  19527. db->mallocFailed = 1;
  19528. }
  19529. sqlite3MemdebugSetType(p,
  19530. (db && db->lookaside.bEnabled) ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP);
  19531. return p;
  19532. }
  19533. /*
  19534. ** Resize the block of memory pointed to by p to n bytes. If the
  19535. ** resize fails, set the mallocFailed flag in the connection object.
  19536. */
  19537. SQLITE_PRIVATE void *sqlite3DbRealloc(sqlite3 *db, void *p, u64 n){
  19538. void *pNew = 0;
  19539. assert( db!=0 );
  19540. assert( sqlite3_mutex_held(db->mutex) );
  19541. if( db->mallocFailed==0 ){
  19542. if( p==0 ){
  19543. return sqlite3DbMallocRaw(db, n);
  19544. }
  19545. if( isLookaside(db, p) ){
  19546. if( n<=db->lookaside.sz ){
  19547. return p;
  19548. }
  19549. pNew = sqlite3DbMallocRaw(db, n);
  19550. if( pNew ){
  19551. memcpy(pNew, p, db->lookaside.sz);
  19552. sqlite3DbFree(db, p);
  19553. }
  19554. }else{
  19555. assert( sqlite3MemdebugHasType(p, (MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19556. assert( sqlite3MemdebugNoType(p, ~(MEMTYPE_LOOKASIDE|MEMTYPE_HEAP)) );
  19557. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  19558. pNew = sqlite3_realloc64(p, n);
  19559. if( !pNew ){
  19560. db->mallocFailed = 1;
  19561. }
  19562. sqlite3MemdebugSetType(pNew,
  19563. (db->lookaside.bEnabled ? MEMTYPE_LOOKASIDE : MEMTYPE_HEAP));
  19564. }
  19565. }
  19566. return pNew;
  19567. }
  19568. /*
  19569. ** Attempt to reallocate p. If the reallocation fails, then free p
  19570. ** and set the mallocFailed flag in the database connection.
  19571. */
  19572. SQLITE_PRIVATE void *sqlite3DbReallocOrFree(sqlite3 *db, void *p, u64 n){
  19573. void *pNew;
  19574. pNew = sqlite3DbRealloc(db, p, n);
  19575. if( !pNew ){
  19576. sqlite3DbFree(db, p);
  19577. }
  19578. return pNew;
  19579. }
  19580. /*
  19581. ** Make a copy of a string in memory obtained from sqliteMalloc(). These
  19582. ** functions call sqlite3MallocRaw() directly instead of sqliteMalloc(). This
  19583. ** is because when memory debugging is turned on, these two functions are
  19584. ** called via macros that record the current file and line number in the
  19585. ** ThreadData structure.
  19586. */
  19587. SQLITE_PRIVATE char *sqlite3DbStrDup(sqlite3 *db, const char *z){
  19588. char *zNew;
  19589. size_t n;
  19590. if( z==0 ){
  19591. return 0;
  19592. }
  19593. n = sqlite3Strlen30(z) + 1;
  19594. assert( (n&0x7fffffff)==n );
  19595. zNew = sqlite3DbMallocRaw(db, (int)n);
  19596. if( zNew ){
  19597. memcpy(zNew, z, n);
  19598. }
  19599. return zNew;
  19600. }
  19601. SQLITE_PRIVATE char *sqlite3DbStrNDup(sqlite3 *db, const char *z, u64 n){
  19602. char *zNew;
  19603. if( z==0 ){
  19604. return 0;
  19605. }
  19606. assert( (n&0x7fffffff)==n );
  19607. zNew = sqlite3DbMallocRaw(db, n+1);
  19608. if( zNew ){
  19609. memcpy(zNew, z, (size_t)n);
  19610. zNew[n] = 0;
  19611. }
  19612. return zNew;
  19613. }
  19614. /*
  19615. ** Create a string from the zFromat argument and the va_list that follows.
  19616. ** Store the string in memory obtained from sqliteMalloc() and make *pz
  19617. ** point to that string.
  19618. */
  19619. SQLITE_PRIVATE void sqlite3SetString(char **pz, sqlite3 *db, const char *zFormat, ...){
  19620. va_list ap;
  19621. char *z;
  19622. va_start(ap, zFormat);
  19623. z = sqlite3VMPrintf(db, zFormat, ap);
  19624. va_end(ap);
  19625. sqlite3DbFree(db, *pz);
  19626. *pz = z;
  19627. }
  19628. /*
  19629. ** Take actions at the end of an API call to indicate an OOM error
  19630. */
  19631. static SQLITE_NOINLINE int apiOomError(sqlite3 *db){
  19632. db->mallocFailed = 0;
  19633. sqlite3Error(db, SQLITE_NOMEM);
  19634. return SQLITE_NOMEM;
  19635. }
  19636. /*
  19637. ** This function must be called before exiting any API function (i.e.
  19638. ** returning control to the user) that has called sqlite3_malloc or
  19639. ** sqlite3_realloc.
  19640. **
  19641. ** The returned value is normally a copy of the second argument to this
  19642. ** function. However, if a malloc() failure has occurred since the previous
  19643. ** invocation SQLITE_NOMEM is returned instead.
  19644. **
  19645. ** If the first argument, db, is not NULL and a malloc() error has occurred,
  19646. ** then the connection error-code (the value returned by sqlite3_errcode())
  19647. ** is set to SQLITE_NOMEM.
  19648. */
  19649. SQLITE_PRIVATE int sqlite3ApiExit(sqlite3* db, int rc){
  19650. /* If the db handle is not NULL, then we must hold the connection handle
  19651. ** mutex here. Otherwise the read (and possible write) of db->mallocFailed
  19652. ** is unsafe, as is the call to sqlite3Error().
  19653. */
  19654. assert( !db || sqlite3_mutex_held(db->mutex) );
  19655. if( db==0 ) return rc & 0xff;
  19656. if( db->mallocFailed || rc==SQLITE_IOERR_NOMEM ){
  19657. return apiOomError(db);
  19658. }
  19659. return rc & db->errMask;
  19660. }
  19661. /************** End of malloc.c **********************************************/
  19662. /************** Begin file printf.c ******************************************/
  19663. /*
  19664. ** The "printf" code that follows dates from the 1980's. It is in
  19665. ** the public domain. The original comments are included here for
  19666. ** completeness. They are very out-of-date but might be useful as
  19667. ** an historical reference. Most of the "enhancements" have been backed
  19668. ** out so that the functionality is now the same as standard printf().
  19669. **
  19670. **************************************************************************
  19671. **
  19672. ** This file contains code for a set of "printf"-like routines. These
  19673. ** routines format strings much like the printf() from the standard C
  19674. ** library, though the implementation here has enhancements to support
  19675. ** SQLlite.
  19676. */
  19677. /*
  19678. ** If the strchrnul() library function is available, then set
  19679. ** HAVE_STRCHRNUL. If that routine is not available, this module
  19680. ** will supply its own. The built-in version is slower than
  19681. ** the glibc version so the glibc version is definitely preferred.
  19682. */
  19683. #if !defined(HAVE_STRCHRNUL)
  19684. # define HAVE_STRCHRNUL 0
  19685. #endif
  19686. /*
  19687. ** Conversion types fall into various categories as defined by the
  19688. ** following enumeration.
  19689. */
  19690. #define etRADIX 1 /* Integer types. %d, %x, %o, and so forth */
  19691. #define etFLOAT 2 /* Floating point. %f */
  19692. #define etEXP 3 /* Exponentional notation. %e and %E */
  19693. #define etGENERIC 4 /* Floating or exponential, depending on exponent. %g */
  19694. #define etSIZE 5 /* Return number of characters processed so far. %n */
  19695. #define etSTRING 6 /* Strings. %s */
  19696. #define etDYNSTRING 7 /* Dynamically allocated strings. %z */
  19697. #define etPERCENT 8 /* Percent symbol. %% */
  19698. #define etCHARX 9 /* Characters. %c */
  19699. /* The rest are extensions, not normally found in printf() */
  19700. #define etSQLESCAPE 10 /* Strings with '\'' doubled. %q */
  19701. #define etSQLESCAPE2 11 /* Strings with '\'' doubled and enclosed in '',
  19702. NULL pointers replaced by SQL NULL. %Q */
  19703. #define etTOKEN 12 /* a pointer to a Token structure */
  19704. #define etSRCLIST 13 /* a pointer to a SrcList */
  19705. #define etPOINTER 14 /* The %p conversion */
  19706. #define etSQLESCAPE3 15 /* %w -> Strings with '\"' doubled */
  19707. #define etORDINAL 16 /* %r -> 1st, 2nd, 3rd, 4th, etc. English only */
  19708. #define etINVALID 0 /* Any unrecognized conversion type */
  19709. /*
  19710. ** An "etByte" is an 8-bit unsigned value.
  19711. */
  19712. typedef unsigned char etByte;
  19713. /*
  19714. ** Each builtin conversion character (ex: the 'd' in "%d") is described
  19715. ** by an instance of the following structure
  19716. */
  19717. typedef struct et_info { /* Information about each format field */
  19718. char fmttype; /* The format field code letter */
  19719. etByte base; /* The base for radix conversion */
  19720. etByte flags; /* One or more of FLAG_ constants below */
  19721. etByte type; /* Conversion paradigm */
  19722. etByte charset; /* Offset into aDigits[] of the digits string */
  19723. etByte prefix; /* Offset into aPrefix[] of the prefix string */
  19724. } et_info;
  19725. /*
  19726. ** Allowed values for et_info.flags
  19727. */
  19728. #define FLAG_SIGNED 1 /* True if the value to convert is signed */
  19729. #define FLAG_INTERN 2 /* True if for internal use only */
  19730. #define FLAG_STRING 4 /* Allow infinity precision */
  19731. /*
  19732. ** The following table is searched linearly, so it is good to put the
  19733. ** most frequently used conversion types first.
  19734. */
  19735. static const char aDigits[] = "0123456789ABCDEF0123456789abcdef";
  19736. static const char aPrefix[] = "-x0\000X0";
  19737. static const et_info fmtinfo[] = {
  19738. { 'd', 10, 1, etRADIX, 0, 0 },
  19739. { 's', 0, 4, etSTRING, 0, 0 },
  19740. { 'g', 0, 1, etGENERIC, 30, 0 },
  19741. { 'z', 0, 4, etDYNSTRING, 0, 0 },
  19742. { 'q', 0, 4, etSQLESCAPE, 0, 0 },
  19743. { 'Q', 0, 4, etSQLESCAPE2, 0, 0 },
  19744. { 'w', 0, 4, etSQLESCAPE3, 0, 0 },
  19745. { 'c', 0, 0, etCHARX, 0, 0 },
  19746. { 'o', 8, 0, etRADIX, 0, 2 },
  19747. { 'u', 10, 0, etRADIX, 0, 0 },
  19748. { 'x', 16, 0, etRADIX, 16, 1 },
  19749. { 'X', 16, 0, etRADIX, 0, 4 },
  19750. #ifndef SQLITE_OMIT_FLOATING_POINT
  19751. { 'f', 0, 1, etFLOAT, 0, 0 },
  19752. { 'e', 0, 1, etEXP, 30, 0 },
  19753. { 'E', 0, 1, etEXP, 14, 0 },
  19754. { 'G', 0, 1, etGENERIC, 14, 0 },
  19755. #endif
  19756. { 'i', 10, 1, etRADIX, 0, 0 },
  19757. { 'n', 0, 0, etSIZE, 0, 0 },
  19758. { '%', 0, 0, etPERCENT, 0, 0 },
  19759. { 'p', 16, 0, etPOINTER, 0, 1 },
  19760. /* All the rest have the FLAG_INTERN bit set and are thus for internal
  19761. ** use only */
  19762. { 'T', 0, 2, etTOKEN, 0, 0 },
  19763. { 'S', 0, 2, etSRCLIST, 0, 0 },
  19764. { 'r', 10, 3, etORDINAL, 0, 0 },
  19765. };
  19766. /*
  19767. ** If SQLITE_OMIT_FLOATING_POINT is defined, then none of the floating point
  19768. ** conversions will work.
  19769. */
  19770. #ifndef SQLITE_OMIT_FLOATING_POINT
  19771. /*
  19772. ** "*val" is a double such that 0.1 <= *val < 10.0
  19773. ** Return the ascii code for the leading digit of *val, then
  19774. ** multiply "*val" by 10.0 to renormalize.
  19775. **
  19776. ** Example:
  19777. ** input: *val = 3.14159
  19778. ** output: *val = 1.4159 function return = '3'
  19779. **
  19780. ** The counter *cnt is incremented each time. After counter exceeds
  19781. ** 16 (the number of significant digits in a 64-bit float) '0' is
  19782. ** always returned.
  19783. */
  19784. static char et_getdigit(LONGDOUBLE_TYPE *val, int *cnt){
  19785. int digit;
  19786. LONGDOUBLE_TYPE d;
  19787. if( (*cnt)<=0 ) return '0';
  19788. (*cnt)--;
  19789. digit = (int)*val;
  19790. d = digit;
  19791. digit += '0';
  19792. *val = (*val - d)*10.0;
  19793. return (char)digit;
  19794. }
  19795. #endif /* SQLITE_OMIT_FLOATING_POINT */
  19796. /*
  19797. ** Set the StrAccum object to an error mode.
  19798. */
  19799. static void setStrAccumError(StrAccum *p, u8 eError){
  19800. p->accError = eError;
  19801. p->nAlloc = 0;
  19802. }
  19803. /*
  19804. ** Extra argument values from a PrintfArguments object
  19805. */
  19806. static sqlite3_int64 getIntArg(PrintfArguments *p){
  19807. if( p->nArg<=p->nUsed ) return 0;
  19808. return sqlite3_value_int64(p->apArg[p->nUsed++]);
  19809. }
  19810. static double getDoubleArg(PrintfArguments *p){
  19811. if( p->nArg<=p->nUsed ) return 0.0;
  19812. return sqlite3_value_double(p->apArg[p->nUsed++]);
  19813. }
  19814. static char *getTextArg(PrintfArguments *p){
  19815. if( p->nArg<=p->nUsed ) return 0;
  19816. return (char*)sqlite3_value_text(p->apArg[p->nUsed++]);
  19817. }
  19818. /*
  19819. ** On machines with a small stack size, you can redefine the
  19820. ** SQLITE_PRINT_BUF_SIZE to be something smaller, if desired.
  19821. */
  19822. #ifndef SQLITE_PRINT_BUF_SIZE
  19823. # define SQLITE_PRINT_BUF_SIZE 70
  19824. #endif
  19825. #define etBUFSIZE SQLITE_PRINT_BUF_SIZE /* Size of the output buffer */
  19826. /*
  19827. ** Render a string given by "fmt" into the StrAccum object.
  19828. */
  19829. SQLITE_PRIVATE void sqlite3VXPrintf(
  19830. StrAccum *pAccum, /* Accumulate results here */
  19831. u32 bFlags, /* SQLITE_PRINTF_* flags */
  19832. const char *fmt, /* Format string */
  19833. va_list ap /* arguments */
  19834. ){
  19835. int c; /* Next character in the format string */
  19836. char *bufpt; /* Pointer to the conversion buffer */
  19837. int precision; /* Precision of the current field */
  19838. int length; /* Length of the field */
  19839. int idx; /* A general purpose loop counter */
  19840. int width; /* Width of the current field */
  19841. etByte flag_leftjustify; /* True if "-" flag is present */
  19842. etByte flag_plussign; /* True if "+" flag is present */
  19843. etByte flag_blanksign; /* True if " " flag is present */
  19844. etByte flag_alternateform; /* True if "#" flag is present */
  19845. etByte flag_altform2; /* True if "!" flag is present */
  19846. etByte flag_zeropad; /* True if field width constant starts with zero */
  19847. etByte flag_long; /* True if "l" flag is present */
  19848. etByte flag_longlong; /* True if the "ll" flag is present */
  19849. etByte done; /* Loop termination flag */
  19850. etByte xtype = 0; /* Conversion paradigm */
  19851. u8 bArgList; /* True for SQLITE_PRINTF_SQLFUNC */
  19852. u8 useIntern; /* Ok to use internal conversions (ex: %T) */
  19853. char prefix; /* Prefix character. "+" or "-" or " " or '\0'. */
  19854. sqlite_uint64 longvalue; /* Value for integer types */
  19855. LONGDOUBLE_TYPE realvalue; /* Value for real types */
  19856. const et_info *infop; /* Pointer to the appropriate info structure */
  19857. char *zOut; /* Rendering buffer */
  19858. int nOut; /* Size of the rendering buffer */
  19859. char *zExtra = 0; /* Malloced memory used by some conversion */
  19860. #ifndef SQLITE_OMIT_FLOATING_POINT
  19861. int exp, e2; /* exponent of real numbers */
  19862. int nsd; /* Number of significant digits returned */
  19863. double rounder; /* Used for rounding floating point values */
  19864. etByte flag_dp; /* True if decimal point should be shown */
  19865. etByte flag_rtz; /* True if trailing zeros should be removed */
  19866. #endif
  19867. PrintfArguments *pArgList = 0; /* Arguments for SQLITE_PRINTF_SQLFUNC */
  19868. char buf[etBUFSIZE]; /* Conversion buffer */
  19869. bufpt = 0;
  19870. if( bFlags ){
  19871. if( (bArgList = (bFlags & SQLITE_PRINTF_SQLFUNC))!=0 ){
  19872. pArgList = va_arg(ap, PrintfArguments*);
  19873. }
  19874. useIntern = bFlags & SQLITE_PRINTF_INTERNAL;
  19875. }else{
  19876. bArgList = useIntern = 0;
  19877. }
  19878. for(; (c=(*fmt))!=0; ++fmt){
  19879. if( c!='%' ){
  19880. bufpt = (char *)fmt;
  19881. #if HAVE_STRCHRNUL
  19882. fmt = strchrnul(fmt, '%');
  19883. #else
  19884. do{ fmt++; }while( *fmt && *fmt != '%' );
  19885. #endif
  19886. sqlite3StrAccumAppend(pAccum, bufpt, (int)(fmt - bufpt));
  19887. if( *fmt==0 ) break;
  19888. }
  19889. if( (c=(*++fmt))==0 ){
  19890. sqlite3StrAccumAppend(pAccum, "%", 1);
  19891. break;
  19892. }
  19893. /* Find out what flags are present */
  19894. flag_leftjustify = flag_plussign = flag_blanksign =
  19895. flag_alternateform = flag_altform2 = flag_zeropad = 0;
  19896. done = 0;
  19897. do{
  19898. switch( c ){
  19899. case '-': flag_leftjustify = 1; break;
  19900. case '+': flag_plussign = 1; break;
  19901. case ' ': flag_blanksign = 1; break;
  19902. case '#': flag_alternateform = 1; break;
  19903. case '!': flag_altform2 = 1; break;
  19904. case '0': flag_zeropad = 1; break;
  19905. default: done = 1; break;
  19906. }
  19907. }while( !done && (c=(*++fmt))!=0 );
  19908. /* Get the field width */
  19909. width = 0;
  19910. if( c=='*' ){
  19911. if( bArgList ){
  19912. width = (int)getIntArg(pArgList);
  19913. }else{
  19914. width = va_arg(ap,int);
  19915. }
  19916. if( width<0 ){
  19917. flag_leftjustify = 1;
  19918. width = -width;
  19919. }
  19920. c = *++fmt;
  19921. }else{
  19922. while( c>='0' && c<='9' ){
  19923. width = width*10 + c - '0';
  19924. c = *++fmt;
  19925. }
  19926. }
  19927. /* Get the precision */
  19928. if( c=='.' ){
  19929. precision = 0;
  19930. c = *++fmt;
  19931. if( c=='*' ){
  19932. if( bArgList ){
  19933. precision = (int)getIntArg(pArgList);
  19934. }else{
  19935. precision = va_arg(ap,int);
  19936. }
  19937. if( precision<0 ) precision = -precision;
  19938. c = *++fmt;
  19939. }else{
  19940. while( c>='0' && c<='9' ){
  19941. precision = precision*10 + c - '0';
  19942. c = *++fmt;
  19943. }
  19944. }
  19945. }else{
  19946. precision = -1;
  19947. }
  19948. /* Get the conversion type modifier */
  19949. if( c=='l' ){
  19950. flag_long = 1;
  19951. c = *++fmt;
  19952. if( c=='l' ){
  19953. flag_longlong = 1;
  19954. c = *++fmt;
  19955. }else{
  19956. flag_longlong = 0;
  19957. }
  19958. }else{
  19959. flag_long = flag_longlong = 0;
  19960. }
  19961. /* Fetch the info entry for the field */
  19962. infop = &fmtinfo[0];
  19963. xtype = etINVALID;
  19964. for(idx=0; idx<ArraySize(fmtinfo); idx++){
  19965. if( c==fmtinfo[idx].fmttype ){
  19966. infop = &fmtinfo[idx];
  19967. if( useIntern || (infop->flags & FLAG_INTERN)==0 ){
  19968. xtype = infop->type;
  19969. }else{
  19970. return;
  19971. }
  19972. break;
  19973. }
  19974. }
  19975. /*
  19976. ** At this point, variables are initialized as follows:
  19977. **
  19978. ** flag_alternateform TRUE if a '#' is present.
  19979. ** flag_altform2 TRUE if a '!' is present.
  19980. ** flag_plussign TRUE if a '+' is present.
  19981. ** flag_leftjustify TRUE if a '-' is present or if the
  19982. ** field width was negative.
  19983. ** flag_zeropad TRUE if the width began with 0.
  19984. ** flag_long TRUE if the letter 'l' (ell) prefixed
  19985. ** the conversion character.
  19986. ** flag_longlong TRUE if the letter 'll' (ell ell) prefixed
  19987. ** the conversion character.
  19988. ** flag_blanksign TRUE if a ' ' is present.
  19989. ** width The specified field width. This is
  19990. ** always non-negative. Zero is the default.
  19991. ** precision The specified precision. The default
  19992. ** is -1.
  19993. ** xtype The class of the conversion.
  19994. ** infop Pointer to the appropriate info struct.
  19995. */
  19996. switch( xtype ){
  19997. case etPOINTER:
  19998. flag_longlong = sizeof(char*)==sizeof(i64);
  19999. flag_long = sizeof(char*)==sizeof(long int);
  20000. /* Fall through into the next case */
  20001. case etORDINAL:
  20002. case etRADIX:
  20003. if( infop->flags & FLAG_SIGNED ){
  20004. i64 v;
  20005. if( bArgList ){
  20006. v = getIntArg(pArgList);
  20007. }else if( flag_longlong ){
  20008. v = va_arg(ap,i64);
  20009. }else if( flag_long ){
  20010. v = va_arg(ap,long int);
  20011. }else{
  20012. v = va_arg(ap,int);
  20013. }
  20014. if( v<0 ){
  20015. if( v==SMALLEST_INT64 ){
  20016. longvalue = ((u64)1)<<63;
  20017. }else{
  20018. longvalue = -v;
  20019. }
  20020. prefix = '-';
  20021. }else{
  20022. longvalue = v;
  20023. if( flag_plussign ) prefix = '+';
  20024. else if( flag_blanksign ) prefix = ' ';
  20025. else prefix = 0;
  20026. }
  20027. }else{
  20028. if( bArgList ){
  20029. longvalue = (u64)getIntArg(pArgList);
  20030. }else if( flag_longlong ){
  20031. longvalue = va_arg(ap,u64);
  20032. }else if( flag_long ){
  20033. longvalue = va_arg(ap,unsigned long int);
  20034. }else{
  20035. longvalue = va_arg(ap,unsigned int);
  20036. }
  20037. prefix = 0;
  20038. }
  20039. if( longvalue==0 ) flag_alternateform = 0;
  20040. if( flag_zeropad && precision<width-(prefix!=0) ){
  20041. precision = width-(prefix!=0);
  20042. }
  20043. if( precision<etBUFSIZE-10 ){
  20044. nOut = etBUFSIZE;
  20045. zOut = buf;
  20046. }else{
  20047. nOut = precision + 10;
  20048. zOut = zExtra = sqlite3Malloc( nOut );
  20049. if( zOut==0 ){
  20050. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20051. return;
  20052. }
  20053. }
  20054. bufpt = &zOut[nOut-1];
  20055. if( xtype==etORDINAL ){
  20056. static const char zOrd[] = "thstndrd";
  20057. int x = (int)(longvalue % 10);
  20058. if( x>=4 || (longvalue/10)%10==1 ){
  20059. x = 0;
  20060. }
  20061. *(--bufpt) = zOrd[x*2+1];
  20062. *(--bufpt) = zOrd[x*2];
  20063. }
  20064. {
  20065. const char *cset = &aDigits[infop->charset];
  20066. u8 base = infop->base;
  20067. do{ /* Convert to ascii */
  20068. *(--bufpt) = cset[longvalue%base];
  20069. longvalue = longvalue/base;
  20070. }while( longvalue>0 );
  20071. }
  20072. length = (int)(&zOut[nOut-1]-bufpt);
  20073. for(idx=precision-length; idx>0; idx--){
  20074. *(--bufpt) = '0'; /* Zero pad */
  20075. }
  20076. if( prefix ) *(--bufpt) = prefix; /* Add sign */
  20077. if( flag_alternateform && infop->prefix ){ /* Add "0" or "0x" */
  20078. const char *pre;
  20079. char x;
  20080. pre = &aPrefix[infop->prefix];
  20081. for(; (x=(*pre))!=0; pre++) *(--bufpt) = x;
  20082. }
  20083. length = (int)(&zOut[nOut-1]-bufpt);
  20084. break;
  20085. case etFLOAT:
  20086. case etEXP:
  20087. case etGENERIC:
  20088. if( bArgList ){
  20089. realvalue = getDoubleArg(pArgList);
  20090. }else{
  20091. realvalue = va_arg(ap,double);
  20092. }
  20093. #ifdef SQLITE_OMIT_FLOATING_POINT
  20094. length = 0;
  20095. #else
  20096. if( precision<0 ) precision = 6; /* Set default precision */
  20097. if( realvalue<0.0 ){
  20098. realvalue = -realvalue;
  20099. prefix = '-';
  20100. }else{
  20101. if( flag_plussign ) prefix = '+';
  20102. else if( flag_blanksign ) prefix = ' ';
  20103. else prefix = 0;
  20104. }
  20105. if( xtype==etGENERIC && precision>0 ) precision--;
  20106. for(idx=precision, rounder=0.5; idx>0; idx--, rounder*=0.1){}
  20107. if( xtype==etFLOAT ) realvalue += rounder;
  20108. /* Normalize realvalue to within 10.0 > realvalue >= 1.0 */
  20109. exp = 0;
  20110. if( sqlite3IsNaN((double)realvalue) ){
  20111. bufpt = "NaN";
  20112. length = 3;
  20113. break;
  20114. }
  20115. if( realvalue>0.0 ){
  20116. LONGDOUBLE_TYPE scale = 1.0;
  20117. while( realvalue>=1e100*scale && exp<=350 ){ scale *= 1e100;exp+=100;}
  20118. while( realvalue>=1e64*scale && exp<=350 ){ scale *= 1e64; exp+=64; }
  20119. while( realvalue>=1e8*scale && exp<=350 ){ scale *= 1e8; exp+=8; }
  20120. while( realvalue>=10.0*scale && exp<=350 ){ scale *= 10.0; exp++; }
  20121. realvalue /= scale;
  20122. while( realvalue<1e-8 ){ realvalue *= 1e8; exp-=8; }
  20123. while( realvalue<1.0 ){ realvalue *= 10.0; exp--; }
  20124. if( exp>350 ){
  20125. if( prefix=='-' ){
  20126. bufpt = "-Inf";
  20127. }else if( prefix=='+' ){
  20128. bufpt = "+Inf";
  20129. }else{
  20130. bufpt = "Inf";
  20131. }
  20132. length = sqlite3Strlen30(bufpt);
  20133. break;
  20134. }
  20135. }
  20136. bufpt = buf;
  20137. /*
  20138. ** If the field type is etGENERIC, then convert to either etEXP
  20139. ** or etFLOAT, as appropriate.
  20140. */
  20141. if( xtype!=etFLOAT ){
  20142. realvalue += rounder;
  20143. if( realvalue>=10.0 ){ realvalue *= 0.1; exp++; }
  20144. }
  20145. if( xtype==etGENERIC ){
  20146. flag_rtz = !flag_alternateform;
  20147. if( exp<-4 || exp>precision ){
  20148. xtype = etEXP;
  20149. }else{
  20150. precision = precision - exp;
  20151. xtype = etFLOAT;
  20152. }
  20153. }else{
  20154. flag_rtz = flag_altform2;
  20155. }
  20156. if( xtype==etEXP ){
  20157. e2 = 0;
  20158. }else{
  20159. e2 = exp;
  20160. }
  20161. if( MAX(e2,0)+precision+width > etBUFSIZE - 15 ){
  20162. bufpt = zExtra = sqlite3Malloc( MAX(e2,0)+precision+width+15 );
  20163. if( bufpt==0 ){
  20164. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20165. return;
  20166. }
  20167. }
  20168. zOut = bufpt;
  20169. nsd = 16 + flag_altform2*10;
  20170. flag_dp = (precision>0 ?1:0) | flag_alternateform | flag_altform2;
  20171. /* The sign in front of the number */
  20172. if( prefix ){
  20173. *(bufpt++) = prefix;
  20174. }
  20175. /* Digits prior to the decimal point */
  20176. if( e2<0 ){
  20177. *(bufpt++) = '0';
  20178. }else{
  20179. for(; e2>=0; e2--){
  20180. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  20181. }
  20182. }
  20183. /* The decimal point */
  20184. if( flag_dp ){
  20185. *(bufpt++) = '.';
  20186. }
  20187. /* "0" digits after the decimal point but before the first
  20188. ** significant digit of the number */
  20189. for(e2++; e2<0; precision--, e2++){
  20190. assert( precision>0 );
  20191. *(bufpt++) = '0';
  20192. }
  20193. /* Significant digits after the decimal point */
  20194. while( (precision--)>0 ){
  20195. *(bufpt++) = et_getdigit(&realvalue,&nsd);
  20196. }
  20197. /* Remove trailing zeros and the "." if no digits follow the "." */
  20198. if( flag_rtz && flag_dp ){
  20199. while( bufpt[-1]=='0' ) *(--bufpt) = 0;
  20200. assert( bufpt>zOut );
  20201. if( bufpt[-1]=='.' ){
  20202. if( flag_altform2 ){
  20203. *(bufpt++) = '0';
  20204. }else{
  20205. *(--bufpt) = 0;
  20206. }
  20207. }
  20208. }
  20209. /* Add the "eNNN" suffix */
  20210. if( xtype==etEXP ){
  20211. *(bufpt++) = aDigits[infop->charset];
  20212. if( exp<0 ){
  20213. *(bufpt++) = '-'; exp = -exp;
  20214. }else{
  20215. *(bufpt++) = '+';
  20216. }
  20217. if( exp>=100 ){
  20218. *(bufpt++) = (char)((exp/100)+'0'); /* 100's digit */
  20219. exp %= 100;
  20220. }
  20221. *(bufpt++) = (char)(exp/10+'0'); /* 10's digit */
  20222. *(bufpt++) = (char)(exp%10+'0'); /* 1's digit */
  20223. }
  20224. *bufpt = 0;
  20225. /* The converted number is in buf[] and zero terminated. Output it.
  20226. ** Note that the number is in the usual order, not reversed as with
  20227. ** integer conversions. */
  20228. length = (int)(bufpt-zOut);
  20229. bufpt = zOut;
  20230. /* Special case: Add leading zeros if the flag_zeropad flag is
  20231. ** set and we are not left justified */
  20232. if( flag_zeropad && !flag_leftjustify && length < width){
  20233. int i;
  20234. int nPad = width - length;
  20235. for(i=width; i>=nPad; i--){
  20236. bufpt[i] = bufpt[i-nPad];
  20237. }
  20238. i = prefix!=0;
  20239. while( nPad-- ) bufpt[i++] = '0';
  20240. length = width;
  20241. }
  20242. #endif /* !defined(SQLITE_OMIT_FLOATING_POINT) */
  20243. break;
  20244. case etSIZE:
  20245. if( !bArgList ){
  20246. *(va_arg(ap,int*)) = pAccum->nChar;
  20247. }
  20248. length = width = 0;
  20249. break;
  20250. case etPERCENT:
  20251. buf[0] = '%';
  20252. bufpt = buf;
  20253. length = 1;
  20254. break;
  20255. case etCHARX:
  20256. if( bArgList ){
  20257. bufpt = getTextArg(pArgList);
  20258. c = bufpt ? bufpt[0] : 0;
  20259. }else{
  20260. c = va_arg(ap,int);
  20261. }
  20262. if( precision>1 ){
  20263. width -= precision-1;
  20264. if( width>1 && !flag_leftjustify ){
  20265. sqlite3AppendChar(pAccum, width-1, ' ');
  20266. width = 0;
  20267. }
  20268. sqlite3AppendChar(pAccum, precision-1, c);
  20269. }
  20270. length = 1;
  20271. buf[0] = c;
  20272. bufpt = buf;
  20273. break;
  20274. case etSTRING:
  20275. case etDYNSTRING:
  20276. if( bArgList ){
  20277. bufpt = getTextArg(pArgList);
  20278. }else{
  20279. bufpt = va_arg(ap,char*);
  20280. }
  20281. if( bufpt==0 ){
  20282. bufpt = "";
  20283. }else if( xtype==etDYNSTRING && !bArgList ){
  20284. zExtra = bufpt;
  20285. }
  20286. if( precision>=0 ){
  20287. for(length=0; length<precision && bufpt[length]; length++){}
  20288. }else{
  20289. length = sqlite3Strlen30(bufpt);
  20290. }
  20291. break;
  20292. case etSQLESCAPE:
  20293. case etSQLESCAPE2:
  20294. case etSQLESCAPE3: {
  20295. int i, j, k, n, isnull;
  20296. int needQuote;
  20297. char ch;
  20298. char q = ((xtype==etSQLESCAPE3)?'"':'\''); /* Quote character */
  20299. char *escarg;
  20300. if( bArgList ){
  20301. escarg = getTextArg(pArgList);
  20302. }else{
  20303. escarg = va_arg(ap,char*);
  20304. }
  20305. isnull = escarg==0;
  20306. if( isnull ) escarg = (xtype==etSQLESCAPE2 ? "NULL" : "(NULL)");
  20307. k = precision;
  20308. for(i=n=0; k!=0 && (ch=escarg[i])!=0; i++, k--){
  20309. if( ch==q ) n++;
  20310. }
  20311. needQuote = !isnull && xtype==etSQLESCAPE2;
  20312. n += i + 1 + needQuote*2;
  20313. if( n>etBUFSIZE ){
  20314. bufpt = zExtra = sqlite3Malloc( n );
  20315. if( bufpt==0 ){
  20316. setStrAccumError(pAccum, STRACCUM_NOMEM);
  20317. return;
  20318. }
  20319. }else{
  20320. bufpt = buf;
  20321. }
  20322. j = 0;
  20323. if( needQuote ) bufpt[j++] = q;
  20324. k = i;
  20325. for(i=0; i<k; i++){
  20326. bufpt[j++] = ch = escarg[i];
  20327. if( ch==q ) bufpt[j++] = ch;
  20328. }
  20329. if( needQuote ) bufpt[j++] = q;
  20330. bufpt[j] = 0;
  20331. length = j;
  20332. /* The precision in %q and %Q means how many input characters to
  20333. ** consume, not the length of the output...
  20334. ** if( precision>=0 && precision<length ) length = precision; */
  20335. break;
  20336. }
  20337. case etTOKEN: {
  20338. Token *pToken = va_arg(ap, Token*);
  20339. assert( bArgList==0 );
  20340. if( pToken && pToken->n ){
  20341. sqlite3StrAccumAppend(pAccum, (const char*)pToken->z, pToken->n);
  20342. }
  20343. length = width = 0;
  20344. break;
  20345. }
  20346. case etSRCLIST: {
  20347. SrcList *pSrc = va_arg(ap, SrcList*);
  20348. int k = va_arg(ap, int);
  20349. struct SrcList_item *pItem = &pSrc->a[k];
  20350. assert( bArgList==0 );
  20351. assert( k>=0 && k<pSrc->nSrc );
  20352. if( pItem->zDatabase ){
  20353. sqlite3StrAccumAppendAll(pAccum, pItem->zDatabase);
  20354. sqlite3StrAccumAppend(pAccum, ".", 1);
  20355. }
  20356. sqlite3StrAccumAppendAll(pAccum, pItem->zName);
  20357. length = width = 0;
  20358. break;
  20359. }
  20360. default: {
  20361. assert( xtype==etINVALID );
  20362. return;
  20363. }
  20364. }/* End switch over the format type */
  20365. /*
  20366. ** The text of the conversion is pointed to by "bufpt" and is
  20367. ** "length" characters long. The field width is "width". Do
  20368. ** the output.
  20369. */
  20370. width -= length;
  20371. if( width>0 && !flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  20372. sqlite3StrAccumAppend(pAccum, bufpt, length);
  20373. if( width>0 && flag_leftjustify ) sqlite3AppendChar(pAccum, width, ' ');
  20374. if( zExtra ){
  20375. sqlite3_free(zExtra);
  20376. zExtra = 0;
  20377. }
  20378. }/* End for loop over the format string */
  20379. } /* End of function */
  20380. /*
  20381. ** Enlarge the memory allocation on a StrAccum object so that it is
  20382. ** able to accept at least N more bytes of text.
  20383. **
  20384. ** Return the number of bytes of text that StrAccum is able to accept
  20385. ** after the attempted enlargement. The value returned might be zero.
  20386. */
  20387. static int sqlite3StrAccumEnlarge(StrAccum *p, int N){
  20388. char *zNew;
  20389. assert( p->nChar+N >= p->nAlloc ); /* Only called if really needed */
  20390. if( p->accError ){
  20391. testcase(p->accError==STRACCUM_TOOBIG);
  20392. testcase(p->accError==STRACCUM_NOMEM);
  20393. return 0;
  20394. }
  20395. if( !p->useMalloc ){
  20396. N = p->nAlloc - p->nChar - 1;
  20397. setStrAccumError(p, STRACCUM_TOOBIG);
  20398. return N;
  20399. }else{
  20400. char *zOld = (p->zText==p->zBase ? 0 : p->zText);
  20401. i64 szNew = p->nChar;
  20402. szNew += N + 1;
  20403. if( szNew > p->mxAlloc ){
  20404. sqlite3StrAccumReset(p);
  20405. setStrAccumError(p, STRACCUM_TOOBIG);
  20406. return 0;
  20407. }else{
  20408. p->nAlloc = (int)szNew;
  20409. }
  20410. if( p->useMalloc==1 ){
  20411. zNew = sqlite3DbRealloc(p->db, zOld, p->nAlloc);
  20412. }else{
  20413. zNew = sqlite3_realloc(zOld, p->nAlloc);
  20414. }
  20415. if( zNew ){
  20416. assert( p->zText!=0 || p->nChar==0 );
  20417. if( zOld==0 && p->nChar>0 ) memcpy(zNew, p->zText, p->nChar);
  20418. p->zText = zNew;
  20419. }else{
  20420. sqlite3StrAccumReset(p);
  20421. setStrAccumError(p, STRACCUM_NOMEM);
  20422. return 0;
  20423. }
  20424. }
  20425. return N;
  20426. }
  20427. /*
  20428. ** Append N copies of character c to the given string buffer.
  20429. */
  20430. SQLITE_PRIVATE void sqlite3AppendChar(StrAccum *p, int N, char c){
  20431. if( p->nChar+N >= p->nAlloc && (N = sqlite3StrAccumEnlarge(p, N))<=0 ) return;
  20432. while( (N--)>0 ) p->zText[p->nChar++] = c;
  20433. }
  20434. /*
  20435. ** The StrAccum "p" is not large enough to accept N new bytes of z[].
  20436. ** So enlarge if first, then do the append.
  20437. **
  20438. ** This is a helper routine to sqlite3StrAccumAppend() that does special-case
  20439. ** work (enlarging the buffer) using tail recursion, so that the
  20440. ** sqlite3StrAccumAppend() routine can use fast calling semantics.
  20441. */
  20442. static void SQLITE_NOINLINE enlargeAndAppend(StrAccum *p, const char *z, int N){
  20443. N = sqlite3StrAccumEnlarge(p, N);
  20444. if( N>0 ){
  20445. memcpy(&p->zText[p->nChar], z, N);
  20446. p->nChar += N;
  20447. }
  20448. }
  20449. /*
  20450. ** Append N bytes of text from z to the StrAccum object. Increase the
  20451. ** size of the memory allocation for StrAccum if necessary.
  20452. */
  20453. SQLITE_PRIVATE void sqlite3StrAccumAppend(StrAccum *p, const char *z, int N){
  20454. assert( z!=0 );
  20455. assert( p->zText!=0 || p->nChar==0 || p->accError );
  20456. assert( N>=0 );
  20457. assert( p->accError==0 || p->nAlloc==0 );
  20458. if( p->nChar+N >= p->nAlloc ){
  20459. enlargeAndAppend(p,z,N);
  20460. }else{
  20461. assert( p->zText );
  20462. p->nChar += N;
  20463. memcpy(&p->zText[p->nChar-N], z, N);
  20464. }
  20465. }
  20466. /*
  20467. ** Append the complete text of zero-terminated string z[] to the p string.
  20468. */
  20469. SQLITE_PRIVATE void sqlite3StrAccumAppendAll(StrAccum *p, const char *z){
  20470. sqlite3StrAccumAppend(p, z, sqlite3Strlen30(z));
  20471. }
  20472. /*
  20473. ** Finish off a string by making sure it is zero-terminated.
  20474. ** Return a pointer to the resulting string. Return a NULL
  20475. ** pointer if any kind of error was encountered.
  20476. */
  20477. SQLITE_PRIVATE char *sqlite3StrAccumFinish(StrAccum *p){
  20478. if( p->zText ){
  20479. p->zText[p->nChar] = 0;
  20480. if( p->useMalloc && p->zText==p->zBase ){
  20481. if( p->useMalloc==1 ){
  20482. p->zText = sqlite3DbMallocRaw(p->db, p->nChar+1 );
  20483. }else{
  20484. p->zText = sqlite3_malloc(p->nChar+1);
  20485. }
  20486. if( p->zText ){
  20487. memcpy(p->zText, p->zBase, p->nChar+1);
  20488. }else{
  20489. setStrAccumError(p, STRACCUM_NOMEM);
  20490. }
  20491. }
  20492. }
  20493. return p->zText;
  20494. }
  20495. /*
  20496. ** Reset an StrAccum string. Reclaim all malloced memory.
  20497. */
  20498. SQLITE_PRIVATE void sqlite3StrAccumReset(StrAccum *p){
  20499. if( p->zText!=p->zBase ){
  20500. if( p->useMalloc==1 ){
  20501. sqlite3DbFree(p->db, p->zText);
  20502. }else{
  20503. sqlite3_free(p->zText);
  20504. }
  20505. }
  20506. p->zText = 0;
  20507. }
  20508. /*
  20509. ** Initialize a string accumulator
  20510. */
  20511. SQLITE_PRIVATE void sqlite3StrAccumInit(StrAccum *p, char *zBase, int n, int mx){
  20512. p->zText = p->zBase = zBase;
  20513. p->db = 0;
  20514. p->nChar = 0;
  20515. p->nAlloc = n;
  20516. p->mxAlloc = mx;
  20517. p->useMalloc = 1;
  20518. p->accError = 0;
  20519. }
  20520. /*
  20521. ** Print into memory obtained from sqliteMalloc(). Use the internal
  20522. ** %-conversion extensions.
  20523. */
  20524. SQLITE_PRIVATE char *sqlite3VMPrintf(sqlite3 *db, const char *zFormat, va_list ap){
  20525. char *z;
  20526. char zBase[SQLITE_PRINT_BUF_SIZE];
  20527. StrAccum acc;
  20528. assert( db!=0 );
  20529. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase),
  20530. db->aLimit[SQLITE_LIMIT_LENGTH]);
  20531. acc.db = db;
  20532. sqlite3VXPrintf(&acc, SQLITE_PRINTF_INTERNAL, zFormat, ap);
  20533. z = sqlite3StrAccumFinish(&acc);
  20534. if( acc.accError==STRACCUM_NOMEM ){
  20535. db->mallocFailed = 1;
  20536. }
  20537. return z;
  20538. }
  20539. /*
  20540. ** Print into memory obtained from sqliteMalloc(). Use the internal
  20541. ** %-conversion extensions.
  20542. */
  20543. SQLITE_PRIVATE char *sqlite3MPrintf(sqlite3 *db, const char *zFormat, ...){
  20544. va_list ap;
  20545. char *z;
  20546. va_start(ap, zFormat);
  20547. z = sqlite3VMPrintf(db, zFormat, ap);
  20548. va_end(ap);
  20549. return z;
  20550. }
  20551. /*
  20552. ** Like sqlite3MPrintf(), but call sqlite3DbFree() on zStr after formatting
  20553. ** the string and before returning. This routine is intended to be used
  20554. ** to modify an existing string. For example:
  20555. **
  20556. ** x = sqlite3MPrintf(db, x, "prefix %s suffix", x);
  20557. **
  20558. */
  20559. SQLITE_PRIVATE char *sqlite3MAppendf(sqlite3 *db, char *zStr, const char *zFormat, ...){
  20560. va_list ap;
  20561. char *z;
  20562. va_start(ap, zFormat);
  20563. z = sqlite3VMPrintf(db, zFormat, ap);
  20564. va_end(ap);
  20565. sqlite3DbFree(db, zStr);
  20566. return z;
  20567. }
  20568. /*
  20569. ** Print into memory obtained from sqlite3_malloc(). Omit the internal
  20570. ** %-conversion extensions.
  20571. */
  20572. SQLITE_API char *sqlite3_vmprintf(const char *zFormat, va_list ap){
  20573. char *z;
  20574. char zBase[SQLITE_PRINT_BUF_SIZE];
  20575. StrAccum acc;
  20576. #ifndef SQLITE_OMIT_AUTOINIT
  20577. if( sqlite3_initialize() ) return 0;
  20578. #endif
  20579. sqlite3StrAccumInit(&acc, zBase, sizeof(zBase), SQLITE_MAX_LENGTH);
  20580. acc.useMalloc = 2;
  20581. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20582. z = sqlite3StrAccumFinish(&acc);
  20583. return z;
  20584. }
  20585. /*
  20586. ** Print into memory obtained from sqlite3_malloc()(). Omit the internal
  20587. ** %-conversion extensions.
  20588. */
  20589. SQLITE_API char *sqlite3_mprintf(const char *zFormat, ...){
  20590. va_list ap;
  20591. char *z;
  20592. #ifndef SQLITE_OMIT_AUTOINIT
  20593. if( sqlite3_initialize() ) return 0;
  20594. #endif
  20595. va_start(ap, zFormat);
  20596. z = sqlite3_vmprintf(zFormat, ap);
  20597. va_end(ap);
  20598. return z;
  20599. }
  20600. /*
  20601. ** sqlite3_snprintf() works like snprintf() except that it ignores the
  20602. ** current locale settings. This is important for SQLite because we
  20603. ** are not able to use a "," as the decimal point in place of "." as
  20604. ** specified by some locales.
  20605. **
  20606. ** Oops: The first two arguments of sqlite3_snprintf() are backwards
  20607. ** from the snprintf() standard. Unfortunately, it is too late to change
  20608. ** this without breaking compatibility, so we just have to live with the
  20609. ** mistake.
  20610. **
  20611. ** sqlite3_vsnprintf() is the varargs version.
  20612. */
  20613. SQLITE_API char *sqlite3_vsnprintf(int n, char *zBuf, const char *zFormat, va_list ap){
  20614. StrAccum acc;
  20615. if( n<=0 ) return zBuf;
  20616. sqlite3StrAccumInit(&acc, zBuf, n, 0);
  20617. acc.useMalloc = 0;
  20618. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20619. return sqlite3StrAccumFinish(&acc);
  20620. }
  20621. SQLITE_API char *sqlite3_snprintf(int n, char *zBuf, const char *zFormat, ...){
  20622. char *z;
  20623. va_list ap;
  20624. va_start(ap,zFormat);
  20625. z = sqlite3_vsnprintf(n, zBuf, zFormat, ap);
  20626. va_end(ap);
  20627. return z;
  20628. }
  20629. /*
  20630. ** This is the routine that actually formats the sqlite3_log() message.
  20631. ** We house it in a separate routine from sqlite3_log() to avoid using
  20632. ** stack space on small-stack systems when logging is disabled.
  20633. **
  20634. ** sqlite3_log() must render into a static buffer. It cannot dynamically
  20635. ** allocate memory because it might be called while the memory allocator
  20636. ** mutex is held.
  20637. */
  20638. static void renderLogMsg(int iErrCode, const char *zFormat, va_list ap){
  20639. StrAccum acc; /* String accumulator */
  20640. char zMsg[SQLITE_PRINT_BUF_SIZE*3]; /* Complete log message */
  20641. sqlite3StrAccumInit(&acc, zMsg, sizeof(zMsg), 0);
  20642. acc.useMalloc = 0;
  20643. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20644. sqlite3GlobalConfig.xLog(sqlite3GlobalConfig.pLogArg, iErrCode,
  20645. sqlite3StrAccumFinish(&acc));
  20646. }
  20647. /*
  20648. ** Format and write a message to the log if logging is enabled.
  20649. */
  20650. SQLITE_API void sqlite3_log(int iErrCode, const char *zFormat, ...){
  20651. va_list ap; /* Vararg list */
  20652. if( sqlite3GlobalConfig.xLog ){
  20653. va_start(ap, zFormat);
  20654. renderLogMsg(iErrCode, zFormat, ap);
  20655. va_end(ap);
  20656. }
  20657. }
  20658. #if defined(SQLITE_DEBUG)
  20659. /*
  20660. ** A version of printf() that understands %lld. Used for debugging.
  20661. ** The printf() built into some versions of windows does not understand %lld
  20662. ** and segfaults if you give it a long long int.
  20663. */
  20664. SQLITE_PRIVATE void sqlite3DebugPrintf(const char *zFormat, ...){
  20665. va_list ap;
  20666. StrAccum acc;
  20667. char zBuf[500];
  20668. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  20669. acc.useMalloc = 0;
  20670. va_start(ap,zFormat);
  20671. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20672. va_end(ap);
  20673. sqlite3StrAccumFinish(&acc);
  20674. fprintf(stdout,"%s", zBuf);
  20675. fflush(stdout);
  20676. }
  20677. #endif
  20678. #ifdef SQLITE_DEBUG
  20679. /*************************************************************************
  20680. ** Routines for implementing the "TreeView" display of hierarchical
  20681. ** data structures for debugging.
  20682. **
  20683. ** The main entry points (coded elsewhere) are:
  20684. ** sqlite3TreeViewExpr(0, pExpr, 0);
  20685. ** sqlite3TreeViewExprList(0, pList, 0, 0);
  20686. ** sqlite3TreeViewSelect(0, pSelect, 0);
  20687. ** Insert calls to those routines while debugging in order to display
  20688. ** a diagram of Expr, ExprList, and Select objects.
  20689. **
  20690. */
  20691. /* Add a new subitem to the tree. The moreToFollow flag indicates that this
  20692. ** is not the last item in the tree. */
  20693. SQLITE_PRIVATE TreeView *sqlite3TreeViewPush(TreeView *p, u8 moreToFollow){
  20694. if( p==0 ){
  20695. p = sqlite3_malloc( sizeof(*p) );
  20696. if( p==0 ) return 0;
  20697. memset(p, 0, sizeof(*p));
  20698. }else{
  20699. p->iLevel++;
  20700. }
  20701. assert( moreToFollow==0 || moreToFollow==1 );
  20702. if( p->iLevel<sizeof(p->bLine) ) p->bLine[p->iLevel] = moreToFollow;
  20703. return p;
  20704. }
  20705. /* Finished with one layer of the tree */
  20706. SQLITE_PRIVATE void sqlite3TreeViewPop(TreeView *p){
  20707. if( p==0 ) return;
  20708. p->iLevel--;
  20709. if( p->iLevel<0 ) sqlite3_free(p);
  20710. }
  20711. /* Generate a single line of output for the tree, with a prefix that contains
  20712. ** all the appropriate tree lines */
  20713. SQLITE_PRIVATE void sqlite3TreeViewLine(TreeView *p, const char *zFormat, ...){
  20714. va_list ap;
  20715. int i;
  20716. StrAccum acc;
  20717. char zBuf[500];
  20718. sqlite3StrAccumInit(&acc, zBuf, sizeof(zBuf), 0);
  20719. acc.useMalloc = 0;
  20720. if( p ){
  20721. for(i=0; i<p->iLevel && i<sizeof(p->bLine)-1; i++){
  20722. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "| " : " ", 4);
  20723. }
  20724. sqlite3StrAccumAppend(&acc, p->bLine[i] ? "|-- " : "'-- ", 4);
  20725. }
  20726. va_start(ap, zFormat);
  20727. sqlite3VXPrintf(&acc, 0, zFormat, ap);
  20728. va_end(ap);
  20729. if( zBuf[acc.nChar-1]!='\n' ) sqlite3StrAccumAppend(&acc, "\n", 1);
  20730. sqlite3StrAccumFinish(&acc);
  20731. fprintf(stdout,"%s", zBuf);
  20732. fflush(stdout);
  20733. }
  20734. /* Shorthand for starting a new tree item that consists of a single label */
  20735. SQLITE_PRIVATE void sqlite3TreeViewItem(TreeView *p, const char *zLabel, u8 moreToFollow){
  20736. p = sqlite3TreeViewPush(p, moreToFollow);
  20737. sqlite3TreeViewLine(p, "%s", zLabel);
  20738. }
  20739. #endif /* SQLITE_DEBUG */
  20740. /*
  20741. ** variable-argument wrapper around sqlite3VXPrintf().
  20742. */
  20743. SQLITE_PRIVATE void sqlite3XPrintf(StrAccum *p, u32 bFlags, const char *zFormat, ...){
  20744. va_list ap;
  20745. va_start(ap,zFormat);
  20746. sqlite3VXPrintf(p, bFlags, zFormat, ap);
  20747. va_end(ap);
  20748. }
  20749. /************** End of printf.c **********************************************/
  20750. /************** Begin file random.c ******************************************/
  20751. /*
  20752. ** 2001 September 15
  20753. **
  20754. ** The author disclaims copyright to this source code. In place of
  20755. ** a legal notice, here is a blessing:
  20756. **
  20757. ** May you do good and not evil.
  20758. ** May you find forgiveness for yourself and forgive others.
  20759. ** May you share freely, never taking more than you give.
  20760. **
  20761. *************************************************************************
  20762. ** This file contains code to implement a pseudo-random number
  20763. ** generator (PRNG) for SQLite.
  20764. **
  20765. ** Random numbers are used by some of the database backends in order
  20766. ** to generate random integer keys for tables or random filenames.
  20767. */
  20768. /* All threads share a single random number generator.
  20769. ** This structure is the current state of the generator.
  20770. */
  20771. static SQLITE_WSD struct sqlite3PrngType {
  20772. unsigned char isInit; /* True if initialized */
  20773. unsigned char i, j; /* State variables */
  20774. unsigned char s[256]; /* State variables */
  20775. } sqlite3Prng;
  20776. /*
  20777. ** Return N random bytes.
  20778. */
  20779. SQLITE_API void sqlite3_randomness(int N, void *pBuf){
  20780. unsigned char t;
  20781. unsigned char *zBuf = pBuf;
  20782. /* The "wsdPrng" macro will resolve to the pseudo-random number generator
  20783. ** state vector. If writable static data is unsupported on the target,
  20784. ** we have to locate the state vector at run-time. In the more common
  20785. ** case where writable static data is supported, wsdPrng can refer directly
  20786. ** to the "sqlite3Prng" state vector declared above.
  20787. */
  20788. #ifdef SQLITE_OMIT_WSD
  20789. struct sqlite3PrngType *p = &GLOBAL(struct sqlite3PrngType, sqlite3Prng);
  20790. # define wsdPrng p[0]
  20791. #else
  20792. # define wsdPrng sqlite3Prng
  20793. #endif
  20794. #if SQLITE_THREADSAFE
  20795. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_PRNG);
  20796. sqlite3_mutex_enter(mutex);
  20797. #endif
  20798. if( N<=0 ){
  20799. wsdPrng.isInit = 0;
  20800. sqlite3_mutex_leave(mutex);
  20801. return;
  20802. }
  20803. /* Initialize the state of the random number generator once,
  20804. ** the first time this routine is called. The seed value does
  20805. ** not need to contain a lot of randomness since we are not
  20806. ** trying to do secure encryption or anything like that...
  20807. **
  20808. ** Nothing in this file or anywhere else in SQLite does any kind of
  20809. ** encryption. The RC4 algorithm is being used as a PRNG (pseudo-random
  20810. ** number generator) not as an encryption device.
  20811. */
  20812. if( !wsdPrng.isInit ){
  20813. int i;
  20814. char k[256];
  20815. wsdPrng.j = 0;
  20816. wsdPrng.i = 0;
  20817. sqlite3OsRandomness(sqlite3_vfs_find(0), 256, k);
  20818. for(i=0; i<256; i++){
  20819. wsdPrng.s[i] = (u8)i;
  20820. }
  20821. for(i=0; i<256; i++){
  20822. wsdPrng.j += wsdPrng.s[i] + k[i];
  20823. t = wsdPrng.s[wsdPrng.j];
  20824. wsdPrng.s[wsdPrng.j] = wsdPrng.s[i];
  20825. wsdPrng.s[i] = t;
  20826. }
  20827. wsdPrng.isInit = 1;
  20828. }
  20829. assert( N>0 );
  20830. do{
  20831. wsdPrng.i++;
  20832. t = wsdPrng.s[wsdPrng.i];
  20833. wsdPrng.j += t;
  20834. wsdPrng.s[wsdPrng.i] = wsdPrng.s[wsdPrng.j];
  20835. wsdPrng.s[wsdPrng.j] = t;
  20836. t += wsdPrng.s[wsdPrng.i];
  20837. *(zBuf++) = wsdPrng.s[t];
  20838. }while( --N );
  20839. sqlite3_mutex_leave(mutex);
  20840. }
  20841. #ifndef SQLITE_OMIT_BUILTIN_TEST
  20842. /*
  20843. ** For testing purposes, we sometimes want to preserve the state of
  20844. ** PRNG and restore the PRNG to its saved state at a later time, or
  20845. ** to reset the PRNG to its initial state. These routines accomplish
  20846. ** those tasks.
  20847. **
  20848. ** The sqlite3_test_control() interface calls these routines to
  20849. ** control the PRNG.
  20850. */
  20851. static SQLITE_WSD struct sqlite3PrngType sqlite3SavedPrng;
  20852. SQLITE_PRIVATE void sqlite3PrngSaveState(void){
  20853. memcpy(
  20854. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  20855. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  20856. sizeof(sqlite3Prng)
  20857. );
  20858. }
  20859. SQLITE_PRIVATE void sqlite3PrngRestoreState(void){
  20860. memcpy(
  20861. &GLOBAL(struct sqlite3PrngType, sqlite3Prng),
  20862. &GLOBAL(struct sqlite3PrngType, sqlite3SavedPrng),
  20863. sizeof(sqlite3Prng)
  20864. );
  20865. }
  20866. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  20867. /************** End of random.c **********************************************/
  20868. /************** Begin file threads.c *****************************************/
  20869. /*
  20870. ** 2012 July 21
  20871. **
  20872. ** The author disclaims copyright to this source code. In place of
  20873. ** a legal notice, here is a blessing:
  20874. **
  20875. ** May you do good and not evil.
  20876. ** May you find forgiveness for yourself and forgive others.
  20877. ** May you share freely, never taking more than you give.
  20878. **
  20879. ******************************************************************************
  20880. **
  20881. ** This file presents a simple cross-platform threading interface for
  20882. ** use internally by SQLite.
  20883. **
  20884. ** A "thread" can be created using sqlite3ThreadCreate(). This thread
  20885. ** runs independently of its creator until it is joined using
  20886. ** sqlite3ThreadJoin(), at which point it terminates.
  20887. **
  20888. ** Threads do not have to be real. It could be that the work of the
  20889. ** "thread" is done by the main thread at either the sqlite3ThreadCreate()
  20890. ** or sqlite3ThreadJoin() call. This is, in fact, what happens in
  20891. ** single threaded systems. Nothing in SQLite requires multiple threads.
  20892. ** This interface exists so that applications that want to take advantage
  20893. ** of multiple cores can do so, while also allowing applications to stay
  20894. ** single-threaded if desired.
  20895. */
  20896. #if SQLITE_MAX_WORKER_THREADS>0
  20897. /********************************* Unix Pthreads ****************************/
  20898. #if SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) && SQLITE_THREADSAFE>0
  20899. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  20900. /* #include <pthread.h> */
  20901. /* A running thread */
  20902. struct SQLiteThread {
  20903. pthread_t tid; /* Thread ID */
  20904. int done; /* Set to true when thread finishes */
  20905. void *pOut; /* Result returned by the thread */
  20906. void *(*xTask)(void*); /* The thread routine */
  20907. void *pIn; /* Argument to the thread */
  20908. };
  20909. /* Create a new thread */
  20910. SQLITE_PRIVATE int sqlite3ThreadCreate(
  20911. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  20912. void *(*xTask)(void*), /* Routine to run in a separate thread */
  20913. void *pIn /* Argument passed into xTask() */
  20914. ){
  20915. SQLiteThread *p;
  20916. int rc;
  20917. assert( ppThread!=0 );
  20918. assert( xTask!=0 );
  20919. /* This routine is never used in single-threaded mode */
  20920. assert( sqlite3GlobalConfig.bCoreMutex!=0 );
  20921. *ppThread = 0;
  20922. p = sqlite3Malloc(sizeof(*p));
  20923. if( p==0 ) return SQLITE_NOMEM;
  20924. memset(p, 0, sizeof(*p));
  20925. p->xTask = xTask;
  20926. p->pIn = pIn;
  20927. if( sqlite3FaultSim(200) ){
  20928. rc = 1;
  20929. }else{
  20930. rc = pthread_create(&p->tid, 0, xTask, pIn);
  20931. }
  20932. if( rc ){
  20933. p->done = 1;
  20934. p->pOut = xTask(pIn);
  20935. }
  20936. *ppThread = p;
  20937. return SQLITE_OK;
  20938. }
  20939. /* Get the results of the thread */
  20940. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  20941. int rc;
  20942. assert( ppOut!=0 );
  20943. if( NEVER(p==0) ) return SQLITE_NOMEM;
  20944. if( p->done ){
  20945. *ppOut = p->pOut;
  20946. rc = SQLITE_OK;
  20947. }else{
  20948. rc = pthread_join(p->tid, ppOut) ? SQLITE_ERROR : SQLITE_OK;
  20949. }
  20950. sqlite3_free(p);
  20951. return rc;
  20952. }
  20953. #endif /* SQLITE_OS_UNIX && defined(SQLITE_MUTEX_PTHREADS) */
  20954. /******************************** End Unix Pthreads *************************/
  20955. /********************************* Win32 Threads ****************************/
  20956. #if SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && SQLITE_THREADSAFE>0
  20957. #define SQLITE_THREADS_IMPLEMENTED 1 /* Prevent the single-thread code below */
  20958. #include <process.h>
  20959. /* A running thread */
  20960. struct SQLiteThread {
  20961. void *tid; /* The thread handle */
  20962. unsigned id; /* The thread identifier */
  20963. void *(*xTask)(void*); /* The routine to run as a thread */
  20964. void *pIn; /* Argument to xTask */
  20965. void *pResult; /* Result of xTask */
  20966. };
  20967. /* Thread procedure Win32 compatibility shim */
  20968. static unsigned __stdcall sqlite3ThreadProc(
  20969. void *pArg /* IN: Pointer to the SQLiteThread structure */
  20970. ){
  20971. SQLiteThread *p = (SQLiteThread *)pArg;
  20972. assert( p!=0 );
  20973. #if 0
  20974. /*
  20975. ** This assert appears to trigger spuriously on certain
  20976. ** versions of Windows, possibly due to _beginthreadex()
  20977. ** and/or CreateThread() not fully setting their thread
  20978. ** ID parameter before starting the thread.
  20979. */
  20980. assert( p->id==GetCurrentThreadId() );
  20981. #endif
  20982. assert( p->xTask!=0 );
  20983. p->pResult = p->xTask(p->pIn);
  20984. _endthreadex(0);
  20985. return 0; /* NOT REACHED */
  20986. }
  20987. /* Create a new thread */
  20988. SQLITE_PRIVATE int sqlite3ThreadCreate(
  20989. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  20990. void *(*xTask)(void*), /* Routine to run in a separate thread */
  20991. void *pIn /* Argument passed into xTask() */
  20992. ){
  20993. SQLiteThread *p;
  20994. assert( ppThread!=0 );
  20995. assert( xTask!=0 );
  20996. *ppThread = 0;
  20997. p = sqlite3Malloc(sizeof(*p));
  20998. if( p==0 ) return SQLITE_NOMEM;
  20999. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  21000. memset(p, 0, sizeof(*p));
  21001. }else{
  21002. p->xTask = xTask;
  21003. p->pIn = pIn;
  21004. p->tid = (void*)_beginthreadex(0, 0, sqlite3ThreadProc, p, 0, &p->id);
  21005. if( p->tid==0 ){
  21006. memset(p, 0, sizeof(*p));
  21007. }
  21008. }
  21009. if( p->xTask==0 ){
  21010. p->id = GetCurrentThreadId();
  21011. p->pResult = xTask(pIn);
  21012. }
  21013. *ppThread = p;
  21014. return SQLITE_OK;
  21015. }
  21016. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject); /* os_win.c */
  21017. /* Get the results of the thread */
  21018. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  21019. DWORD rc;
  21020. BOOL bRc;
  21021. assert( ppOut!=0 );
  21022. if( NEVER(p==0) ) return SQLITE_NOMEM;
  21023. if( p->xTask==0 ){
  21024. assert( p->id==GetCurrentThreadId() );
  21025. rc = WAIT_OBJECT_0;
  21026. assert( p->tid==0 );
  21027. }else{
  21028. assert( p->id!=0 && p->id!=GetCurrentThreadId() );
  21029. rc = sqlite3Win32Wait((HANDLE)p->tid);
  21030. assert( rc!=WAIT_IO_COMPLETION );
  21031. bRc = CloseHandle((HANDLE)p->tid);
  21032. assert( bRc );
  21033. }
  21034. if( rc==WAIT_OBJECT_0 ) *ppOut = p->pResult;
  21035. sqlite3_free(p);
  21036. return (rc==WAIT_OBJECT_0) ? SQLITE_OK : SQLITE_ERROR;
  21037. }
  21038. #endif /* SQLITE_OS_WIN && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT */
  21039. /******************************** End Win32 Threads *************************/
  21040. /********************************* Single-Threaded **************************/
  21041. #ifndef SQLITE_THREADS_IMPLEMENTED
  21042. /*
  21043. ** This implementation does not actually create a new thread. It does the
  21044. ** work of the thread in the main thread, when either the thread is created
  21045. ** or when it is joined
  21046. */
  21047. /* A running thread */
  21048. struct SQLiteThread {
  21049. void *(*xTask)(void*); /* The routine to run as a thread */
  21050. void *pIn; /* Argument to xTask */
  21051. void *pResult; /* Result of xTask */
  21052. };
  21053. /* Create a new thread */
  21054. SQLITE_PRIVATE int sqlite3ThreadCreate(
  21055. SQLiteThread **ppThread, /* OUT: Write the thread object here */
  21056. void *(*xTask)(void*), /* Routine to run in a separate thread */
  21057. void *pIn /* Argument passed into xTask() */
  21058. ){
  21059. SQLiteThread *p;
  21060. assert( ppThread!=0 );
  21061. assert( xTask!=0 );
  21062. *ppThread = 0;
  21063. p = sqlite3Malloc(sizeof(*p));
  21064. if( p==0 ) return SQLITE_NOMEM;
  21065. if( (SQLITE_PTR_TO_INT(p)/17)&1 ){
  21066. p->xTask = xTask;
  21067. p->pIn = pIn;
  21068. }else{
  21069. p->xTask = 0;
  21070. p->pResult = xTask(pIn);
  21071. }
  21072. *ppThread = p;
  21073. return SQLITE_OK;
  21074. }
  21075. /* Get the results of the thread */
  21076. SQLITE_PRIVATE int sqlite3ThreadJoin(SQLiteThread *p, void **ppOut){
  21077. assert( ppOut!=0 );
  21078. if( NEVER(p==0) ) return SQLITE_NOMEM;
  21079. if( p->xTask ){
  21080. *ppOut = p->xTask(p->pIn);
  21081. }else{
  21082. *ppOut = p->pResult;
  21083. }
  21084. sqlite3_free(p);
  21085. #if defined(SQLITE_TEST)
  21086. {
  21087. void *pTstAlloc = sqlite3Malloc(10);
  21088. if (!pTstAlloc) return SQLITE_NOMEM;
  21089. sqlite3_free(pTstAlloc);
  21090. }
  21091. #endif
  21092. return SQLITE_OK;
  21093. }
  21094. #endif /* !defined(SQLITE_THREADS_IMPLEMENTED) */
  21095. /****************************** End Single-Threaded *************************/
  21096. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  21097. /************** End of threads.c *********************************************/
  21098. /************** Begin file utf.c *********************************************/
  21099. /*
  21100. ** 2004 April 13
  21101. **
  21102. ** The author disclaims copyright to this source code. In place of
  21103. ** a legal notice, here is a blessing:
  21104. **
  21105. ** May you do good and not evil.
  21106. ** May you find forgiveness for yourself and forgive others.
  21107. ** May you share freely, never taking more than you give.
  21108. **
  21109. *************************************************************************
  21110. ** This file contains routines used to translate between UTF-8,
  21111. ** UTF-16, UTF-16BE, and UTF-16LE.
  21112. **
  21113. ** Notes on UTF-8:
  21114. **
  21115. ** Byte-0 Byte-1 Byte-2 Byte-3 Value
  21116. ** 0xxxxxxx 00000000 00000000 0xxxxxxx
  21117. ** 110yyyyy 10xxxxxx 00000000 00000yyy yyxxxxxx
  21118. ** 1110zzzz 10yyyyyy 10xxxxxx 00000000 zzzzyyyy yyxxxxxx
  21119. ** 11110uuu 10uuzzzz 10yyyyyy 10xxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  21120. **
  21121. **
  21122. ** Notes on UTF-16: (with wwww+1==uuuuu)
  21123. **
  21124. ** Word-0 Word-1 Value
  21125. ** 110110ww wwzzzzyy 110111yy yyxxxxxx 000uuuuu zzzzyyyy yyxxxxxx
  21126. ** zzzzyyyy yyxxxxxx 00000000 zzzzyyyy yyxxxxxx
  21127. **
  21128. **
  21129. ** BOM or Byte Order Mark:
  21130. ** 0xff 0xfe little-endian utf-16 follows
  21131. ** 0xfe 0xff big-endian utf-16 follows
  21132. **
  21133. */
  21134. /* #include <assert.h> */
  21135. #ifndef SQLITE_AMALGAMATION
  21136. /*
  21137. ** The following constant value is used by the SQLITE_BIGENDIAN and
  21138. ** SQLITE_LITTLEENDIAN macros.
  21139. */
  21140. SQLITE_PRIVATE const int sqlite3one = 1;
  21141. #endif /* SQLITE_AMALGAMATION */
  21142. /*
  21143. ** This lookup table is used to help decode the first byte of
  21144. ** a multi-byte UTF8 character.
  21145. */
  21146. static const unsigned char sqlite3Utf8Trans1[] = {
  21147. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21148. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  21149. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  21150. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  21151. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21152. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  21153. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  21154. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  21155. };
  21156. #define WRITE_UTF8(zOut, c) { \
  21157. if( c<0x00080 ){ \
  21158. *zOut++ = (u8)(c&0xFF); \
  21159. } \
  21160. else if( c<0x00800 ){ \
  21161. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  21162. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21163. } \
  21164. else if( c<0x10000 ){ \
  21165. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  21166. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  21167. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21168. }else{ \
  21169. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  21170. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  21171. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  21172. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  21173. } \
  21174. }
  21175. #define WRITE_UTF16LE(zOut, c) { \
  21176. if( c<=0xFFFF ){ \
  21177. *zOut++ = (u8)(c&0x00FF); \
  21178. *zOut++ = (u8)((c>>8)&0x00FF); \
  21179. }else{ \
  21180. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  21181. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  21182. *zOut++ = (u8)(c&0x00FF); \
  21183. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  21184. } \
  21185. }
  21186. #define WRITE_UTF16BE(zOut, c) { \
  21187. if( c<=0xFFFF ){ \
  21188. *zOut++ = (u8)((c>>8)&0x00FF); \
  21189. *zOut++ = (u8)(c&0x00FF); \
  21190. }else{ \
  21191. *zOut++ = (u8)(0x00D8 + (((c-0x10000)>>18)&0x03)); \
  21192. *zOut++ = (u8)(((c>>10)&0x003F) + (((c-0x10000)>>10)&0x00C0)); \
  21193. *zOut++ = (u8)(0x00DC + ((c>>8)&0x03)); \
  21194. *zOut++ = (u8)(c&0x00FF); \
  21195. } \
  21196. }
  21197. #define READ_UTF16LE(zIn, TERM, c){ \
  21198. c = (*zIn++); \
  21199. c += ((*zIn++)<<8); \
  21200. if( c>=0xD800 && c<0xE000 && TERM ){ \
  21201. int c2 = (*zIn++); \
  21202. c2 += ((*zIn++)<<8); \
  21203. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  21204. } \
  21205. }
  21206. #define READ_UTF16BE(zIn, TERM, c){ \
  21207. c = ((*zIn++)<<8); \
  21208. c += (*zIn++); \
  21209. if( c>=0xD800 && c<0xE000 && TERM ){ \
  21210. int c2 = ((*zIn++)<<8); \
  21211. c2 += (*zIn++); \
  21212. c = (c2&0x03FF) + ((c&0x003F)<<10) + (((c&0x03C0)+0x0040)<<10); \
  21213. } \
  21214. }
  21215. /*
  21216. ** Translate a single UTF-8 character. Return the unicode value.
  21217. **
  21218. ** During translation, assume that the byte that zTerm points
  21219. ** is a 0x00.
  21220. **
  21221. ** Write a pointer to the next unread byte back into *pzNext.
  21222. **
  21223. ** Notes On Invalid UTF-8:
  21224. **
  21225. ** * This routine never allows a 7-bit character (0x00 through 0x7f) to
  21226. ** be encoded as a multi-byte character. Any multi-byte character that
  21227. ** attempts to encode a value between 0x00 and 0x7f is rendered as 0xfffd.
  21228. **
  21229. ** * This routine never allows a UTF16 surrogate value to be encoded.
  21230. ** If a multi-byte character attempts to encode a value between
  21231. ** 0xd800 and 0xe000 then it is rendered as 0xfffd.
  21232. **
  21233. ** * Bytes in the range of 0x80 through 0xbf which occur as the first
  21234. ** byte of a character are interpreted as single-byte characters
  21235. ** and rendered as themselves even though they are technically
  21236. ** invalid characters.
  21237. **
  21238. ** * This routine accepts over-length UTF8 encodings
  21239. ** for unicode values 0x80 and greater. It does not change over-length
  21240. ** encodings to 0xfffd as some systems recommend.
  21241. */
  21242. #define READ_UTF8(zIn, zTerm, c) \
  21243. c = *(zIn++); \
  21244. if( c>=0xc0 ){ \
  21245. c = sqlite3Utf8Trans1[c-0xc0]; \
  21246. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  21247. c = (c<<6) + (0x3f & *(zIn++)); \
  21248. } \
  21249. if( c<0x80 \
  21250. || (c&0xFFFFF800)==0xD800 \
  21251. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  21252. }
  21253. SQLITE_PRIVATE u32 sqlite3Utf8Read(
  21254. const unsigned char **pz /* Pointer to string from which to read char */
  21255. ){
  21256. unsigned int c;
  21257. /* Same as READ_UTF8() above but without the zTerm parameter.
  21258. ** For this routine, we assume the UTF8 string is always zero-terminated.
  21259. */
  21260. c = *((*pz)++);
  21261. if( c>=0xc0 ){
  21262. c = sqlite3Utf8Trans1[c-0xc0];
  21263. while( (*(*pz) & 0xc0)==0x80 ){
  21264. c = (c<<6) + (0x3f & *((*pz)++));
  21265. }
  21266. if( c<0x80
  21267. || (c&0xFFFFF800)==0xD800
  21268. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; }
  21269. }
  21270. return c;
  21271. }
  21272. /*
  21273. ** If the TRANSLATE_TRACE macro is defined, the value of each Mem is
  21274. ** printed on stderr on the way into and out of sqlite3VdbeMemTranslate().
  21275. */
  21276. /* #define TRANSLATE_TRACE 1 */
  21277. #ifndef SQLITE_OMIT_UTF16
  21278. /*
  21279. ** This routine transforms the internal text encoding used by pMem to
  21280. ** desiredEnc. It is an error if the string is already of the desired
  21281. ** encoding, or if *pMem does not contain a string value.
  21282. */
  21283. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemTranslate(Mem *pMem, u8 desiredEnc){
  21284. int len; /* Maximum length of output string in bytes */
  21285. unsigned char *zOut; /* Output buffer */
  21286. unsigned char *zIn; /* Input iterator */
  21287. unsigned char *zTerm; /* End of input */
  21288. unsigned char *z; /* Output iterator */
  21289. unsigned int c;
  21290. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  21291. assert( pMem->flags&MEM_Str );
  21292. assert( pMem->enc!=desiredEnc );
  21293. assert( pMem->enc!=0 );
  21294. assert( pMem->n>=0 );
  21295. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  21296. {
  21297. char zBuf[100];
  21298. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  21299. fprintf(stderr, "INPUT: %s\n", zBuf);
  21300. }
  21301. #endif
  21302. /* If the translation is between UTF-16 little and big endian, then
  21303. ** all that is required is to swap the byte order. This case is handled
  21304. ** differently from the others.
  21305. */
  21306. if( pMem->enc!=SQLITE_UTF8 && desiredEnc!=SQLITE_UTF8 ){
  21307. u8 temp;
  21308. int rc;
  21309. rc = sqlite3VdbeMemMakeWriteable(pMem);
  21310. if( rc!=SQLITE_OK ){
  21311. assert( rc==SQLITE_NOMEM );
  21312. return SQLITE_NOMEM;
  21313. }
  21314. zIn = (u8*)pMem->z;
  21315. zTerm = &zIn[pMem->n&~1];
  21316. while( zIn<zTerm ){
  21317. temp = *zIn;
  21318. *zIn = *(zIn+1);
  21319. zIn++;
  21320. *zIn++ = temp;
  21321. }
  21322. pMem->enc = desiredEnc;
  21323. goto translate_out;
  21324. }
  21325. /* Set len to the maximum number of bytes required in the output buffer. */
  21326. if( desiredEnc==SQLITE_UTF8 ){
  21327. /* When converting from UTF-16, the maximum growth results from
  21328. ** translating a 2-byte character to a 4-byte UTF-8 character.
  21329. ** A single byte is required for the output string
  21330. ** nul-terminator.
  21331. */
  21332. pMem->n &= ~1;
  21333. len = pMem->n * 2 + 1;
  21334. }else{
  21335. /* When converting from UTF-8 to UTF-16 the maximum growth is caused
  21336. ** when a 1-byte UTF-8 character is translated into a 2-byte UTF-16
  21337. ** character. Two bytes are required in the output buffer for the
  21338. ** nul-terminator.
  21339. */
  21340. len = pMem->n * 2 + 2;
  21341. }
  21342. /* Set zIn to point at the start of the input buffer and zTerm to point 1
  21343. ** byte past the end.
  21344. **
  21345. ** Variable zOut is set to point at the output buffer, space obtained
  21346. ** from sqlite3_malloc().
  21347. */
  21348. zIn = (u8*)pMem->z;
  21349. zTerm = &zIn[pMem->n];
  21350. zOut = sqlite3DbMallocRaw(pMem->db, len);
  21351. if( !zOut ){
  21352. return SQLITE_NOMEM;
  21353. }
  21354. z = zOut;
  21355. if( pMem->enc==SQLITE_UTF8 ){
  21356. if( desiredEnc==SQLITE_UTF16LE ){
  21357. /* UTF-8 -> UTF-16 Little-endian */
  21358. while( zIn<zTerm ){
  21359. READ_UTF8(zIn, zTerm, c);
  21360. WRITE_UTF16LE(z, c);
  21361. }
  21362. }else{
  21363. assert( desiredEnc==SQLITE_UTF16BE );
  21364. /* UTF-8 -> UTF-16 Big-endian */
  21365. while( zIn<zTerm ){
  21366. READ_UTF8(zIn, zTerm, c);
  21367. WRITE_UTF16BE(z, c);
  21368. }
  21369. }
  21370. pMem->n = (int)(z - zOut);
  21371. *z++ = 0;
  21372. }else{
  21373. assert( desiredEnc==SQLITE_UTF8 );
  21374. if( pMem->enc==SQLITE_UTF16LE ){
  21375. /* UTF-16 Little-endian -> UTF-8 */
  21376. while( zIn<zTerm ){
  21377. READ_UTF16LE(zIn, zIn<zTerm, c);
  21378. WRITE_UTF8(z, c);
  21379. }
  21380. }else{
  21381. /* UTF-16 Big-endian -> UTF-8 */
  21382. while( zIn<zTerm ){
  21383. READ_UTF16BE(zIn, zIn<zTerm, c);
  21384. WRITE_UTF8(z, c);
  21385. }
  21386. }
  21387. pMem->n = (int)(z - zOut);
  21388. }
  21389. *z = 0;
  21390. assert( (pMem->n+(desiredEnc==SQLITE_UTF8?1:2))<=len );
  21391. c = pMem->flags;
  21392. sqlite3VdbeMemRelease(pMem);
  21393. pMem->flags = MEM_Str|MEM_Term|(c&MEM_AffMask);
  21394. pMem->enc = desiredEnc;
  21395. pMem->z = (char*)zOut;
  21396. pMem->zMalloc = pMem->z;
  21397. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->z);
  21398. translate_out:
  21399. #if defined(TRANSLATE_TRACE) && defined(SQLITE_DEBUG)
  21400. {
  21401. char zBuf[100];
  21402. sqlite3VdbeMemPrettyPrint(pMem, zBuf);
  21403. fprintf(stderr, "OUTPUT: %s\n", zBuf);
  21404. }
  21405. #endif
  21406. return SQLITE_OK;
  21407. }
  21408. /*
  21409. ** This routine checks for a byte-order mark at the beginning of the
  21410. ** UTF-16 string stored in *pMem. If one is present, it is removed and
  21411. ** the encoding of the Mem adjusted. This routine does not do any
  21412. ** byte-swapping, it just sets Mem.enc appropriately.
  21413. **
  21414. ** The allocation (static, dynamic etc.) and encoding of the Mem may be
  21415. ** changed by this function.
  21416. */
  21417. SQLITE_PRIVATE int sqlite3VdbeMemHandleBom(Mem *pMem){
  21418. int rc = SQLITE_OK;
  21419. u8 bom = 0;
  21420. assert( pMem->n>=0 );
  21421. if( pMem->n>1 ){
  21422. u8 b1 = *(u8 *)pMem->z;
  21423. u8 b2 = *(((u8 *)pMem->z) + 1);
  21424. if( b1==0xFE && b2==0xFF ){
  21425. bom = SQLITE_UTF16BE;
  21426. }
  21427. if( b1==0xFF && b2==0xFE ){
  21428. bom = SQLITE_UTF16LE;
  21429. }
  21430. }
  21431. if( bom ){
  21432. rc = sqlite3VdbeMemMakeWriteable(pMem);
  21433. if( rc==SQLITE_OK ){
  21434. pMem->n -= 2;
  21435. memmove(pMem->z, &pMem->z[2], pMem->n);
  21436. pMem->z[pMem->n] = '\0';
  21437. pMem->z[pMem->n+1] = '\0';
  21438. pMem->flags |= MEM_Term;
  21439. pMem->enc = bom;
  21440. }
  21441. }
  21442. return rc;
  21443. }
  21444. #endif /* SQLITE_OMIT_UTF16 */
  21445. /*
  21446. ** pZ is a UTF-8 encoded unicode string. If nByte is less than zero,
  21447. ** return the number of unicode characters in pZ up to (but not including)
  21448. ** the first 0x00 byte. If nByte is not less than zero, return the
  21449. ** number of unicode characters in the first nByte of pZ (or up to
  21450. ** the first 0x00, whichever comes first).
  21451. */
  21452. SQLITE_PRIVATE int sqlite3Utf8CharLen(const char *zIn, int nByte){
  21453. int r = 0;
  21454. const u8 *z = (const u8*)zIn;
  21455. const u8 *zTerm;
  21456. if( nByte>=0 ){
  21457. zTerm = &z[nByte];
  21458. }else{
  21459. zTerm = (const u8*)(-1);
  21460. }
  21461. assert( z<=zTerm );
  21462. while( *z!=0 && z<zTerm ){
  21463. SQLITE_SKIP_UTF8(z);
  21464. r++;
  21465. }
  21466. return r;
  21467. }
  21468. /* This test function is not currently used by the automated test-suite.
  21469. ** Hence it is only available in debug builds.
  21470. */
  21471. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  21472. /*
  21473. ** Translate UTF-8 to UTF-8.
  21474. **
  21475. ** This has the effect of making sure that the string is well-formed
  21476. ** UTF-8. Miscoded characters are removed.
  21477. **
  21478. ** The translation is done in-place and aborted if the output
  21479. ** overruns the input.
  21480. */
  21481. SQLITE_PRIVATE int sqlite3Utf8To8(unsigned char *zIn){
  21482. unsigned char *zOut = zIn;
  21483. unsigned char *zStart = zIn;
  21484. u32 c;
  21485. while( zIn[0] && zOut<=zIn ){
  21486. c = sqlite3Utf8Read((const u8**)&zIn);
  21487. if( c!=0xfffd ){
  21488. WRITE_UTF8(zOut, c);
  21489. }
  21490. }
  21491. *zOut = 0;
  21492. return (int)(zOut - zStart);
  21493. }
  21494. #endif
  21495. #ifndef SQLITE_OMIT_UTF16
  21496. /*
  21497. ** Convert a UTF-16 string in the native encoding into a UTF-8 string.
  21498. ** Memory to hold the UTF-8 string is obtained from sqlite3_malloc and must
  21499. ** be freed by the calling function.
  21500. **
  21501. ** NULL is returned if there is an allocation error.
  21502. */
  21503. SQLITE_PRIVATE char *sqlite3Utf16to8(sqlite3 *db, const void *z, int nByte, u8 enc){
  21504. Mem m;
  21505. memset(&m, 0, sizeof(m));
  21506. m.db = db;
  21507. sqlite3VdbeMemSetStr(&m, z, nByte, enc, SQLITE_STATIC);
  21508. sqlite3VdbeChangeEncoding(&m, SQLITE_UTF8);
  21509. if( db->mallocFailed ){
  21510. sqlite3VdbeMemRelease(&m);
  21511. m.z = 0;
  21512. }
  21513. assert( (m.flags & MEM_Term)!=0 || db->mallocFailed );
  21514. assert( (m.flags & MEM_Str)!=0 || db->mallocFailed );
  21515. assert( m.z || db->mallocFailed );
  21516. return m.z;
  21517. }
  21518. /*
  21519. ** zIn is a UTF-16 encoded unicode string at least nChar characters long.
  21520. ** Return the number of bytes in the first nChar unicode characters
  21521. ** in pZ. nChar must be non-negative.
  21522. */
  21523. SQLITE_PRIVATE int sqlite3Utf16ByteLen(const void *zIn, int nChar){
  21524. int c;
  21525. unsigned char const *z = zIn;
  21526. int n = 0;
  21527. if( SQLITE_UTF16NATIVE==SQLITE_UTF16BE ){
  21528. while( n<nChar ){
  21529. READ_UTF16BE(z, 1, c);
  21530. n++;
  21531. }
  21532. }else{
  21533. while( n<nChar ){
  21534. READ_UTF16LE(z, 1, c);
  21535. n++;
  21536. }
  21537. }
  21538. return (int)(z-(unsigned char const *)zIn);
  21539. }
  21540. #if defined(SQLITE_TEST)
  21541. /*
  21542. ** This routine is called from the TCL test function "translate_selftest".
  21543. ** It checks that the primitives for serializing and deserializing
  21544. ** characters in each encoding are inverses of each other.
  21545. */
  21546. SQLITE_PRIVATE void sqlite3UtfSelfTest(void){
  21547. unsigned int i, t;
  21548. unsigned char zBuf[20];
  21549. unsigned char *z;
  21550. int n;
  21551. unsigned int c;
  21552. for(i=0; i<0x00110000; i++){
  21553. z = zBuf;
  21554. WRITE_UTF8(z, i);
  21555. n = (int)(z-zBuf);
  21556. assert( n>0 && n<=4 );
  21557. z[0] = 0;
  21558. z = zBuf;
  21559. c = sqlite3Utf8Read((const u8**)&z);
  21560. t = i;
  21561. if( i>=0xD800 && i<=0xDFFF ) t = 0xFFFD;
  21562. if( (i&0xFFFFFFFE)==0xFFFE ) t = 0xFFFD;
  21563. assert( c==t );
  21564. assert( (z-zBuf)==n );
  21565. }
  21566. for(i=0; i<0x00110000; i++){
  21567. if( i>=0xD800 && i<0xE000 ) continue;
  21568. z = zBuf;
  21569. WRITE_UTF16LE(z, i);
  21570. n = (int)(z-zBuf);
  21571. assert( n>0 && n<=4 );
  21572. z[0] = 0;
  21573. z = zBuf;
  21574. READ_UTF16LE(z, 1, c);
  21575. assert( c==i );
  21576. assert( (z-zBuf)==n );
  21577. }
  21578. for(i=0; i<0x00110000; i++){
  21579. if( i>=0xD800 && i<0xE000 ) continue;
  21580. z = zBuf;
  21581. WRITE_UTF16BE(z, i);
  21582. n = (int)(z-zBuf);
  21583. assert( n>0 && n<=4 );
  21584. z[0] = 0;
  21585. z = zBuf;
  21586. READ_UTF16BE(z, 1, c);
  21587. assert( c==i );
  21588. assert( (z-zBuf)==n );
  21589. }
  21590. }
  21591. #endif /* SQLITE_TEST */
  21592. #endif /* SQLITE_OMIT_UTF16 */
  21593. /************** End of utf.c *************************************************/
  21594. /************** Begin file util.c ********************************************/
  21595. /*
  21596. ** 2001 September 15
  21597. **
  21598. ** The author disclaims copyright to this source code. In place of
  21599. ** a legal notice, here is a blessing:
  21600. **
  21601. ** May you do good and not evil.
  21602. ** May you find forgiveness for yourself and forgive others.
  21603. ** May you share freely, never taking more than you give.
  21604. **
  21605. *************************************************************************
  21606. ** Utility functions used throughout sqlite.
  21607. **
  21608. ** This file contains functions for allocating memory, comparing
  21609. ** strings, and stuff like that.
  21610. **
  21611. */
  21612. /* #include <stdarg.h> */
  21613. #ifdef SQLITE_HAVE_ISNAN
  21614. # include <math.h>
  21615. #endif
  21616. /*
  21617. ** Routine needed to support the testcase() macro.
  21618. */
  21619. #ifdef SQLITE_COVERAGE_TEST
  21620. SQLITE_PRIVATE void sqlite3Coverage(int x){
  21621. static unsigned dummy = 0;
  21622. dummy += (unsigned)x;
  21623. }
  21624. #endif
  21625. /*
  21626. ** Give a callback to the test harness that can be used to simulate faults
  21627. ** in places where it is difficult or expensive to do so purely by means
  21628. ** of inputs.
  21629. **
  21630. ** The intent of the integer argument is to let the fault simulator know
  21631. ** which of multiple sqlite3FaultSim() calls has been hit.
  21632. **
  21633. ** Return whatever integer value the test callback returns, or return
  21634. ** SQLITE_OK if no test callback is installed.
  21635. */
  21636. #ifndef SQLITE_OMIT_BUILTIN_TEST
  21637. SQLITE_PRIVATE int sqlite3FaultSim(int iTest){
  21638. int (*xCallback)(int) = sqlite3GlobalConfig.xTestCallback;
  21639. return xCallback ? xCallback(iTest) : SQLITE_OK;
  21640. }
  21641. #endif
  21642. #ifndef SQLITE_OMIT_FLOATING_POINT
  21643. /*
  21644. ** Return true if the floating point value is Not a Number (NaN).
  21645. **
  21646. ** Use the math library isnan() function if compiled with SQLITE_HAVE_ISNAN.
  21647. ** Otherwise, we have our own implementation that works on most systems.
  21648. */
  21649. SQLITE_PRIVATE int sqlite3IsNaN(double x){
  21650. int rc; /* The value return */
  21651. #if !defined(SQLITE_HAVE_ISNAN)
  21652. /*
  21653. ** Systems that support the isnan() library function should probably
  21654. ** make use of it by compiling with -DSQLITE_HAVE_ISNAN. But we have
  21655. ** found that many systems do not have a working isnan() function so
  21656. ** this implementation is provided as an alternative.
  21657. **
  21658. ** This NaN test sometimes fails if compiled on GCC with -ffast-math.
  21659. ** On the other hand, the use of -ffast-math comes with the following
  21660. ** warning:
  21661. **
  21662. ** This option [-ffast-math] should never be turned on by any
  21663. ** -O option since it can result in incorrect output for programs
  21664. ** which depend on an exact implementation of IEEE or ISO
  21665. ** rules/specifications for math functions.
  21666. **
  21667. ** Under MSVC, this NaN test may fail if compiled with a floating-
  21668. ** point precision mode other than /fp:precise. From the MSDN
  21669. ** documentation:
  21670. **
  21671. ** The compiler [with /fp:precise] will properly handle comparisons
  21672. ** involving NaN. For example, x != x evaluates to true if x is NaN
  21673. ** ...
  21674. */
  21675. #ifdef __FAST_MATH__
  21676. # error SQLite will not work correctly with the -ffast-math option of GCC.
  21677. #endif
  21678. volatile double y = x;
  21679. volatile double z = y;
  21680. rc = (y!=z);
  21681. #else /* if defined(SQLITE_HAVE_ISNAN) */
  21682. rc = isnan(x);
  21683. #endif /* SQLITE_HAVE_ISNAN */
  21684. testcase( rc );
  21685. return rc;
  21686. }
  21687. #endif /* SQLITE_OMIT_FLOATING_POINT */
  21688. /*
  21689. ** Compute a string length that is limited to what can be stored in
  21690. ** lower 30 bits of a 32-bit signed integer.
  21691. **
  21692. ** The value returned will never be negative. Nor will it ever be greater
  21693. ** than the actual length of the string. For very long strings (greater
  21694. ** than 1GiB) the value returned might be less than the true string length.
  21695. */
  21696. SQLITE_PRIVATE int sqlite3Strlen30(const char *z){
  21697. const char *z2 = z;
  21698. if( z==0 ) return 0;
  21699. while( *z2 ){ z2++; }
  21700. return 0x3fffffff & (int)(z2 - z);
  21701. }
  21702. /*
  21703. ** Set the current error code to err_code and clear any prior error message.
  21704. */
  21705. SQLITE_PRIVATE void sqlite3Error(sqlite3 *db, int err_code){
  21706. assert( db!=0 );
  21707. db->errCode = err_code;
  21708. if( db->pErr ) sqlite3ValueSetNull(db->pErr);
  21709. }
  21710. /*
  21711. ** Set the most recent error code and error string for the sqlite
  21712. ** handle "db". The error code is set to "err_code".
  21713. **
  21714. ** If it is not NULL, string zFormat specifies the format of the
  21715. ** error string in the style of the printf functions: The following
  21716. ** format characters are allowed:
  21717. **
  21718. ** %s Insert a string
  21719. ** %z A string that should be freed after use
  21720. ** %d Insert an integer
  21721. ** %T Insert a token
  21722. ** %S Insert the first element of a SrcList
  21723. **
  21724. ** zFormat and any string tokens that follow it are assumed to be
  21725. ** encoded in UTF-8.
  21726. **
  21727. ** To clear the most recent error for sqlite handle "db", sqlite3Error
  21728. ** should be called with err_code set to SQLITE_OK and zFormat set
  21729. ** to NULL.
  21730. */
  21731. SQLITE_PRIVATE void sqlite3ErrorWithMsg(sqlite3 *db, int err_code, const char *zFormat, ...){
  21732. assert( db!=0 );
  21733. db->errCode = err_code;
  21734. if( zFormat==0 ){
  21735. sqlite3Error(db, err_code);
  21736. }else if( db->pErr || (db->pErr = sqlite3ValueNew(db))!=0 ){
  21737. char *z;
  21738. va_list ap;
  21739. va_start(ap, zFormat);
  21740. z = sqlite3VMPrintf(db, zFormat, ap);
  21741. va_end(ap);
  21742. sqlite3ValueSetStr(db->pErr, -1, z, SQLITE_UTF8, SQLITE_DYNAMIC);
  21743. }
  21744. }
  21745. /*
  21746. ** Add an error message to pParse->zErrMsg and increment pParse->nErr.
  21747. ** The following formatting characters are allowed:
  21748. **
  21749. ** %s Insert a string
  21750. ** %z A string that should be freed after use
  21751. ** %d Insert an integer
  21752. ** %T Insert a token
  21753. ** %S Insert the first element of a SrcList
  21754. **
  21755. ** This function should be used to report any error that occurs while
  21756. ** compiling an SQL statement (i.e. within sqlite3_prepare()). The
  21757. ** last thing the sqlite3_prepare() function does is copy the error
  21758. ** stored by this function into the database handle using sqlite3Error().
  21759. ** Functions sqlite3Error() or sqlite3ErrorWithMsg() should be used
  21760. ** during statement execution (sqlite3_step() etc.).
  21761. */
  21762. SQLITE_PRIVATE void sqlite3ErrorMsg(Parse *pParse, const char *zFormat, ...){
  21763. char *zMsg;
  21764. va_list ap;
  21765. sqlite3 *db = pParse->db;
  21766. va_start(ap, zFormat);
  21767. zMsg = sqlite3VMPrintf(db, zFormat, ap);
  21768. va_end(ap);
  21769. if( db->suppressErr ){
  21770. sqlite3DbFree(db, zMsg);
  21771. }else{
  21772. pParse->nErr++;
  21773. sqlite3DbFree(db, pParse->zErrMsg);
  21774. pParse->zErrMsg = zMsg;
  21775. pParse->rc = SQLITE_ERROR;
  21776. }
  21777. }
  21778. /*
  21779. ** Convert an SQL-style quoted string into a normal string by removing
  21780. ** the quote characters. The conversion is done in-place. If the
  21781. ** input does not begin with a quote character, then this routine
  21782. ** is a no-op.
  21783. **
  21784. ** The input string must be zero-terminated. A new zero-terminator
  21785. ** is added to the dequoted string.
  21786. **
  21787. ** The return value is -1 if no dequoting occurs or the length of the
  21788. ** dequoted string, exclusive of the zero terminator, if dequoting does
  21789. ** occur.
  21790. **
  21791. ** 2002-Feb-14: This routine is extended to remove MS-Access style
  21792. ** brackets from around identifiers. For example: "[a-b-c]" becomes
  21793. ** "a-b-c".
  21794. */
  21795. SQLITE_PRIVATE int sqlite3Dequote(char *z){
  21796. char quote;
  21797. int i, j;
  21798. if( z==0 ) return -1;
  21799. quote = z[0];
  21800. switch( quote ){
  21801. case '\'': break;
  21802. case '"': break;
  21803. case '`': break; /* For MySQL compatibility */
  21804. case '[': quote = ']'; break; /* For MS SqlServer compatibility */
  21805. default: return -1;
  21806. }
  21807. for(i=1, j=0;; i++){
  21808. assert( z[i] );
  21809. if( z[i]==quote ){
  21810. if( z[i+1]==quote ){
  21811. z[j++] = quote;
  21812. i++;
  21813. }else{
  21814. break;
  21815. }
  21816. }else{
  21817. z[j++] = z[i];
  21818. }
  21819. }
  21820. z[j] = 0;
  21821. return j;
  21822. }
  21823. /* Convenient short-hand */
  21824. #define UpperToLower sqlite3UpperToLower
  21825. /*
  21826. ** Some systems have stricmp(). Others have strcasecmp(). Because
  21827. ** there is no consistency, we will define our own.
  21828. **
  21829. ** IMPLEMENTATION-OF: R-30243-02494 The sqlite3_stricmp() and
  21830. ** sqlite3_strnicmp() APIs allow applications and extensions to compare
  21831. ** the contents of two buffers containing UTF-8 strings in a
  21832. ** case-independent fashion, using the same definition of "case
  21833. ** independence" that SQLite uses internally when comparing identifiers.
  21834. */
  21835. SQLITE_API int sqlite3_stricmp(const char *zLeft, const char *zRight){
  21836. register unsigned char *a, *b;
  21837. a = (unsigned char *)zLeft;
  21838. b = (unsigned char *)zRight;
  21839. while( *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  21840. return UpperToLower[*a] - UpperToLower[*b];
  21841. }
  21842. SQLITE_API int sqlite3_strnicmp(const char *zLeft, const char *zRight, int N){
  21843. register unsigned char *a, *b;
  21844. a = (unsigned char *)zLeft;
  21845. b = (unsigned char *)zRight;
  21846. while( N-- > 0 && *a!=0 && UpperToLower[*a]==UpperToLower[*b]){ a++; b++; }
  21847. return N<0 ? 0 : UpperToLower[*a] - UpperToLower[*b];
  21848. }
  21849. /*
  21850. ** The string z[] is an text representation of a real number.
  21851. ** Convert this string to a double and write it into *pResult.
  21852. **
  21853. ** The string z[] is length bytes in length (bytes, not characters) and
  21854. ** uses the encoding enc. The string is not necessarily zero-terminated.
  21855. **
  21856. ** Return TRUE if the result is a valid real number (or integer) and FALSE
  21857. ** if the string is empty or contains extraneous text. Valid numbers
  21858. ** are in one of these formats:
  21859. **
  21860. ** [+-]digits[E[+-]digits]
  21861. ** [+-]digits.[digits][E[+-]digits]
  21862. ** [+-].digits[E[+-]digits]
  21863. **
  21864. ** Leading and trailing whitespace is ignored for the purpose of determining
  21865. ** validity.
  21866. **
  21867. ** If some prefix of the input string is a valid number, this routine
  21868. ** returns FALSE but it still converts the prefix and writes the result
  21869. ** into *pResult.
  21870. */
  21871. SQLITE_PRIVATE int sqlite3AtoF(const char *z, double *pResult, int length, u8 enc){
  21872. #ifndef SQLITE_OMIT_FLOATING_POINT
  21873. int incr;
  21874. const char *zEnd = z + length;
  21875. /* sign * significand * (10 ^ (esign * exponent)) */
  21876. int sign = 1; /* sign of significand */
  21877. i64 s = 0; /* significand */
  21878. int d = 0; /* adjust exponent for shifting decimal point */
  21879. int esign = 1; /* sign of exponent */
  21880. int e = 0; /* exponent */
  21881. int eValid = 1; /* True exponent is either not used or is well-formed */
  21882. double result;
  21883. int nDigits = 0;
  21884. int nonNum = 0;
  21885. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  21886. *pResult = 0.0; /* Default return value, in case of an error */
  21887. if( enc==SQLITE_UTF8 ){
  21888. incr = 1;
  21889. }else{
  21890. int i;
  21891. incr = 2;
  21892. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  21893. for(i=3-enc; i<length && z[i]==0; i+=2){}
  21894. nonNum = i<length;
  21895. zEnd = z+i+enc-3;
  21896. z += (enc&1);
  21897. }
  21898. /* skip leading spaces */
  21899. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  21900. if( z>=zEnd ) return 0;
  21901. /* get sign of significand */
  21902. if( *z=='-' ){
  21903. sign = -1;
  21904. z+=incr;
  21905. }else if( *z=='+' ){
  21906. z+=incr;
  21907. }
  21908. /* skip leading zeroes */
  21909. while( z<zEnd && z[0]=='0' ) z+=incr, nDigits++;
  21910. /* copy max significant digits to significand */
  21911. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  21912. s = s*10 + (*z - '0');
  21913. z+=incr, nDigits++;
  21914. }
  21915. /* skip non-significant significand digits
  21916. ** (increase exponent by d to shift decimal left) */
  21917. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++, d++;
  21918. if( z>=zEnd ) goto do_atof_calc;
  21919. /* if decimal point is present */
  21920. if( *z=='.' ){
  21921. z+=incr;
  21922. /* copy digits from after decimal to significand
  21923. ** (decrease exponent by d to shift decimal right) */
  21924. while( z<zEnd && sqlite3Isdigit(*z) && s<((LARGEST_INT64-9)/10) ){
  21925. s = s*10 + (*z - '0');
  21926. z+=incr, nDigits++, d--;
  21927. }
  21928. /* skip non-significant digits */
  21929. while( z<zEnd && sqlite3Isdigit(*z) ) z+=incr, nDigits++;
  21930. }
  21931. if( z>=zEnd ) goto do_atof_calc;
  21932. /* if exponent is present */
  21933. if( *z=='e' || *z=='E' ){
  21934. z+=incr;
  21935. eValid = 0;
  21936. if( z>=zEnd ) goto do_atof_calc;
  21937. /* get sign of exponent */
  21938. if( *z=='-' ){
  21939. esign = -1;
  21940. z+=incr;
  21941. }else if( *z=='+' ){
  21942. z+=incr;
  21943. }
  21944. /* copy digits to exponent */
  21945. while( z<zEnd && sqlite3Isdigit(*z) ){
  21946. e = e<10000 ? (e*10 + (*z - '0')) : 10000;
  21947. z+=incr;
  21948. eValid = 1;
  21949. }
  21950. }
  21951. /* skip trailing spaces */
  21952. if( nDigits && eValid ){
  21953. while( z<zEnd && sqlite3Isspace(*z) ) z+=incr;
  21954. }
  21955. do_atof_calc:
  21956. /* adjust exponent by d, and update sign */
  21957. e = (e*esign) + d;
  21958. if( e<0 ) {
  21959. esign = -1;
  21960. e *= -1;
  21961. } else {
  21962. esign = 1;
  21963. }
  21964. /* if 0 significand */
  21965. if( !s ) {
  21966. /* In the IEEE 754 standard, zero is signed.
  21967. ** Add the sign if we've seen at least one digit */
  21968. result = (sign<0 && nDigits) ? -(double)0 : (double)0;
  21969. } else {
  21970. /* attempt to reduce exponent */
  21971. if( esign>0 ){
  21972. while( s<(LARGEST_INT64/10) && e>0 ) e--,s*=10;
  21973. }else{
  21974. while( !(s%10) && e>0 ) e--,s/=10;
  21975. }
  21976. /* adjust the sign of significand */
  21977. s = sign<0 ? -s : s;
  21978. /* if exponent, scale significand as appropriate
  21979. ** and store in result. */
  21980. if( e ){
  21981. LONGDOUBLE_TYPE scale = 1.0;
  21982. /* attempt to handle extremely small/large numbers better */
  21983. if( e>307 && e<342 ){
  21984. while( e%308 ) { scale *= 1.0e+1; e -= 1; }
  21985. if( esign<0 ){
  21986. result = s / scale;
  21987. result /= 1.0e+308;
  21988. }else{
  21989. result = s * scale;
  21990. result *= 1.0e+308;
  21991. }
  21992. }else if( e>=342 ){
  21993. if( esign<0 ){
  21994. result = 0.0*s;
  21995. }else{
  21996. result = 1e308*1e308*s; /* Infinity */
  21997. }
  21998. }else{
  21999. /* 1.0e+22 is the largest power of 10 than can be
  22000. ** represented exactly. */
  22001. while( e%22 ) { scale *= 1.0e+1; e -= 1; }
  22002. while( e>0 ) { scale *= 1.0e+22; e -= 22; }
  22003. if( esign<0 ){
  22004. result = s / scale;
  22005. }else{
  22006. result = s * scale;
  22007. }
  22008. }
  22009. } else {
  22010. result = (double)s;
  22011. }
  22012. }
  22013. /* store the result */
  22014. *pResult = result;
  22015. /* return true if number and no extra non-whitespace chracters after */
  22016. return z>=zEnd && nDigits>0 && eValid && nonNum==0;
  22017. #else
  22018. return !sqlite3Atoi64(z, pResult, length, enc);
  22019. #endif /* SQLITE_OMIT_FLOATING_POINT */
  22020. }
  22021. /*
  22022. ** Compare the 19-character string zNum against the text representation
  22023. ** value 2^63: 9223372036854775808. Return negative, zero, or positive
  22024. ** if zNum is less than, equal to, or greater than the string.
  22025. ** Note that zNum must contain exactly 19 characters.
  22026. **
  22027. ** Unlike memcmp() this routine is guaranteed to return the difference
  22028. ** in the values of the last digit if the only difference is in the
  22029. ** last digit. So, for example,
  22030. **
  22031. ** compare2pow63("9223372036854775800", 1)
  22032. **
  22033. ** will return -8.
  22034. */
  22035. static int compare2pow63(const char *zNum, int incr){
  22036. int c = 0;
  22037. int i;
  22038. /* 012345678901234567 */
  22039. const char *pow63 = "922337203685477580";
  22040. for(i=0; c==0 && i<18; i++){
  22041. c = (zNum[i*incr]-pow63[i])*10;
  22042. }
  22043. if( c==0 ){
  22044. c = zNum[18*incr] - '8';
  22045. testcase( c==(-1) );
  22046. testcase( c==0 );
  22047. testcase( c==(+1) );
  22048. }
  22049. return c;
  22050. }
  22051. /*
  22052. ** Convert zNum to a 64-bit signed integer. zNum must be decimal. This
  22053. ** routine does *not* accept hexadecimal notation.
  22054. **
  22055. ** If the zNum value is representable as a 64-bit twos-complement
  22056. ** integer, then write that value into *pNum and return 0.
  22057. **
  22058. ** If zNum is exactly 9223372036854775808, return 2. This special
  22059. ** case is broken out because while 9223372036854775808 cannot be a
  22060. ** signed 64-bit integer, its negative -9223372036854775808 can be.
  22061. **
  22062. ** If zNum is too big for a 64-bit integer and is not
  22063. ** 9223372036854775808 or if zNum contains any non-numeric text,
  22064. ** then return 1.
  22065. **
  22066. ** length is the number of bytes in the string (bytes, not characters).
  22067. ** The string is not necessarily zero-terminated. The encoding is
  22068. ** given by enc.
  22069. */
  22070. SQLITE_PRIVATE int sqlite3Atoi64(const char *zNum, i64 *pNum, int length, u8 enc){
  22071. int incr;
  22072. u64 u = 0;
  22073. int neg = 0; /* assume positive */
  22074. int i;
  22075. int c = 0;
  22076. int nonNum = 0;
  22077. const char *zStart;
  22078. const char *zEnd = zNum + length;
  22079. assert( enc==SQLITE_UTF8 || enc==SQLITE_UTF16LE || enc==SQLITE_UTF16BE );
  22080. if( enc==SQLITE_UTF8 ){
  22081. incr = 1;
  22082. }else{
  22083. incr = 2;
  22084. assert( SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  22085. for(i=3-enc; i<length && zNum[i]==0; i+=2){}
  22086. nonNum = i<length;
  22087. zEnd = zNum+i+enc-3;
  22088. zNum += (enc&1);
  22089. }
  22090. while( zNum<zEnd && sqlite3Isspace(*zNum) ) zNum+=incr;
  22091. if( zNum<zEnd ){
  22092. if( *zNum=='-' ){
  22093. neg = 1;
  22094. zNum+=incr;
  22095. }else if( *zNum=='+' ){
  22096. zNum+=incr;
  22097. }
  22098. }
  22099. zStart = zNum;
  22100. while( zNum<zEnd && zNum[0]=='0' ){ zNum+=incr; } /* Skip leading zeros. */
  22101. for(i=0; &zNum[i]<zEnd && (c=zNum[i])>='0' && c<='9'; i+=incr){
  22102. u = u*10 + c - '0';
  22103. }
  22104. if( u>LARGEST_INT64 ){
  22105. *pNum = neg ? SMALLEST_INT64 : LARGEST_INT64;
  22106. }else if( neg ){
  22107. *pNum = -(i64)u;
  22108. }else{
  22109. *pNum = (i64)u;
  22110. }
  22111. testcase( i==18 );
  22112. testcase( i==19 );
  22113. testcase( i==20 );
  22114. if( (c!=0 && &zNum[i]<zEnd) || (i==0 && zStart==zNum) || i>19*incr || nonNum ){
  22115. /* zNum is empty or contains non-numeric text or is longer
  22116. ** than 19 digits (thus guaranteeing that it is too large) */
  22117. return 1;
  22118. }else if( i<19*incr ){
  22119. /* Less than 19 digits, so we know that it fits in 64 bits */
  22120. assert( u<=LARGEST_INT64 );
  22121. return 0;
  22122. }else{
  22123. /* zNum is a 19-digit numbers. Compare it against 9223372036854775808. */
  22124. c = compare2pow63(zNum, incr);
  22125. if( c<0 ){
  22126. /* zNum is less than 9223372036854775808 so it fits */
  22127. assert( u<=LARGEST_INT64 );
  22128. return 0;
  22129. }else if( c>0 ){
  22130. /* zNum is greater than 9223372036854775808 so it overflows */
  22131. return 1;
  22132. }else{
  22133. /* zNum is exactly 9223372036854775808. Fits if negative. The
  22134. ** special case 2 overflow if positive */
  22135. assert( u-1==LARGEST_INT64 );
  22136. return neg ? 0 : 2;
  22137. }
  22138. }
  22139. }
  22140. /*
  22141. ** Transform a UTF-8 integer literal, in either decimal or hexadecimal,
  22142. ** into a 64-bit signed integer. This routine accepts hexadecimal literals,
  22143. ** whereas sqlite3Atoi64() does not.
  22144. **
  22145. ** Returns:
  22146. **
  22147. ** 0 Successful transformation. Fits in a 64-bit signed integer.
  22148. ** 1 Integer too large for a 64-bit signed integer or is malformed
  22149. ** 2 Special case of 9223372036854775808
  22150. */
  22151. SQLITE_PRIVATE int sqlite3DecOrHexToI64(const char *z, i64 *pOut){
  22152. #ifndef SQLITE_OMIT_HEX_INTEGER
  22153. if( z[0]=='0'
  22154. && (z[1]=='x' || z[1]=='X')
  22155. && sqlite3Isxdigit(z[2])
  22156. ){
  22157. u64 u = 0;
  22158. int i, k;
  22159. for(i=2; z[i]=='0'; i++){}
  22160. for(k=i; sqlite3Isxdigit(z[k]); k++){
  22161. u = u*16 + sqlite3HexToInt(z[k]);
  22162. }
  22163. memcpy(pOut, &u, 8);
  22164. return (z[k]==0 && k-i<=16) ? 0 : 1;
  22165. }else
  22166. #endif /* SQLITE_OMIT_HEX_INTEGER */
  22167. {
  22168. return sqlite3Atoi64(z, pOut, sqlite3Strlen30(z), SQLITE_UTF8);
  22169. }
  22170. }
  22171. /*
  22172. ** If zNum represents an integer that will fit in 32-bits, then set
  22173. ** *pValue to that integer and return true. Otherwise return false.
  22174. **
  22175. ** This routine accepts both decimal and hexadecimal notation for integers.
  22176. **
  22177. ** Any non-numeric characters that following zNum are ignored.
  22178. ** This is different from sqlite3Atoi64() which requires the
  22179. ** input number to be zero-terminated.
  22180. */
  22181. SQLITE_PRIVATE int sqlite3GetInt32(const char *zNum, int *pValue){
  22182. sqlite_int64 v = 0;
  22183. int i, c;
  22184. int neg = 0;
  22185. if( zNum[0]=='-' ){
  22186. neg = 1;
  22187. zNum++;
  22188. }else if( zNum[0]=='+' ){
  22189. zNum++;
  22190. }
  22191. #ifndef SQLITE_OMIT_HEX_INTEGER
  22192. else if( zNum[0]=='0'
  22193. && (zNum[1]=='x' || zNum[1]=='X')
  22194. && sqlite3Isxdigit(zNum[2])
  22195. ){
  22196. u32 u = 0;
  22197. zNum += 2;
  22198. while( zNum[0]=='0' ) zNum++;
  22199. for(i=0; sqlite3Isxdigit(zNum[i]) && i<8; i++){
  22200. u = u*16 + sqlite3HexToInt(zNum[i]);
  22201. }
  22202. if( (u&0x80000000)==0 && sqlite3Isxdigit(zNum[i])==0 ){
  22203. memcpy(pValue, &u, 4);
  22204. return 1;
  22205. }else{
  22206. return 0;
  22207. }
  22208. }
  22209. #endif
  22210. for(i=0; i<11 && (c = zNum[i] - '0')>=0 && c<=9; i++){
  22211. v = v*10 + c;
  22212. }
  22213. /* The longest decimal representation of a 32 bit integer is 10 digits:
  22214. **
  22215. ** 1234567890
  22216. ** 2^31 -> 2147483648
  22217. */
  22218. testcase( i==10 );
  22219. if( i>10 ){
  22220. return 0;
  22221. }
  22222. testcase( v-neg==2147483647 );
  22223. if( v-neg>2147483647 ){
  22224. return 0;
  22225. }
  22226. if( neg ){
  22227. v = -v;
  22228. }
  22229. *pValue = (int)v;
  22230. return 1;
  22231. }
  22232. /*
  22233. ** Return a 32-bit integer value extracted from a string. If the
  22234. ** string is not an integer, just return 0.
  22235. */
  22236. SQLITE_PRIVATE int sqlite3Atoi(const char *z){
  22237. int x = 0;
  22238. if( z ) sqlite3GetInt32(z, &x);
  22239. return x;
  22240. }
  22241. /*
  22242. ** The variable-length integer encoding is as follows:
  22243. **
  22244. ** KEY:
  22245. ** A = 0xxxxxxx 7 bits of data and one flag bit
  22246. ** B = 1xxxxxxx 7 bits of data and one flag bit
  22247. ** C = xxxxxxxx 8 bits of data
  22248. **
  22249. ** 7 bits - A
  22250. ** 14 bits - BA
  22251. ** 21 bits - BBA
  22252. ** 28 bits - BBBA
  22253. ** 35 bits - BBBBA
  22254. ** 42 bits - BBBBBA
  22255. ** 49 bits - BBBBBBA
  22256. ** 56 bits - BBBBBBBA
  22257. ** 64 bits - BBBBBBBBC
  22258. */
  22259. /*
  22260. ** Write a 64-bit variable-length integer to memory starting at p[0].
  22261. ** The length of data write will be between 1 and 9 bytes. The number
  22262. ** of bytes written is returned.
  22263. **
  22264. ** A variable-length integer consists of the lower 7 bits of each byte
  22265. ** for all bytes that have the 8th bit set and one byte with the 8th
  22266. ** bit clear. Except, if we get to the 9th byte, it stores the full
  22267. ** 8 bits and is the last byte.
  22268. */
  22269. static int SQLITE_NOINLINE putVarint64(unsigned char *p, u64 v){
  22270. int i, j, n;
  22271. u8 buf[10];
  22272. if( v & (((u64)0xff000000)<<32) ){
  22273. p[8] = (u8)v;
  22274. v >>= 8;
  22275. for(i=7; i>=0; i--){
  22276. p[i] = (u8)((v & 0x7f) | 0x80);
  22277. v >>= 7;
  22278. }
  22279. return 9;
  22280. }
  22281. n = 0;
  22282. do{
  22283. buf[n++] = (u8)((v & 0x7f) | 0x80);
  22284. v >>= 7;
  22285. }while( v!=0 );
  22286. buf[0] &= 0x7f;
  22287. assert( n<=9 );
  22288. for(i=0, j=n-1; j>=0; j--, i++){
  22289. p[i] = buf[j];
  22290. }
  22291. return n;
  22292. }
  22293. SQLITE_PRIVATE int sqlite3PutVarint(unsigned char *p, u64 v){
  22294. if( v<=0x7f ){
  22295. p[0] = v&0x7f;
  22296. return 1;
  22297. }
  22298. if( v<=0x3fff ){
  22299. p[0] = ((v>>7)&0x7f)|0x80;
  22300. p[1] = v&0x7f;
  22301. return 2;
  22302. }
  22303. return putVarint64(p,v);
  22304. }
  22305. /*
  22306. ** Bitmasks used by sqlite3GetVarint(). These precomputed constants
  22307. ** are defined here rather than simply putting the constant expressions
  22308. ** inline in order to work around bugs in the RVT compiler.
  22309. **
  22310. ** SLOT_2_0 A mask for (0x7f<<14) | 0x7f
  22311. **
  22312. ** SLOT_4_2_0 A mask for (0x7f<<28) | SLOT_2_0
  22313. */
  22314. #define SLOT_2_0 0x001fc07f
  22315. #define SLOT_4_2_0 0xf01fc07f
  22316. /*
  22317. ** Read a 64-bit variable-length integer from memory starting at p[0].
  22318. ** Return the number of bytes read. The value is stored in *v.
  22319. */
  22320. SQLITE_PRIVATE u8 sqlite3GetVarint(const unsigned char *p, u64 *v){
  22321. u32 a,b,s;
  22322. a = *p;
  22323. /* a: p0 (unmasked) */
  22324. if (!(a&0x80))
  22325. {
  22326. *v = a;
  22327. return 1;
  22328. }
  22329. p++;
  22330. b = *p;
  22331. /* b: p1 (unmasked) */
  22332. if (!(b&0x80))
  22333. {
  22334. a &= 0x7f;
  22335. a = a<<7;
  22336. a |= b;
  22337. *v = a;
  22338. return 2;
  22339. }
  22340. /* Verify that constants are precomputed correctly */
  22341. assert( SLOT_2_0 == ((0x7f<<14) | (0x7f)) );
  22342. assert( SLOT_4_2_0 == ((0xfU<<28) | (0x7f<<14) | (0x7f)) );
  22343. p++;
  22344. a = a<<14;
  22345. a |= *p;
  22346. /* a: p0<<14 | p2 (unmasked) */
  22347. if (!(a&0x80))
  22348. {
  22349. a &= SLOT_2_0;
  22350. b &= 0x7f;
  22351. b = b<<7;
  22352. a |= b;
  22353. *v = a;
  22354. return 3;
  22355. }
  22356. /* CSE1 from below */
  22357. a &= SLOT_2_0;
  22358. p++;
  22359. b = b<<14;
  22360. b |= *p;
  22361. /* b: p1<<14 | p3 (unmasked) */
  22362. if (!(b&0x80))
  22363. {
  22364. b &= SLOT_2_0;
  22365. /* moved CSE1 up */
  22366. /* a &= (0x7f<<14)|(0x7f); */
  22367. a = a<<7;
  22368. a |= b;
  22369. *v = a;
  22370. return 4;
  22371. }
  22372. /* a: p0<<14 | p2 (masked) */
  22373. /* b: p1<<14 | p3 (unmasked) */
  22374. /* 1:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  22375. /* moved CSE1 up */
  22376. /* a &= (0x7f<<14)|(0x7f); */
  22377. b &= SLOT_2_0;
  22378. s = a;
  22379. /* s: p0<<14 | p2 (masked) */
  22380. p++;
  22381. a = a<<14;
  22382. a |= *p;
  22383. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  22384. if (!(a&0x80))
  22385. {
  22386. /* we can skip these cause they were (effectively) done above in calc'ing s */
  22387. /* a &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  22388. /* b &= (0x7f<<14)|(0x7f); */
  22389. b = b<<7;
  22390. a |= b;
  22391. s = s>>18;
  22392. *v = ((u64)s)<<32 | a;
  22393. return 5;
  22394. }
  22395. /* 2:save off p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  22396. s = s<<7;
  22397. s |= b;
  22398. /* s: p0<<21 | p1<<14 | p2<<7 | p3 (masked) */
  22399. p++;
  22400. b = b<<14;
  22401. b |= *p;
  22402. /* b: p1<<28 | p3<<14 | p5 (unmasked) */
  22403. if (!(b&0x80))
  22404. {
  22405. /* we can skip this cause it was (effectively) done above in calc'ing s */
  22406. /* b &= (0x7f<<28)|(0x7f<<14)|(0x7f); */
  22407. a &= SLOT_2_0;
  22408. a = a<<7;
  22409. a |= b;
  22410. s = s>>18;
  22411. *v = ((u64)s)<<32 | a;
  22412. return 6;
  22413. }
  22414. p++;
  22415. a = a<<14;
  22416. a |= *p;
  22417. /* a: p2<<28 | p4<<14 | p6 (unmasked) */
  22418. if (!(a&0x80))
  22419. {
  22420. a &= SLOT_4_2_0;
  22421. b &= SLOT_2_0;
  22422. b = b<<7;
  22423. a |= b;
  22424. s = s>>11;
  22425. *v = ((u64)s)<<32 | a;
  22426. return 7;
  22427. }
  22428. /* CSE2 from below */
  22429. a &= SLOT_2_0;
  22430. p++;
  22431. b = b<<14;
  22432. b |= *p;
  22433. /* b: p3<<28 | p5<<14 | p7 (unmasked) */
  22434. if (!(b&0x80))
  22435. {
  22436. b &= SLOT_4_2_0;
  22437. /* moved CSE2 up */
  22438. /* a &= (0x7f<<14)|(0x7f); */
  22439. a = a<<7;
  22440. a |= b;
  22441. s = s>>4;
  22442. *v = ((u64)s)<<32 | a;
  22443. return 8;
  22444. }
  22445. p++;
  22446. a = a<<15;
  22447. a |= *p;
  22448. /* a: p4<<29 | p6<<15 | p8 (unmasked) */
  22449. /* moved CSE2 up */
  22450. /* a &= (0x7f<<29)|(0x7f<<15)|(0xff); */
  22451. b &= SLOT_2_0;
  22452. b = b<<8;
  22453. a |= b;
  22454. s = s<<4;
  22455. b = p[-4];
  22456. b &= 0x7f;
  22457. b = b>>3;
  22458. s |= b;
  22459. *v = ((u64)s)<<32 | a;
  22460. return 9;
  22461. }
  22462. /*
  22463. ** Read a 32-bit variable-length integer from memory starting at p[0].
  22464. ** Return the number of bytes read. The value is stored in *v.
  22465. **
  22466. ** If the varint stored in p[0] is larger than can fit in a 32-bit unsigned
  22467. ** integer, then set *v to 0xffffffff.
  22468. **
  22469. ** A MACRO version, getVarint32, is provided which inlines the
  22470. ** single-byte case. All code should use the MACRO version as
  22471. ** this function assumes the single-byte case has already been handled.
  22472. */
  22473. SQLITE_PRIVATE u8 sqlite3GetVarint32(const unsigned char *p, u32 *v){
  22474. u32 a,b;
  22475. /* The 1-byte case. Overwhelmingly the most common. Handled inline
  22476. ** by the getVarin32() macro */
  22477. a = *p;
  22478. /* a: p0 (unmasked) */
  22479. #ifndef getVarint32
  22480. if (!(a&0x80))
  22481. {
  22482. /* Values between 0 and 127 */
  22483. *v = a;
  22484. return 1;
  22485. }
  22486. #endif
  22487. /* The 2-byte case */
  22488. p++;
  22489. b = *p;
  22490. /* b: p1 (unmasked) */
  22491. if (!(b&0x80))
  22492. {
  22493. /* Values between 128 and 16383 */
  22494. a &= 0x7f;
  22495. a = a<<7;
  22496. *v = a | b;
  22497. return 2;
  22498. }
  22499. /* The 3-byte case */
  22500. p++;
  22501. a = a<<14;
  22502. a |= *p;
  22503. /* a: p0<<14 | p2 (unmasked) */
  22504. if (!(a&0x80))
  22505. {
  22506. /* Values between 16384 and 2097151 */
  22507. a &= (0x7f<<14)|(0x7f);
  22508. b &= 0x7f;
  22509. b = b<<7;
  22510. *v = a | b;
  22511. return 3;
  22512. }
  22513. /* A 32-bit varint is used to store size information in btrees.
  22514. ** Objects are rarely larger than 2MiB limit of a 3-byte varint.
  22515. ** A 3-byte varint is sufficient, for example, to record the size
  22516. ** of a 1048569-byte BLOB or string.
  22517. **
  22518. ** We only unroll the first 1-, 2-, and 3- byte cases. The very
  22519. ** rare larger cases can be handled by the slower 64-bit varint
  22520. ** routine.
  22521. */
  22522. #if 1
  22523. {
  22524. u64 v64;
  22525. u8 n;
  22526. p -= 2;
  22527. n = sqlite3GetVarint(p, &v64);
  22528. assert( n>3 && n<=9 );
  22529. if( (v64 & SQLITE_MAX_U32)!=v64 ){
  22530. *v = 0xffffffff;
  22531. }else{
  22532. *v = (u32)v64;
  22533. }
  22534. return n;
  22535. }
  22536. #else
  22537. /* For following code (kept for historical record only) shows an
  22538. ** unrolling for the 3- and 4-byte varint cases. This code is
  22539. ** slightly faster, but it is also larger and much harder to test.
  22540. */
  22541. p++;
  22542. b = b<<14;
  22543. b |= *p;
  22544. /* b: p1<<14 | p3 (unmasked) */
  22545. if (!(b&0x80))
  22546. {
  22547. /* Values between 2097152 and 268435455 */
  22548. b &= (0x7f<<14)|(0x7f);
  22549. a &= (0x7f<<14)|(0x7f);
  22550. a = a<<7;
  22551. *v = a | b;
  22552. return 4;
  22553. }
  22554. p++;
  22555. a = a<<14;
  22556. a |= *p;
  22557. /* a: p0<<28 | p2<<14 | p4 (unmasked) */
  22558. if (!(a&0x80))
  22559. {
  22560. /* Values between 268435456 and 34359738367 */
  22561. a &= SLOT_4_2_0;
  22562. b &= SLOT_4_2_0;
  22563. b = b<<7;
  22564. *v = a | b;
  22565. return 5;
  22566. }
  22567. /* We can only reach this point when reading a corrupt database
  22568. ** file. In that case we are not in any hurry. Use the (relatively
  22569. ** slow) general-purpose sqlite3GetVarint() routine to extract the
  22570. ** value. */
  22571. {
  22572. u64 v64;
  22573. u8 n;
  22574. p -= 4;
  22575. n = sqlite3GetVarint(p, &v64);
  22576. assert( n>5 && n<=9 );
  22577. *v = (u32)v64;
  22578. return n;
  22579. }
  22580. #endif
  22581. }
  22582. /*
  22583. ** Return the number of bytes that will be needed to store the given
  22584. ** 64-bit integer.
  22585. */
  22586. SQLITE_PRIVATE int sqlite3VarintLen(u64 v){
  22587. int i = 0;
  22588. do{
  22589. i++;
  22590. v >>= 7;
  22591. }while( v!=0 && ALWAYS(i<9) );
  22592. return i;
  22593. }
  22594. /*
  22595. ** Read or write a four-byte big-endian integer value.
  22596. */
  22597. SQLITE_PRIVATE u32 sqlite3Get4byte(const u8 *p){
  22598. testcase( p[0]&0x80 );
  22599. return ((unsigned)p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];
  22600. }
  22601. SQLITE_PRIVATE void sqlite3Put4byte(unsigned char *p, u32 v){
  22602. p[0] = (u8)(v>>24);
  22603. p[1] = (u8)(v>>16);
  22604. p[2] = (u8)(v>>8);
  22605. p[3] = (u8)v;
  22606. }
  22607. /*
  22608. ** Translate a single byte of Hex into an integer.
  22609. ** This routine only works if h really is a valid hexadecimal
  22610. ** character: 0..9a..fA..F
  22611. */
  22612. SQLITE_PRIVATE u8 sqlite3HexToInt(int h){
  22613. assert( (h>='0' && h<='9') || (h>='a' && h<='f') || (h>='A' && h<='F') );
  22614. #ifdef SQLITE_ASCII
  22615. h += 9*(1&(h>>6));
  22616. #endif
  22617. #ifdef SQLITE_EBCDIC
  22618. h += 9*(1&~(h>>4));
  22619. #endif
  22620. return (u8)(h & 0xf);
  22621. }
  22622. #if !defined(SQLITE_OMIT_BLOB_LITERAL) || defined(SQLITE_HAS_CODEC)
  22623. /*
  22624. ** Convert a BLOB literal of the form "x'hhhhhh'" into its binary
  22625. ** value. Return a pointer to its binary value. Space to hold the
  22626. ** binary value has been obtained from malloc and must be freed by
  22627. ** the calling routine.
  22628. */
  22629. SQLITE_PRIVATE void *sqlite3HexToBlob(sqlite3 *db, const char *z, int n){
  22630. char *zBlob;
  22631. int i;
  22632. zBlob = (char *)sqlite3DbMallocRaw(db, n/2 + 1);
  22633. n--;
  22634. if( zBlob ){
  22635. for(i=0; i<n; i+=2){
  22636. zBlob[i/2] = (sqlite3HexToInt(z[i])<<4) | sqlite3HexToInt(z[i+1]);
  22637. }
  22638. zBlob[i/2] = 0;
  22639. }
  22640. return zBlob;
  22641. }
  22642. #endif /* !SQLITE_OMIT_BLOB_LITERAL || SQLITE_HAS_CODEC */
  22643. /*
  22644. ** Log an error that is an API call on a connection pointer that should
  22645. ** not have been used. The "type" of connection pointer is given as the
  22646. ** argument. The zType is a word like "NULL" or "closed" or "invalid".
  22647. */
  22648. static void logBadConnection(const char *zType){
  22649. sqlite3_log(SQLITE_MISUSE,
  22650. "API call with %s database connection pointer",
  22651. zType
  22652. );
  22653. }
  22654. /*
  22655. ** Check to make sure we have a valid db pointer. This test is not
  22656. ** foolproof but it does provide some measure of protection against
  22657. ** misuse of the interface such as passing in db pointers that are
  22658. ** NULL or which have been previously closed. If this routine returns
  22659. ** 1 it means that the db pointer is valid and 0 if it should not be
  22660. ** dereferenced for any reason. The calling function should invoke
  22661. ** SQLITE_MISUSE immediately.
  22662. **
  22663. ** sqlite3SafetyCheckOk() requires that the db pointer be valid for
  22664. ** use. sqlite3SafetyCheckSickOrOk() allows a db pointer that failed to
  22665. ** open properly and is not fit for general use but which can be
  22666. ** used as an argument to sqlite3_errmsg() or sqlite3_close().
  22667. */
  22668. SQLITE_PRIVATE int sqlite3SafetyCheckOk(sqlite3 *db){
  22669. u32 magic;
  22670. if( db==0 ){
  22671. logBadConnection("NULL");
  22672. return 0;
  22673. }
  22674. magic = db->magic;
  22675. if( magic!=SQLITE_MAGIC_OPEN ){
  22676. if( sqlite3SafetyCheckSickOrOk(db) ){
  22677. testcase( sqlite3GlobalConfig.xLog!=0 );
  22678. logBadConnection("unopened");
  22679. }
  22680. return 0;
  22681. }else{
  22682. return 1;
  22683. }
  22684. }
  22685. SQLITE_PRIVATE int sqlite3SafetyCheckSickOrOk(sqlite3 *db){
  22686. u32 magic;
  22687. magic = db->magic;
  22688. if( magic!=SQLITE_MAGIC_SICK &&
  22689. magic!=SQLITE_MAGIC_OPEN &&
  22690. magic!=SQLITE_MAGIC_BUSY ){
  22691. testcase( sqlite3GlobalConfig.xLog!=0 );
  22692. logBadConnection("invalid");
  22693. return 0;
  22694. }else{
  22695. return 1;
  22696. }
  22697. }
  22698. /*
  22699. ** Attempt to add, substract, or multiply the 64-bit signed value iB against
  22700. ** the other 64-bit signed integer at *pA and store the result in *pA.
  22701. ** Return 0 on success. Or if the operation would have resulted in an
  22702. ** overflow, leave *pA unchanged and return 1.
  22703. */
  22704. SQLITE_PRIVATE int sqlite3AddInt64(i64 *pA, i64 iB){
  22705. i64 iA = *pA;
  22706. testcase( iA==0 ); testcase( iA==1 );
  22707. testcase( iB==-1 ); testcase( iB==0 );
  22708. if( iB>=0 ){
  22709. testcase( iA>0 && LARGEST_INT64 - iA == iB );
  22710. testcase( iA>0 && LARGEST_INT64 - iA == iB - 1 );
  22711. if( iA>0 && LARGEST_INT64 - iA < iB ) return 1;
  22712. }else{
  22713. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 1 );
  22714. testcase( iA<0 && -(iA + LARGEST_INT64) == iB + 2 );
  22715. if( iA<0 && -(iA + LARGEST_INT64) > iB + 1 ) return 1;
  22716. }
  22717. *pA += iB;
  22718. return 0;
  22719. }
  22720. SQLITE_PRIVATE int sqlite3SubInt64(i64 *pA, i64 iB){
  22721. testcase( iB==SMALLEST_INT64+1 );
  22722. if( iB==SMALLEST_INT64 ){
  22723. testcase( (*pA)==(-1) ); testcase( (*pA)==0 );
  22724. if( (*pA)>=0 ) return 1;
  22725. *pA -= iB;
  22726. return 0;
  22727. }else{
  22728. return sqlite3AddInt64(pA, -iB);
  22729. }
  22730. }
  22731. #define TWOPOWER32 (((i64)1)<<32)
  22732. #define TWOPOWER31 (((i64)1)<<31)
  22733. SQLITE_PRIVATE int sqlite3MulInt64(i64 *pA, i64 iB){
  22734. i64 iA = *pA;
  22735. i64 iA1, iA0, iB1, iB0, r;
  22736. iA1 = iA/TWOPOWER32;
  22737. iA0 = iA % TWOPOWER32;
  22738. iB1 = iB/TWOPOWER32;
  22739. iB0 = iB % TWOPOWER32;
  22740. if( iA1==0 ){
  22741. if( iB1==0 ){
  22742. *pA *= iB;
  22743. return 0;
  22744. }
  22745. r = iA0*iB1;
  22746. }else if( iB1==0 ){
  22747. r = iA1*iB0;
  22748. }else{
  22749. /* If both iA1 and iB1 are non-zero, overflow will result */
  22750. return 1;
  22751. }
  22752. testcase( r==(-TWOPOWER31)-1 );
  22753. testcase( r==(-TWOPOWER31) );
  22754. testcase( r==TWOPOWER31 );
  22755. testcase( r==TWOPOWER31-1 );
  22756. if( r<(-TWOPOWER31) || r>=TWOPOWER31 ) return 1;
  22757. r *= TWOPOWER32;
  22758. if( sqlite3AddInt64(&r, iA0*iB0) ) return 1;
  22759. *pA = r;
  22760. return 0;
  22761. }
  22762. /*
  22763. ** Compute the absolute value of a 32-bit signed integer, of possible. Or
  22764. ** if the integer has a value of -2147483648, return +2147483647
  22765. */
  22766. SQLITE_PRIVATE int sqlite3AbsInt32(int x){
  22767. if( x>=0 ) return x;
  22768. if( x==(int)0x80000000 ) return 0x7fffffff;
  22769. return -x;
  22770. }
  22771. #ifdef SQLITE_ENABLE_8_3_NAMES
  22772. /*
  22773. ** If SQLITE_ENABLE_8_3_NAMES is set at compile-time and if the database
  22774. ** filename in zBaseFilename is a URI with the "8_3_names=1" parameter and
  22775. ** if filename in z[] has a suffix (a.k.a. "extension") that is longer than
  22776. ** three characters, then shorten the suffix on z[] to be the last three
  22777. ** characters of the original suffix.
  22778. **
  22779. ** If SQLITE_ENABLE_8_3_NAMES is set to 2 at compile-time, then always
  22780. ** do the suffix shortening regardless of URI parameter.
  22781. **
  22782. ** Examples:
  22783. **
  22784. ** test.db-journal => test.nal
  22785. ** test.db-wal => test.wal
  22786. ** test.db-shm => test.shm
  22787. ** test.db-mj7f3319fa => test.9fa
  22788. */
  22789. SQLITE_PRIVATE void sqlite3FileSuffix3(const char *zBaseFilename, char *z){
  22790. #if SQLITE_ENABLE_8_3_NAMES<2
  22791. if( sqlite3_uri_boolean(zBaseFilename, "8_3_names", 0) )
  22792. #endif
  22793. {
  22794. int i, sz;
  22795. sz = sqlite3Strlen30(z);
  22796. for(i=sz-1; i>0 && z[i]!='/' && z[i]!='.'; i--){}
  22797. if( z[i]=='.' && ALWAYS(sz>i+4) ) memmove(&z[i+1], &z[sz-3], 4);
  22798. }
  22799. }
  22800. #endif
  22801. /*
  22802. ** Find (an approximate) sum of two LogEst values. This computation is
  22803. ** not a simple "+" operator because LogEst is stored as a logarithmic
  22804. ** value.
  22805. **
  22806. */
  22807. SQLITE_PRIVATE LogEst sqlite3LogEstAdd(LogEst a, LogEst b){
  22808. static const unsigned char x[] = {
  22809. 10, 10, /* 0,1 */
  22810. 9, 9, /* 2,3 */
  22811. 8, 8, /* 4,5 */
  22812. 7, 7, 7, /* 6,7,8 */
  22813. 6, 6, 6, /* 9,10,11 */
  22814. 5, 5, 5, /* 12-14 */
  22815. 4, 4, 4, 4, /* 15-18 */
  22816. 3, 3, 3, 3, 3, 3, /* 19-24 */
  22817. 2, 2, 2, 2, 2, 2, 2, /* 25-31 */
  22818. };
  22819. if( a>=b ){
  22820. if( a>b+49 ) return a;
  22821. if( a>b+31 ) return a+1;
  22822. return a+x[a-b];
  22823. }else{
  22824. if( b>a+49 ) return b;
  22825. if( b>a+31 ) return b+1;
  22826. return b+x[b-a];
  22827. }
  22828. }
  22829. /*
  22830. ** Convert an integer into a LogEst. In other words, compute an
  22831. ** approximation for 10*log2(x).
  22832. */
  22833. SQLITE_PRIVATE LogEst sqlite3LogEst(u64 x){
  22834. static LogEst a[] = { 0, 2, 3, 5, 6, 7, 8, 9 };
  22835. LogEst y = 40;
  22836. if( x<8 ){
  22837. if( x<2 ) return 0;
  22838. while( x<8 ){ y -= 10; x <<= 1; }
  22839. }else{
  22840. while( x>255 ){ y += 40; x >>= 4; }
  22841. while( x>15 ){ y += 10; x >>= 1; }
  22842. }
  22843. return a[x&7] + y - 10;
  22844. }
  22845. #ifndef SQLITE_OMIT_VIRTUALTABLE
  22846. /*
  22847. ** Convert a double into a LogEst
  22848. ** In other words, compute an approximation for 10*log2(x).
  22849. */
  22850. SQLITE_PRIVATE LogEst sqlite3LogEstFromDouble(double x){
  22851. u64 a;
  22852. LogEst e;
  22853. assert( sizeof(x)==8 && sizeof(a)==8 );
  22854. if( x<=1 ) return 0;
  22855. if( x<=2000000000 ) return sqlite3LogEst((u64)x);
  22856. memcpy(&a, &x, 8);
  22857. e = (a>>52) - 1022;
  22858. return e*10;
  22859. }
  22860. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  22861. /*
  22862. ** Convert a LogEst into an integer.
  22863. */
  22864. SQLITE_PRIVATE u64 sqlite3LogEstToInt(LogEst x){
  22865. u64 n;
  22866. if( x<10 ) return 1;
  22867. n = x%10;
  22868. x /= 10;
  22869. if( n>=5 ) n -= 2;
  22870. else if( n>=1 ) n -= 1;
  22871. if( x>=3 ){
  22872. return x>60 ? (u64)LARGEST_INT64 : (n+8)<<(x-3);
  22873. }
  22874. return (n+8)>>(3-x);
  22875. }
  22876. /************** End of util.c ************************************************/
  22877. /************** Begin file hash.c ********************************************/
  22878. /*
  22879. ** 2001 September 22
  22880. **
  22881. ** The author disclaims copyright to this source code. In place of
  22882. ** a legal notice, here is a blessing:
  22883. **
  22884. ** May you do good and not evil.
  22885. ** May you find forgiveness for yourself and forgive others.
  22886. ** May you share freely, never taking more than you give.
  22887. **
  22888. *************************************************************************
  22889. ** This is the implementation of generic hash-tables
  22890. ** used in SQLite.
  22891. */
  22892. /* #include <assert.h> */
  22893. /* Turn bulk memory into a hash table object by initializing the
  22894. ** fields of the Hash structure.
  22895. **
  22896. ** "pNew" is a pointer to the hash table that is to be initialized.
  22897. */
  22898. SQLITE_PRIVATE void sqlite3HashInit(Hash *pNew){
  22899. assert( pNew!=0 );
  22900. pNew->first = 0;
  22901. pNew->count = 0;
  22902. pNew->htsize = 0;
  22903. pNew->ht = 0;
  22904. }
  22905. /* Remove all entries from a hash table. Reclaim all memory.
  22906. ** Call this routine to delete a hash table or to reset a hash table
  22907. ** to the empty state.
  22908. */
  22909. SQLITE_PRIVATE void sqlite3HashClear(Hash *pH){
  22910. HashElem *elem; /* For looping over all elements of the table */
  22911. assert( pH!=0 );
  22912. elem = pH->first;
  22913. pH->first = 0;
  22914. sqlite3_free(pH->ht);
  22915. pH->ht = 0;
  22916. pH->htsize = 0;
  22917. while( elem ){
  22918. HashElem *next_elem = elem->next;
  22919. sqlite3_free(elem);
  22920. elem = next_elem;
  22921. }
  22922. pH->count = 0;
  22923. }
  22924. /*
  22925. ** The hashing function.
  22926. */
  22927. static unsigned int strHash(const char *z){
  22928. unsigned int h = 0;
  22929. unsigned char c;
  22930. while( (c = (unsigned char)*z++)!=0 ){
  22931. h = (h<<3) ^ h ^ sqlite3UpperToLower[c];
  22932. }
  22933. return h;
  22934. }
  22935. /* Link pNew element into the hash table pH. If pEntry!=0 then also
  22936. ** insert pNew into the pEntry hash bucket.
  22937. */
  22938. static void insertElement(
  22939. Hash *pH, /* The complete hash table */
  22940. struct _ht *pEntry, /* The entry into which pNew is inserted */
  22941. HashElem *pNew /* The element to be inserted */
  22942. ){
  22943. HashElem *pHead; /* First element already in pEntry */
  22944. if( pEntry ){
  22945. pHead = pEntry->count ? pEntry->chain : 0;
  22946. pEntry->count++;
  22947. pEntry->chain = pNew;
  22948. }else{
  22949. pHead = 0;
  22950. }
  22951. if( pHead ){
  22952. pNew->next = pHead;
  22953. pNew->prev = pHead->prev;
  22954. if( pHead->prev ){ pHead->prev->next = pNew; }
  22955. else { pH->first = pNew; }
  22956. pHead->prev = pNew;
  22957. }else{
  22958. pNew->next = pH->first;
  22959. if( pH->first ){ pH->first->prev = pNew; }
  22960. pNew->prev = 0;
  22961. pH->first = pNew;
  22962. }
  22963. }
  22964. /* Resize the hash table so that it cantains "new_size" buckets.
  22965. **
  22966. ** The hash table might fail to resize if sqlite3_malloc() fails or
  22967. ** if the new size is the same as the prior size.
  22968. ** Return TRUE if the resize occurs and false if not.
  22969. */
  22970. static int rehash(Hash *pH, unsigned int new_size){
  22971. struct _ht *new_ht; /* The new hash table */
  22972. HashElem *elem, *next_elem; /* For looping over existing elements */
  22973. #if SQLITE_MALLOC_SOFT_LIMIT>0
  22974. if( new_size*sizeof(struct _ht)>SQLITE_MALLOC_SOFT_LIMIT ){
  22975. new_size = SQLITE_MALLOC_SOFT_LIMIT/sizeof(struct _ht);
  22976. }
  22977. if( new_size==pH->htsize ) return 0;
  22978. #endif
  22979. /* The inability to allocates space for a larger hash table is
  22980. ** a performance hit but it is not a fatal error. So mark the
  22981. ** allocation as a benign. Use sqlite3Malloc()/memset(0) instead of
  22982. ** sqlite3MallocZero() to make the allocation, as sqlite3MallocZero()
  22983. ** only zeroes the requested number of bytes whereas this module will
  22984. ** use the actual amount of space allocated for the hash table (which
  22985. ** may be larger than the requested amount).
  22986. */
  22987. sqlite3BeginBenignMalloc();
  22988. new_ht = (struct _ht *)sqlite3Malloc( new_size*sizeof(struct _ht) );
  22989. sqlite3EndBenignMalloc();
  22990. if( new_ht==0 ) return 0;
  22991. sqlite3_free(pH->ht);
  22992. pH->ht = new_ht;
  22993. pH->htsize = new_size = sqlite3MallocSize(new_ht)/sizeof(struct _ht);
  22994. memset(new_ht, 0, new_size*sizeof(struct _ht));
  22995. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  22996. unsigned int h = strHash(elem->pKey) % new_size;
  22997. next_elem = elem->next;
  22998. insertElement(pH, &new_ht[h], elem);
  22999. }
  23000. return 1;
  23001. }
  23002. /* This function (for internal use only) locates an element in an
  23003. ** hash table that matches the given key. The hash for this key is
  23004. ** also computed and returned in the *pH parameter.
  23005. */
  23006. static HashElem *findElementWithHash(
  23007. const Hash *pH, /* The pH to be searched */
  23008. const char *pKey, /* The key we are searching for */
  23009. unsigned int *pHash /* Write the hash value here */
  23010. ){
  23011. HashElem *elem; /* Used to loop thru the element list */
  23012. int count; /* Number of elements left to test */
  23013. unsigned int h; /* The computed hash */
  23014. if( pH->ht ){
  23015. struct _ht *pEntry;
  23016. h = strHash(pKey) % pH->htsize;
  23017. pEntry = &pH->ht[h];
  23018. elem = pEntry->chain;
  23019. count = pEntry->count;
  23020. }else{
  23021. h = 0;
  23022. elem = pH->first;
  23023. count = pH->count;
  23024. }
  23025. *pHash = h;
  23026. while( count-- ){
  23027. assert( elem!=0 );
  23028. if( sqlite3StrICmp(elem->pKey,pKey)==0 ){
  23029. return elem;
  23030. }
  23031. elem = elem->next;
  23032. }
  23033. return 0;
  23034. }
  23035. /* Remove a single entry from the hash table given a pointer to that
  23036. ** element and a hash on the element's key.
  23037. */
  23038. static void removeElementGivenHash(
  23039. Hash *pH, /* The pH containing "elem" */
  23040. HashElem* elem, /* The element to be removed from the pH */
  23041. unsigned int h /* Hash value for the element */
  23042. ){
  23043. struct _ht *pEntry;
  23044. if( elem->prev ){
  23045. elem->prev->next = elem->next;
  23046. }else{
  23047. pH->first = elem->next;
  23048. }
  23049. if( elem->next ){
  23050. elem->next->prev = elem->prev;
  23051. }
  23052. if( pH->ht ){
  23053. pEntry = &pH->ht[h];
  23054. if( pEntry->chain==elem ){
  23055. pEntry->chain = elem->next;
  23056. }
  23057. pEntry->count--;
  23058. assert( pEntry->count>=0 );
  23059. }
  23060. sqlite3_free( elem );
  23061. pH->count--;
  23062. if( pH->count==0 ){
  23063. assert( pH->first==0 );
  23064. assert( pH->count==0 );
  23065. sqlite3HashClear(pH);
  23066. }
  23067. }
  23068. /* Attempt to locate an element of the hash table pH with a key
  23069. ** that matches pKey. Return the data for this element if it is
  23070. ** found, or NULL if there is no match.
  23071. */
  23072. SQLITE_PRIVATE void *sqlite3HashFind(const Hash *pH, const char *pKey){
  23073. HashElem *elem; /* The element that matches key */
  23074. unsigned int h; /* A hash on key */
  23075. assert( pH!=0 );
  23076. assert( pKey!=0 );
  23077. elem = findElementWithHash(pH, pKey, &h);
  23078. return elem ? elem->data : 0;
  23079. }
  23080. /* Insert an element into the hash table pH. The key is pKey
  23081. ** and the data is "data".
  23082. **
  23083. ** If no element exists with a matching key, then a new
  23084. ** element is created and NULL is returned.
  23085. **
  23086. ** If another element already exists with the same key, then the
  23087. ** new data replaces the old data and the old data is returned.
  23088. ** The key is not copied in this instance. If a malloc fails, then
  23089. ** the new data is returned and the hash table is unchanged.
  23090. **
  23091. ** If the "data" parameter to this function is NULL, then the
  23092. ** element corresponding to "key" is removed from the hash table.
  23093. */
  23094. SQLITE_PRIVATE void *sqlite3HashInsert(Hash *pH, const char *pKey, void *data){
  23095. unsigned int h; /* the hash of the key modulo hash table size */
  23096. HashElem *elem; /* Used to loop thru the element list */
  23097. HashElem *new_elem; /* New element added to the pH */
  23098. assert( pH!=0 );
  23099. assert( pKey!=0 );
  23100. elem = findElementWithHash(pH,pKey,&h);
  23101. if( elem ){
  23102. void *old_data = elem->data;
  23103. if( data==0 ){
  23104. removeElementGivenHash(pH,elem,h);
  23105. }else{
  23106. elem->data = data;
  23107. elem->pKey = pKey;
  23108. }
  23109. return old_data;
  23110. }
  23111. if( data==0 ) return 0;
  23112. new_elem = (HashElem*)sqlite3Malloc( sizeof(HashElem) );
  23113. if( new_elem==0 ) return data;
  23114. new_elem->pKey = pKey;
  23115. new_elem->data = data;
  23116. pH->count++;
  23117. if( pH->count>=10 && pH->count > 2*pH->htsize ){
  23118. if( rehash(pH, pH->count*2) ){
  23119. assert( pH->htsize>0 );
  23120. h = strHash(pKey) % pH->htsize;
  23121. }
  23122. }
  23123. insertElement(pH, pH->ht ? &pH->ht[h] : 0, new_elem);
  23124. return 0;
  23125. }
  23126. /************** End of hash.c ************************************************/
  23127. /************** Begin file opcodes.c *****************************************/
  23128. /* Automatically generated. Do not edit */
  23129. /* See the mkopcodec.awk script for details. */
  23130. #if !defined(SQLITE_OMIT_EXPLAIN) || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  23131. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS) || defined(SQLITE_DEBUG)
  23132. # define OpHelp(X) "\0" X
  23133. #else
  23134. # define OpHelp(X)
  23135. #endif
  23136. SQLITE_PRIVATE const char *sqlite3OpcodeName(int i){
  23137. static const char *const azName[] = { "?",
  23138. /* 1 */ "Function" OpHelp("r[P3]=func(r[P2@P5])"),
  23139. /* 2 */ "Savepoint" OpHelp(""),
  23140. /* 3 */ "AutoCommit" OpHelp(""),
  23141. /* 4 */ "Transaction" OpHelp(""),
  23142. /* 5 */ "SorterNext" OpHelp(""),
  23143. /* 6 */ "PrevIfOpen" OpHelp(""),
  23144. /* 7 */ "NextIfOpen" OpHelp(""),
  23145. /* 8 */ "Prev" OpHelp(""),
  23146. /* 9 */ "Next" OpHelp(""),
  23147. /* 10 */ "AggStep" OpHelp("accum=r[P3] step(r[P2@P5])"),
  23148. /* 11 */ "Checkpoint" OpHelp(""),
  23149. /* 12 */ "JournalMode" OpHelp(""),
  23150. /* 13 */ "Vacuum" OpHelp(""),
  23151. /* 14 */ "VFilter" OpHelp("iplan=r[P3] zplan='P4'"),
  23152. /* 15 */ "VUpdate" OpHelp("data=r[P3@P2]"),
  23153. /* 16 */ "Goto" OpHelp(""),
  23154. /* 17 */ "Gosub" OpHelp(""),
  23155. /* 18 */ "Return" OpHelp(""),
  23156. /* 19 */ "Not" OpHelp("r[P2]= !r[P1]"),
  23157. /* 20 */ "InitCoroutine" OpHelp(""),
  23158. /* 21 */ "EndCoroutine" OpHelp(""),
  23159. /* 22 */ "Yield" OpHelp(""),
  23160. /* 23 */ "HaltIfNull" OpHelp("if r[P3]=null halt"),
  23161. /* 24 */ "Halt" OpHelp(""),
  23162. /* 25 */ "Integer" OpHelp("r[P2]=P1"),
  23163. /* 26 */ "Int64" OpHelp("r[P2]=P4"),
  23164. /* 27 */ "String" OpHelp("r[P2]='P4' (len=P1)"),
  23165. /* 28 */ "Null" OpHelp("r[P2..P3]=NULL"),
  23166. /* 29 */ "SoftNull" OpHelp("r[P1]=NULL"),
  23167. /* 30 */ "Blob" OpHelp("r[P2]=P4 (len=P1)"),
  23168. /* 31 */ "Variable" OpHelp("r[P2]=parameter(P1,P4)"),
  23169. /* 32 */ "Move" OpHelp("r[P2@P3]=r[P1@P3]"),
  23170. /* 33 */ "Copy" OpHelp("r[P2@P3+1]=r[P1@P3+1]"),
  23171. /* 34 */ "SCopy" OpHelp("r[P2]=r[P1]"),
  23172. /* 35 */ "ResultRow" OpHelp("output=r[P1@P2]"),
  23173. /* 36 */ "CollSeq" OpHelp(""),
  23174. /* 37 */ "AddImm" OpHelp("r[P1]=r[P1]+P2"),
  23175. /* 38 */ "MustBeInt" OpHelp(""),
  23176. /* 39 */ "RealAffinity" OpHelp(""),
  23177. /* 40 */ "Cast" OpHelp("affinity(r[P1])"),
  23178. /* 41 */ "Permutation" OpHelp(""),
  23179. /* 42 */ "Compare" OpHelp("r[P1@P3] <-> r[P2@P3]"),
  23180. /* 43 */ "Jump" OpHelp(""),
  23181. /* 44 */ "Once" OpHelp(""),
  23182. /* 45 */ "If" OpHelp(""),
  23183. /* 46 */ "IfNot" OpHelp(""),
  23184. /* 47 */ "Column" OpHelp("r[P3]=PX"),
  23185. /* 48 */ "Affinity" OpHelp("affinity(r[P1@P2])"),
  23186. /* 49 */ "MakeRecord" OpHelp("r[P3]=mkrec(r[P1@P2])"),
  23187. /* 50 */ "Count" OpHelp("r[P2]=count()"),
  23188. /* 51 */ "ReadCookie" OpHelp(""),
  23189. /* 52 */ "SetCookie" OpHelp(""),
  23190. /* 53 */ "ReopenIdx" OpHelp("root=P2 iDb=P3"),
  23191. /* 54 */ "OpenRead" OpHelp("root=P2 iDb=P3"),
  23192. /* 55 */ "OpenWrite" OpHelp("root=P2 iDb=P3"),
  23193. /* 56 */ "OpenAutoindex" OpHelp("nColumn=P2"),
  23194. /* 57 */ "OpenEphemeral" OpHelp("nColumn=P2"),
  23195. /* 58 */ "SorterOpen" OpHelp(""),
  23196. /* 59 */ "SequenceTest" OpHelp("if( cursor[P1].ctr++ ) pc = P2"),
  23197. /* 60 */ "OpenPseudo" OpHelp("P3 columns in r[P2]"),
  23198. /* 61 */ "Close" OpHelp(""),
  23199. /* 62 */ "SeekLT" OpHelp("key=r[P3@P4]"),
  23200. /* 63 */ "SeekLE" OpHelp("key=r[P3@P4]"),
  23201. /* 64 */ "SeekGE" OpHelp("key=r[P3@P4]"),
  23202. /* 65 */ "SeekGT" OpHelp("key=r[P3@P4]"),
  23203. /* 66 */ "Seek" OpHelp("intkey=r[P2]"),
  23204. /* 67 */ "NoConflict" OpHelp("key=r[P3@P4]"),
  23205. /* 68 */ "NotFound" OpHelp("key=r[P3@P4]"),
  23206. /* 69 */ "Found" OpHelp("key=r[P3@P4]"),
  23207. /* 70 */ "NotExists" OpHelp("intkey=r[P3]"),
  23208. /* 71 */ "Or" OpHelp("r[P3]=(r[P1] || r[P2])"),
  23209. /* 72 */ "And" OpHelp("r[P3]=(r[P1] && r[P2])"),
  23210. /* 73 */ "Sequence" OpHelp("r[P2]=cursor[P1].ctr++"),
  23211. /* 74 */ "NewRowid" OpHelp("r[P2]=rowid"),
  23212. /* 75 */ "Insert" OpHelp("intkey=r[P3] data=r[P2]"),
  23213. /* 76 */ "IsNull" OpHelp("if r[P1]==NULL goto P2"),
  23214. /* 77 */ "NotNull" OpHelp("if r[P1]!=NULL goto P2"),
  23215. /* 78 */ "Ne" OpHelp("if r[P1]!=r[P3] goto P2"),
  23216. /* 79 */ "Eq" OpHelp("if r[P1]==r[P3] goto P2"),
  23217. /* 80 */ "Gt" OpHelp("if r[P1]>r[P3] goto P2"),
  23218. /* 81 */ "Le" OpHelp("if r[P1]<=r[P3] goto P2"),
  23219. /* 82 */ "Lt" OpHelp("if r[P1]<r[P3] goto P2"),
  23220. /* 83 */ "Ge" OpHelp("if r[P1]>=r[P3] goto P2"),
  23221. /* 84 */ "InsertInt" OpHelp("intkey=P3 data=r[P2]"),
  23222. /* 85 */ "BitAnd" OpHelp("r[P3]=r[P1]&r[P2]"),
  23223. /* 86 */ "BitOr" OpHelp("r[P3]=r[P1]|r[P2]"),
  23224. /* 87 */ "ShiftLeft" OpHelp("r[P3]=r[P2]<<r[P1]"),
  23225. /* 88 */ "ShiftRight" OpHelp("r[P3]=r[P2]>>r[P1]"),
  23226. /* 89 */ "Add" OpHelp("r[P3]=r[P1]+r[P2]"),
  23227. /* 90 */ "Subtract" OpHelp("r[P3]=r[P2]-r[P1]"),
  23228. /* 91 */ "Multiply" OpHelp("r[P3]=r[P1]*r[P2]"),
  23229. /* 92 */ "Divide" OpHelp("r[P3]=r[P2]/r[P1]"),
  23230. /* 93 */ "Remainder" OpHelp("r[P3]=r[P2]%r[P1]"),
  23231. /* 94 */ "Concat" OpHelp("r[P3]=r[P2]+r[P1]"),
  23232. /* 95 */ "Delete" OpHelp(""),
  23233. /* 96 */ "BitNot" OpHelp("r[P1]= ~r[P1]"),
  23234. /* 97 */ "String8" OpHelp("r[P2]='P4'"),
  23235. /* 98 */ "ResetCount" OpHelp(""),
  23236. /* 99 */ "SorterCompare" OpHelp("if key(P1)!=trim(r[P3],P4) goto P2"),
  23237. /* 100 */ "SorterData" OpHelp("r[P2]=data"),
  23238. /* 101 */ "RowKey" OpHelp("r[P2]=key"),
  23239. /* 102 */ "RowData" OpHelp("r[P2]=data"),
  23240. /* 103 */ "Rowid" OpHelp("r[P2]=rowid"),
  23241. /* 104 */ "NullRow" OpHelp(""),
  23242. /* 105 */ "Last" OpHelp(""),
  23243. /* 106 */ "SorterSort" OpHelp(""),
  23244. /* 107 */ "Sort" OpHelp(""),
  23245. /* 108 */ "Rewind" OpHelp(""),
  23246. /* 109 */ "SorterInsert" OpHelp(""),
  23247. /* 110 */ "IdxInsert" OpHelp("key=r[P2]"),
  23248. /* 111 */ "IdxDelete" OpHelp("key=r[P2@P3]"),
  23249. /* 112 */ "IdxRowid" OpHelp("r[P2]=rowid"),
  23250. /* 113 */ "IdxLE" OpHelp("key=r[P3@P4]"),
  23251. /* 114 */ "IdxGT" OpHelp("key=r[P3@P4]"),
  23252. /* 115 */ "IdxLT" OpHelp("key=r[P3@P4]"),
  23253. /* 116 */ "IdxGE" OpHelp("key=r[P3@P4]"),
  23254. /* 117 */ "Destroy" OpHelp(""),
  23255. /* 118 */ "Clear" OpHelp(""),
  23256. /* 119 */ "ResetSorter" OpHelp(""),
  23257. /* 120 */ "CreateIndex" OpHelp("r[P2]=root iDb=P1"),
  23258. /* 121 */ "CreateTable" OpHelp("r[P2]=root iDb=P1"),
  23259. /* 122 */ "ParseSchema" OpHelp(""),
  23260. /* 123 */ "LoadAnalysis" OpHelp(""),
  23261. /* 124 */ "DropTable" OpHelp(""),
  23262. /* 125 */ "DropIndex" OpHelp(""),
  23263. /* 126 */ "DropTrigger" OpHelp(""),
  23264. /* 127 */ "IntegrityCk" OpHelp(""),
  23265. /* 128 */ "RowSetAdd" OpHelp("rowset(P1)=r[P2]"),
  23266. /* 129 */ "RowSetRead" OpHelp("r[P3]=rowset(P1)"),
  23267. /* 130 */ "RowSetTest" OpHelp("if r[P3] in rowset(P1) goto P2"),
  23268. /* 131 */ "Program" OpHelp(""),
  23269. /* 132 */ "Param" OpHelp(""),
  23270. /* 133 */ "Real" OpHelp("r[P2]=P4"),
  23271. /* 134 */ "FkCounter" OpHelp("fkctr[P1]+=P2"),
  23272. /* 135 */ "FkIfZero" OpHelp("if fkctr[P1]==0 goto P2"),
  23273. /* 136 */ "MemMax" OpHelp("r[P1]=max(r[P1],r[P2])"),
  23274. /* 137 */ "IfPos" OpHelp("if r[P1]>0 goto P2"),
  23275. /* 138 */ "IfNeg" OpHelp("r[P1]+=P3, if r[P1]<0 goto P2"),
  23276. /* 139 */ "IfZero" OpHelp("r[P1]+=P3, if r[P1]==0 goto P2"),
  23277. /* 140 */ "AggFinal" OpHelp("accum=r[P1] N=P2"),
  23278. /* 141 */ "IncrVacuum" OpHelp(""),
  23279. /* 142 */ "Expire" OpHelp(""),
  23280. /* 143 */ "TableLock" OpHelp("iDb=P1 root=P2 write=P3"),
  23281. /* 144 */ "VBegin" OpHelp(""),
  23282. /* 145 */ "VCreate" OpHelp(""),
  23283. /* 146 */ "VDestroy" OpHelp(""),
  23284. /* 147 */ "VOpen" OpHelp(""),
  23285. /* 148 */ "VColumn" OpHelp("r[P3]=vcolumn(P2)"),
  23286. /* 149 */ "VNext" OpHelp(""),
  23287. /* 150 */ "VRename" OpHelp(""),
  23288. /* 151 */ "Pagecount" OpHelp(""),
  23289. /* 152 */ "MaxPgcnt" OpHelp(""),
  23290. /* 153 */ "Init" OpHelp("Start at P2"),
  23291. /* 154 */ "Noop" OpHelp(""),
  23292. /* 155 */ "Explain" OpHelp(""),
  23293. };
  23294. return azName[i];
  23295. }
  23296. #endif
  23297. /************** End of opcodes.c *********************************************/
  23298. /************** Begin file os_unix.c *****************************************/
  23299. /*
  23300. ** 2004 May 22
  23301. **
  23302. ** The author disclaims copyright to this source code. In place of
  23303. ** a legal notice, here is a blessing:
  23304. **
  23305. ** May you do good and not evil.
  23306. ** May you find forgiveness for yourself and forgive others.
  23307. ** May you share freely, never taking more than you give.
  23308. **
  23309. ******************************************************************************
  23310. **
  23311. ** This file contains the VFS implementation for unix-like operating systems
  23312. ** include Linux, MacOSX, *BSD, QNX, VxWorks, AIX, HPUX, and others.
  23313. **
  23314. ** There are actually several different VFS implementations in this file.
  23315. ** The differences are in the way that file locking is done. The default
  23316. ** implementation uses Posix Advisory Locks. Alternative implementations
  23317. ** use flock(), dot-files, various proprietary locking schemas, or simply
  23318. ** skip locking all together.
  23319. **
  23320. ** This source file is organized into divisions where the logic for various
  23321. ** subfunctions is contained within the appropriate division. PLEASE
  23322. ** KEEP THE STRUCTURE OF THIS FILE INTACT. New code should be placed
  23323. ** in the correct division and should be clearly labeled.
  23324. **
  23325. ** The layout of divisions is as follows:
  23326. **
  23327. ** * General-purpose declarations and utility functions.
  23328. ** * Unique file ID logic used by VxWorks.
  23329. ** * Various locking primitive implementations (all except proxy locking):
  23330. ** + for Posix Advisory Locks
  23331. ** + for no-op locks
  23332. ** + for dot-file locks
  23333. ** + for flock() locking
  23334. ** + for named semaphore locks (VxWorks only)
  23335. ** + for AFP filesystem locks (MacOSX only)
  23336. ** * sqlite3_file methods not associated with locking.
  23337. ** * Definitions of sqlite3_io_methods objects for all locking
  23338. ** methods plus "finder" functions for each locking method.
  23339. ** * sqlite3_vfs method implementations.
  23340. ** * Locking primitives for the proxy uber-locking-method. (MacOSX only)
  23341. ** * Definitions of sqlite3_vfs objects for all locking methods
  23342. ** plus implementations of sqlite3_os_init() and sqlite3_os_end().
  23343. */
  23344. #if SQLITE_OS_UNIX /* This file is used on unix only */
  23345. /*
  23346. ** There are various methods for file locking used for concurrency
  23347. ** control:
  23348. **
  23349. ** 1. POSIX locking (the default),
  23350. ** 2. No locking,
  23351. ** 3. Dot-file locking,
  23352. ** 4. flock() locking,
  23353. ** 5. AFP locking (OSX only),
  23354. ** 6. Named POSIX semaphores (VXWorks only),
  23355. ** 7. proxy locking. (OSX only)
  23356. **
  23357. ** Styles 4, 5, and 7 are only available of SQLITE_ENABLE_LOCKING_STYLE
  23358. ** is defined to 1. The SQLITE_ENABLE_LOCKING_STYLE also enables automatic
  23359. ** selection of the appropriate locking style based on the filesystem
  23360. ** where the database is located.
  23361. */
  23362. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  23363. # if defined(__APPLE__)
  23364. # define SQLITE_ENABLE_LOCKING_STYLE 1
  23365. # else
  23366. # define SQLITE_ENABLE_LOCKING_STYLE 0
  23367. # endif
  23368. #endif
  23369. /*
  23370. ** Define the OS_VXWORKS pre-processor macro to 1 if building on
  23371. ** vxworks, or 0 otherwise.
  23372. */
  23373. #ifndef OS_VXWORKS
  23374. # if defined(__RTP__) || defined(_WRS_KERNEL)
  23375. # define OS_VXWORKS 1
  23376. # else
  23377. # define OS_VXWORKS 0
  23378. # endif
  23379. #endif
  23380. /*
  23381. ** standard include files.
  23382. */
  23383. #include <sys/types.h>
  23384. #include <sys/stat.h>
  23385. #include <fcntl.h>
  23386. #include <unistd.h>
  23387. /* #include <time.h> */
  23388. #include <sys/time.h>
  23389. #include <errno.h>
  23390. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  23391. # include <sys/mman.h>
  23392. #endif
  23393. #if SQLITE_ENABLE_LOCKING_STYLE || OS_VXWORKS
  23394. # include <sys/ioctl.h>
  23395. # if OS_VXWORKS
  23396. # include <semaphore.h>
  23397. # include <limits.h>
  23398. # else
  23399. # include <sys/file.h>
  23400. # include <sys/param.h>
  23401. # endif
  23402. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  23403. #if defined(__APPLE__) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  23404. # include <sys/mount.h>
  23405. #endif
  23406. #ifdef HAVE_UTIME
  23407. # include <utime.h>
  23408. #endif
  23409. /*
  23410. ** Allowed values of unixFile.fsFlags
  23411. */
  23412. #define SQLITE_FSFLAGS_IS_MSDOS 0x1
  23413. /*
  23414. ** If we are to be thread-safe, include the pthreads header and define
  23415. ** the SQLITE_UNIX_THREADS macro.
  23416. */
  23417. #if SQLITE_THREADSAFE
  23418. /* # include <pthread.h> */
  23419. # define SQLITE_UNIX_THREADS 1
  23420. #endif
  23421. /*
  23422. ** Default permissions when creating a new file
  23423. */
  23424. #ifndef SQLITE_DEFAULT_FILE_PERMISSIONS
  23425. # define SQLITE_DEFAULT_FILE_PERMISSIONS 0644
  23426. #endif
  23427. /*
  23428. ** Default permissions when creating auto proxy dir
  23429. */
  23430. #ifndef SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  23431. # define SQLITE_DEFAULT_PROXYDIR_PERMISSIONS 0755
  23432. #endif
  23433. /*
  23434. ** Maximum supported path-length.
  23435. */
  23436. #define MAX_PATHNAME 512
  23437. /*
  23438. ** Only set the lastErrno if the error code is a real error and not
  23439. ** a normal expected return code of SQLITE_BUSY or SQLITE_OK
  23440. */
  23441. #define IS_LOCK_ERROR(x) ((x != SQLITE_OK) && (x != SQLITE_BUSY))
  23442. /* Forward references */
  23443. typedef struct unixShm unixShm; /* Connection shared memory */
  23444. typedef struct unixShmNode unixShmNode; /* Shared memory instance */
  23445. typedef struct unixInodeInfo unixInodeInfo; /* An i-node */
  23446. typedef struct UnixUnusedFd UnixUnusedFd; /* An unused file descriptor */
  23447. /*
  23448. ** Sometimes, after a file handle is closed by SQLite, the file descriptor
  23449. ** cannot be closed immediately. In these cases, instances of the following
  23450. ** structure are used to store the file descriptor while waiting for an
  23451. ** opportunity to either close or reuse it.
  23452. */
  23453. struct UnixUnusedFd {
  23454. int fd; /* File descriptor to close */
  23455. int flags; /* Flags this file descriptor was opened with */
  23456. UnixUnusedFd *pNext; /* Next unused file descriptor on same file */
  23457. };
  23458. /*
  23459. ** The unixFile structure is subclass of sqlite3_file specific to the unix
  23460. ** VFS implementations.
  23461. */
  23462. typedef struct unixFile unixFile;
  23463. struct unixFile {
  23464. sqlite3_io_methods const *pMethod; /* Always the first entry */
  23465. sqlite3_vfs *pVfs; /* The VFS that created this unixFile */
  23466. unixInodeInfo *pInode; /* Info about locks on this inode */
  23467. int h; /* The file descriptor */
  23468. unsigned char eFileLock; /* The type of lock held on this fd */
  23469. unsigned short int ctrlFlags; /* Behavioral bits. UNIXFILE_* flags */
  23470. int lastErrno; /* The unix errno from last I/O error */
  23471. void *lockingContext; /* Locking style specific state */
  23472. UnixUnusedFd *pUnused; /* Pre-allocated UnixUnusedFd */
  23473. const char *zPath; /* Name of the file */
  23474. unixShm *pShm; /* Shared memory segment information */
  23475. int szChunk; /* Configured by FCNTL_CHUNK_SIZE */
  23476. #if SQLITE_MAX_MMAP_SIZE>0
  23477. int nFetchOut; /* Number of outstanding xFetch refs */
  23478. sqlite3_int64 mmapSize; /* Usable size of mapping at pMapRegion */
  23479. sqlite3_int64 mmapSizeActual; /* Actual size of mapping at pMapRegion */
  23480. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  23481. void *pMapRegion; /* Memory mapped region */
  23482. #endif
  23483. #ifdef __QNXNTO__
  23484. int sectorSize; /* Device sector size */
  23485. int deviceCharacteristics; /* Precomputed device characteristics */
  23486. #endif
  23487. #if SQLITE_ENABLE_LOCKING_STYLE
  23488. int openFlags; /* The flags specified at open() */
  23489. #endif
  23490. #if SQLITE_ENABLE_LOCKING_STYLE || defined(__APPLE__)
  23491. unsigned fsFlags; /* cached details from statfs() */
  23492. #endif
  23493. #if OS_VXWORKS
  23494. struct vxworksFileId *pId; /* Unique file ID */
  23495. #endif
  23496. #ifdef SQLITE_DEBUG
  23497. /* The next group of variables are used to track whether or not the
  23498. ** transaction counter in bytes 24-27 of database files are updated
  23499. ** whenever any part of the database changes. An assertion fault will
  23500. ** occur if a file is updated without also updating the transaction
  23501. ** counter. This test is made to avoid new problems similar to the
  23502. ** one described by ticket #3584.
  23503. */
  23504. unsigned char transCntrChng; /* True if the transaction counter changed */
  23505. unsigned char dbUpdate; /* True if any part of database file changed */
  23506. unsigned char inNormalWrite; /* True if in a normal write operation */
  23507. #endif
  23508. #ifdef SQLITE_TEST
  23509. /* In test mode, increase the size of this structure a bit so that
  23510. ** it is larger than the struct CrashFile defined in test6.c.
  23511. */
  23512. char aPadding[32];
  23513. #endif
  23514. };
  23515. /* This variable holds the process id (pid) from when the xRandomness()
  23516. ** method was called. If xOpen() is called from a different process id,
  23517. ** indicating that a fork() has occurred, the PRNG will be reset.
  23518. */
  23519. static int randomnessPid = 0;
  23520. /*
  23521. ** Allowed values for the unixFile.ctrlFlags bitmask:
  23522. */
  23523. #define UNIXFILE_EXCL 0x01 /* Connections from one process only */
  23524. #define UNIXFILE_RDONLY 0x02 /* Connection is read only */
  23525. #define UNIXFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  23526. #ifndef SQLITE_DISABLE_DIRSYNC
  23527. # define UNIXFILE_DIRSYNC 0x08 /* Directory sync needed */
  23528. #else
  23529. # define UNIXFILE_DIRSYNC 0x00
  23530. #endif
  23531. #define UNIXFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  23532. #define UNIXFILE_DELETE 0x20 /* Delete on close */
  23533. #define UNIXFILE_URI 0x40 /* Filename might have query parameters */
  23534. #define UNIXFILE_NOLOCK 0x80 /* Do no file locking */
  23535. #define UNIXFILE_WARNED 0x0100 /* verifyDbFile() warnings have been issued */
  23536. /*
  23537. ** Include code that is common to all os_*.c files
  23538. */
  23539. /************** Include os_common.h in the middle of os_unix.c ***************/
  23540. /************** Begin file os_common.h ***************************************/
  23541. /*
  23542. ** 2004 May 22
  23543. **
  23544. ** The author disclaims copyright to this source code. In place of
  23545. ** a legal notice, here is a blessing:
  23546. **
  23547. ** May you do good and not evil.
  23548. ** May you find forgiveness for yourself and forgive others.
  23549. ** May you share freely, never taking more than you give.
  23550. **
  23551. ******************************************************************************
  23552. **
  23553. ** This file contains macros and a little bit of code that is common to
  23554. ** all of the platform-specific files (os_*.c) and is #included into those
  23555. ** files.
  23556. **
  23557. ** This file should be #included by the os_*.c files only. It is not a
  23558. ** general purpose header file.
  23559. */
  23560. #ifndef _OS_COMMON_H_
  23561. #define _OS_COMMON_H_
  23562. /*
  23563. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  23564. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  23565. ** switch. The following code should catch this problem at compile-time.
  23566. */
  23567. #ifdef MEMORY_DEBUG
  23568. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  23569. #endif
  23570. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  23571. # ifndef SQLITE_DEBUG_OS_TRACE
  23572. # define SQLITE_DEBUG_OS_TRACE 0
  23573. # endif
  23574. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  23575. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  23576. #else
  23577. # define OSTRACE(X)
  23578. #endif
  23579. /*
  23580. ** Macros for performance tracing. Normally turned off. Only works
  23581. ** on i486 hardware.
  23582. */
  23583. #ifdef SQLITE_PERFORMANCE_TRACE
  23584. /*
  23585. ** hwtime.h contains inline assembler code for implementing
  23586. ** high-performance timing routines.
  23587. */
  23588. /************** Include hwtime.h in the middle of os_common.h ****************/
  23589. /************** Begin file hwtime.h ******************************************/
  23590. /*
  23591. ** 2008 May 27
  23592. **
  23593. ** The author disclaims copyright to this source code. In place of
  23594. ** a legal notice, here is a blessing:
  23595. **
  23596. ** May you do good and not evil.
  23597. ** May you find forgiveness for yourself and forgive others.
  23598. ** May you share freely, never taking more than you give.
  23599. **
  23600. ******************************************************************************
  23601. **
  23602. ** This file contains inline asm code for retrieving "high-performance"
  23603. ** counters for x86 class CPUs.
  23604. */
  23605. #ifndef _HWTIME_H_
  23606. #define _HWTIME_H_
  23607. /*
  23608. ** The following routine only works on pentium-class (or newer) processors.
  23609. ** It uses the RDTSC opcode to read the cycle count value out of the
  23610. ** processor and returns that value. This can be used for high-res
  23611. ** profiling.
  23612. */
  23613. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  23614. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  23615. #if defined(__GNUC__)
  23616. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23617. unsigned int lo, hi;
  23618. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  23619. return (sqlite_uint64)hi << 32 | lo;
  23620. }
  23621. #elif defined(_MSC_VER)
  23622. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  23623. __asm {
  23624. rdtsc
  23625. ret ; return value at EDX:EAX
  23626. }
  23627. }
  23628. #endif
  23629. #elif (defined(__GNUC__) && defined(__x86_64__))
  23630. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23631. unsigned long val;
  23632. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  23633. return val;
  23634. }
  23635. #elif (defined(__GNUC__) && defined(__ppc__))
  23636. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  23637. unsigned long long retval;
  23638. unsigned long junk;
  23639. __asm__ __volatile__ ("\n\
  23640. 1: mftbu %1\n\
  23641. mftb %L0\n\
  23642. mftbu %0\n\
  23643. cmpw %0,%1\n\
  23644. bne 1b"
  23645. : "=r" (retval), "=r" (junk));
  23646. return retval;
  23647. }
  23648. #else
  23649. #error Need implementation of sqlite3Hwtime() for your platform.
  23650. /*
  23651. ** To compile without implementing sqlite3Hwtime() for your platform,
  23652. ** you can remove the above #error and use the following
  23653. ** stub function. You will lose timing support for many
  23654. ** of the debugging and testing utilities, but it should at
  23655. ** least compile and run.
  23656. */
  23657. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  23658. #endif
  23659. #endif /* !defined(_HWTIME_H_) */
  23660. /************** End of hwtime.h **********************************************/
  23661. /************** Continuing where we left off in os_common.h ******************/
  23662. static sqlite_uint64 g_start;
  23663. static sqlite_uint64 g_elapsed;
  23664. #define TIMER_START g_start=sqlite3Hwtime()
  23665. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  23666. #define TIMER_ELAPSED g_elapsed
  23667. #else
  23668. #define TIMER_START
  23669. #define TIMER_END
  23670. #define TIMER_ELAPSED ((sqlite_uint64)0)
  23671. #endif
  23672. /*
  23673. ** If we compile with the SQLITE_TEST macro set, then the following block
  23674. ** of code will give us the ability to simulate a disk I/O error. This
  23675. ** is used for testing the I/O recovery logic.
  23676. */
  23677. #ifdef SQLITE_TEST
  23678. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  23679. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  23680. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  23681. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  23682. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  23683. SQLITE_API int sqlite3_diskfull_pending = 0;
  23684. SQLITE_API int sqlite3_diskfull = 0;
  23685. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  23686. #define SimulateIOError(CODE) \
  23687. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  23688. || sqlite3_io_error_pending-- == 1 ) \
  23689. { local_ioerr(); CODE; }
  23690. static void local_ioerr(){
  23691. IOTRACE(("IOERR\n"));
  23692. sqlite3_io_error_hit++;
  23693. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  23694. }
  23695. #define SimulateDiskfullError(CODE) \
  23696. if( sqlite3_diskfull_pending ){ \
  23697. if( sqlite3_diskfull_pending == 1 ){ \
  23698. local_ioerr(); \
  23699. sqlite3_diskfull = 1; \
  23700. sqlite3_io_error_hit = 1; \
  23701. CODE; \
  23702. }else{ \
  23703. sqlite3_diskfull_pending--; \
  23704. } \
  23705. }
  23706. #else
  23707. #define SimulateIOErrorBenign(X)
  23708. #define SimulateIOError(A)
  23709. #define SimulateDiskfullError(A)
  23710. #endif
  23711. /*
  23712. ** When testing, keep a count of the number of open files.
  23713. */
  23714. #ifdef SQLITE_TEST
  23715. SQLITE_API int sqlite3_open_file_count = 0;
  23716. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  23717. #else
  23718. #define OpenCounter(X)
  23719. #endif
  23720. #endif /* !defined(_OS_COMMON_H_) */
  23721. /************** End of os_common.h *******************************************/
  23722. /************** Continuing where we left off in os_unix.c ********************/
  23723. /*
  23724. ** Define various macros that are missing from some systems.
  23725. */
  23726. #ifndef O_LARGEFILE
  23727. # define O_LARGEFILE 0
  23728. #endif
  23729. #ifdef SQLITE_DISABLE_LFS
  23730. # undef O_LARGEFILE
  23731. # define O_LARGEFILE 0
  23732. #endif
  23733. #ifndef O_NOFOLLOW
  23734. # define O_NOFOLLOW 0
  23735. #endif
  23736. #ifndef O_BINARY
  23737. # define O_BINARY 0
  23738. #endif
  23739. /*
  23740. ** The threadid macro resolves to the thread-id or to 0. Used for
  23741. ** testing and debugging only.
  23742. */
  23743. #if SQLITE_THREADSAFE
  23744. #define threadid pthread_self()
  23745. #else
  23746. #define threadid 0
  23747. #endif
  23748. /*
  23749. ** HAVE_MREMAP defaults to true on Linux and false everywhere else.
  23750. */
  23751. #if !defined(HAVE_MREMAP)
  23752. # if defined(__linux__) && defined(_GNU_SOURCE)
  23753. # define HAVE_MREMAP 1
  23754. # else
  23755. # define HAVE_MREMAP 0
  23756. # endif
  23757. #endif
  23758. /*
  23759. ** Explicitly call the 64-bit version of lseek() on Android. Otherwise, lseek()
  23760. ** is the 32-bit version, even if _FILE_OFFSET_BITS=64 is defined.
  23761. */
  23762. #ifdef __ANDROID__
  23763. # define lseek lseek64
  23764. #endif
  23765. /*
  23766. ** Different Unix systems declare open() in different ways. Same use
  23767. ** open(const char*,int,mode_t). Others use open(const char*,int,...).
  23768. ** The difference is important when using a pointer to the function.
  23769. **
  23770. ** The safest way to deal with the problem is to always use this wrapper
  23771. ** which always has the same well-defined interface.
  23772. */
  23773. static int posixOpen(const char *zFile, int flags, int mode){
  23774. return open(zFile, flags, mode);
  23775. }
  23776. /*
  23777. ** On some systems, calls to fchown() will trigger a message in a security
  23778. ** log if they come from non-root processes. So avoid calling fchown() if
  23779. ** we are not running as root.
  23780. */
  23781. static int posixFchown(int fd, uid_t uid, gid_t gid){
  23782. #if OS_VXWORKS
  23783. return 0;
  23784. #else
  23785. return geteuid() ? 0 : fchown(fd,uid,gid);
  23786. #endif
  23787. }
  23788. /* Forward reference */
  23789. static int openDirectory(const char*, int*);
  23790. static int unixGetpagesize(void);
  23791. /*
  23792. ** Many system calls are accessed through pointer-to-functions so that
  23793. ** they may be overridden at runtime to facilitate fault injection during
  23794. ** testing and sandboxing. The following array holds the names and pointers
  23795. ** to all overrideable system calls.
  23796. */
  23797. static struct unix_syscall {
  23798. const char *zName; /* Name of the system call */
  23799. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  23800. sqlite3_syscall_ptr pDefault; /* Default value */
  23801. } aSyscall[] = {
  23802. { "open", (sqlite3_syscall_ptr)posixOpen, 0 },
  23803. #define osOpen ((int(*)(const char*,int,int))aSyscall[0].pCurrent)
  23804. { "close", (sqlite3_syscall_ptr)close, 0 },
  23805. #define osClose ((int(*)(int))aSyscall[1].pCurrent)
  23806. { "access", (sqlite3_syscall_ptr)access, 0 },
  23807. #define osAccess ((int(*)(const char*,int))aSyscall[2].pCurrent)
  23808. { "getcwd", (sqlite3_syscall_ptr)getcwd, 0 },
  23809. #define osGetcwd ((char*(*)(char*,size_t))aSyscall[3].pCurrent)
  23810. { "stat", (sqlite3_syscall_ptr)stat, 0 },
  23811. #define osStat ((int(*)(const char*,struct stat*))aSyscall[4].pCurrent)
  23812. /*
  23813. ** The DJGPP compiler environment looks mostly like Unix, but it
  23814. ** lacks the fcntl() system call. So redefine fcntl() to be something
  23815. ** that always succeeds. This means that locking does not occur under
  23816. ** DJGPP. But it is DOS - what did you expect?
  23817. */
  23818. #ifdef __DJGPP__
  23819. { "fstat", 0, 0 },
  23820. #define osFstat(a,b,c) 0
  23821. #else
  23822. { "fstat", (sqlite3_syscall_ptr)fstat, 0 },
  23823. #define osFstat ((int(*)(int,struct stat*))aSyscall[5].pCurrent)
  23824. #endif
  23825. { "ftruncate", (sqlite3_syscall_ptr)ftruncate, 0 },
  23826. #define osFtruncate ((int(*)(int,off_t))aSyscall[6].pCurrent)
  23827. { "fcntl", (sqlite3_syscall_ptr)fcntl, 0 },
  23828. #define osFcntl ((int(*)(int,int,...))aSyscall[7].pCurrent)
  23829. { "read", (sqlite3_syscall_ptr)read, 0 },
  23830. #define osRead ((ssize_t(*)(int,void*,size_t))aSyscall[8].pCurrent)
  23831. #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  23832. { "pread", (sqlite3_syscall_ptr)pread, 0 },
  23833. #else
  23834. { "pread", (sqlite3_syscall_ptr)0, 0 },
  23835. #endif
  23836. #define osPread ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[9].pCurrent)
  23837. #if defined(USE_PREAD64)
  23838. { "pread64", (sqlite3_syscall_ptr)pread64, 0 },
  23839. #else
  23840. { "pread64", (sqlite3_syscall_ptr)0, 0 },
  23841. #endif
  23842. #define osPread64 ((ssize_t(*)(int,void*,size_t,off_t))aSyscall[10].pCurrent)
  23843. { "write", (sqlite3_syscall_ptr)write, 0 },
  23844. #define osWrite ((ssize_t(*)(int,const void*,size_t))aSyscall[11].pCurrent)
  23845. #if defined(USE_PREAD) || (SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS)
  23846. { "pwrite", (sqlite3_syscall_ptr)pwrite, 0 },
  23847. #else
  23848. { "pwrite", (sqlite3_syscall_ptr)0, 0 },
  23849. #endif
  23850. #define osPwrite ((ssize_t(*)(int,const void*,size_t,off_t))\
  23851. aSyscall[12].pCurrent)
  23852. #if defined(USE_PREAD64)
  23853. { "pwrite64", (sqlite3_syscall_ptr)pwrite64, 0 },
  23854. #else
  23855. { "pwrite64", (sqlite3_syscall_ptr)0, 0 },
  23856. #endif
  23857. #define osPwrite64 ((ssize_t(*)(int,const void*,size_t,off_t))\
  23858. aSyscall[13].pCurrent)
  23859. { "fchmod", (sqlite3_syscall_ptr)fchmod, 0 },
  23860. #define osFchmod ((int(*)(int,mode_t))aSyscall[14].pCurrent)
  23861. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  23862. { "fallocate", (sqlite3_syscall_ptr)posix_fallocate, 0 },
  23863. #else
  23864. { "fallocate", (sqlite3_syscall_ptr)0, 0 },
  23865. #endif
  23866. #define osFallocate ((int(*)(int,off_t,off_t))aSyscall[15].pCurrent)
  23867. { "unlink", (sqlite3_syscall_ptr)unlink, 0 },
  23868. #define osUnlink ((int(*)(const char*))aSyscall[16].pCurrent)
  23869. { "openDirectory", (sqlite3_syscall_ptr)openDirectory, 0 },
  23870. #define osOpenDirectory ((int(*)(const char*,int*))aSyscall[17].pCurrent)
  23871. { "mkdir", (sqlite3_syscall_ptr)mkdir, 0 },
  23872. #define osMkdir ((int(*)(const char*,mode_t))aSyscall[18].pCurrent)
  23873. { "rmdir", (sqlite3_syscall_ptr)rmdir, 0 },
  23874. #define osRmdir ((int(*)(const char*))aSyscall[19].pCurrent)
  23875. { "fchown", (sqlite3_syscall_ptr)posixFchown, 0 },
  23876. #define osFchown ((int(*)(int,uid_t,gid_t))aSyscall[20].pCurrent)
  23877. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  23878. { "mmap", (sqlite3_syscall_ptr)mmap, 0 },
  23879. #define osMmap ((void*(*)(void*,size_t,int,int,int,off_t))aSyscall[21].pCurrent)
  23880. { "munmap", (sqlite3_syscall_ptr)munmap, 0 },
  23881. #define osMunmap ((void*(*)(void*,size_t))aSyscall[22].pCurrent)
  23882. #if HAVE_MREMAP
  23883. { "mremap", (sqlite3_syscall_ptr)mremap, 0 },
  23884. #else
  23885. { "mremap", (sqlite3_syscall_ptr)0, 0 },
  23886. #endif
  23887. #define osMremap ((void*(*)(void*,size_t,size_t,int,...))aSyscall[23].pCurrent)
  23888. { "getpagesize", (sqlite3_syscall_ptr)unixGetpagesize, 0 },
  23889. #define osGetpagesize ((int(*)(void))aSyscall[24].pCurrent)
  23890. #endif
  23891. }; /* End of the overrideable system calls */
  23892. /*
  23893. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  23894. ** "unix" VFSes. Return SQLITE_OK opon successfully updating the
  23895. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  23896. ** system call named zName.
  23897. */
  23898. static int unixSetSystemCall(
  23899. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  23900. const char *zName, /* Name of system call to override */
  23901. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  23902. ){
  23903. unsigned int i;
  23904. int rc = SQLITE_NOTFOUND;
  23905. UNUSED_PARAMETER(pNotUsed);
  23906. if( zName==0 ){
  23907. /* If no zName is given, restore all system calls to their default
  23908. ** settings and return NULL
  23909. */
  23910. rc = SQLITE_OK;
  23911. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23912. if( aSyscall[i].pDefault ){
  23913. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  23914. }
  23915. }
  23916. }else{
  23917. /* If zName is specified, operate on only the one system call
  23918. ** specified.
  23919. */
  23920. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23921. if( strcmp(zName, aSyscall[i].zName)==0 ){
  23922. if( aSyscall[i].pDefault==0 ){
  23923. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  23924. }
  23925. rc = SQLITE_OK;
  23926. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  23927. aSyscall[i].pCurrent = pNewFunc;
  23928. break;
  23929. }
  23930. }
  23931. }
  23932. return rc;
  23933. }
  23934. /*
  23935. ** Return the value of a system call. Return NULL if zName is not a
  23936. ** recognized system call name. NULL is also returned if the system call
  23937. ** is currently undefined.
  23938. */
  23939. static sqlite3_syscall_ptr unixGetSystemCall(
  23940. sqlite3_vfs *pNotUsed,
  23941. const char *zName
  23942. ){
  23943. unsigned int i;
  23944. UNUSED_PARAMETER(pNotUsed);
  23945. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  23946. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  23947. }
  23948. return 0;
  23949. }
  23950. /*
  23951. ** Return the name of the first system call after zName. If zName==NULL
  23952. ** then return the name of the first system call. Return NULL if zName
  23953. ** is the last system call or if zName is not the name of a valid
  23954. ** system call.
  23955. */
  23956. static const char *unixNextSystemCall(sqlite3_vfs *p, const char *zName){
  23957. int i = -1;
  23958. UNUSED_PARAMETER(p);
  23959. if( zName ){
  23960. for(i=0; i<ArraySize(aSyscall)-1; i++){
  23961. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  23962. }
  23963. }
  23964. for(i++; i<ArraySize(aSyscall); i++){
  23965. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  23966. }
  23967. return 0;
  23968. }
  23969. /*
  23970. ** Do not accept any file descriptor less than this value, in order to avoid
  23971. ** opening database file using file descriptors that are commonly used for
  23972. ** standard input, output, and error.
  23973. */
  23974. #ifndef SQLITE_MINIMUM_FILE_DESCRIPTOR
  23975. # define SQLITE_MINIMUM_FILE_DESCRIPTOR 3
  23976. #endif
  23977. /*
  23978. ** Invoke open(). Do so multiple times, until it either succeeds or
  23979. ** fails for some reason other than EINTR.
  23980. **
  23981. ** If the file creation mode "m" is 0 then set it to the default for
  23982. ** SQLite. The default is SQLITE_DEFAULT_FILE_PERMISSIONS (normally
  23983. ** 0644) as modified by the system umask. If m is not 0, then
  23984. ** make the file creation mode be exactly m ignoring the umask.
  23985. **
  23986. ** The m parameter will be non-zero only when creating -wal, -journal,
  23987. ** and -shm files. We want those files to have *exactly* the same
  23988. ** permissions as their original database, unadulterated by the umask.
  23989. ** In that way, if a database file is -rw-rw-rw or -rw-rw-r-, and a
  23990. ** transaction crashes and leaves behind hot journals, then any
  23991. ** process that is able to write to the database will also be able to
  23992. ** recover the hot journals.
  23993. */
  23994. static int robust_open(const char *z, int f, mode_t m){
  23995. int fd;
  23996. mode_t m2 = m ? m : SQLITE_DEFAULT_FILE_PERMISSIONS;
  23997. while(1){
  23998. #if defined(O_CLOEXEC)
  23999. fd = osOpen(z,f|O_CLOEXEC,m2);
  24000. #else
  24001. fd = osOpen(z,f,m2);
  24002. #endif
  24003. if( fd<0 ){
  24004. if( errno==EINTR ) continue;
  24005. break;
  24006. }
  24007. if( fd>=SQLITE_MINIMUM_FILE_DESCRIPTOR ) break;
  24008. osClose(fd);
  24009. sqlite3_log(SQLITE_WARNING,
  24010. "attempt to open \"%s\" as file descriptor %d", z, fd);
  24011. fd = -1;
  24012. if( osOpen("/dev/null", f, m)<0 ) break;
  24013. }
  24014. if( fd>=0 ){
  24015. if( m!=0 ){
  24016. struct stat statbuf;
  24017. if( osFstat(fd, &statbuf)==0
  24018. && statbuf.st_size==0
  24019. && (statbuf.st_mode&0777)!=m
  24020. ){
  24021. osFchmod(fd, m);
  24022. }
  24023. }
  24024. #if defined(FD_CLOEXEC) && (!defined(O_CLOEXEC) || O_CLOEXEC==0)
  24025. osFcntl(fd, F_SETFD, osFcntl(fd, F_GETFD, 0) | FD_CLOEXEC);
  24026. #endif
  24027. }
  24028. return fd;
  24029. }
  24030. /*
  24031. ** Helper functions to obtain and relinquish the global mutex. The
  24032. ** global mutex is used to protect the unixInodeInfo and
  24033. ** vxworksFileId objects used by this file, all of which may be
  24034. ** shared by multiple threads.
  24035. **
  24036. ** Function unixMutexHeld() is used to assert() that the global mutex
  24037. ** is held when required. This function is only used as part of assert()
  24038. ** statements. e.g.
  24039. **
  24040. ** unixEnterMutex()
  24041. ** assert( unixMutexHeld() );
  24042. ** unixEnterLeave()
  24043. */
  24044. static void unixEnterMutex(void){
  24045. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24046. }
  24047. static void unixLeaveMutex(void){
  24048. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24049. }
  24050. #ifdef SQLITE_DEBUG
  24051. static int unixMutexHeld(void) {
  24052. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  24053. }
  24054. #endif
  24055. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  24056. /*
  24057. ** Helper function for printing out trace information from debugging
  24058. ** binaries. This returns the string representation of the supplied
  24059. ** integer lock-type.
  24060. */
  24061. static const char *azFileLock(int eFileLock){
  24062. switch( eFileLock ){
  24063. case NO_LOCK: return "NONE";
  24064. case SHARED_LOCK: return "SHARED";
  24065. case RESERVED_LOCK: return "RESERVED";
  24066. case PENDING_LOCK: return "PENDING";
  24067. case EXCLUSIVE_LOCK: return "EXCLUSIVE";
  24068. }
  24069. return "ERROR";
  24070. }
  24071. #endif
  24072. #ifdef SQLITE_LOCK_TRACE
  24073. /*
  24074. ** Print out information about all locking operations.
  24075. **
  24076. ** This routine is used for troubleshooting locks on multithreaded
  24077. ** platforms. Enable by compiling with the -DSQLITE_LOCK_TRACE
  24078. ** command-line option on the compiler. This code is normally
  24079. ** turned off.
  24080. */
  24081. static int lockTrace(int fd, int op, struct flock *p){
  24082. char *zOpName, *zType;
  24083. int s;
  24084. int savedErrno;
  24085. if( op==F_GETLK ){
  24086. zOpName = "GETLK";
  24087. }else if( op==F_SETLK ){
  24088. zOpName = "SETLK";
  24089. }else{
  24090. s = osFcntl(fd, op, p);
  24091. sqlite3DebugPrintf("fcntl unknown %d %d %d\n", fd, op, s);
  24092. return s;
  24093. }
  24094. if( p->l_type==F_RDLCK ){
  24095. zType = "RDLCK";
  24096. }else if( p->l_type==F_WRLCK ){
  24097. zType = "WRLCK";
  24098. }else if( p->l_type==F_UNLCK ){
  24099. zType = "UNLCK";
  24100. }else{
  24101. assert( 0 );
  24102. }
  24103. assert( p->l_whence==SEEK_SET );
  24104. s = osFcntl(fd, op, p);
  24105. savedErrno = errno;
  24106. sqlite3DebugPrintf("fcntl %d %d %s %s %d %d %d %d\n",
  24107. threadid, fd, zOpName, zType, (int)p->l_start, (int)p->l_len,
  24108. (int)p->l_pid, s);
  24109. if( s==(-1) && op==F_SETLK && (p->l_type==F_RDLCK || p->l_type==F_WRLCK) ){
  24110. struct flock l2;
  24111. l2 = *p;
  24112. osFcntl(fd, F_GETLK, &l2);
  24113. if( l2.l_type==F_RDLCK ){
  24114. zType = "RDLCK";
  24115. }else if( l2.l_type==F_WRLCK ){
  24116. zType = "WRLCK";
  24117. }else if( l2.l_type==F_UNLCK ){
  24118. zType = "UNLCK";
  24119. }else{
  24120. assert( 0 );
  24121. }
  24122. sqlite3DebugPrintf("fcntl-failure-reason: %s %d %d %d\n",
  24123. zType, (int)l2.l_start, (int)l2.l_len, (int)l2.l_pid);
  24124. }
  24125. errno = savedErrno;
  24126. return s;
  24127. }
  24128. #undef osFcntl
  24129. #define osFcntl lockTrace
  24130. #endif /* SQLITE_LOCK_TRACE */
  24131. /*
  24132. ** Retry ftruncate() calls that fail due to EINTR
  24133. **
  24134. ** All calls to ftruncate() within this file should be made through this wrapper.
  24135. ** On the Android platform, bypassing the logic below could lead to a corrupt
  24136. ** database.
  24137. */
  24138. static int robust_ftruncate(int h, sqlite3_int64 sz){
  24139. int rc;
  24140. #ifdef __ANDROID__
  24141. /* On Android, ftruncate() always uses 32-bit offsets, even if
  24142. ** _FILE_OFFSET_BITS=64 is defined. This means it is unsafe to attempt to
  24143. ** truncate a file to any size larger than 2GiB. Silently ignore any
  24144. ** such attempts. */
  24145. if( sz>(sqlite3_int64)0x7FFFFFFF ){
  24146. rc = SQLITE_OK;
  24147. }else
  24148. #endif
  24149. do{ rc = osFtruncate(h,sz); }while( rc<0 && errno==EINTR );
  24150. return rc;
  24151. }
  24152. /*
  24153. ** This routine translates a standard POSIX errno code into something
  24154. ** useful to the clients of the sqlite3 functions. Specifically, it is
  24155. ** intended to translate a variety of "try again" errors into SQLITE_BUSY
  24156. ** and a variety of "please close the file descriptor NOW" errors into
  24157. ** SQLITE_IOERR
  24158. **
  24159. ** Errors during initialization of locks, or file system support for locks,
  24160. ** should handle ENOLCK, ENOTSUP, EOPNOTSUPP separately.
  24161. */
  24162. static int sqliteErrorFromPosixError(int posixError, int sqliteIOErr) {
  24163. switch (posixError) {
  24164. #if 0
  24165. /* At one point this code was not commented out. In theory, this branch
  24166. ** should never be hit, as this function should only be called after
  24167. ** a locking-related function (i.e. fcntl()) has returned non-zero with
  24168. ** the value of errno as the first argument. Since a system call has failed,
  24169. ** errno should be non-zero.
  24170. **
  24171. ** Despite this, if errno really is zero, we still don't want to return
  24172. ** SQLITE_OK. The system call failed, and *some* SQLite error should be
  24173. ** propagated back to the caller. Commenting this branch out means errno==0
  24174. ** will be handled by the "default:" case below.
  24175. */
  24176. case 0:
  24177. return SQLITE_OK;
  24178. #endif
  24179. case EAGAIN:
  24180. case ETIMEDOUT:
  24181. case EBUSY:
  24182. case EINTR:
  24183. case ENOLCK:
  24184. /* random NFS retry error, unless during file system support
  24185. * introspection, in which it actually means what it says */
  24186. return SQLITE_BUSY;
  24187. case EACCES:
  24188. /* EACCES is like EAGAIN during locking operations, but not any other time*/
  24189. if( (sqliteIOErr == SQLITE_IOERR_LOCK) ||
  24190. (sqliteIOErr == SQLITE_IOERR_UNLOCK) ||
  24191. (sqliteIOErr == SQLITE_IOERR_RDLOCK) ||
  24192. (sqliteIOErr == SQLITE_IOERR_CHECKRESERVEDLOCK) ){
  24193. return SQLITE_BUSY;
  24194. }
  24195. /* else fall through */
  24196. case EPERM:
  24197. return SQLITE_PERM;
  24198. #if EOPNOTSUPP!=ENOTSUP
  24199. case EOPNOTSUPP:
  24200. /* something went terribly awry, unless during file system support
  24201. * introspection, in which it actually means what it says */
  24202. #endif
  24203. #ifdef ENOTSUP
  24204. case ENOTSUP:
  24205. /* invalid fd, unless during file system support introspection, in which
  24206. * it actually means what it says */
  24207. #endif
  24208. case EIO:
  24209. case EBADF:
  24210. case EINVAL:
  24211. case ENOTCONN:
  24212. case ENODEV:
  24213. case ENXIO:
  24214. case ENOENT:
  24215. #ifdef ESTALE /* ESTALE is not defined on Interix systems */
  24216. case ESTALE:
  24217. #endif
  24218. case ENOSYS:
  24219. /* these should force the client to close the file and reconnect */
  24220. default:
  24221. return sqliteIOErr;
  24222. }
  24223. }
  24224. /******************************************************************************
  24225. ****************** Begin Unique File ID Utility Used By VxWorks ***************
  24226. **
  24227. ** On most versions of unix, we can get a unique ID for a file by concatenating
  24228. ** the device number and the inode number. But this does not work on VxWorks.
  24229. ** On VxWorks, a unique file id must be based on the canonical filename.
  24230. **
  24231. ** A pointer to an instance of the following structure can be used as a
  24232. ** unique file ID in VxWorks. Each instance of this structure contains
  24233. ** a copy of the canonical filename. There is also a reference count.
  24234. ** The structure is reclaimed when the number of pointers to it drops to
  24235. ** zero.
  24236. **
  24237. ** There are never very many files open at one time and lookups are not
  24238. ** a performance-critical path, so it is sufficient to put these
  24239. ** structures on a linked list.
  24240. */
  24241. struct vxworksFileId {
  24242. struct vxworksFileId *pNext; /* Next in a list of them all */
  24243. int nRef; /* Number of references to this one */
  24244. int nName; /* Length of the zCanonicalName[] string */
  24245. char *zCanonicalName; /* Canonical filename */
  24246. };
  24247. #if OS_VXWORKS
  24248. /*
  24249. ** All unique filenames are held on a linked list headed by this
  24250. ** variable:
  24251. */
  24252. static struct vxworksFileId *vxworksFileList = 0;
  24253. /*
  24254. ** Simplify a filename into its canonical form
  24255. ** by making the following changes:
  24256. **
  24257. ** * removing any trailing and duplicate /
  24258. ** * convert /./ into just /
  24259. ** * convert /A/../ where A is any simple name into just /
  24260. **
  24261. ** Changes are made in-place. Return the new name length.
  24262. **
  24263. ** The original filename is in z[0..n-1]. Return the number of
  24264. ** characters in the simplified name.
  24265. */
  24266. static int vxworksSimplifyName(char *z, int n){
  24267. int i, j;
  24268. while( n>1 && z[n-1]=='/' ){ n--; }
  24269. for(i=j=0; i<n; i++){
  24270. if( z[i]=='/' ){
  24271. if( z[i+1]=='/' ) continue;
  24272. if( z[i+1]=='.' && i+2<n && z[i+2]=='/' ){
  24273. i += 1;
  24274. continue;
  24275. }
  24276. if( z[i+1]=='.' && i+3<n && z[i+2]=='.' && z[i+3]=='/' ){
  24277. while( j>0 && z[j-1]!='/' ){ j--; }
  24278. if( j>0 ){ j--; }
  24279. i += 2;
  24280. continue;
  24281. }
  24282. }
  24283. z[j++] = z[i];
  24284. }
  24285. z[j] = 0;
  24286. return j;
  24287. }
  24288. /*
  24289. ** Find a unique file ID for the given absolute pathname. Return
  24290. ** a pointer to the vxworksFileId object. This pointer is the unique
  24291. ** file ID.
  24292. **
  24293. ** The nRef field of the vxworksFileId object is incremented before
  24294. ** the object is returned. A new vxworksFileId object is created
  24295. ** and added to the global list if necessary.
  24296. **
  24297. ** If a memory allocation error occurs, return NULL.
  24298. */
  24299. static struct vxworksFileId *vxworksFindFileId(const char *zAbsoluteName){
  24300. struct vxworksFileId *pNew; /* search key and new file ID */
  24301. struct vxworksFileId *pCandidate; /* For looping over existing file IDs */
  24302. int n; /* Length of zAbsoluteName string */
  24303. assert( zAbsoluteName[0]=='/' );
  24304. n = (int)strlen(zAbsoluteName);
  24305. pNew = sqlite3_malloc( sizeof(*pNew) + (n+1) );
  24306. if( pNew==0 ) return 0;
  24307. pNew->zCanonicalName = (char*)&pNew[1];
  24308. memcpy(pNew->zCanonicalName, zAbsoluteName, n+1);
  24309. n = vxworksSimplifyName(pNew->zCanonicalName, n);
  24310. /* Search for an existing entry that matching the canonical name.
  24311. ** If found, increment the reference count and return a pointer to
  24312. ** the existing file ID.
  24313. */
  24314. unixEnterMutex();
  24315. for(pCandidate=vxworksFileList; pCandidate; pCandidate=pCandidate->pNext){
  24316. if( pCandidate->nName==n
  24317. && memcmp(pCandidate->zCanonicalName, pNew->zCanonicalName, n)==0
  24318. ){
  24319. sqlite3_free(pNew);
  24320. pCandidate->nRef++;
  24321. unixLeaveMutex();
  24322. return pCandidate;
  24323. }
  24324. }
  24325. /* No match was found. We will make a new file ID */
  24326. pNew->nRef = 1;
  24327. pNew->nName = n;
  24328. pNew->pNext = vxworksFileList;
  24329. vxworksFileList = pNew;
  24330. unixLeaveMutex();
  24331. return pNew;
  24332. }
  24333. /*
  24334. ** Decrement the reference count on a vxworksFileId object. Free
  24335. ** the object when the reference count reaches zero.
  24336. */
  24337. static void vxworksReleaseFileId(struct vxworksFileId *pId){
  24338. unixEnterMutex();
  24339. assert( pId->nRef>0 );
  24340. pId->nRef--;
  24341. if( pId->nRef==0 ){
  24342. struct vxworksFileId **pp;
  24343. for(pp=&vxworksFileList; *pp && *pp!=pId; pp = &((*pp)->pNext)){}
  24344. assert( *pp==pId );
  24345. *pp = pId->pNext;
  24346. sqlite3_free(pId);
  24347. }
  24348. unixLeaveMutex();
  24349. }
  24350. #endif /* OS_VXWORKS */
  24351. /*************** End of Unique File ID Utility Used By VxWorks ****************
  24352. ******************************************************************************/
  24353. /******************************************************************************
  24354. *************************** Posix Advisory Locking ****************************
  24355. **
  24356. ** POSIX advisory locks are broken by design. ANSI STD 1003.1 (1996)
  24357. ** section 6.5.2.2 lines 483 through 490 specify that when a process
  24358. ** sets or clears a lock, that operation overrides any prior locks set
  24359. ** by the same process. It does not explicitly say so, but this implies
  24360. ** that it overrides locks set by the same process using a different
  24361. ** file descriptor. Consider this test case:
  24362. **
  24363. ** int fd1 = open("./file1", O_RDWR|O_CREAT, 0644);
  24364. ** int fd2 = open("./file2", O_RDWR|O_CREAT, 0644);
  24365. **
  24366. ** Suppose ./file1 and ./file2 are really the same file (because
  24367. ** one is a hard or symbolic link to the other) then if you set
  24368. ** an exclusive lock on fd1, then try to get an exclusive lock
  24369. ** on fd2, it works. I would have expected the second lock to
  24370. ** fail since there was already a lock on the file due to fd1.
  24371. ** But not so. Since both locks came from the same process, the
  24372. ** second overrides the first, even though they were on different
  24373. ** file descriptors opened on different file names.
  24374. **
  24375. ** This means that we cannot use POSIX locks to synchronize file access
  24376. ** among competing threads of the same process. POSIX locks will work fine
  24377. ** to synchronize access for threads in separate processes, but not
  24378. ** threads within the same process.
  24379. **
  24380. ** To work around the problem, SQLite has to manage file locks internally
  24381. ** on its own. Whenever a new database is opened, we have to find the
  24382. ** specific inode of the database file (the inode is determined by the
  24383. ** st_dev and st_ino fields of the stat structure that fstat() fills in)
  24384. ** and check for locks already existing on that inode. When locks are
  24385. ** created or removed, we have to look at our own internal record of the
  24386. ** locks to see if another thread has previously set a lock on that same
  24387. ** inode.
  24388. **
  24389. ** (Aside: The use of inode numbers as unique IDs does not work on VxWorks.
  24390. ** For VxWorks, we have to use the alternative unique ID system based on
  24391. ** canonical filename and implemented in the previous division.)
  24392. **
  24393. ** The sqlite3_file structure for POSIX is no longer just an integer file
  24394. ** descriptor. It is now a structure that holds the integer file
  24395. ** descriptor and a pointer to a structure that describes the internal
  24396. ** locks on the corresponding inode. There is one locking structure
  24397. ** per inode, so if the same inode is opened twice, both unixFile structures
  24398. ** point to the same locking structure. The locking structure keeps
  24399. ** a reference count (so we will know when to delete it) and a "cnt"
  24400. ** field that tells us its internal lock status. cnt==0 means the
  24401. ** file is unlocked. cnt==-1 means the file has an exclusive lock.
  24402. ** cnt>0 means there are cnt shared locks on the file.
  24403. **
  24404. ** Any attempt to lock or unlock a file first checks the locking
  24405. ** structure. The fcntl() system call is only invoked to set a
  24406. ** POSIX lock if the internal lock structure transitions between
  24407. ** a locked and an unlocked state.
  24408. **
  24409. ** But wait: there are yet more problems with POSIX advisory locks.
  24410. **
  24411. ** If you close a file descriptor that points to a file that has locks,
  24412. ** all locks on that file that are owned by the current process are
  24413. ** released. To work around this problem, each unixInodeInfo object
  24414. ** maintains a count of the number of pending locks on tha inode.
  24415. ** When an attempt is made to close an unixFile, if there are
  24416. ** other unixFile open on the same inode that are holding locks, the call
  24417. ** to close() the file descriptor is deferred until all of the locks clear.
  24418. ** The unixInodeInfo structure keeps a list of file descriptors that need to
  24419. ** be closed and that list is walked (and cleared) when the last lock
  24420. ** clears.
  24421. **
  24422. ** Yet another problem: LinuxThreads do not play well with posix locks.
  24423. **
  24424. ** Many older versions of linux use the LinuxThreads library which is
  24425. ** not posix compliant. Under LinuxThreads, a lock created by thread
  24426. ** A cannot be modified or overridden by a different thread B.
  24427. ** Only thread A can modify the lock. Locking behavior is correct
  24428. ** if the appliation uses the newer Native Posix Thread Library (NPTL)
  24429. ** on linux - with NPTL a lock created by thread A can override locks
  24430. ** in thread B. But there is no way to know at compile-time which
  24431. ** threading library is being used. So there is no way to know at
  24432. ** compile-time whether or not thread A can override locks on thread B.
  24433. ** One has to do a run-time check to discover the behavior of the
  24434. ** current process.
  24435. **
  24436. ** SQLite used to support LinuxThreads. But support for LinuxThreads
  24437. ** was dropped beginning with version 3.7.0. SQLite will still work with
  24438. ** LinuxThreads provided that (1) there is no more than one connection
  24439. ** per database file in the same process and (2) database connections
  24440. ** do not move across threads.
  24441. */
  24442. /*
  24443. ** An instance of the following structure serves as the key used
  24444. ** to locate a particular unixInodeInfo object.
  24445. */
  24446. struct unixFileId {
  24447. dev_t dev; /* Device number */
  24448. #if OS_VXWORKS
  24449. struct vxworksFileId *pId; /* Unique file ID for vxworks. */
  24450. #else
  24451. ino_t ino; /* Inode number */
  24452. #endif
  24453. };
  24454. /*
  24455. ** An instance of the following structure is allocated for each open
  24456. ** inode. Or, on LinuxThreads, there is one of these structures for
  24457. ** each inode opened by each thread.
  24458. **
  24459. ** A single inode can have multiple file descriptors, so each unixFile
  24460. ** structure contains a pointer to an instance of this object and this
  24461. ** object keeps a count of the number of unixFile pointing to it.
  24462. */
  24463. struct unixInodeInfo {
  24464. struct unixFileId fileId; /* The lookup key */
  24465. int nShared; /* Number of SHARED locks held */
  24466. unsigned char eFileLock; /* One of SHARED_LOCK, RESERVED_LOCK etc. */
  24467. unsigned char bProcessLock; /* An exclusive process lock is held */
  24468. int nRef; /* Number of pointers to this structure */
  24469. unixShmNode *pShmNode; /* Shared memory associated with this inode */
  24470. int nLock; /* Number of outstanding file locks */
  24471. UnixUnusedFd *pUnused; /* Unused file descriptors to close */
  24472. unixInodeInfo *pNext; /* List of all unixInodeInfo objects */
  24473. unixInodeInfo *pPrev; /* .... doubly linked */
  24474. #if SQLITE_ENABLE_LOCKING_STYLE
  24475. unsigned long long sharedByte; /* for AFP simulated shared lock */
  24476. #endif
  24477. #if OS_VXWORKS
  24478. sem_t *pSem; /* Named POSIX semaphore */
  24479. char aSemName[MAX_PATHNAME+2]; /* Name of that semaphore */
  24480. #endif
  24481. };
  24482. /*
  24483. ** A lists of all unixInodeInfo objects.
  24484. */
  24485. static unixInodeInfo *inodeList = 0;
  24486. /*
  24487. **
  24488. ** This function - unixLogError_x(), is only ever called via the macro
  24489. ** unixLogError().
  24490. **
  24491. ** It is invoked after an error occurs in an OS function and errno has been
  24492. ** set. It logs a message using sqlite3_log() containing the current value of
  24493. ** errno and, if possible, the human-readable equivalent from strerror() or
  24494. ** strerror_r().
  24495. **
  24496. ** The first argument passed to the macro should be the error code that
  24497. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  24498. ** The two subsequent arguments should be the name of the OS function that
  24499. ** failed (e.g. "unlink", "open") and the associated file-system path,
  24500. ** if any.
  24501. */
  24502. #define unixLogError(a,b,c) unixLogErrorAtLine(a,b,c,__LINE__)
  24503. static int unixLogErrorAtLine(
  24504. int errcode, /* SQLite error code */
  24505. const char *zFunc, /* Name of OS function that failed */
  24506. const char *zPath, /* File path associated with error */
  24507. int iLine /* Source line number where error occurred */
  24508. ){
  24509. char *zErr; /* Message from strerror() or equivalent */
  24510. int iErrno = errno; /* Saved syscall error number */
  24511. /* If this is not a threadsafe build (SQLITE_THREADSAFE==0), then use
  24512. ** the strerror() function to obtain the human-readable error message
  24513. ** equivalent to errno. Otherwise, use strerror_r().
  24514. */
  24515. #if SQLITE_THREADSAFE && defined(HAVE_STRERROR_R)
  24516. char aErr[80];
  24517. memset(aErr, 0, sizeof(aErr));
  24518. zErr = aErr;
  24519. /* If STRERROR_R_CHAR_P (set by autoconf scripts) or __USE_GNU is defined,
  24520. ** assume that the system provides the GNU version of strerror_r() that
  24521. ** returns a pointer to a buffer containing the error message. That pointer
  24522. ** may point to aErr[], or it may point to some static storage somewhere.
  24523. ** Otherwise, assume that the system provides the POSIX version of
  24524. ** strerror_r(), which always writes an error message into aErr[].
  24525. **
  24526. ** If the code incorrectly assumes that it is the POSIX version that is
  24527. ** available, the error message will often be an empty string. Not a
  24528. ** huge problem. Incorrectly concluding that the GNU version is available
  24529. ** could lead to a segfault though.
  24530. */
  24531. #if defined(STRERROR_R_CHAR_P) || defined(__USE_GNU)
  24532. zErr =
  24533. # endif
  24534. strerror_r(iErrno, aErr, sizeof(aErr)-1);
  24535. #elif SQLITE_THREADSAFE
  24536. /* This is a threadsafe build, but strerror_r() is not available. */
  24537. zErr = "";
  24538. #else
  24539. /* Non-threadsafe build, use strerror(). */
  24540. zErr = strerror(iErrno);
  24541. #endif
  24542. if( zPath==0 ) zPath = "";
  24543. sqlite3_log(errcode,
  24544. "os_unix.c:%d: (%d) %s(%s) - %s",
  24545. iLine, iErrno, zFunc, zPath, zErr
  24546. );
  24547. return errcode;
  24548. }
  24549. /*
  24550. ** Close a file descriptor.
  24551. **
  24552. ** We assume that close() almost always works, since it is only in a
  24553. ** very sick application or on a very sick platform that it might fail.
  24554. ** If it does fail, simply leak the file descriptor, but do log the
  24555. ** error.
  24556. **
  24557. ** Note that it is not safe to retry close() after EINTR since the
  24558. ** file descriptor might have already been reused by another thread.
  24559. ** So we don't even try to recover from an EINTR. Just log the error
  24560. ** and move on.
  24561. */
  24562. static void robust_close(unixFile *pFile, int h, int lineno){
  24563. if( osClose(h) ){
  24564. unixLogErrorAtLine(SQLITE_IOERR_CLOSE, "close",
  24565. pFile ? pFile->zPath : 0, lineno);
  24566. }
  24567. }
  24568. /*
  24569. ** Close all file descriptors accumuated in the unixInodeInfo->pUnused list.
  24570. */
  24571. static void closePendingFds(unixFile *pFile){
  24572. unixInodeInfo *pInode = pFile->pInode;
  24573. UnixUnusedFd *p;
  24574. UnixUnusedFd *pNext;
  24575. for(p=pInode->pUnused; p; p=pNext){
  24576. pNext = p->pNext;
  24577. robust_close(pFile, p->fd, __LINE__);
  24578. sqlite3_free(p);
  24579. }
  24580. pInode->pUnused = 0;
  24581. }
  24582. /*
  24583. ** Release a unixInodeInfo structure previously allocated by findInodeInfo().
  24584. **
  24585. ** The mutex entered using the unixEnterMutex() function must be held
  24586. ** when this function is called.
  24587. */
  24588. static void releaseInodeInfo(unixFile *pFile){
  24589. unixInodeInfo *pInode = pFile->pInode;
  24590. assert( unixMutexHeld() );
  24591. if( ALWAYS(pInode) ){
  24592. pInode->nRef--;
  24593. if( pInode->nRef==0 ){
  24594. assert( pInode->pShmNode==0 );
  24595. closePendingFds(pFile);
  24596. if( pInode->pPrev ){
  24597. assert( pInode->pPrev->pNext==pInode );
  24598. pInode->pPrev->pNext = pInode->pNext;
  24599. }else{
  24600. assert( inodeList==pInode );
  24601. inodeList = pInode->pNext;
  24602. }
  24603. if( pInode->pNext ){
  24604. assert( pInode->pNext->pPrev==pInode );
  24605. pInode->pNext->pPrev = pInode->pPrev;
  24606. }
  24607. sqlite3_free(pInode);
  24608. }
  24609. }
  24610. }
  24611. /*
  24612. ** Given a file descriptor, locate the unixInodeInfo object that
  24613. ** describes that file descriptor. Create a new one if necessary. The
  24614. ** return value might be uninitialized if an error occurs.
  24615. **
  24616. ** The mutex entered using the unixEnterMutex() function must be held
  24617. ** when this function is called.
  24618. **
  24619. ** Return an appropriate error code.
  24620. */
  24621. static int findInodeInfo(
  24622. unixFile *pFile, /* Unix file with file desc used in the key */
  24623. unixInodeInfo **ppInode /* Return the unixInodeInfo object here */
  24624. ){
  24625. int rc; /* System call return code */
  24626. int fd; /* The file descriptor for pFile */
  24627. struct unixFileId fileId; /* Lookup key for the unixInodeInfo */
  24628. struct stat statbuf; /* Low-level file information */
  24629. unixInodeInfo *pInode = 0; /* Candidate unixInodeInfo object */
  24630. assert( unixMutexHeld() );
  24631. /* Get low-level information about the file that we can used to
  24632. ** create a unique name for the file.
  24633. */
  24634. fd = pFile->h;
  24635. rc = osFstat(fd, &statbuf);
  24636. if( rc!=0 ){
  24637. pFile->lastErrno = errno;
  24638. #ifdef EOVERFLOW
  24639. if( pFile->lastErrno==EOVERFLOW ) return SQLITE_NOLFS;
  24640. #endif
  24641. return SQLITE_IOERR;
  24642. }
  24643. #ifdef __APPLE__
  24644. /* On OS X on an msdos filesystem, the inode number is reported
  24645. ** incorrectly for zero-size files. See ticket #3260. To work
  24646. ** around this problem (we consider it a bug in OS X, not SQLite)
  24647. ** we always increase the file size to 1 by writing a single byte
  24648. ** prior to accessing the inode number. The one byte written is
  24649. ** an ASCII 'S' character which also happens to be the first byte
  24650. ** in the header of every SQLite database. In this way, if there
  24651. ** is a race condition such that another thread has already populated
  24652. ** the first page of the database, no damage is done.
  24653. */
  24654. if( statbuf.st_size==0 && (pFile->fsFlags & SQLITE_FSFLAGS_IS_MSDOS)!=0 ){
  24655. do{ rc = osWrite(fd, "S", 1); }while( rc<0 && errno==EINTR );
  24656. if( rc!=1 ){
  24657. pFile->lastErrno = errno;
  24658. return SQLITE_IOERR;
  24659. }
  24660. rc = osFstat(fd, &statbuf);
  24661. if( rc!=0 ){
  24662. pFile->lastErrno = errno;
  24663. return SQLITE_IOERR;
  24664. }
  24665. }
  24666. #endif
  24667. memset(&fileId, 0, sizeof(fileId));
  24668. fileId.dev = statbuf.st_dev;
  24669. #if OS_VXWORKS
  24670. fileId.pId = pFile->pId;
  24671. #else
  24672. fileId.ino = statbuf.st_ino;
  24673. #endif
  24674. pInode = inodeList;
  24675. while( pInode && memcmp(&fileId, &pInode->fileId, sizeof(fileId)) ){
  24676. pInode = pInode->pNext;
  24677. }
  24678. if( pInode==0 ){
  24679. pInode = sqlite3_malloc( sizeof(*pInode) );
  24680. if( pInode==0 ){
  24681. return SQLITE_NOMEM;
  24682. }
  24683. memset(pInode, 0, sizeof(*pInode));
  24684. memcpy(&pInode->fileId, &fileId, sizeof(fileId));
  24685. pInode->nRef = 1;
  24686. pInode->pNext = inodeList;
  24687. pInode->pPrev = 0;
  24688. if( inodeList ) inodeList->pPrev = pInode;
  24689. inodeList = pInode;
  24690. }else{
  24691. pInode->nRef++;
  24692. }
  24693. *ppInode = pInode;
  24694. return SQLITE_OK;
  24695. }
  24696. /*
  24697. ** Return TRUE if pFile has been renamed or unlinked since it was first opened.
  24698. */
  24699. static int fileHasMoved(unixFile *pFile){
  24700. #if OS_VXWORKS
  24701. return pFile->pInode!=0 && pFile->pId!=pFile->pInode->fileId.pId;
  24702. #else
  24703. struct stat buf;
  24704. return pFile->pInode!=0 &&
  24705. (osStat(pFile->zPath, &buf)!=0 || buf.st_ino!=pFile->pInode->fileId.ino);
  24706. #endif
  24707. }
  24708. /*
  24709. ** Check a unixFile that is a database. Verify the following:
  24710. **
  24711. ** (1) There is exactly one hard link on the file
  24712. ** (2) The file is not a symbolic link
  24713. ** (3) The file has not been renamed or unlinked
  24714. **
  24715. ** Issue sqlite3_log(SQLITE_WARNING,...) messages if anything is not right.
  24716. */
  24717. static void verifyDbFile(unixFile *pFile){
  24718. struct stat buf;
  24719. int rc;
  24720. if( pFile->ctrlFlags & UNIXFILE_WARNED ){
  24721. /* One or more of the following warnings have already been issued. Do not
  24722. ** repeat them so as not to clutter the error log */
  24723. return;
  24724. }
  24725. rc = osFstat(pFile->h, &buf);
  24726. if( rc!=0 ){
  24727. sqlite3_log(SQLITE_WARNING, "cannot fstat db file %s", pFile->zPath);
  24728. pFile->ctrlFlags |= UNIXFILE_WARNED;
  24729. return;
  24730. }
  24731. if( buf.st_nlink==0 && (pFile->ctrlFlags & UNIXFILE_DELETE)==0 ){
  24732. sqlite3_log(SQLITE_WARNING, "file unlinked while open: %s", pFile->zPath);
  24733. pFile->ctrlFlags |= UNIXFILE_WARNED;
  24734. return;
  24735. }
  24736. if( buf.st_nlink>1 ){
  24737. sqlite3_log(SQLITE_WARNING, "multiple links to file: %s", pFile->zPath);
  24738. pFile->ctrlFlags |= UNIXFILE_WARNED;
  24739. return;
  24740. }
  24741. if( fileHasMoved(pFile) ){
  24742. sqlite3_log(SQLITE_WARNING, "file renamed while open: %s", pFile->zPath);
  24743. pFile->ctrlFlags |= UNIXFILE_WARNED;
  24744. return;
  24745. }
  24746. }
  24747. /*
  24748. ** This routine checks if there is a RESERVED lock held on the specified
  24749. ** file by this or any other process. If such a lock is held, set *pResOut
  24750. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  24751. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  24752. */
  24753. static int unixCheckReservedLock(sqlite3_file *id, int *pResOut){
  24754. int rc = SQLITE_OK;
  24755. int reserved = 0;
  24756. unixFile *pFile = (unixFile*)id;
  24757. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  24758. assert( pFile );
  24759. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  24760. /* Check if a thread in this process holds such a lock */
  24761. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  24762. reserved = 1;
  24763. }
  24764. /* Otherwise see if some other process holds it.
  24765. */
  24766. #ifndef __DJGPP__
  24767. if( !reserved && !pFile->pInode->bProcessLock ){
  24768. struct flock lock;
  24769. lock.l_whence = SEEK_SET;
  24770. lock.l_start = RESERVED_BYTE;
  24771. lock.l_len = 1;
  24772. lock.l_type = F_WRLCK;
  24773. if( osFcntl(pFile->h, F_GETLK, &lock) ){
  24774. rc = SQLITE_IOERR_CHECKRESERVEDLOCK;
  24775. pFile->lastErrno = errno;
  24776. } else if( lock.l_type!=F_UNLCK ){
  24777. reserved = 1;
  24778. }
  24779. }
  24780. #endif
  24781. unixLeaveMutex();
  24782. OSTRACE(("TEST WR-LOCK %d %d %d (unix)\n", pFile->h, rc, reserved));
  24783. *pResOut = reserved;
  24784. return rc;
  24785. }
  24786. /*
  24787. ** Attempt to set a system-lock on the file pFile. The lock is
  24788. ** described by pLock.
  24789. **
  24790. ** If the pFile was opened read/write from unix-excl, then the only lock
  24791. ** ever obtained is an exclusive lock, and it is obtained exactly once
  24792. ** the first time any lock is attempted. All subsequent system locking
  24793. ** operations become no-ops. Locking operations still happen internally,
  24794. ** in order to coordinate access between separate database connections
  24795. ** within this process, but all of that is handled in memory and the
  24796. ** operating system does not participate.
  24797. **
  24798. ** This function is a pass-through to fcntl(F_SETLK) if pFile is using
  24799. ** any VFS other than "unix-excl" or if pFile is opened on "unix-excl"
  24800. ** and is read-only.
  24801. **
  24802. ** Zero is returned if the call completes successfully, or -1 if a call
  24803. ** to fcntl() fails. In this case, errno is set appropriately (by fcntl()).
  24804. */
  24805. static int unixFileLock(unixFile *pFile, struct flock *pLock){
  24806. int rc;
  24807. unixInodeInfo *pInode = pFile->pInode;
  24808. assert( unixMutexHeld() );
  24809. assert( pInode!=0 );
  24810. if( ((pFile->ctrlFlags & UNIXFILE_EXCL)!=0 || pInode->bProcessLock)
  24811. && ((pFile->ctrlFlags & UNIXFILE_RDONLY)==0)
  24812. ){
  24813. if( pInode->bProcessLock==0 ){
  24814. struct flock lock;
  24815. assert( pInode->nLock==0 );
  24816. lock.l_whence = SEEK_SET;
  24817. lock.l_start = SHARED_FIRST;
  24818. lock.l_len = SHARED_SIZE;
  24819. lock.l_type = F_WRLCK;
  24820. rc = osFcntl(pFile->h, F_SETLK, &lock);
  24821. if( rc<0 ) return rc;
  24822. pInode->bProcessLock = 1;
  24823. pInode->nLock++;
  24824. }else{
  24825. rc = 0;
  24826. }
  24827. }else{
  24828. rc = osFcntl(pFile->h, F_SETLK, pLock);
  24829. }
  24830. return rc;
  24831. }
  24832. /*
  24833. ** Lock the file with the lock specified by parameter eFileLock - one
  24834. ** of the following:
  24835. **
  24836. ** (1) SHARED_LOCK
  24837. ** (2) RESERVED_LOCK
  24838. ** (3) PENDING_LOCK
  24839. ** (4) EXCLUSIVE_LOCK
  24840. **
  24841. ** Sometimes when requesting one lock state, additional lock states
  24842. ** are inserted in between. The locking might fail on one of the later
  24843. ** transitions leaving the lock state different from what it started but
  24844. ** still short of its goal. The following chart shows the allowed
  24845. ** transitions and the inserted intermediate states:
  24846. **
  24847. ** UNLOCKED -> SHARED
  24848. ** SHARED -> RESERVED
  24849. ** SHARED -> (PENDING) -> EXCLUSIVE
  24850. ** RESERVED -> (PENDING) -> EXCLUSIVE
  24851. ** PENDING -> EXCLUSIVE
  24852. **
  24853. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  24854. ** routine to lower a locking level.
  24855. */
  24856. static int unixLock(sqlite3_file *id, int eFileLock){
  24857. /* The following describes the implementation of the various locks and
  24858. ** lock transitions in terms of the POSIX advisory shared and exclusive
  24859. ** lock primitives (called read-locks and write-locks below, to avoid
  24860. ** confusion with SQLite lock names). The algorithms are complicated
  24861. ** slightly in order to be compatible with windows systems simultaneously
  24862. ** accessing the same database file, in case that is ever required.
  24863. **
  24864. ** Symbols defined in os.h indentify the 'pending byte' and the 'reserved
  24865. ** byte', each single bytes at well known offsets, and the 'shared byte
  24866. ** range', a range of 510 bytes at a well known offset.
  24867. **
  24868. ** To obtain a SHARED lock, a read-lock is obtained on the 'pending
  24869. ** byte'. If this is successful, a random byte from the 'shared byte
  24870. ** range' is read-locked and the lock on the 'pending byte' released.
  24871. **
  24872. ** A process may only obtain a RESERVED lock after it has a SHARED lock.
  24873. ** A RESERVED lock is implemented by grabbing a write-lock on the
  24874. ** 'reserved byte'.
  24875. **
  24876. ** A process may only obtain a PENDING lock after it has obtained a
  24877. ** SHARED lock. A PENDING lock is implemented by obtaining a write-lock
  24878. ** on the 'pending byte'. This ensures that no new SHARED locks can be
  24879. ** obtained, but existing SHARED locks are allowed to persist. A process
  24880. ** does not have to obtain a RESERVED lock on the way to a PENDING lock.
  24881. ** This property is used by the algorithm for rolling back a journal file
  24882. ** after a crash.
  24883. **
  24884. ** An EXCLUSIVE lock, obtained after a PENDING lock is held, is
  24885. ** implemented by obtaining a write-lock on the entire 'shared byte
  24886. ** range'. Since all other locks require a read-lock on one of the bytes
  24887. ** within this range, this ensures that no other locks are held on the
  24888. ** database.
  24889. **
  24890. ** The reason a single byte cannot be used instead of the 'shared byte
  24891. ** range' is that some versions of windows do not support read-locks. By
  24892. ** locking a random byte from a range, concurrent SHARED locks may exist
  24893. ** even if the locking primitive used is always a write-lock.
  24894. */
  24895. int rc = SQLITE_OK;
  24896. unixFile *pFile = (unixFile*)id;
  24897. unixInodeInfo *pInode;
  24898. struct flock lock;
  24899. int tErrno = 0;
  24900. assert( pFile );
  24901. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (unix)\n", pFile->h,
  24902. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  24903. azFileLock(pFile->pInode->eFileLock), pFile->pInode->nShared , getpid()));
  24904. /* If there is already a lock of this type or more restrictive on the
  24905. ** unixFile, do nothing. Don't use the end_lock: exit path, as
  24906. ** unixEnterMutex() hasn't been called yet.
  24907. */
  24908. if( pFile->eFileLock>=eFileLock ){
  24909. OSTRACE(("LOCK %d %s ok (already held) (unix)\n", pFile->h,
  24910. azFileLock(eFileLock)));
  24911. return SQLITE_OK;
  24912. }
  24913. /* Make sure the locking sequence is correct.
  24914. ** (1) We never move from unlocked to anything higher than shared lock.
  24915. ** (2) SQLite never explicitly requests a pendig lock.
  24916. ** (3) A shared lock is always held when a reserve lock is requested.
  24917. */
  24918. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  24919. assert( eFileLock!=PENDING_LOCK );
  24920. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  24921. /* This mutex is needed because pFile->pInode is shared across threads
  24922. */
  24923. unixEnterMutex();
  24924. pInode = pFile->pInode;
  24925. /* If some thread using this PID has a lock via a different unixFile*
  24926. ** handle that precludes the requested lock, return BUSY.
  24927. */
  24928. if( (pFile->eFileLock!=pInode->eFileLock &&
  24929. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  24930. ){
  24931. rc = SQLITE_BUSY;
  24932. goto end_lock;
  24933. }
  24934. /* If a SHARED lock is requested, and some thread using this PID already
  24935. ** has a SHARED or RESERVED lock, then increment reference counts and
  24936. ** return SQLITE_OK.
  24937. */
  24938. if( eFileLock==SHARED_LOCK &&
  24939. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  24940. assert( eFileLock==SHARED_LOCK );
  24941. assert( pFile->eFileLock==0 );
  24942. assert( pInode->nShared>0 );
  24943. pFile->eFileLock = SHARED_LOCK;
  24944. pInode->nShared++;
  24945. pInode->nLock++;
  24946. goto end_lock;
  24947. }
  24948. /* A PENDING lock is needed before acquiring a SHARED lock and before
  24949. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  24950. ** be released.
  24951. */
  24952. lock.l_len = 1L;
  24953. lock.l_whence = SEEK_SET;
  24954. if( eFileLock==SHARED_LOCK
  24955. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  24956. ){
  24957. lock.l_type = (eFileLock==SHARED_LOCK?F_RDLCK:F_WRLCK);
  24958. lock.l_start = PENDING_BYTE;
  24959. if( unixFileLock(pFile, &lock) ){
  24960. tErrno = errno;
  24961. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24962. if( rc!=SQLITE_BUSY ){
  24963. pFile->lastErrno = tErrno;
  24964. }
  24965. goto end_lock;
  24966. }
  24967. }
  24968. /* If control gets to this point, then actually go ahead and make
  24969. ** operating system calls for the specified lock.
  24970. */
  24971. if( eFileLock==SHARED_LOCK ){
  24972. assert( pInode->nShared==0 );
  24973. assert( pInode->eFileLock==0 );
  24974. assert( rc==SQLITE_OK );
  24975. /* Now get the read-lock */
  24976. lock.l_start = SHARED_FIRST;
  24977. lock.l_len = SHARED_SIZE;
  24978. if( unixFileLock(pFile, &lock) ){
  24979. tErrno = errno;
  24980. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  24981. }
  24982. /* Drop the temporary PENDING lock */
  24983. lock.l_start = PENDING_BYTE;
  24984. lock.l_len = 1L;
  24985. lock.l_type = F_UNLCK;
  24986. if( unixFileLock(pFile, &lock) && rc==SQLITE_OK ){
  24987. /* This could happen with a network mount */
  24988. tErrno = errno;
  24989. rc = SQLITE_IOERR_UNLOCK;
  24990. }
  24991. if( rc ){
  24992. if( rc!=SQLITE_BUSY ){
  24993. pFile->lastErrno = tErrno;
  24994. }
  24995. goto end_lock;
  24996. }else{
  24997. pFile->eFileLock = SHARED_LOCK;
  24998. pInode->nLock++;
  24999. pInode->nShared = 1;
  25000. }
  25001. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  25002. /* We are trying for an exclusive lock but another thread in this
  25003. ** same process is still holding a shared lock. */
  25004. rc = SQLITE_BUSY;
  25005. }else{
  25006. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  25007. ** assumed that there is a SHARED or greater lock on the file
  25008. ** already.
  25009. */
  25010. assert( 0!=pFile->eFileLock );
  25011. lock.l_type = F_WRLCK;
  25012. assert( eFileLock==RESERVED_LOCK || eFileLock==EXCLUSIVE_LOCK );
  25013. if( eFileLock==RESERVED_LOCK ){
  25014. lock.l_start = RESERVED_BYTE;
  25015. lock.l_len = 1L;
  25016. }else{
  25017. lock.l_start = SHARED_FIRST;
  25018. lock.l_len = SHARED_SIZE;
  25019. }
  25020. if( unixFileLock(pFile, &lock) ){
  25021. tErrno = errno;
  25022. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25023. if( rc!=SQLITE_BUSY ){
  25024. pFile->lastErrno = tErrno;
  25025. }
  25026. }
  25027. }
  25028. #ifdef SQLITE_DEBUG
  25029. /* Set up the transaction-counter change checking flags when
  25030. ** transitioning from a SHARED to a RESERVED lock. The change
  25031. ** from SHARED to RESERVED marks the beginning of a normal
  25032. ** write operation (not a hot journal rollback).
  25033. */
  25034. if( rc==SQLITE_OK
  25035. && pFile->eFileLock<=SHARED_LOCK
  25036. && eFileLock==RESERVED_LOCK
  25037. ){
  25038. pFile->transCntrChng = 0;
  25039. pFile->dbUpdate = 0;
  25040. pFile->inNormalWrite = 1;
  25041. }
  25042. #endif
  25043. if( rc==SQLITE_OK ){
  25044. pFile->eFileLock = eFileLock;
  25045. pInode->eFileLock = eFileLock;
  25046. }else if( eFileLock==EXCLUSIVE_LOCK ){
  25047. pFile->eFileLock = PENDING_LOCK;
  25048. pInode->eFileLock = PENDING_LOCK;
  25049. }
  25050. end_lock:
  25051. unixLeaveMutex();
  25052. OSTRACE(("LOCK %d %s %s (unix)\n", pFile->h, azFileLock(eFileLock),
  25053. rc==SQLITE_OK ? "ok" : "failed"));
  25054. return rc;
  25055. }
  25056. /*
  25057. ** Add the file descriptor used by file handle pFile to the corresponding
  25058. ** pUnused list.
  25059. */
  25060. static void setPendingFd(unixFile *pFile){
  25061. unixInodeInfo *pInode = pFile->pInode;
  25062. UnixUnusedFd *p = pFile->pUnused;
  25063. p->pNext = pInode->pUnused;
  25064. pInode->pUnused = p;
  25065. pFile->h = -1;
  25066. pFile->pUnused = 0;
  25067. }
  25068. /*
  25069. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25070. ** must be either NO_LOCK or SHARED_LOCK.
  25071. **
  25072. ** If the locking level of the file descriptor is already at or below
  25073. ** the requested locking level, this routine is a no-op.
  25074. **
  25075. ** If handleNFSUnlock is true, then on downgrading an EXCLUSIVE_LOCK to SHARED
  25076. ** the byte range is divided into 2 parts and the first part is unlocked then
  25077. ** set to a read lock, then the other part is simply unlocked. This works
  25078. ** around a bug in BSD NFS lockd (also seen on MacOSX 10.3+) that fails to
  25079. ** remove the write lock on a region when a read lock is set.
  25080. */
  25081. static int posixUnlock(sqlite3_file *id, int eFileLock, int handleNFSUnlock){
  25082. unixFile *pFile = (unixFile*)id;
  25083. unixInodeInfo *pInode;
  25084. struct flock lock;
  25085. int rc = SQLITE_OK;
  25086. assert( pFile );
  25087. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (unix)\n", pFile->h, eFileLock,
  25088. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  25089. getpid()));
  25090. assert( eFileLock<=SHARED_LOCK );
  25091. if( pFile->eFileLock<=eFileLock ){
  25092. return SQLITE_OK;
  25093. }
  25094. unixEnterMutex();
  25095. pInode = pFile->pInode;
  25096. assert( pInode->nShared!=0 );
  25097. if( pFile->eFileLock>SHARED_LOCK ){
  25098. assert( pInode->eFileLock==pFile->eFileLock );
  25099. #ifdef SQLITE_DEBUG
  25100. /* When reducing a lock such that other processes can start
  25101. ** reading the database file again, make sure that the
  25102. ** transaction counter was updated if any part of the database
  25103. ** file changed. If the transaction counter is not updated,
  25104. ** other connections to the same file might not realize that
  25105. ** the file has changed and hence might not know to flush their
  25106. ** cache. The use of a stale cache can lead to database corruption.
  25107. */
  25108. pFile->inNormalWrite = 0;
  25109. #endif
  25110. /* downgrading to a shared lock on NFS involves clearing the write lock
  25111. ** before establishing the readlock - to avoid a race condition we downgrade
  25112. ** the lock in 2 blocks, so that part of the range will be covered by a
  25113. ** write lock until the rest is covered by a read lock:
  25114. ** 1: [WWWWW]
  25115. ** 2: [....W]
  25116. ** 3: [RRRRW]
  25117. ** 4: [RRRR.]
  25118. */
  25119. if( eFileLock==SHARED_LOCK ){
  25120. #if !defined(__APPLE__) || !SQLITE_ENABLE_LOCKING_STYLE
  25121. (void)handleNFSUnlock;
  25122. assert( handleNFSUnlock==0 );
  25123. #endif
  25124. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25125. if( handleNFSUnlock ){
  25126. int tErrno; /* Error code from system call errors */
  25127. off_t divSize = SHARED_SIZE - 1;
  25128. lock.l_type = F_UNLCK;
  25129. lock.l_whence = SEEK_SET;
  25130. lock.l_start = SHARED_FIRST;
  25131. lock.l_len = divSize;
  25132. if( unixFileLock(pFile, &lock)==(-1) ){
  25133. tErrno = errno;
  25134. rc = SQLITE_IOERR_UNLOCK;
  25135. if( IS_LOCK_ERROR(rc) ){
  25136. pFile->lastErrno = tErrno;
  25137. }
  25138. goto end_unlock;
  25139. }
  25140. lock.l_type = F_RDLCK;
  25141. lock.l_whence = SEEK_SET;
  25142. lock.l_start = SHARED_FIRST;
  25143. lock.l_len = divSize;
  25144. if( unixFileLock(pFile, &lock)==(-1) ){
  25145. tErrno = errno;
  25146. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_RDLOCK);
  25147. if( IS_LOCK_ERROR(rc) ){
  25148. pFile->lastErrno = tErrno;
  25149. }
  25150. goto end_unlock;
  25151. }
  25152. lock.l_type = F_UNLCK;
  25153. lock.l_whence = SEEK_SET;
  25154. lock.l_start = SHARED_FIRST+divSize;
  25155. lock.l_len = SHARED_SIZE-divSize;
  25156. if( unixFileLock(pFile, &lock)==(-1) ){
  25157. tErrno = errno;
  25158. rc = SQLITE_IOERR_UNLOCK;
  25159. if( IS_LOCK_ERROR(rc) ){
  25160. pFile->lastErrno = tErrno;
  25161. }
  25162. goto end_unlock;
  25163. }
  25164. }else
  25165. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  25166. {
  25167. lock.l_type = F_RDLCK;
  25168. lock.l_whence = SEEK_SET;
  25169. lock.l_start = SHARED_FIRST;
  25170. lock.l_len = SHARED_SIZE;
  25171. if( unixFileLock(pFile, &lock) ){
  25172. /* In theory, the call to unixFileLock() cannot fail because another
  25173. ** process is holding an incompatible lock. If it does, this
  25174. ** indicates that the other process is not following the locking
  25175. ** protocol. If this happens, return SQLITE_IOERR_RDLOCK. Returning
  25176. ** SQLITE_BUSY would confuse the upper layer (in practice it causes
  25177. ** an assert to fail). */
  25178. rc = SQLITE_IOERR_RDLOCK;
  25179. pFile->lastErrno = errno;
  25180. goto end_unlock;
  25181. }
  25182. }
  25183. }
  25184. lock.l_type = F_UNLCK;
  25185. lock.l_whence = SEEK_SET;
  25186. lock.l_start = PENDING_BYTE;
  25187. lock.l_len = 2L; assert( PENDING_BYTE+1==RESERVED_BYTE );
  25188. if( unixFileLock(pFile, &lock)==0 ){
  25189. pInode->eFileLock = SHARED_LOCK;
  25190. }else{
  25191. rc = SQLITE_IOERR_UNLOCK;
  25192. pFile->lastErrno = errno;
  25193. goto end_unlock;
  25194. }
  25195. }
  25196. if( eFileLock==NO_LOCK ){
  25197. /* Decrement the shared lock counter. Release the lock using an
  25198. ** OS call only when all threads in this same process have released
  25199. ** the lock.
  25200. */
  25201. pInode->nShared--;
  25202. if( pInode->nShared==0 ){
  25203. lock.l_type = F_UNLCK;
  25204. lock.l_whence = SEEK_SET;
  25205. lock.l_start = lock.l_len = 0L;
  25206. if( unixFileLock(pFile, &lock)==0 ){
  25207. pInode->eFileLock = NO_LOCK;
  25208. }else{
  25209. rc = SQLITE_IOERR_UNLOCK;
  25210. pFile->lastErrno = errno;
  25211. pInode->eFileLock = NO_LOCK;
  25212. pFile->eFileLock = NO_LOCK;
  25213. }
  25214. }
  25215. /* Decrement the count of locks against this same file. When the
  25216. ** count reaches zero, close any other file descriptors whose close
  25217. ** was deferred because of outstanding locks.
  25218. */
  25219. pInode->nLock--;
  25220. assert( pInode->nLock>=0 );
  25221. if( pInode->nLock==0 ){
  25222. closePendingFds(pFile);
  25223. }
  25224. }
  25225. end_unlock:
  25226. unixLeaveMutex();
  25227. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  25228. return rc;
  25229. }
  25230. /*
  25231. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25232. ** must be either NO_LOCK or SHARED_LOCK.
  25233. **
  25234. ** If the locking level of the file descriptor is already at or below
  25235. ** the requested locking level, this routine is a no-op.
  25236. */
  25237. static int unixUnlock(sqlite3_file *id, int eFileLock){
  25238. #if SQLITE_MAX_MMAP_SIZE>0
  25239. assert( eFileLock==SHARED_LOCK || ((unixFile *)id)->nFetchOut==0 );
  25240. #endif
  25241. return posixUnlock(id, eFileLock, 0);
  25242. }
  25243. #if SQLITE_MAX_MMAP_SIZE>0
  25244. static int unixMapfile(unixFile *pFd, i64 nByte);
  25245. static void unixUnmapfile(unixFile *pFd);
  25246. #endif
  25247. /*
  25248. ** This function performs the parts of the "close file" operation
  25249. ** common to all locking schemes. It closes the directory and file
  25250. ** handles, if they are valid, and sets all fields of the unixFile
  25251. ** structure to 0.
  25252. **
  25253. ** It is *not* necessary to hold the mutex when this routine is called,
  25254. ** even on VxWorks. A mutex will be acquired on VxWorks by the
  25255. ** vxworksReleaseFileId() routine.
  25256. */
  25257. static int closeUnixFile(sqlite3_file *id){
  25258. unixFile *pFile = (unixFile*)id;
  25259. #if SQLITE_MAX_MMAP_SIZE>0
  25260. unixUnmapfile(pFile);
  25261. #endif
  25262. if( pFile->h>=0 ){
  25263. robust_close(pFile, pFile->h, __LINE__);
  25264. pFile->h = -1;
  25265. }
  25266. #if OS_VXWORKS
  25267. if( pFile->pId ){
  25268. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  25269. osUnlink(pFile->pId->zCanonicalName);
  25270. }
  25271. vxworksReleaseFileId(pFile->pId);
  25272. pFile->pId = 0;
  25273. }
  25274. #endif
  25275. #ifdef SQLITE_UNLINK_AFTER_CLOSE
  25276. if( pFile->ctrlFlags & UNIXFILE_DELETE ){
  25277. osUnlink(pFile->zPath);
  25278. sqlite3_free(*(char**)&pFile->zPath);
  25279. pFile->zPath = 0;
  25280. }
  25281. #endif
  25282. OSTRACE(("CLOSE %-3d\n", pFile->h));
  25283. OpenCounter(-1);
  25284. sqlite3_free(pFile->pUnused);
  25285. memset(pFile, 0, sizeof(unixFile));
  25286. return SQLITE_OK;
  25287. }
  25288. /*
  25289. ** Close a file.
  25290. */
  25291. static int unixClose(sqlite3_file *id){
  25292. int rc = SQLITE_OK;
  25293. unixFile *pFile = (unixFile *)id;
  25294. verifyDbFile(pFile);
  25295. unixUnlock(id, NO_LOCK);
  25296. unixEnterMutex();
  25297. /* unixFile.pInode is always valid here. Otherwise, a different close
  25298. ** routine (e.g. nolockClose()) would be called instead.
  25299. */
  25300. assert( pFile->pInode->nLock>0 || pFile->pInode->bProcessLock==0 );
  25301. if( ALWAYS(pFile->pInode) && pFile->pInode->nLock ){
  25302. /* If there are outstanding locks, do not actually close the file just
  25303. ** yet because that would clear those locks. Instead, add the file
  25304. ** descriptor to pInode->pUnused list. It will be automatically closed
  25305. ** when the last lock is cleared.
  25306. */
  25307. setPendingFd(pFile);
  25308. }
  25309. releaseInodeInfo(pFile);
  25310. rc = closeUnixFile(id);
  25311. unixLeaveMutex();
  25312. return rc;
  25313. }
  25314. /************** End of the posix advisory lock implementation *****************
  25315. ******************************************************************************/
  25316. /******************************************************************************
  25317. ****************************** No-op Locking **********************************
  25318. **
  25319. ** Of the various locking implementations available, this is by far the
  25320. ** simplest: locking is ignored. No attempt is made to lock the database
  25321. ** file for reading or writing.
  25322. **
  25323. ** This locking mode is appropriate for use on read-only databases
  25324. ** (ex: databases that are burned into CD-ROM, for example.) It can
  25325. ** also be used if the application employs some external mechanism to
  25326. ** prevent simultaneous access of the same database by two or more
  25327. ** database connections. But there is a serious risk of database
  25328. ** corruption if this locking mode is used in situations where multiple
  25329. ** database connections are accessing the same database file at the same
  25330. ** time and one or more of those connections are writing.
  25331. */
  25332. static int nolockCheckReservedLock(sqlite3_file *NotUsed, int *pResOut){
  25333. UNUSED_PARAMETER(NotUsed);
  25334. *pResOut = 0;
  25335. return SQLITE_OK;
  25336. }
  25337. static int nolockLock(sqlite3_file *NotUsed, int NotUsed2){
  25338. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  25339. return SQLITE_OK;
  25340. }
  25341. static int nolockUnlock(sqlite3_file *NotUsed, int NotUsed2){
  25342. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  25343. return SQLITE_OK;
  25344. }
  25345. /*
  25346. ** Close the file.
  25347. */
  25348. static int nolockClose(sqlite3_file *id) {
  25349. return closeUnixFile(id);
  25350. }
  25351. /******************* End of the no-op lock implementation *********************
  25352. ******************************************************************************/
  25353. /******************************************************************************
  25354. ************************* Begin dot-file Locking ******************************
  25355. **
  25356. ** The dotfile locking implementation uses the existence of separate lock
  25357. ** files (really a directory) to control access to the database. This works
  25358. ** on just about every filesystem imaginable. But there are serious downsides:
  25359. **
  25360. ** (1) There is zero concurrency. A single reader blocks all other
  25361. ** connections from reading or writing the database.
  25362. **
  25363. ** (2) An application crash or power loss can leave stale lock files
  25364. ** sitting around that need to be cleared manually.
  25365. **
  25366. ** Nevertheless, a dotlock is an appropriate locking mode for use if no
  25367. ** other locking strategy is available.
  25368. **
  25369. ** Dotfile locking works by creating a subdirectory in the same directory as
  25370. ** the database and with the same name but with a ".lock" extension added.
  25371. ** The existence of a lock directory implies an EXCLUSIVE lock. All other
  25372. ** lock types (SHARED, RESERVED, PENDING) are mapped into EXCLUSIVE.
  25373. */
  25374. /*
  25375. ** The file suffix added to the data base filename in order to create the
  25376. ** lock directory.
  25377. */
  25378. #define DOTLOCK_SUFFIX ".lock"
  25379. /*
  25380. ** This routine checks if there is a RESERVED lock held on the specified
  25381. ** file by this or any other process. If such a lock is held, set *pResOut
  25382. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25383. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25384. **
  25385. ** In dotfile locking, either a lock exists or it does not. So in this
  25386. ** variation of CheckReservedLock(), *pResOut is set to true if any lock
  25387. ** is held on the file and false if the file is unlocked.
  25388. */
  25389. static int dotlockCheckReservedLock(sqlite3_file *id, int *pResOut) {
  25390. int rc = SQLITE_OK;
  25391. int reserved = 0;
  25392. unixFile *pFile = (unixFile*)id;
  25393. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25394. assert( pFile );
  25395. /* Check if a thread in this process holds such a lock */
  25396. if( pFile->eFileLock>SHARED_LOCK ){
  25397. /* Either this connection or some other connection in the same process
  25398. ** holds a lock on the file. No need to check further. */
  25399. reserved = 1;
  25400. }else{
  25401. /* The lock is held if and only if the lockfile exists */
  25402. const char *zLockFile = (const char*)pFile->lockingContext;
  25403. reserved = osAccess(zLockFile, 0)==0;
  25404. }
  25405. OSTRACE(("TEST WR-LOCK %d %d %d (dotlock)\n", pFile->h, rc, reserved));
  25406. *pResOut = reserved;
  25407. return rc;
  25408. }
  25409. /*
  25410. ** Lock the file with the lock specified by parameter eFileLock - one
  25411. ** of the following:
  25412. **
  25413. ** (1) SHARED_LOCK
  25414. ** (2) RESERVED_LOCK
  25415. ** (3) PENDING_LOCK
  25416. ** (4) EXCLUSIVE_LOCK
  25417. **
  25418. ** Sometimes when requesting one lock state, additional lock states
  25419. ** are inserted in between. The locking might fail on one of the later
  25420. ** transitions leaving the lock state different from what it started but
  25421. ** still short of its goal. The following chart shows the allowed
  25422. ** transitions and the inserted intermediate states:
  25423. **
  25424. ** UNLOCKED -> SHARED
  25425. ** SHARED -> RESERVED
  25426. ** SHARED -> (PENDING) -> EXCLUSIVE
  25427. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25428. ** PENDING -> EXCLUSIVE
  25429. **
  25430. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25431. ** routine to lower a locking level.
  25432. **
  25433. ** With dotfile locking, we really only support state (4): EXCLUSIVE.
  25434. ** But we track the other locking levels internally.
  25435. */
  25436. static int dotlockLock(sqlite3_file *id, int eFileLock) {
  25437. unixFile *pFile = (unixFile*)id;
  25438. char *zLockFile = (char *)pFile->lockingContext;
  25439. int rc = SQLITE_OK;
  25440. /* If we have any lock, then the lock file already exists. All we have
  25441. ** to do is adjust our internal record of the lock level.
  25442. */
  25443. if( pFile->eFileLock > NO_LOCK ){
  25444. pFile->eFileLock = eFileLock;
  25445. /* Always update the timestamp on the old file */
  25446. #ifdef HAVE_UTIME
  25447. utime(zLockFile, NULL);
  25448. #else
  25449. utimes(zLockFile, NULL);
  25450. #endif
  25451. return SQLITE_OK;
  25452. }
  25453. /* grab an exclusive lock */
  25454. rc = osMkdir(zLockFile, 0777);
  25455. if( rc<0 ){
  25456. /* failed to open/create the lock directory */
  25457. int tErrno = errno;
  25458. if( EEXIST == tErrno ){
  25459. rc = SQLITE_BUSY;
  25460. } else {
  25461. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25462. if( IS_LOCK_ERROR(rc) ){
  25463. pFile->lastErrno = tErrno;
  25464. }
  25465. }
  25466. return rc;
  25467. }
  25468. /* got it, set the type and return ok */
  25469. pFile->eFileLock = eFileLock;
  25470. return rc;
  25471. }
  25472. /*
  25473. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25474. ** must be either NO_LOCK or SHARED_LOCK.
  25475. **
  25476. ** If the locking level of the file descriptor is already at or below
  25477. ** the requested locking level, this routine is a no-op.
  25478. **
  25479. ** When the locking level reaches NO_LOCK, delete the lock file.
  25480. */
  25481. static int dotlockUnlock(sqlite3_file *id, int eFileLock) {
  25482. unixFile *pFile = (unixFile*)id;
  25483. char *zLockFile = (char *)pFile->lockingContext;
  25484. int rc;
  25485. assert( pFile );
  25486. OSTRACE(("UNLOCK %d %d was %d pid=%d (dotlock)\n", pFile->h, eFileLock,
  25487. pFile->eFileLock, getpid()));
  25488. assert( eFileLock<=SHARED_LOCK );
  25489. /* no-op if possible */
  25490. if( pFile->eFileLock==eFileLock ){
  25491. return SQLITE_OK;
  25492. }
  25493. /* To downgrade to shared, simply update our internal notion of the
  25494. ** lock state. No need to mess with the file on disk.
  25495. */
  25496. if( eFileLock==SHARED_LOCK ){
  25497. pFile->eFileLock = SHARED_LOCK;
  25498. return SQLITE_OK;
  25499. }
  25500. /* To fully unlock the database, delete the lock file */
  25501. assert( eFileLock==NO_LOCK );
  25502. rc = osRmdir(zLockFile);
  25503. if( rc<0 && errno==ENOTDIR ) rc = osUnlink(zLockFile);
  25504. if( rc<0 ){
  25505. int tErrno = errno;
  25506. rc = 0;
  25507. if( ENOENT != tErrno ){
  25508. rc = SQLITE_IOERR_UNLOCK;
  25509. }
  25510. if( IS_LOCK_ERROR(rc) ){
  25511. pFile->lastErrno = tErrno;
  25512. }
  25513. return rc;
  25514. }
  25515. pFile->eFileLock = NO_LOCK;
  25516. return SQLITE_OK;
  25517. }
  25518. /*
  25519. ** Close a file. Make sure the lock has been released before closing.
  25520. */
  25521. static int dotlockClose(sqlite3_file *id) {
  25522. int rc = SQLITE_OK;
  25523. if( id ){
  25524. unixFile *pFile = (unixFile*)id;
  25525. dotlockUnlock(id, NO_LOCK);
  25526. sqlite3_free(pFile->lockingContext);
  25527. rc = closeUnixFile(id);
  25528. }
  25529. return rc;
  25530. }
  25531. /****************** End of the dot-file lock implementation *******************
  25532. ******************************************************************************/
  25533. /******************************************************************************
  25534. ************************** Begin flock Locking ********************************
  25535. **
  25536. ** Use the flock() system call to do file locking.
  25537. **
  25538. ** flock() locking is like dot-file locking in that the various
  25539. ** fine-grain locking levels supported by SQLite are collapsed into
  25540. ** a single exclusive lock. In other words, SHARED, RESERVED, and
  25541. ** PENDING locks are the same thing as an EXCLUSIVE lock. SQLite
  25542. ** still works when you do this, but concurrency is reduced since
  25543. ** only a single process can be reading the database at a time.
  25544. **
  25545. ** Omit this section if SQLITE_ENABLE_LOCKING_STYLE is turned off or if
  25546. ** compiling for VXWORKS.
  25547. */
  25548. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  25549. /*
  25550. ** Retry flock() calls that fail with EINTR
  25551. */
  25552. #ifdef EINTR
  25553. static int robust_flock(int fd, int op){
  25554. int rc;
  25555. do{ rc = flock(fd,op); }while( rc<0 && errno==EINTR );
  25556. return rc;
  25557. }
  25558. #else
  25559. # define robust_flock(a,b) flock(a,b)
  25560. #endif
  25561. /*
  25562. ** This routine checks if there is a RESERVED lock held on the specified
  25563. ** file by this or any other process. If such a lock is held, set *pResOut
  25564. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25565. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25566. */
  25567. static int flockCheckReservedLock(sqlite3_file *id, int *pResOut){
  25568. int rc = SQLITE_OK;
  25569. int reserved = 0;
  25570. unixFile *pFile = (unixFile*)id;
  25571. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25572. assert( pFile );
  25573. /* Check if a thread in this process holds such a lock */
  25574. if( pFile->eFileLock>SHARED_LOCK ){
  25575. reserved = 1;
  25576. }
  25577. /* Otherwise see if some other process holds it. */
  25578. if( !reserved ){
  25579. /* attempt to get the lock */
  25580. int lrc = robust_flock(pFile->h, LOCK_EX | LOCK_NB);
  25581. if( !lrc ){
  25582. /* got the lock, unlock it */
  25583. lrc = robust_flock(pFile->h, LOCK_UN);
  25584. if ( lrc ) {
  25585. int tErrno = errno;
  25586. /* unlock failed with an error */
  25587. lrc = SQLITE_IOERR_UNLOCK;
  25588. if( IS_LOCK_ERROR(lrc) ){
  25589. pFile->lastErrno = tErrno;
  25590. rc = lrc;
  25591. }
  25592. }
  25593. } else {
  25594. int tErrno = errno;
  25595. reserved = 1;
  25596. /* someone else might have it reserved */
  25597. lrc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25598. if( IS_LOCK_ERROR(lrc) ){
  25599. pFile->lastErrno = tErrno;
  25600. rc = lrc;
  25601. }
  25602. }
  25603. }
  25604. OSTRACE(("TEST WR-LOCK %d %d %d (flock)\n", pFile->h, rc, reserved));
  25605. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  25606. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  25607. rc = SQLITE_OK;
  25608. reserved=1;
  25609. }
  25610. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  25611. *pResOut = reserved;
  25612. return rc;
  25613. }
  25614. /*
  25615. ** Lock the file with the lock specified by parameter eFileLock - one
  25616. ** of the following:
  25617. **
  25618. ** (1) SHARED_LOCK
  25619. ** (2) RESERVED_LOCK
  25620. ** (3) PENDING_LOCK
  25621. ** (4) EXCLUSIVE_LOCK
  25622. **
  25623. ** Sometimes when requesting one lock state, additional lock states
  25624. ** are inserted in between. The locking might fail on one of the later
  25625. ** transitions leaving the lock state different from what it started but
  25626. ** still short of its goal. The following chart shows the allowed
  25627. ** transitions and the inserted intermediate states:
  25628. **
  25629. ** UNLOCKED -> SHARED
  25630. ** SHARED -> RESERVED
  25631. ** SHARED -> (PENDING) -> EXCLUSIVE
  25632. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25633. ** PENDING -> EXCLUSIVE
  25634. **
  25635. ** flock() only really support EXCLUSIVE locks. We track intermediate
  25636. ** lock states in the sqlite3_file structure, but all locks SHARED or
  25637. ** above are really EXCLUSIVE locks and exclude all other processes from
  25638. ** access the file.
  25639. **
  25640. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25641. ** routine to lower a locking level.
  25642. */
  25643. static int flockLock(sqlite3_file *id, int eFileLock) {
  25644. int rc = SQLITE_OK;
  25645. unixFile *pFile = (unixFile*)id;
  25646. assert( pFile );
  25647. /* if we already have a lock, it is exclusive.
  25648. ** Just adjust level and punt on outta here. */
  25649. if (pFile->eFileLock > NO_LOCK) {
  25650. pFile->eFileLock = eFileLock;
  25651. return SQLITE_OK;
  25652. }
  25653. /* grab an exclusive lock */
  25654. if (robust_flock(pFile->h, LOCK_EX | LOCK_NB)) {
  25655. int tErrno = errno;
  25656. /* didn't get, must be busy */
  25657. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_LOCK);
  25658. if( IS_LOCK_ERROR(rc) ){
  25659. pFile->lastErrno = tErrno;
  25660. }
  25661. } else {
  25662. /* got it, set the type and return ok */
  25663. pFile->eFileLock = eFileLock;
  25664. }
  25665. OSTRACE(("LOCK %d %s %s (flock)\n", pFile->h, azFileLock(eFileLock),
  25666. rc==SQLITE_OK ? "ok" : "failed"));
  25667. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  25668. if( (rc & SQLITE_IOERR) == SQLITE_IOERR ){
  25669. rc = SQLITE_BUSY;
  25670. }
  25671. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  25672. return rc;
  25673. }
  25674. /*
  25675. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25676. ** must be either NO_LOCK or SHARED_LOCK.
  25677. **
  25678. ** If the locking level of the file descriptor is already at or below
  25679. ** the requested locking level, this routine is a no-op.
  25680. */
  25681. static int flockUnlock(sqlite3_file *id, int eFileLock) {
  25682. unixFile *pFile = (unixFile*)id;
  25683. assert( pFile );
  25684. OSTRACE(("UNLOCK %d %d was %d pid=%d (flock)\n", pFile->h, eFileLock,
  25685. pFile->eFileLock, getpid()));
  25686. assert( eFileLock<=SHARED_LOCK );
  25687. /* no-op if possible */
  25688. if( pFile->eFileLock==eFileLock ){
  25689. return SQLITE_OK;
  25690. }
  25691. /* shared can just be set because we always have an exclusive */
  25692. if (eFileLock==SHARED_LOCK) {
  25693. pFile->eFileLock = eFileLock;
  25694. return SQLITE_OK;
  25695. }
  25696. /* no, really, unlock. */
  25697. if( robust_flock(pFile->h, LOCK_UN) ){
  25698. #ifdef SQLITE_IGNORE_FLOCK_LOCK_ERRORS
  25699. return SQLITE_OK;
  25700. #endif /* SQLITE_IGNORE_FLOCK_LOCK_ERRORS */
  25701. return SQLITE_IOERR_UNLOCK;
  25702. }else{
  25703. pFile->eFileLock = NO_LOCK;
  25704. return SQLITE_OK;
  25705. }
  25706. }
  25707. /*
  25708. ** Close a file.
  25709. */
  25710. static int flockClose(sqlite3_file *id) {
  25711. int rc = SQLITE_OK;
  25712. if( id ){
  25713. flockUnlock(id, NO_LOCK);
  25714. rc = closeUnixFile(id);
  25715. }
  25716. return rc;
  25717. }
  25718. #endif /* SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORK */
  25719. /******************* End of the flock lock implementation *********************
  25720. ******************************************************************************/
  25721. /******************************************************************************
  25722. ************************ Begin Named Semaphore Locking ************************
  25723. **
  25724. ** Named semaphore locking is only supported on VxWorks.
  25725. **
  25726. ** Semaphore locking is like dot-lock and flock in that it really only
  25727. ** supports EXCLUSIVE locking. Only a single process can read or write
  25728. ** the database file at a time. This reduces potential concurrency, but
  25729. ** makes the lock implementation much easier.
  25730. */
  25731. #if OS_VXWORKS
  25732. /*
  25733. ** This routine checks if there is a RESERVED lock held on the specified
  25734. ** file by this or any other process. If such a lock is held, set *pResOut
  25735. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25736. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25737. */
  25738. static int semCheckReservedLock(sqlite3_file *id, int *pResOut) {
  25739. int rc = SQLITE_OK;
  25740. int reserved = 0;
  25741. unixFile *pFile = (unixFile*)id;
  25742. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25743. assert( pFile );
  25744. /* Check if a thread in this process holds such a lock */
  25745. if( pFile->eFileLock>SHARED_LOCK ){
  25746. reserved = 1;
  25747. }
  25748. /* Otherwise see if some other process holds it. */
  25749. if( !reserved ){
  25750. sem_t *pSem = pFile->pInode->pSem;
  25751. if( sem_trywait(pSem)==-1 ){
  25752. int tErrno = errno;
  25753. if( EAGAIN != tErrno ){
  25754. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_CHECKRESERVEDLOCK);
  25755. pFile->lastErrno = tErrno;
  25756. } else {
  25757. /* someone else has the lock when we are in NO_LOCK */
  25758. reserved = (pFile->eFileLock < SHARED_LOCK);
  25759. }
  25760. }else{
  25761. /* we could have it if we want it */
  25762. sem_post(pSem);
  25763. }
  25764. }
  25765. OSTRACE(("TEST WR-LOCK %d %d %d (sem)\n", pFile->h, rc, reserved));
  25766. *pResOut = reserved;
  25767. return rc;
  25768. }
  25769. /*
  25770. ** Lock the file with the lock specified by parameter eFileLock - one
  25771. ** of the following:
  25772. **
  25773. ** (1) SHARED_LOCK
  25774. ** (2) RESERVED_LOCK
  25775. ** (3) PENDING_LOCK
  25776. ** (4) EXCLUSIVE_LOCK
  25777. **
  25778. ** Sometimes when requesting one lock state, additional lock states
  25779. ** are inserted in between. The locking might fail on one of the later
  25780. ** transitions leaving the lock state different from what it started but
  25781. ** still short of its goal. The following chart shows the allowed
  25782. ** transitions and the inserted intermediate states:
  25783. **
  25784. ** UNLOCKED -> SHARED
  25785. ** SHARED -> RESERVED
  25786. ** SHARED -> (PENDING) -> EXCLUSIVE
  25787. ** RESERVED -> (PENDING) -> EXCLUSIVE
  25788. ** PENDING -> EXCLUSIVE
  25789. **
  25790. ** Semaphore locks only really support EXCLUSIVE locks. We track intermediate
  25791. ** lock states in the sqlite3_file structure, but all locks SHARED or
  25792. ** above are really EXCLUSIVE locks and exclude all other processes from
  25793. ** access the file.
  25794. **
  25795. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  25796. ** routine to lower a locking level.
  25797. */
  25798. static int semLock(sqlite3_file *id, int eFileLock) {
  25799. unixFile *pFile = (unixFile*)id;
  25800. sem_t *pSem = pFile->pInode->pSem;
  25801. int rc = SQLITE_OK;
  25802. /* if we already have a lock, it is exclusive.
  25803. ** Just adjust level and punt on outta here. */
  25804. if (pFile->eFileLock > NO_LOCK) {
  25805. pFile->eFileLock = eFileLock;
  25806. rc = SQLITE_OK;
  25807. goto sem_end_lock;
  25808. }
  25809. /* lock semaphore now but bail out when already locked. */
  25810. if( sem_trywait(pSem)==-1 ){
  25811. rc = SQLITE_BUSY;
  25812. goto sem_end_lock;
  25813. }
  25814. /* got it, set the type and return ok */
  25815. pFile->eFileLock = eFileLock;
  25816. sem_end_lock:
  25817. return rc;
  25818. }
  25819. /*
  25820. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  25821. ** must be either NO_LOCK or SHARED_LOCK.
  25822. **
  25823. ** If the locking level of the file descriptor is already at or below
  25824. ** the requested locking level, this routine is a no-op.
  25825. */
  25826. static int semUnlock(sqlite3_file *id, int eFileLock) {
  25827. unixFile *pFile = (unixFile*)id;
  25828. sem_t *pSem = pFile->pInode->pSem;
  25829. assert( pFile );
  25830. assert( pSem );
  25831. OSTRACE(("UNLOCK %d %d was %d pid=%d (sem)\n", pFile->h, eFileLock,
  25832. pFile->eFileLock, getpid()));
  25833. assert( eFileLock<=SHARED_LOCK );
  25834. /* no-op if possible */
  25835. if( pFile->eFileLock==eFileLock ){
  25836. return SQLITE_OK;
  25837. }
  25838. /* shared can just be set because we always have an exclusive */
  25839. if (eFileLock==SHARED_LOCK) {
  25840. pFile->eFileLock = eFileLock;
  25841. return SQLITE_OK;
  25842. }
  25843. /* no, really unlock. */
  25844. if ( sem_post(pSem)==-1 ) {
  25845. int rc, tErrno = errno;
  25846. rc = sqliteErrorFromPosixError(tErrno, SQLITE_IOERR_UNLOCK);
  25847. if( IS_LOCK_ERROR(rc) ){
  25848. pFile->lastErrno = tErrno;
  25849. }
  25850. return rc;
  25851. }
  25852. pFile->eFileLock = NO_LOCK;
  25853. return SQLITE_OK;
  25854. }
  25855. /*
  25856. ** Close a file.
  25857. */
  25858. static int semClose(sqlite3_file *id) {
  25859. if( id ){
  25860. unixFile *pFile = (unixFile*)id;
  25861. semUnlock(id, NO_LOCK);
  25862. assert( pFile );
  25863. unixEnterMutex();
  25864. releaseInodeInfo(pFile);
  25865. unixLeaveMutex();
  25866. closeUnixFile(id);
  25867. }
  25868. return SQLITE_OK;
  25869. }
  25870. #endif /* OS_VXWORKS */
  25871. /*
  25872. ** Named semaphore locking is only available on VxWorks.
  25873. **
  25874. *************** End of the named semaphore lock implementation ****************
  25875. ******************************************************************************/
  25876. /******************************************************************************
  25877. *************************** Begin AFP Locking *********************************
  25878. **
  25879. ** AFP is the Apple Filing Protocol. AFP is a network filesystem found
  25880. ** on Apple Macintosh computers - both OS9 and OSX.
  25881. **
  25882. ** Third-party implementations of AFP are available. But this code here
  25883. ** only works on OSX.
  25884. */
  25885. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  25886. /*
  25887. ** The afpLockingContext structure contains all afp lock specific state
  25888. */
  25889. typedef struct afpLockingContext afpLockingContext;
  25890. struct afpLockingContext {
  25891. int reserved;
  25892. const char *dbPath; /* Name of the open file */
  25893. };
  25894. struct ByteRangeLockPB2
  25895. {
  25896. unsigned long long offset; /* offset to first byte to lock */
  25897. unsigned long long length; /* nbr of bytes to lock */
  25898. unsigned long long retRangeStart; /* nbr of 1st byte locked if successful */
  25899. unsigned char unLockFlag; /* 1 = unlock, 0 = lock */
  25900. unsigned char startEndFlag; /* 1=rel to end of fork, 0=rel to start */
  25901. int fd; /* file desc to assoc this lock with */
  25902. };
  25903. #define afpfsByteRangeLock2FSCTL _IOWR('z', 23, struct ByteRangeLockPB2)
  25904. /*
  25905. ** This is a utility for setting or clearing a bit-range lock on an
  25906. ** AFP filesystem.
  25907. **
  25908. ** Return SQLITE_OK on success, SQLITE_BUSY on failure.
  25909. */
  25910. static int afpSetLock(
  25911. const char *path, /* Name of the file to be locked or unlocked */
  25912. unixFile *pFile, /* Open file descriptor on path */
  25913. unsigned long long offset, /* First byte to be locked */
  25914. unsigned long long length, /* Number of bytes to lock */
  25915. int setLockFlag /* True to set lock. False to clear lock */
  25916. ){
  25917. struct ByteRangeLockPB2 pb;
  25918. int err;
  25919. pb.unLockFlag = setLockFlag ? 0 : 1;
  25920. pb.startEndFlag = 0;
  25921. pb.offset = offset;
  25922. pb.length = length;
  25923. pb.fd = pFile->h;
  25924. OSTRACE(("AFPSETLOCK [%s] for %d%s in range %llx:%llx\n",
  25925. (setLockFlag?"ON":"OFF"), pFile->h, (pb.fd==-1?"[testval-1]":""),
  25926. offset, length));
  25927. err = fsctl(path, afpfsByteRangeLock2FSCTL, &pb, 0);
  25928. if ( err==-1 ) {
  25929. int rc;
  25930. int tErrno = errno;
  25931. OSTRACE(("AFPSETLOCK failed to fsctl() '%s' %d %s\n",
  25932. path, tErrno, strerror(tErrno)));
  25933. #ifdef SQLITE_IGNORE_AFP_LOCK_ERRORS
  25934. rc = SQLITE_BUSY;
  25935. #else
  25936. rc = sqliteErrorFromPosixError(tErrno,
  25937. setLockFlag ? SQLITE_IOERR_LOCK : SQLITE_IOERR_UNLOCK);
  25938. #endif /* SQLITE_IGNORE_AFP_LOCK_ERRORS */
  25939. if( IS_LOCK_ERROR(rc) ){
  25940. pFile->lastErrno = tErrno;
  25941. }
  25942. return rc;
  25943. } else {
  25944. return SQLITE_OK;
  25945. }
  25946. }
  25947. /*
  25948. ** This routine checks if there is a RESERVED lock held on the specified
  25949. ** file by this or any other process. If such a lock is held, set *pResOut
  25950. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  25951. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  25952. */
  25953. static int afpCheckReservedLock(sqlite3_file *id, int *pResOut){
  25954. int rc = SQLITE_OK;
  25955. int reserved = 0;
  25956. unixFile *pFile = (unixFile*)id;
  25957. afpLockingContext *context;
  25958. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  25959. assert( pFile );
  25960. context = (afpLockingContext *) pFile->lockingContext;
  25961. if( context->reserved ){
  25962. *pResOut = 1;
  25963. return SQLITE_OK;
  25964. }
  25965. unixEnterMutex(); /* Because pFile->pInode is shared across threads */
  25966. /* Check if a thread in this process holds such a lock */
  25967. if( pFile->pInode->eFileLock>SHARED_LOCK ){
  25968. reserved = 1;
  25969. }
  25970. /* Otherwise see if some other process holds it.
  25971. */
  25972. if( !reserved ){
  25973. /* lock the RESERVED byte */
  25974. int lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  25975. if( SQLITE_OK==lrc ){
  25976. /* if we succeeded in taking the reserved lock, unlock it to restore
  25977. ** the original state */
  25978. lrc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  25979. } else {
  25980. /* if we failed to get the lock then someone else must have it */
  25981. reserved = 1;
  25982. }
  25983. if( IS_LOCK_ERROR(lrc) ){
  25984. rc=lrc;
  25985. }
  25986. }
  25987. unixLeaveMutex();
  25988. OSTRACE(("TEST WR-LOCK %d %d %d (afp)\n", pFile->h, rc, reserved));
  25989. *pResOut = reserved;
  25990. return rc;
  25991. }
  25992. /*
  25993. ** Lock the file with the lock specified by parameter eFileLock - one
  25994. ** of the following:
  25995. **
  25996. ** (1) SHARED_LOCK
  25997. ** (2) RESERVED_LOCK
  25998. ** (3) PENDING_LOCK
  25999. ** (4) EXCLUSIVE_LOCK
  26000. **
  26001. ** Sometimes when requesting one lock state, additional lock states
  26002. ** are inserted in between. The locking might fail on one of the later
  26003. ** transitions leaving the lock state different from what it started but
  26004. ** still short of its goal. The following chart shows the allowed
  26005. ** transitions and the inserted intermediate states:
  26006. **
  26007. ** UNLOCKED -> SHARED
  26008. ** SHARED -> RESERVED
  26009. ** SHARED -> (PENDING) -> EXCLUSIVE
  26010. ** RESERVED -> (PENDING) -> EXCLUSIVE
  26011. ** PENDING -> EXCLUSIVE
  26012. **
  26013. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  26014. ** routine to lower a locking level.
  26015. */
  26016. static int afpLock(sqlite3_file *id, int eFileLock){
  26017. int rc = SQLITE_OK;
  26018. unixFile *pFile = (unixFile*)id;
  26019. unixInodeInfo *pInode = pFile->pInode;
  26020. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  26021. assert( pFile );
  26022. OSTRACE(("LOCK %d %s was %s(%s,%d) pid=%d (afp)\n", pFile->h,
  26023. azFileLock(eFileLock), azFileLock(pFile->eFileLock),
  26024. azFileLock(pInode->eFileLock), pInode->nShared , getpid()));
  26025. /* If there is already a lock of this type or more restrictive on the
  26026. ** unixFile, do nothing. Don't use the afp_end_lock: exit path, as
  26027. ** unixEnterMutex() hasn't been called yet.
  26028. */
  26029. if( pFile->eFileLock>=eFileLock ){
  26030. OSTRACE(("LOCK %d %s ok (already held) (afp)\n", pFile->h,
  26031. azFileLock(eFileLock)));
  26032. return SQLITE_OK;
  26033. }
  26034. /* Make sure the locking sequence is correct
  26035. ** (1) We never move from unlocked to anything higher than shared lock.
  26036. ** (2) SQLite never explicitly requests a pendig lock.
  26037. ** (3) A shared lock is always held when a reserve lock is requested.
  26038. */
  26039. assert( pFile->eFileLock!=NO_LOCK || eFileLock==SHARED_LOCK );
  26040. assert( eFileLock!=PENDING_LOCK );
  26041. assert( eFileLock!=RESERVED_LOCK || pFile->eFileLock==SHARED_LOCK );
  26042. /* This mutex is needed because pFile->pInode is shared across threads
  26043. */
  26044. unixEnterMutex();
  26045. pInode = pFile->pInode;
  26046. /* If some thread using this PID has a lock via a different unixFile*
  26047. ** handle that precludes the requested lock, return BUSY.
  26048. */
  26049. if( (pFile->eFileLock!=pInode->eFileLock &&
  26050. (pInode->eFileLock>=PENDING_LOCK || eFileLock>SHARED_LOCK))
  26051. ){
  26052. rc = SQLITE_BUSY;
  26053. goto afp_end_lock;
  26054. }
  26055. /* If a SHARED lock is requested, and some thread using this PID already
  26056. ** has a SHARED or RESERVED lock, then increment reference counts and
  26057. ** return SQLITE_OK.
  26058. */
  26059. if( eFileLock==SHARED_LOCK &&
  26060. (pInode->eFileLock==SHARED_LOCK || pInode->eFileLock==RESERVED_LOCK) ){
  26061. assert( eFileLock==SHARED_LOCK );
  26062. assert( pFile->eFileLock==0 );
  26063. assert( pInode->nShared>0 );
  26064. pFile->eFileLock = SHARED_LOCK;
  26065. pInode->nShared++;
  26066. pInode->nLock++;
  26067. goto afp_end_lock;
  26068. }
  26069. /* A PENDING lock is needed before acquiring a SHARED lock and before
  26070. ** acquiring an EXCLUSIVE lock. For the SHARED lock, the PENDING will
  26071. ** be released.
  26072. */
  26073. if( eFileLock==SHARED_LOCK
  26074. || (eFileLock==EXCLUSIVE_LOCK && pFile->eFileLock<PENDING_LOCK)
  26075. ){
  26076. int failed;
  26077. failed = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 1);
  26078. if (failed) {
  26079. rc = failed;
  26080. goto afp_end_lock;
  26081. }
  26082. }
  26083. /* If control gets to this point, then actually go ahead and make
  26084. ** operating system calls for the specified lock.
  26085. */
  26086. if( eFileLock==SHARED_LOCK ){
  26087. int lrc1, lrc2, lrc1Errno = 0;
  26088. long lk, mask;
  26089. assert( pInode->nShared==0 );
  26090. assert( pInode->eFileLock==0 );
  26091. mask = (sizeof(long)==8) ? LARGEST_INT64 : 0x7fffffff;
  26092. /* Now get the read-lock SHARED_LOCK */
  26093. /* note that the quality of the randomness doesn't matter that much */
  26094. lk = random();
  26095. pInode->sharedByte = (lk & mask)%(SHARED_SIZE - 1);
  26096. lrc1 = afpSetLock(context->dbPath, pFile,
  26097. SHARED_FIRST+pInode->sharedByte, 1, 1);
  26098. if( IS_LOCK_ERROR(lrc1) ){
  26099. lrc1Errno = pFile->lastErrno;
  26100. }
  26101. /* Drop the temporary PENDING lock */
  26102. lrc2 = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  26103. if( IS_LOCK_ERROR(lrc1) ) {
  26104. pFile->lastErrno = lrc1Errno;
  26105. rc = lrc1;
  26106. goto afp_end_lock;
  26107. } else if( IS_LOCK_ERROR(lrc2) ){
  26108. rc = lrc2;
  26109. goto afp_end_lock;
  26110. } else if( lrc1 != SQLITE_OK ) {
  26111. rc = lrc1;
  26112. } else {
  26113. pFile->eFileLock = SHARED_LOCK;
  26114. pInode->nLock++;
  26115. pInode->nShared = 1;
  26116. }
  26117. }else if( eFileLock==EXCLUSIVE_LOCK && pInode->nShared>1 ){
  26118. /* We are trying for an exclusive lock but another thread in this
  26119. ** same process is still holding a shared lock. */
  26120. rc = SQLITE_BUSY;
  26121. }else{
  26122. /* The request was for a RESERVED or EXCLUSIVE lock. It is
  26123. ** assumed that there is a SHARED or greater lock on the file
  26124. ** already.
  26125. */
  26126. int failed = 0;
  26127. assert( 0!=pFile->eFileLock );
  26128. if (eFileLock >= RESERVED_LOCK && pFile->eFileLock < RESERVED_LOCK) {
  26129. /* Acquire a RESERVED lock */
  26130. failed = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1,1);
  26131. if( !failed ){
  26132. context->reserved = 1;
  26133. }
  26134. }
  26135. if (!failed && eFileLock == EXCLUSIVE_LOCK) {
  26136. /* Acquire an EXCLUSIVE lock */
  26137. /* Remove the shared lock before trying the range. we'll need to
  26138. ** reestablish the shared lock if we can't get the afpUnlock
  26139. */
  26140. if( !(failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST +
  26141. pInode->sharedByte, 1, 0)) ){
  26142. int failed2 = SQLITE_OK;
  26143. /* now attemmpt to get the exclusive lock range */
  26144. failed = afpSetLock(context->dbPath, pFile, SHARED_FIRST,
  26145. SHARED_SIZE, 1);
  26146. if( failed && (failed2 = afpSetLock(context->dbPath, pFile,
  26147. SHARED_FIRST + pInode->sharedByte, 1, 1)) ){
  26148. /* Can't reestablish the shared lock. Sqlite can't deal, this is
  26149. ** a critical I/O error
  26150. */
  26151. rc = ((failed & SQLITE_IOERR) == SQLITE_IOERR) ? failed2 :
  26152. SQLITE_IOERR_LOCK;
  26153. goto afp_end_lock;
  26154. }
  26155. }else{
  26156. rc = failed;
  26157. }
  26158. }
  26159. if( failed ){
  26160. rc = failed;
  26161. }
  26162. }
  26163. if( rc==SQLITE_OK ){
  26164. pFile->eFileLock = eFileLock;
  26165. pInode->eFileLock = eFileLock;
  26166. }else if( eFileLock==EXCLUSIVE_LOCK ){
  26167. pFile->eFileLock = PENDING_LOCK;
  26168. pInode->eFileLock = PENDING_LOCK;
  26169. }
  26170. afp_end_lock:
  26171. unixLeaveMutex();
  26172. OSTRACE(("LOCK %d %s %s (afp)\n", pFile->h, azFileLock(eFileLock),
  26173. rc==SQLITE_OK ? "ok" : "failed"));
  26174. return rc;
  26175. }
  26176. /*
  26177. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26178. ** must be either NO_LOCK or SHARED_LOCK.
  26179. **
  26180. ** If the locking level of the file descriptor is already at or below
  26181. ** the requested locking level, this routine is a no-op.
  26182. */
  26183. static int afpUnlock(sqlite3_file *id, int eFileLock) {
  26184. int rc = SQLITE_OK;
  26185. unixFile *pFile = (unixFile*)id;
  26186. unixInodeInfo *pInode;
  26187. afpLockingContext *context = (afpLockingContext *) pFile->lockingContext;
  26188. int skipShared = 0;
  26189. #ifdef SQLITE_TEST
  26190. int h = pFile->h;
  26191. #endif
  26192. assert( pFile );
  26193. OSTRACE(("UNLOCK %d %d was %d(%d,%d) pid=%d (afp)\n", pFile->h, eFileLock,
  26194. pFile->eFileLock, pFile->pInode->eFileLock, pFile->pInode->nShared,
  26195. getpid()));
  26196. assert( eFileLock<=SHARED_LOCK );
  26197. if( pFile->eFileLock<=eFileLock ){
  26198. return SQLITE_OK;
  26199. }
  26200. unixEnterMutex();
  26201. pInode = pFile->pInode;
  26202. assert( pInode->nShared!=0 );
  26203. if( pFile->eFileLock>SHARED_LOCK ){
  26204. assert( pInode->eFileLock==pFile->eFileLock );
  26205. SimulateIOErrorBenign(1);
  26206. SimulateIOError( h=(-1) )
  26207. SimulateIOErrorBenign(0);
  26208. #ifdef SQLITE_DEBUG
  26209. /* When reducing a lock such that other processes can start
  26210. ** reading the database file again, make sure that the
  26211. ** transaction counter was updated if any part of the database
  26212. ** file changed. If the transaction counter is not updated,
  26213. ** other connections to the same file might not realize that
  26214. ** the file has changed and hence might not know to flush their
  26215. ** cache. The use of a stale cache can lead to database corruption.
  26216. */
  26217. assert( pFile->inNormalWrite==0
  26218. || pFile->dbUpdate==0
  26219. || pFile->transCntrChng==1 );
  26220. pFile->inNormalWrite = 0;
  26221. #endif
  26222. if( pFile->eFileLock==EXCLUSIVE_LOCK ){
  26223. rc = afpSetLock(context->dbPath, pFile, SHARED_FIRST, SHARED_SIZE, 0);
  26224. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1) ){
  26225. /* only re-establish the shared lock if necessary */
  26226. int sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  26227. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 1);
  26228. } else {
  26229. skipShared = 1;
  26230. }
  26231. }
  26232. if( rc==SQLITE_OK && pFile->eFileLock>=PENDING_LOCK ){
  26233. rc = afpSetLock(context->dbPath, pFile, PENDING_BYTE, 1, 0);
  26234. }
  26235. if( rc==SQLITE_OK && pFile->eFileLock>=RESERVED_LOCK && context->reserved ){
  26236. rc = afpSetLock(context->dbPath, pFile, RESERVED_BYTE, 1, 0);
  26237. if( !rc ){
  26238. context->reserved = 0;
  26239. }
  26240. }
  26241. if( rc==SQLITE_OK && (eFileLock==SHARED_LOCK || pInode->nShared>1)){
  26242. pInode->eFileLock = SHARED_LOCK;
  26243. }
  26244. }
  26245. if( rc==SQLITE_OK && eFileLock==NO_LOCK ){
  26246. /* Decrement the shared lock counter. Release the lock using an
  26247. ** OS call only when all threads in this same process have released
  26248. ** the lock.
  26249. */
  26250. unsigned long long sharedLockByte = SHARED_FIRST+pInode->sharedByte;
  26251. pInode->nShared--;
  26252. if( pInode->nShared==0 ){
  26253. SimulateIOErrorBenign(1);
  26254. SimulateIOError( h=(-1) )
  26255. SimulateIOErrorBenign(0);
  26256. if( !skipShared ){
  26257. rc = afpSetLock(context->dbPath, pFile, sharedLockByte, 1, 0);
  26258. }
  26259. if( !rc ){
  26260. pInode->eFileLock = NO_LOCK;
  26261. pFile->eFileLock = NO_LOCK;
  26262. }
  26263. }
  26264. if( rc==SQLITE_OK ){
  26265. pInode->nLock--;
  26266. assert( pInode->nLock>=0 );
  26267. if( pInode->nLock==0 ){
  26268. closePendingFds(pFile);
  26269. }
  26270. }
  26271. }
  26272. unixLeaveMutex();
  26273. if( rc==SQLITE_OK ) pFile->eFileLock = eFileLock;
  26274. return rc;
  26275. }
  26276. /*
  26277. ** Close a file & cleanup AFP specific locking context
  26278. */
  26279. static int afpClose(sqlite3_file *id) {
  26280. int rc = SQLITE_OK;
  26281. if( id ){
  26282. unixFile *pFile = (unixFile*)id;
  26283. afpUnlock(id, NO_LOCK);
  26284. unixEnterMutex();
  26285. if( pFile->pInode && pFile->pInode->nLock ){
  26286. /* If there are outstanding locks, do not actually close the file just
  26287. ** yet because that would clear those locks. Instead, add the file
  26288. ** descriptor to pInode->aPending. It will be automatically closed when
  26289. ** the last lock is cleared.
  26290. */
  26291. setPendingFd(pFile);
  26292. }
  26293. releaseInodeInfo(pFile);
  26294. sqlite3_free(pFile->lockingContext);
  26295. rc = closeUnixFile(id);
  26296. unixLeaveMutex();
  26297. }
  26298. return rc;
  26299. }
  26300. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26301. /*
  26302. ** The code above is the AFP lock implementation. The code is specific
  26303. ** to MacOSX and does not work on other unix platforms. No alternative
  26304. ** is available. If you don't compile for a mac, then the "unix-afp"
  26305. ** VFS is not available.
  26306. **
  26307. ********************* End of the AFP lock implementation **********************
  26308. ******************************************************************************/
  26309. /******************************************************************************
  26310. *************************** Begin NFS Locking ********************************/
  26311. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  26312. /*
  26313. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  26314. ** must be either NO_LOCK or SHARED_LOCK.
  26315. **
  26316. ** If the locking level of the file descriptor is already at or below
  26317. ** the requested locking level, this routine is a no-op.
  26318. */
  26319. static int nfsUnlock(sqlite3_file *id, int eFileLock){
  26320. return posixUnlock(id, eFileLock, 1);
  26321. }
  26322. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  26323. /*
  26324. ** The code above is the NFS lock implementation. The code is specific
  26325. ** to MacOSX and does not work on other unix platforms. No alternative
  26326. ** is available.
  26327. **
  26328. ********************* End of the NFS lock implementation **********************
  26329. ******************************************************************************/
  26330. /******************************************************************************
  26331. **************** Non-locking sqlite3_file methods *****************************
  26332. **
  26333. ** The next division contains implementations for all methods of the
  26334. ** sqlite3_file object other than the locking methods. The locking
  26335. ** methods were defined in divisions above (one locking method per
  26336. ** division). Those methods that are common to all locking modes
  26337. ** are gather together into this division.
  26338. */
  26339. /*
  26340. ** Seek to the offset passed as the second argument, then read cnt
  26341. ** bytes into pBuf. Return the number of bytes actually read.
  26342. **
  26343. ** NB: If you define USE_PREAD or USE_PREAD64, then it might also
  26344. ** be necessary to define _XOPEN_SOURCE to be 500. This varies from
  26345. ** one system to another. Since SQLite does not define USE_PREAD
  26346. ** in any form by default, we will not attempt to define _XOPEN_SOURCE.
  26347. ** See tickets #2741 and #2681.
  26348. **
  26349. ** To avoid stomping the errno value on a failed read the lastErrno value
  26350. ** is set before returning.
  26351. */
  26352. static int seekAndRead(unixFile *id, sqlite3_int64 offset, void *pBuf, int cnt){
  26353. int got;
  26354. int prior = 0;
  26355. #if (!defined(USE_PREAD) && !defined(USE_PREAD64))
  26356. i64 newOffset;
  26357. #endif
  26358. TIMER_START;
  26359. assert( cnt==(cnt&0x1ffff) );
  26360. assert( id->h>2 );
  26361. cnt &= 0x1ffff;
  26362. do{
  26363. #if defined(USE_PREAD)
  26364. got = osPread(id->h, pBuf, cnt, offset);
  26365. SimulateIOError( got = -1 );
  26366. #elif defined(USE_PREAD64)
  26367. got = osPread64(id->h, pBuf, cnt, offset);
  26368. SimulateIOError( got = -1 );
  26369. #else
  26370. newOffset = lseek(id->h, offset, SEEK_SET);
  26371. SimulateIOError( newOffset-- );
  26372. if( newOffset!=offset ){
  26373. if( newOffset == -1 ){
  26374. ((unixFile*)id)->lastErrno = errno;
  26375. }else{
  26376. ((unixFile*)id)->lastErrno = 0;
  26377. }
  26378. return -1;
  26379. }
  26380. got = osRead(id->h, pBuf, cnt);
  26381. #endif
  26382. if( got==cnt ) break;
  26383. if( got<0 ){
  26384. if( errno==EINTR ){ got = 1; continue; }
  26385. prior = 0;
  26386. ((unixFile*)id)->lastErrno = errno;
  26387. break;
  26388. }else if( got>0 ){
  26389. cnt -= got;
  26390. offset += got;
  26391. prior += got;
  26392. pBuf = (void*)(got + (char*)pBuf);
  26393. }
  26394. }while( got>0 );
  26395. TIMER_END;
  26396. OSTRACE(("READ %-3d %5d %7lld %llu\n",
  26397. id->h, got+prior, offset-prior, TIMER_ELAPSED));
  26398. return got+prior;
  26399. }
  26400. /*
  26401. ** Read data from a file into a buffer. Return SQLITE_OK if all
  26402. ** bytes were read successfully and SQLITE_IOERR if anything goes
  26403. ** wrong.
  26404. */
  26405. static int unixRead(
  26406. sqlite3_file *id,
  26407. void *pBuf,
  26408. int amt,
  26409. sqlite3_int64 offset
  26410. ){
  26411. unixFile *pFile = (unixFile *)id;
  26412. int got;
  26413. assert( id );
  26414. assert( offset>=0 );
  26415. assert( amt>0 );
  26416. /* If this is a database file (not a journal, master-journal or temp
  26417. ** file), the bytes in the locking range should never be read or written. */
  26418. #if 0
  26419. assert( pFile->pUnused==0
  26420. || offset>=PENDING_BYTE+512
  26421. || offset+amt<=PENDING_BYTE
  26422. );
  26423. #endif
  26424. #if SQLITE_MAX_MMAP_SIZE>0
  26425. /* Deal with as much of this read request as possible by transfering
  26426. ** data from the memory mapping using memcpy(). */
  26427. if( offset<pFile->mmapSize ){
  26428. if( offset+amt <= pFile->mmapSize ){
  26429. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  26430. return SQLITE_OK;
  26431. }else{
  26432. int nCopy = pFile->mmapSize - offset;
  26433. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  26434. pBuf = &((u8 *)pBuf)[nCopy];
  26435. amt -= nCopy;
  26436. offset += nCopy;
  26437. }
  26438. }
  26439. #endif
  26440. got = seekAndRead(pFile, offset, pBuf, amt);
  26441. if( got==amt ){
  26442. return SQLITE_OK;
  26443. }else if( got<0 ){
  26444. /* lastErrno set by seekAndRead */
  26445. return SQLITE_IOERR_READ;
  26446. }else{
  26447. pFile->lastErrno = 0; /* not a system error */
  26448. /* Unread parts of the buffer must be zero-filled */
  26449. memset(&((char*)pBuf)[got], 0, amt-got);
  26450. return SQLITE_IOERR_SHORT_READ;
  26451. }
  26452. }
  26453. /*
  26454. ** Attempt to seek the file-descriptor passed as the first argument to
  26455. ** absolute offset iOff, then attempt to write nBuf bytes of data from
  26456. ** pBuf to it. If an error occurs, return -1 and set *piErrno. Otherwise,
  26457. ** return the actual number of bytes written (which may be less than
  26458. ** nBuf).
  26459. */
  26460. static int seekAndWriteFd(
  26461. int fd, /* File descriptor to write to */
  26462. i64 iOff, /* File offset to begin writing at */
  26463. const void *pBuf, /* Copy data from this buffer to the file */
  26464. int nBuf, /* Size of buffer pBuf in bytes */
  26465. int *piErrno /* OUT: Error number if error occurs */
  26466. ){
  26467. int rc = 0; /* Value returned by system call */
  26468. assert( nBuf==(nBuf&0x1ffff) );
  26469. assert( fd>2 );
  26470. nBuf &= 0x1ffff;
  26471. TIMER_START;
  26472. #if defined(USE_PREAD)
  26473. do{ rc = osPwrite(fd, pBuf, nBuf, iOff); }while( rc<0 && errno==EINTR );
  26474. #elif defined(USE_PREAD64)
  26475. do{ rc = osPwrite64(fd, pBuf, nBuf, iOff);}while( rc<0 && errno==EINTR);
  26476. #else
  26477. do{
  26478. i64 iSeek = lseek(fd, iOff, SEEK_SET);
  26479. SimulateIOError( iSeek-- );
  26480. if( iSeek!=iOff ){
  26481. if( piErrno ) *piErrno = (iSeek==-1 ? errno : 0);
  26482. return -1;
  26483. }
  26484. rc = osWrite(fd, pBuf, nBuf);
  26485. }while( rc<0 && errno==EINTR );
  26486. #endif
  26487. TIMER_END;
  26488. OSTRACE(("WRITE %-3d %5d %7lld %llu\n", fd, rc, iOff, TIMER_ELAPSED));
  26489. if( rc<0 && piErrno ) *piErrno = errno;
  26490. return rc;
  26491. }
  26492. /*
  26493. ** Seek to the offset in id->offset then read cnt bytes into pBuf.
  26494. ** Return the number of bytes actually read. Update the offset.
  26495. **
  26496. ** To avoid stomping the errno value on a failed write the lastErrno value
  26497. ** is set before returning.
  26498. */
  26499. static int seekAndWrite(unixFile *id, i64 offset, const void *pBuf, int cnt){
  26500. return seekAndWriteFd(id->h, offset, pBuf, cnt, &id->lastErrno);
  26501. }
  26502. /*
  26503. ** Write data from a buffer into a file. Return SQLITE_OK on success
  26504. ** or some other error code on failure.
  26505. */
  26506. static int unixWrite(
  26507. sqlite3_file *id,
  26508. const void *pBuf,
  26509. int amt,
  26510. sqlite3_int64 offset
  26511. ){
  26512. unixFile *pFile = (unixFile*)id;
  26513. int wrote = 0;
  26514. assert( id );
  26515. assert( amt>0 );
  26516. /* If this is a database file (not a journal, master-journal or temp
  26517. ** file), the bytes in the locking range should never be read or written. */
  26518. #if 0
  26519. assert( pFile->pUnused==0
  26520. || offset>=PENDING_BYTE+512
  26521. || offset+amt<=PENDING_BYTE
  26522. );
  26523. #endif
  26524. #ifdef SQLITE_DEBUG
  26525. /* If we are doing a normal write to a database file (as opposed to
  26526. ** doing a hot-journal rollback or a write to some file other than a
  26527. ** normal database file) then record the fact that the database
  26528. ** has changed. If the transaction counter is modified, record that
  26529. ** fact too.
  26530. */
  26531. if( pFile->inNormalWrite ){
  26532. pFile->dbUpdate = 1; /* The database has been modified */
  26533. if( offset<=24 && offset+amt>=27 ){
  26534. int rc;
  26535. char oldCntr[4];
  26536. SimulateIOErrorBenign(1);
  26537. rc = seekAndRead(pFile, 24, oldCntr, 4);
  26538. SimulateIOErrorBenign(0);
  26539. if( rc!=4 || memcmp(oldCntr, &((char*)pBuf)[24-offset], 4)!=0 ){
  26540. pFile->transCntrChng = 1; /* The transaction counter has changed */
  26541. }
  26542. }
  26543. }
  26544. #endif
  26545. #if SQLITE_MAX_MMAP_SIZE>0
  26546. /* Deal with as much of this write request as possible by transfering
  26547. ** data from the memory mapping using memcpy(). */
  26548. if( offset<pFile->mmapSize ){
  26549. if( offset+amt <= pFile->mmapSize ){
  26550. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  26551. return SQLITE_OK;
  26552. }else{
  26553. int nCopy = pFile->mmapSize - offset;
  26554. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  26555. pBuf = &((u8 *)pBuf)[nCopy];
  26556. amt -= nCopy;
  26557. offset += nCopy;
  26558. }
  26559. }
  26560. #endif
  26561. while( amt>0 && (wrote = seekAndWrite(pFile, offset, pBuf, amt))>0 ){
  26562. amt -= wrote;
  26563. offset += wrote;
  26564. pBuf = &((char*)pBuf)[wrote];
  26565. }
  26566. SimulateIOError(( wrote=(-1), amt=1 ));
  26567. SimulateDiskfullError(( wrote=0, amt=1 ));
  26568. if( amt>0 ){
  26569. if( wrote<0 && pFile->lastErrno!=ENOSPC ){
  26570. /* lastErrno set by seekAndWrite */
  26571. return SQLITE_IOERR_WRITE;
  26572. }else{
  26573. pFile->lastErrno = 0; /* not a system error */
  26574. return SQLITE_FULL;
  26575. }
  26576. }
  26577. return SQLITE_OK;
  26578. }
  26579. #ifdef SQLITE_TEST
  26580. /*
  26581. ** Count the number of fullsyncs and normal syncs. This is used to test
  26582. ** that syncs and fullsyncs are occurring at the right times.
  26583. */
  26584. SQLITE_API int sqlite3_sync_count = 0;
  26585. SQLITE_API int sqlite3_fullsync_count = 0;
  26586. #endif
  26587. /*
  26588. ** We do not trust systems to provide a working fdatasync(). Some do.
  26589. ** Others do no. To be safe, we will stick with the (slightly slower)
  26590. ** fsync(). If you know that your system does support fdatasync() correctly,
  26591. ** then simply compile with -Dfdatasync=fdatasync
  26592. */
  26593. #if !defined(fdatasync)
  26594. # define fdatasync fsync
  26595. #endif
  26596. /*
  26597. ** Define HAVE_FULLFSYNC to 0 or 1 depending on whether or not
  26598. ** the F_FULLFSYNC macro is defined. F_FULLFSYNC is currently
  26599. ** only available on Mac OS X. But that could change.
  26600. */
  26601. #ifdef F_FULLFSYNC
  26602. # define HAVE_FULLFSYNC 1
  26603. #else
  26604. # define HAVE_FULLFSYNC 0
  26605. #endif
  26606. /*
  26607. ** The fsync() system call does not work as advertised on many
  26608. ** unix systems. The following procedure is an attempt to make
  26609. ** it work better.
  26610. **
  26611. ** The SQLITE_NO_SYNC macro disables all fsync()s. This is useful
  26612. ** for testing when we want to run through the test suite quickly.
  26613. ** You are strongly advised *not* to deploy with SQLITE_NO_SYNC
  26614. ** enabled, however, since with SQLITE_NO_SYNC enabled, an OS crash
  26615. ** or power failure will likely corrupt the database file.
  26616. **
  26617. ** SQLite sets the dataOnly flag if the size of the file is unchanged.
  26618. ** The idea behind dataOnly is that it should only write the file content
  26619. ** to disk, not the inode. We only set dataOnly if the file size is
  26620. ** unchanged since the file size is part of the inode. However,
  26621. ** Ted Ts'o tells us that fdatasync() will also write the inode if the
  26622. ** file size has changed. The only real difference between fdatasync()
  26623. ** and fsync(), Ted tells us, is that fdatasync() will not flush the
  26624. ** inode if the mtime or owner or other inode attributes have changed.
  26625. ** We only care about the file size, not the other file attributes, so
  26626. ** as far as SQLite is concerned, an fdatasync() is always adequate.
  26627. ** So, we always use fdatasync() if it is available, regardless of
  26628. ** the value of the dataOnly flag.
  26629. */
  26630. static int full_fsync(int fd, int fullSync, int dataOnly){
  26631. int rc;
  26632. /* The following "ifdef/elif/else/" block has the same structure as
  26633. ** the one below. It is replicated here solely to avoid cluttering
  26634. ** up the real code with the UNUSED_PARAMETER() macros.
  26635. */
  26636. #ifdef SQLITE_NO_SYNC
  26637. UNUSED_PARAMETER(fd);
  26638. UNUSED_PARAMETER(fullSync);
  26639. UNUSED_PARAMETER(dataOnly);
  26640. #elif HAVE_FULLFSYNC
  26641. UNUSED_PARAMETER(dataOnly);
  26642. #else
  26643. UNUSED_PARAMETER(fullSync);
  26644. UNUSED_PARAMETER(dataOnly);
  26645. #endif
  26646. /* Record the number of times that we do a normal fsync() and
  26647. ** FULLSYNC. This is used during testing to verify that this procedure
  26648. ** gets called with the correct arguments.
  26649. */
  26650. #ifdef SQLITE_TEST
  26651. if( fullSync ) sqlite3_fullsync_count++;
  26652. sqlite3_sync_count++;
  26653. #endif
  26654. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  26655. ** no-op
  26656. */
  26657. #ifdef SQLITE_NO_SYNC
  26658. rc = SQLITE_OK;
  26659. #elif HAVE_FULLFSYNC
  26660. if( fullSync ){
  26661. rc = osFcntl(fd, F_FULLFSYNC, 0);
  26662. }else{
  26663. rc = 1;
  26664. }
  26665. /* If the FULLFSYNC failed, fall back to attempting an fsync().
  26666. ** It shouldn't be possible for fullfsync to fail on the local
  26667. ** file system (on OSX), so failure indicates that FULLFSYNC
  26668. ** isn't supported for this file system. So, attempt an fsync
  26669. ** and (for now) ignore the overhead of a superfluous fcntl call.
  26670. ** It'd be better to detect fullfsync support once and avoid
  26671. ** the fcntl call every time sync is called.
  26672. */
  26673. if( rc ) rc = fsync(fd);
  26674. #elif defined(__APPLE__)
  26675. /* fdatasync() on HFS+ doesn't yet flush the file size if it changed correctly
  26676. ** so currently we default to the macro that redefines fdatasync to fsync
  26677. */
  26678. rc = fsync(fd);
  26679. #else
  26680. rc = fdatasync(fd);
  26681. #if OS_VXWORKS
  26682. if( rc==-1 && errno==ENOTSUP ){
  26683. rc = fsync(fd);
  26684. }
  26685. #endif /* OS_VXWORKS */
  26686. #endif /* ifdef SQLITE_NO_SYNC elif HAVE_FULLFSYNC */
  26687. if( OS_VXWORKS && rc!= -1 ){
  26688. rc = 0;
  26689. }
  26690. return rc;
  26691. }
  26692. /*
  26693. ** Open a file descriptor to the directory containing file zFilename.
  26694. ** If successful, *pFd is set to the opened file descriptor and
  26695. ** SQLITE_OK is returned. If an error occurs, either SQLITE_NOMEM
  26696. ** or SQLITE_CANTOPEN is returned and *pFd is set to an undefined
  26697. ** value.
  26698. **
  26699. ** The directory file descriptor is used for only one thing - to
  26700. ** fsync() a directory to make sure file creation and deletion events
  26701. ** are flushed to disk. Such fsyncs are not needed on newer
  26702. ** journaling filesystems, but are required on older filesystems.
  26703. **
  26704. ** This routine can be overridden using the xSetSysCall interface.
  26705. ** The ability to override this routine was added in support of the
  26706. ** chromium sandbox. Opening a directory is a security risk (we are
  26707. ** told) so making it overrideable allows the chromium sandbox to
  26708. ** replace this routine with a harmless no-op. To make this routine
  26709. ** a no-op, replace it with a stub that returns SQLITE_OK but leaves
  26710. ** *pFd set to a negative number.
  26711. **
  26712. ** If SQLITE_OK is returned, the caller is responsible for closing
  26713. ** the file descriptor *pFd using close().
  26714. */
  26715. static int openDirectory(const char *zFilename, int *pFd){
  26716. int ii;
  26717. int fd = -1;
  26718. char zDirname[MAX_PATHNAME+1];
  26719. sqlite3_snprintf(MAX_PATHNAME, zDirname, "%s", zFilename);
  26720. for(ii=(int)strlen(zDirname); ii>1 && zDirname[ii]!='/'; ii--);
  26721. if( ii>0 ){
  26722. zDirname[ii] = '\0';
  26723. fd = robust_open(zDirname, O_RDONLY|O_BINARY, 0);
  26724. if( fd>=0 ){
  26725. OSTRACE(("OPENDIR %-3d %s\n", fd, zDirname));
  26726. }
  26727. }
  26728. *pFd = fd;
  26729. return (fd>=0?SQLITE_OK:unixLogError(SQLITE_CANTOPEN_BKPT, "open", zDirname));
  26730. }
  26731. /*
  26732. ** Make sure all writes to a particular file are committed to disk.
  26733. **
  26734. ** If dataOnly==0 then both the file itself and its metadata (file
  26735. ** size, access time, etc) are synced. If dataOnly!=0 then only the
  26736. ** file data is synced.
  26737. **
  26738. ** Under Unix, also make sure that the directory entry for the file
  26739. ** has been created by fsync-ing the directory that contains the file.
  26740. ** If we do not do this and we encounter a power failure, the directory
  26741. ** entry for the journal might not exist after we reboot. The next
  26742. ** SQLite to access the file will not know that the journal exists (because
  26743. ** the directory entry for the journal was never created) and the transaction
  26744. ** will not roll back - possibly leading to database corruption.
  26745. */
  26746. static int unixSync(sqlite3_file *id, int flags){
  26747. int rc;
  26748. unixFile *pFile = (unixFile*)id;
  26749. int isDataOnly = (flags&SQLITE_SYNC_DATAONLY);
  26750. int isFullsync = (flags&0x0F)==SQLITE_SYNC_FULL;
  26751. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  26752. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  26753. || (flags&0x0F)==SQLITE_SYNC_FULL
  26754. );
  26755. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  26756. ** line is to test that doing so does not cause any problems.
  26757. */
  26758. SimulateDiskfullError( return SQLITE_FULL );
  26759. assert( pFile );
  26760. OSTRACE(("SYNC %-3d\n", pFile->h));
  26761. rc = full_fsync(pFile->h, isFullsync, isDataOnly);
  26762. SimulateIOError( rc=1 );
  26763. if( rc ){
  26764. pFile->lastErrno = errno;
  26765. return unixLogError(SQLITE_IOERR_FSYNC, "full_fsync", pFile->zPath);
  26766. }
  26767. /* Also fsync the directory containing the file if the DIRSYNC flag
  26768. ** is set. This is a one-time occurrence. Many systems (examples: AIX)
  26769. ** are unable to fsync a directory, so ignore errors on the fsync.
  26770. */
  26771. if( pFile->ctrlFlags & UNIXFILE_DIRSYNC ){
  26772. int dirfd;
  26773. OSTRACE(("DIRSYNC %s (have_fullfsync=%d fullsync=%d)\n", pFile->zPath,
  26774. HAVE_FULLFSYNC, isFullsync));
  26775. rc = osOpenDirectory(pFile->zPath, &dirfd);
  26776. if( rc==SQLITE_OK && dirfd>=0 ){
  26777. full_fsync(dirfd, 0, 0);
  26778. robust_close(pFile, dirfd, __LINE__);
  26779. }else if( rc==SQLITE_CANTOPEN ){
  26780. rc = SQLITE_OK;
  26781. }
  26782. pFile->ctrlFlags &= ~UNIXFILE_DIRSYNC;
  26783. }
  26784. return rc;
  26785. }
  26786. /*
  26787. ** Truncate an open file to a specified size
  26788. */
  26789. static int unixTruncate(sqlite3_file *id, i64 nByte){
  26790. unixFile *pFile = (unixFile *)id;
  26791. int rc;
  26792. assert( pFile );
  26793. SimulateIOError( return SQLITE_IOERR_TRUNCATE );
  26794. /* If the user has configured a chunk-size for this file, truncate the
  26795. ** file so that it consists of an integer number of chunks (i.e. the
  26796. ** actual file size after the operation may be larger than the requested
  26797. ** size).
  26798. */
  26799. if( pFile->szChunk>0 ){
  26800. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  26801. }
  26802. rc = robust_ftruncate(pFile->h, nByte);
  26803. if( rc ){
  26804. pFile->lastErrno = errno;
  26805. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  26806. }else{
  26807. #ifdef SQLITE_DEBUG
  26808. /* If we are doing a normal write to a database file (as opposed to
  26809. ** doing a hot-journal rollback or a write to some file other than a
  26810. ** normal database file) and we truncate the file to zero length,
  26811. ** that effectively updates the change counter. This might happen
  26812. ** when restoring a database using the backup API from a zero-length
  26813. ** source.
  26814. */
  26815. if( pFile->inNormalWrite && nByte==0 ){
  26816. pFile->transCntrChng = 1;
  26817. }
  26818. #endif
  26819. #if SQLITE_MAX_MMAP_SIZE>0
  26820. /* If the file was just truncated to a size smaller than the currently
  26821. ** mapped region, reduce the effective mapping size as well. SQLite will
  26822. ** use read() and write() to access data beyond this point from now on.
  26823. */
  26824. if( nByte<pFile->mmapSize ){
  26825. pFile->mmapSize = nByte;
  26826. }
  26827. #endif
  26828. return SQLITE_OK;
  26829. }
  26830. }
  26831. /*
  26832. ** Determine the current size of a file in bytes
  26833. */
  26834. static int unixFileSize(sqlite3_file *id, i64 *pSize){
  26835. int rc;
  26836. struct stat buf;
  26837. assert( id );
  26838. rc = osFstat(((unixFile*)id)->h, &buf);
  26839. SimulateIOError( rc=1 );
  26840. if( rc!=0 ){
  26841. ((unixFile*)id)->lastErrno = errno;
  26842. return SQLITE_IOERR_FSTAT;
  26843. }
  26844. *pSize = buf.st_size;
  26845. /* When opening a zero-size database, the findInodeInfo() procedure
  26846. ** writes a single byte into that file in order to work around a bug
  26847. ** in the OS-X msdos filesystem. In order to avoid problems with upper
  26848. ** layers, we need to report this file size as zero even though it is
  26849. ** really 1. Ticket #3260.
  26850. */
  26851. if( *pSize==1 ) *pSize = 0;
  26852. return SQLITE_OK;
  26853. }
  26854. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  26855. /*
  26856. ** Handler for proxy-locking file-control verbs. Defined below in the
  26857. ** proxying locking division.
  26858. */
  26859. static int proxyFileControl(sqlite3_file*,int,void*);
  26860. #endif
  26861. /*
  26862. ** This function is called to handle the SQLITE_FCNTL_SIZE_HINT
  26863. ** file-control operation. Enlarge the database to nBytes in size
  26864. ** (rounded up to the next chunk-size). If the database is already
  26865. ** nBytes or larger, this routine is a no-op.
  26866. */
  26867. static int fcntlSizeHint(unixFile *pFile, i64 nByte){
  26868. if( pFile->szChunk>0 ){
  26869. i64 nSize; /* Required file size */
  26870. struct stat buf; /* Used to hold return values of fstat() */
  26871. if( osFstat(pFile->h, &buf) ) return SQLITE_IOERR_FSTAT;
  26872. nSize = ((nByte+pFile->szChunk-1) / pFile->szChunk) * pFile->szChunk;
  26873. if( nSize>(i64)buf.st_size ){
  26874. #if defined(HAVE_POSIX_FALLOCATE) && HAVE_POSIX_FALLOCATE
  26875. /* The code below is handling the return value of osFallocate()
  26876. ** correctly. posix_fallocate() is defined to "returns zero on success,
  26877. ** or an error number on failure". See the manpage for details. */
  26878. int err;
  26879. do{
  26880. err = osFallocate(pFile->h, buf.st_size, nSize-buf.st_size);
  26881. }while( err==EINTR );
  26882. if( err ) return SQLITE_IOERR_WRITE;
  26883. #else
  26884. /* If the OS does not have posix_fallocate(), fake it. First use
  26885. ** ftruncate() to set the file size, then write a single byte to
  26886. ** the last byte in each block within the extended region. This
  26887. ** is the same technique used by glibc to implement posix_fallocate()
  26888. ** on systems that do not have a real fallocate() system call.
  26889. */
  26890. int nBlk = buf.st_blksize; /* File-system block size */
  26891. i64 iWrite; /* Next offset to write to */
  26892. if( robust_ftruncate(pFile->h, nSize) ){
  26893. pFile->lastErrno = errno;
  26894. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  26895. }
  26896. iWrite = ((buf.st_size + 2*nBlk - 1)/nBlk)*nBlk-1;
  26897. while( iWrite<nSize ){
  26898. int nWrite = seekAndWrite(pFile, iWrite, "", 1);
  26899. if( nWrite!=1 ) return SQLITE_IOERR_WRITE;
  26900. iWrite += nBlk;
  26901. }
  26902. #endif
  26903. }
  26904. }
  26905. #if SQLITE_MAX_MMAP_SIZE>0
  26906. if( pFile->mmapSizeMax>0 && nByte>pFile->mmapSize ){
  26907. int rc;
  26908. if( pFile->szChunk<=0 ){
  26909. if( robust_ftruncate(pFile->h, nByte) ){
  26910. pFile->lastErrno = errno;
  26911. return unixLogError(SQLITE_IOERR_TRUNCATE, "ftruncate", pFile->zPath);
  26912. }
  26913. }
  26914. rc = unixMapfile(pFile, nByte);
  26915. return rc;
  26916. }
  26917. #endif
  26918. return SQLITE_OK;
  26919. }
  26920. /*
  26921. ** If *pArg is initially negative then this is a query. Set *pArg to
  26922. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  26923. **
  26924. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  26925. */
  26926. static void unixModeBit(unixFile *pFile, unsigned char mask, int *pArg){
  26927. if( *pArg<0 ){
  26928. *pArg = (pFile->ctrlFlags & mask)!=0;
  26929. }else if( (*pArg)==0 ){
  26930. pFile->ctrlFlags &= ~mask;
  26931. }else{
  26932. pFile->ctrlFlags |= mask;
  26933. }
  26934. }
  26935. /* Forward declaration */
  26936. static int unixGetTempname(int nBuf, char *zBuf);
  26937. /*
  26938. ** Information and control of an open file handle.
  26939. */
  26940. static int unixFileControl(sqlite3_file *id, int op, void *pArg){
  26941. unixFile *pFile = (unixFile*)id;
  26942. switch( op ){
  26943. case SQLITE_FCNTL_LOCKSTATE: {
  26944. *(int*)pArg = pFile->eFileLock;
  26945. return SQLITE_OK;
  26946. }
  26947. case SQLITE_LAST_ERRNO: {
  26948. *(int*)pArg = pFile->lastErrno;
  26949. return SQLITE_OK;
  26950. }
  26951. case SQLITE_FCNTL_CHUNK_SIZE: {
  26952. pFile->szChunk = *(int *)pArg;
  26953. return SQLITE_OK;
  26954. }
  26955. case SQLITE_FCNTL_SIZE_HINT: {
  26956. int rc;
  26957. SimulateIOErrorBenign(1);
  26958. rc = fcntlSizeHint(pFile, *(i64 *)pArg);
  26959. SimulateIOErrorBenign(0);
  26960. return rc;
  26961. }
  26962. case SQLITE_FCNTL_PERSIST_WAL: {
  26963. unixModeBit(pFile, UNIXFILE_PERSIST_WAL, (int*)pArg);
  26964. return SQLITE_OK;
  26965. }
  26966. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  26967. unixModeBit(pFile, UNIXFILE_PSOW, (int*)pArg);
  26968. return SQLITE_OK;
  26969. }
  26970. case SQLITE_FCNTL_VFSNAME: {
  26971. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  26972. return SQLITE_OK;
  26973. }
  26974. case SQLITE_FCNTL_TEMPFILENAME: {
  26975. char *zTFile = sqlite3_malloc( pFile->pVfs->mxPathname );
  26976. if( zTFile ){
  26977. unixGetTempname(pFile->pVfs->mxPathname, zTFile);
  26978. *(char**)pArg = zTFile;
  26979. }
  26980. return SQLITE_OK;
  26981. }
  26982. case SQLITE_FCNTL_HAS_MOVED: {
  26983. *(int*)pArg = fileHasMoved(pFile);
  26984. return SQLITE_OK;
  26985. }
  26986. #if SQLITE_MAX_MMAP_SIZE>0
  26987. case SQLITE_FCNTL_MMAP_SIZE: {
  26988. i64 newLimit = *(i64*)pArg;
  26989. int rc = SQLITE_OK;
  26990. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  26991. newLimit = sqlite3GlobalConfig.mxMmap;
  26992. }
  26993. *(i64*)pArg = pFile->mmapSizeMax;
  26994. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  26995. pFile->mmapSizeMax = newLimit;
  26996. if( pFile->mmapSize>0 ){
  26997. unixUnmapfile(pFile);
  26998. rc = unixMapfile(pFile, -1);
  26999. }
  27000. }
  27001. return rc;
  27002. }
  27003. #endif
  27004. #ifdef SQLITE_DEBUG
  27005. /* The pager calls this method to signal that it has done
  27006. ** a rollback and that the database is therefore unchanged and
  27007. ** it hence it is OK for the transaction change counter to be
  27008. ** unchanged.
  27009. */
  27010. case SQLITE_FCNTL_DB_UNCHANGED: {
  27011. ((unixFile*)id)->dbUpdate = 0;
  27012. return SQLITE_OK;
  27013. }
  27014. #endif
  27015. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  27016. case SQLITE_SET_LOCKPROXYFILE:
  27017. case SQLITE_GET_LOCKPROXYFILE: {
  27018. return proxyFileControl(id,op,pArg);
  27019. }
  27020. #endif /* SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__) */
  27021. }
  27022. return SQLITE_NOTFOUND;
  27023. }
  27024. /*
  27025. ** Return the sector size in bytes of the underlying block device for
  27026. ** the specified file. This is almost always 512 bytes, but may be
  27027. ** larger for some devices.
  27028. **
  27029. ** SQLite code assumes this function cannot fail. It also assumes that
  27030. ** if two files are created in the same file-system directory (i.e.
  27031. ** a database and its journal file) that the sector size will be the
  27032. ** same for both.
  27033. */
  27034. #ifndef __QNXNTO__
  27035. static int unixSectorSize(sqlite3_file *NotUsed){
  27036. UNUSED_PARAMETER(NotUsed);
  27037. return SQLITE_DEFAULT_SECTOR_SIZE;
  27038. }
  27039. #endif
  27040. /*
  27041. ** The following version of unixSectorSize() is optimized for QNX.
  27042. */
  27043. #ifdef __QNXNTO__
  27044. #include <sys/dcmd_blk.h>
  27045. #include <sys/statvfs.h>
  27046. static int unixSectorSize(sqlite3_file *id){
  27047. unixFile *pFile = (unixFile*)id;
  27048. if( pFile->sectorSize == 0 ){
  27049. struct statvfs fsInfo;
  27050. /* Set defaults for non-supported filesystems */
  27051. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  27052. pFile->deviceCharacteristics = 0;
  27053. if( fstatvfs(pFile->h, &fsInfo) == -1 ) {
  27054. return pFile->sectorSize;
  27055. }
  27056. if( !strcmp(fsInfo.f_basetype, "tmp") ) {
  27057. pFile->sectorSize = fsInfo.f_bsize;
  27058. pFile->deviceCharacteristics =
  27059. SQLITE_IOCAP_ATOMIC4K | /* All ram filesystem writes are atomic */
  27060. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27061. ** the write succeeds */
  27062. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27063. ** so it is ordered */
  27064. 0;
  27065. }else if( strstr(fsInfo.f_basetype, "etfs") ){
  27066. pFile->sectorSize = fsInfo.f_bsize;
  27067. pFile->deviceCharacteristics =
  27068. /* etfs cluster size writes are atomic */
  27069. (pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) |
  27070. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27071. ** the write succeeds */
  27072. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27073. ** so it is ordered */
  27074. 0;
  27075. }else if( !strcmp(fsInfo.f_basetype, "qnx6") ){
  27076. pFile->sectorSize = fsInfo.f_bsize;
  27077. pFile->deviceCharacteristics =
  27078. SQLITE_IOCAP_ATOMIC | /* All filesystem writes are atomic */
  27079. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27080. ** the write succeeds */
  27081. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27082. ** so it is ordered */
  27083. 0;
  27084. }else if( !strcmp(fsInfo.f_basetype, "qnx4") ){
  27085. pFile->sectorSize = fsInfo.f_bsize;
  27086. pFile->deviceCharacteristics =
  27087. /* full bitset of atomics from max sector size and smaller */
  27088. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  27089. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27090. ** so it is ordered */
  27091. 0;
  27092. }else if( strstr(fsInfo.f_basetype, "dos") ){
  27093. pFile->sectorSize = fsInfo.f_bsize;
  27094. pFile->deviceCharacteristics =
  27095. /* full bitset of atomics from max sector size and smaller */
  27096. ((pFile->sectorSize / 512 * SQLITE_IOCAP_ATOMIC512) << 1) - 2 |
  27097. SQLITE_IOCAP_SEQUENTIAL | /* The ram filesystem has no write behind
  27098. ** so it is ordered */
  27099. 0;
  27100. }else{
  27101. pFile->deviceCharacteristics =
  27102. SQLITE_IOCAP_ATOMIC512 | /* blocks are atomic */
  27103. SQLITE_IOCAP_SAFE_APPEND | /* growing the file does not occur until
  27104. ** the write succeeds */
  27105. 0;
  27106. }
  27107. }
  27108. /* Last chance verification. If the sector size isn't a multiple of 512
  27109. ** then it isn't valid.*/
  27110. if( pFile->sectorSize % 512 != 0 ){
  27111. pFile->deviceCharacteristics = 0;
  27112. pFile->sectorSize = SQLITE_DEFAULT_SECTOR_SIZE;
  27113. }
  27114. return pFile->sectorSize;
  27115. }
  27116. #endif /* __QNXNTO__ */
  27117. /*
  27118. ** Return the device characteristics for the file.
  27119. **
  27120. ** This VFS is set up to return SQLITE_IOCAP_POWERSAFE_OVERWRITE by default.
  27121. ** However, that choice is controversial since technically the underlying
  27122. ** file system does not always provide powersafe overwrites. (In other
  27123. ** words, after a power-loss event, parts of the file that were never
  27124. ** written might end up being altered.) However, non-PSOW behavior is very,
  27125. ** very rare. And asserting PSOW makes a large reduction in the amount
  27126. ** of required I/O for journaling, since a lot of padding is eliminated.
  27127. ** Hence, while POWERSAFE_OVERWRITE is on by default, there is a file-control
  27128. ** available to turn it off and URI query parameter available to turn it off.
  27129. */
  27130. static int unixDeviceCharacteristics(sqlite3_file *id){
  27131. unixFile *p = (unixFile*)id;
  27132. int rc = 0;
  27133. #ifdef __QNXNTO__
  27134. if( p->sectorSize==0 ) unixSectorSize(id);
  27135. rc = p->deviceCharacteristics;
  27136. #endif
  27137. if( p->ctrlFlags & UNIXFILE_PSOW ){
  27138. rc |= SQLITE_IOCAP_POWERSAFE_OVERWRITE;
  27139. }
  27140. return rc;
  27141. }
  27142. #if !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0
  27143. /*
  27144. ** Return the system page size.
  27145. **
  27146. ** This function should not be called directly by other code in this file.
  27147. ** Instead, it should be called via macro osGetpagesize().
  27148. */
  27149. static int unixGetpagesize(void){
  27150. #if defined(_BSD_SOURCE)
  27151. return getpagesize();
  27152. #else
  27153. return (int)sysconf(_SC_PAGESIZE);
  27154. #endif
  27155. }
  27156. #endif /* !defined(SQLITE_OMIT_WAL) || SQLITE_MAX_MMAP_SIZE>0 */
  27157. #ifndef SQLITE_OMIT_WAL
  27158. /*
  27159. ** Object used to represent an shared memory buffer.
  27160. **
  27161. ** When multiple threads all reference the same wal-index, each thread
  27162. ** has its own unixShm object, but they all point to a single instance
  27163. ** of this unixShmNode object. In other words, each wal-index is opened
  27164. ** only once per process.
  27165. **
  27166. ** Each unixShmNode object is connected to a single unixInodeInfo object.
  27167. ** We could coalesce this object into unixInodeInfo, but that would mean
  27168. ** every open file that does not use shared memory (in other words, most
  27169. ** open files) would have to carry around this extra information. So
  27170. ** the unixInodeInfo object contains a pointer to this unixShmNode object
  27171. ** and the unixShmNode object is created only when needed.
  27172. **
  27173. ** unixMutexHeld() must be true when creating or destroying
  27174. ** this object or while reading or writing the following fields:
  27175. **
  27176. ** nRef
  27177. **
  27178. ** The following fields are read-only after the object is created:
  27179. **
  27180. ** fid
  27181. ** zFilename
  27182. **
  27183. ** Either unixShmNode.mutex must be held or unixShmNode.nRef==0 and
  27184. ** unixMutexHeld() is true when reading or writing any other field
  27185. ** in this structure.
  27186. */
  27187. struct unixShmNode {
  27188. unixInodeInfo *pInode; /* unixInodeInfo that owns this SHM node */
  27189. sqlite3_mutex *mutex; /* Mutex to access this object */
  27190. char *zFilename; /* Name of the mmapped file */
  27191. int h; /* Open file descriptor */
  27192. int szRegion; /* Size of shared-memory regions */
  27193. u16 nRegion; /* Size of array apRegion */
  27194. u8 isReadonly; /* True if read-only */
  27195. char **apRegion; /* Array of mapped shared-memory regions */
  27196. int nRef; /* Number of unixShm objects pointing to this */
  27197. unixShm *pFirst; /* All unixShm objects pointing to this */
  27198. #ifdef SQLITE_DEBUG
  27199. u8 exclMask; /* Mask of exclusive locks held */
  27200. u8 sharedMask; /* Mask of shared locks held */
  27201. u8 nextShmId; /* Next available unixShm.id value */
  27202. #endif
  27203. };
  27204. /*
  27205. ** Structure used internally by this VFS to record the state of an
  27206. ** open shared memory connection.
  27207. **
  27208. ** The following fields are initialized when this object is created and
  27209. ** are read-only thereafter:
  27210. **
  27211. ** unixShm.pFile
  27212. ** unixShm.id
  27213. **
  27214. ** All other fields are read/write. The unixShm.pFile->mutex must be held
  27215. ** while accessing any read/write fields.
  27216. */
  27217. struct unixShm {
  27218. unixShmNode *pShmNode; /* The underlying unixShmNode object */
  27219. unixShm *pNext; /* Next unixShm with the same unixShmNode */
  27220. u8 hasMutex; /* True if holding the unixShmNode mutex */
  27221. u8 id; /* Id of this connection within its unixShmNode */
  27222. u16 sharedMask; /* Mask of shared locks held */
  27223. u16 exclMask; /* Mask of exclusive locks held */
  27224. };
  27225. /*
  27226. ** Constants used for locking
  27227. */
  27228. #define UNIX_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  27229. #define UNIX_SHM_DMS (UNIX_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  27230. /*
  27231. ** Apply posix advisory locks for all bytes from ofst through ofst+n-1.
  27232. **
  27233. ** Locks block if the mask is exactly UNIX_SHM_C and are non-blocking
  27234. ** otherwise.
  27235. */
  27236. static int unixShmSystemLock(
  27237. unixShmNode *pShmNode, /* Apply locks to this open shared-memory segment */
  27238. int lockType, /* F_UNLCK, F_RDLCK, or F_WRLCK */
  27239. int ofst, /* First byte of the locking range */
  27240. int n /* Number of bytes to lock */
  27241. ){
  27242. struct flock f; /* The posix advisory locking structure */
  27243. int rc = SQLITE_OK; /* Result code form fcntl() */
  27244. /* Access to the unixShmNode object is serialized by the caller */
  27245. assert( sqlite3_mutex_held(pShmNode->mutex) || pShmNode->nRef==0 );
  27246. /* Shared locks never span more than one byte */
  27247. assert( n==1 || lockType!=F_RDLCK );
  27248. /* Locks are within range */
  27249. assert( n>=1 && n<SQLITE_SHM_NLOCK );
  27250. if( pShmNode->h>=0 ){
  27251. /* Initialize the locking parameters */
  27252. memset(&f, 0, sizeof(f));
  27253. f.l_type = lockType;
  27254. f.l_whence = SEEK_SET;
  27255. f.l_start = ofst;
  27256. f.l_len = n;
  27257. rc = osFcntl(pShmNode->h, F_SETLK, &f);
  27258. rc = (rc!=(-1)) ? SQLITE_OK : SQLITE_BUSY;
  27259. }
  27260. /* Update the global lock state and do debug tracing */
  27261. #ifdef SQLITE_DEBUG
  27262. { u16 mask;
  27263. OSTRACE(("SHM-LOCK "));
  27264. mask = ofst>31 ? 0xffff : (1<<(ofst+n)) - (1<<ofst);
  27265. if( rc==SQLITE_OK ){
  27266. if( lockType==F_UNLCK ){
  27267. OSTRACE(("unlock %d ok", ofst));
  27268. pShmNode->exclMask &= ~mask;
  27269. pShmNode->sharedMask &= ~mask;
  27270. }else if( lockType==F_RDLCK ){
  27271. OSTRACE(("read-lock %d ok", ofst));
  27272. pShmNode->exclMask &= ~mask;
  27273. pShmNode->sharedMask |= mask;
  27274. }else{
  27275. assert( lockType==F_WRLCK );
  27276. OSTRACE(("write-lock %d ok", ofst));
  27277. pShmNode->exclMask |= mask;
  27278. pShmNode->sharedMask &= ~mask;
  27279. }
  27280. }else{
  27281. if( lockType==F_UNLCK ){
  27282. OSTRACE(("unlock %d failed", ofst));
  27283. }else if( lockType==F_RDLCK ){
  27284. OSTRACE(("read-lock failed"));
  27285. }else{
  27286. assert( lockType==F_WRLCK );
  27287. OSTRACE(("write-lock %d failed", ofst));
  27288. }
  27289. }
  27290. OSTRACE((" - afterwards %03x,%03x\n",
  27291. pShmNode->sharedMask, pShmNode->exclMask));
  27292. }
  27293. #endif
  27294. return rc;
  27295. }
  27296. /*
  27297. ** Return the minimum number of 32KB shm regions that should be mapped at
  27298. ** a time, assuming that each mapping must be an integer multiple of the
  27299. ** current system page-size.
  27300. **
  27301. ** Usually, this is 1. The exception seems to be systems that are configured
  27302. ** to use 64KB pages - in this case each mapping must cover at least two
  27303. ** shm regions.
  27304. */
  27305. static int unixShmRegionPerMap(void){
  27306. int shmsz = 32*1024; /* SHM region size */
  27307. int pgsz = osGetpagesize(); /* System page size */
  27308. assert( ((pgsz-1)&pgsz)==0 ); /* Page size must be a power of 2 */
  27309. if( pgsz<shmsz ) return 1;
  27310. return pgsz/shmsz;
  27311. }
  27312. /*
  27313. ** Purge the unixShmNodeList list of all entries with unixShmNode.nRef==0.
  27314. **
  27315. ** This is not a VFS shared-memory method; it is a utility function called
  27316. ** by VFS shared-memory methods.
  27317. */
  27318. static void unixShmPurge(unixFile *pFd){
  27319. unixShmNode *p = pFd->pInode->pShmNode;
  27320. assert( unixMutexHeld() );
  27321. if( p && p->nRef==0 ){
  27322. int nShmPerMap = unixShmRegionPerMap();
  27323. int i;
  27324. assert( p->pInode==pFd->pInode );
  27325. sqlite3_mutex_free(p->mutex);
  27326. for(i=0; i<p->nRegion; i+=nShmPerMap){
  27327. if( p->h>=0 ){
  27328. osMunmap(p->apRegion[i], p->szRegion);
  27329. }else{
  27330. sqlite3_free(p->apRegion[i]);
  27331. }
  27332. }
  27333. sqlite3_free(p->apRegion);
  27334. if( p->h>=0 ){
  27335. robust_close(pFd, p->h, __LINE__);
  27336. p->h = -1;
  27337. }
  27338. p->pInode->pShmNode = 0;
  27339. sqlite3_free(p);
  27340. }
  27341. }
  27342. /*
  27343. ** Open a shared-memory area associated with open database file pDbFd.
  27344. ** This particular implementation uses mmapped files.
  27345. **
  27346. ** The file used to implement shared-memory is in the same directory
  27347. ** as the open database file and has the same name as the open database
  27348. ** file with the "-shm" suffix added. For example, if the database file
  27349. ** is "/home/user1/config.db" then the file that is created and mmapped
  27350. ** for shared memory will be called "/home/user1/config.db-shm".
  27351. **
  27352. ** Another approach to is to use files in /dev/shm or /dev/tmp or an
  27353. ** some other tmpfs mount. But if a file in a different directory
  27354. ** from the database file is used, then differing access permissions
  27355. ** or a chroot() might cause two different processes on the same
  27356. ** database to end up using different files for shared memory -
  27357. ** meaning that their memory would not really be shared - resulting
  27358. ** in database corruption. Nevertheless, this tmpfs file usage
  27359. ** can be enabled at compile-time using -DSQLITE_SHM_DIRECTORY="/dev/shm"
  27360. ** or the equivalent. The use of the SQLITE_SHM_DIRECTORY compile-time
  27361. ** option results in an incompatible build of SQLite; builds of SQLite
  27362. ** that with differing SQLITE_SHM_DIRECTORY settings attempt to use the
  27363. ** same database file at the same time, database corruption will likely
  27364. ** result. The SQLITE_SHM_DIRECTORY compile-time option is considered
  27365. ** "unsupported" and may go away in a future SQLite release.
  27366. **
  27367. ** When opening a new shared-memory file, if no other instances of that
  27368. ** file are currently open, in this process or in other processes, then
  27369. ** the file must be truncated to zero length or have its header cleared.
  27370. **
  27371. ** If the original database file (pDbFd) is using the "unix-excl" VFS
  27372. ** that means that an exclusive lock is held on the database file and
  27373. ** that no other processes are able to read or write the database. In
  27374. ** that case, we do not really need shared memory. No shared memory
  27375. ** file is created. The shared memory will be simulated with heap memory.
  27376. */
  27377. static int unixOpenSharedMemory(unixFile *pDbFd){
  27378. struct unixShm *p = 0; /* The connection to be opened */
  27379. struct unixShmNode *pShmNode; /* The underlying mmapped file */
  27380. int rc; /* Result code */
  27381. unixInodeInfo *pInode; /* The inode of fd */
  27382. char *zShmFilename; /* Name of the file used for SHM */
  27383. int nShmFilename; /* Size of the SHM filename in bytes */
  27384. /* Allocate space for the new unixShm object. */
  27385. p = sqlite3_malloc( sizeof(*p) );
  27386. if( p==0 ) return SQLITE_NOMEM;
  27387. memset(p, 0, sizeof(*p));
  27388. assert( pDbFd->pShm==0 );
  27389. /* Check to see if a unixShmNode object already exists. Reuse an existing
  27390. ** one if present. Create a new one if necessary.
  27391. */
  27392. unixEnterMutex();
  27393. pInode = pDbFd->pInode;
  27394. pShmNode = pInode->pShmNode;
  27395. if( pShmNode==0 ){
  27396. struct stat sStat; /* fstat() info for database file */
  27397. /* Call fstat() to figure out the permissions on the database file. If
  27398. ** a new *-shm file is created, an attempt will be made to create it
  27399. ** with the same permissions.
  27400. */
  27401. if( osFstat(pDbFd->h, &sStat) && pInode->bProcessLock==0 ){
  27402. rc = SQLITE_IOERR_FSTAT;
  27403. goto shm_open_err;
  27404. }
  27405. #ifdef SQLITE_SHM_DIRECTORY
  27406. nShmFilename = sizeof(SQLITE_SHM_DIRECTORY) + 31;
  27407. #else
  27408. nShmFilename = 6 + (int)strlen(pDbFd->zPath);
  27409. #endif
  27410. pShmNode = sqlite3_malloc( sizeof(*pShmNode) + nShmFilename );
  27411. if( pShmNode==0 ){
  27412. rc = SQLITE_NOMEM;
  27413. goto shm_open_err;
  27414. }
  27415. memset(pShmNode, 0, sizeof(*pShmNode)+nShmFilename);
  27416. zShmFilename = pShmNode->zFilename = (char*)&pShmNode[1];
  27417. #ifdef SQLITE_SHM_DIRECTORY
  27418. sqlite3_snprintf(nShmFilename, zShmFilename,
  27419. SQLITE_SHM_DIRECTORY "/sqlite-shm-%x-%x",
  27420. (u32)sStat.st_ino, (u32)sStat.st_dev);
  27421. #else
  27422. sqlite3_snprintf(nShmFilename, zShmFilename, "%s-shm", pDbFd->zPath);
  27423. sqlite3FileSuffix3(pDbFd->zPath, zShmFilename);
  27424. #endif
  27425. pShmNode->h = -1;
  27426. pDbFd->pInode->pShmNode = pShmNode;
  27427. pShmNode->pInode = pDbFd->pInode;
  27428. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  27429. if( pShmNode->mutex==0 ){
  27430. rc = SQLITE_NOMEM;
  27431. goto shm_open_err;
  27432. }
  27433. if( pInode->bProcessLock==0 ){
  27434. int openFlags = O_RDWR | O_CREAT;
  27435. if( sqlite3_uri_boolean(pDbFd->zPath, "readonly_shm", 0) ){
  27436. openFlags = O_RDONLY;
  27437. pShmNode->isReadonly = 1;
  27438. }
  27439. pShmNode->h = robust_open(zShmFilename, openFlags, (sStat.st_mode&0777));
  27440. if( pShmNode->h<0 ){
  27441. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zShmFilename);
  27442. goto shm_open_err;
  27443. }
  27444. /* If this process is running as root, make sure that the SHM file
  27445. ** is owned by the same user that owns the original database. Otherwise,
  27446. ** the original owner will not be able to connect.
  27447. */
  27448. osFchown(pShmNode->h, sStat.st_uid, sStat.st_gid);
  27449. /* Check to see if another process is holding the dead-man switch.
  27450. ** If not, truncate the file to zero length.
  27451. */
  27452. rc = SQLITE_OK;
  27453. if( unixShmSystemLock(pShmNode, F_WRLCK, UNIX_SHM_DMS, 1)==SQLITE_OK ){
  27454. if( robust_ftruncate(pShmNode->h, 0) ){
  27455. rc = unixLogError(SQLITE_IOERR_SHMOPEN, "ftruncate", zShmFilename);
  27456. }
  27457. }
  27458. if( rc==SQLITE_OK ){
  27459. rc = unixShmSystemLock(pShmNode, F_RDLCK, UNIX_SHM_DMS, 1);
  27460. }
  27461. if( rc ) goto shm_open_err;
  27462. }
  27463. }
  27464. /* Make the new connection a child of the unixShmNode */
  27465. p->pShmNode = pShmNode;
  27466. #ifdef SQLITE_DEBUG
  27467. p->id = pShmNode->nextShmId++;
  27468. #endif
  27469. pShmNode->nRef++;
  27470. pDbFd->pShm = p;
  27471. unixLeaveMutex();
  27472. /* The reference count on pShmNode has already been incremented under
  27473. ** the cover of the unixEnterMutex() mutex and the pointer from the
  27474. ** new (struct unixShm) object to the pShmNode has been set. All that is
  27475. ** left to do is to link the new object into the linked list starting
  27476. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  27477. ** mutex.
  27478. */
  27479. sqlite3_mutex_enter(pShmNode->mutex);
  27480. p->pNext = pShmNode->pFirst;
  27481. pShmNode->pFirst = p;
  27482. sqlite3_mutex_leave(pShmNode->mutex);
  27483. return SQLITE_OK;
  27484. /* Jump here on any error */
  27485. shm_open_err:
  27486. unixShmPurge(pDbFd); /* This call frees pShmNode if required */
  27487. sqlite3_free(p);
  27488. unixLeaveMutex();
  27489. return rc;
  27490. }
  27491. /*
  27492. ** This function is called to obtain a pointer to region iRegion of the
  27493. ** shared-memory associated with the database file fd. Shared-memory regions
  27494. ** are numbered starting from zero. Each shared-memory region is szRegion
  27495. ** bytes in size.
  27496. **
  27497. ** If an error occurs, an error code is returned and *pp is set to NULL.
  27498. **
  27499. ** Otherwise, if the bExtend parameter is 0 and the requested shared-memory
  27500. ** region has not been allocated (by any client, including one running in a
  27501. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  27502. ** bExtend is non-zero and the requested shared-memory region has not yet
  27503. ** been allocated, it is allocated by this function.
  27504. **
  27505. ** If the shared-memory region has already been allocated or is allocated by
  27506. ** this call as described above, then it is mapped into this processes
  27507. ** address space (if it is not already), *pp is set to point to the mapped
  27508. ** memory and SQLITE_OK returned.
  27509. */
  27510. static int unixShmMap(
  27511. sqlite3_file *fd, /* Handle open on database file */
  27512. int iRegion, /* Region to retrieve */
  27513. int szRegion, /* Size of regions */
  27514. int bExtend, /* True to extend file if necessary */
  27515. void volatile **pp /* OUT: Mapped memory */
  27516. ){
  27517. unixFile *pDbFd = (unixFile*)fd;
  27518. unixShm *p;
  27519. unixShmNode *pShmNode;
  27520. int rc = SQLITE_OK;
  27521. int nShmPerMap = unixShmRegionPerMap();
  27522. int nReqRegion;
  27523. /* If the shared-memory file has not yet been opened, open it now. */
  27524. if( pDbFd->pShm==0 ){
  27525. rc = unixOpenSharedMemory(pDbFd);
  27526. if( rc!=SQLITE_OK ) return rc;
  27527. }
  27528. p = pDbFd->pShm;
  27529. pShmNode = p->pShmNode;
  27530. sqlite3_mutex_enter(pShmNode->mutex);
  27531. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  27532. assert( pShmNode->pInode==pDbFd->pInode );
  27533. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  27534. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  27535. /* Minimum number of regions required to be mapped. */
  27536. nReqRegion = ((iRegion+nShmPerMap) / nShmPerMap) * nShmPerMap;
  27537. if( pShmNode->nRegion<nReqRegion ){
  27538. char **apNew; /* New apRegion[] array */
  27539. int nByte = nReqRegion*szRegion; /* Minimum required file size */
  27540. struct stat sStat; /* Used by fstat() */
  27541. pShmNode->szRegion = szRegion;
  27542. if( pShmNode->h>=0 ){
  27543. /* The requested region is not mapped into this processes address space.
  27544. ** Check to see if it has been allocated (i.e. if the wal-index file is
  27545. ** large enough to contain the requested region).
  27546. */
  27547. if( osFstat(pShmNode->h, &sStat) ){
  27548. rc = SQLITE_IOERR_SHMSIZE;
  27549. goto shmpage_out;
  27550. }
  27551. if( sStat.st_size<nByte ){
  27552. /* The requested memory region does not exist. If bExtend is set to
  27553. ** false, exit early. *pp will be set to NULL and SQLITE_OK returned.
  27554. */
  27555. if( !bExtend ){
  27556. goto shmpage_out;
  27557. }
  27558. /* Alternatively, if bExtend is true, extend the file. Do this by
  27559. ** writing a single byte to the end of each (OS) page being
  27560. ** allocated or extended. Technically, we need only write to the
  27561. ** last page in order to extend the file. But writing to all new
  27562. ** pages forces the OS to allocate them immediately, which reduces
  27563. ** the chances of SIGBUS while accessing the mapped region later on.
  27564. */
  27565. else{
  27566. static const int pgsz = 4096;
  27567. int iPg;
  27568. /* Write to the last byte of each newly allocated or extended page */
  27569. assert( (nByte % pgsz)==0 );
  27570. for(iPg=(sStat.st_size/pgsz); iPg<(nByte/pgsz); iPg++){
  27571. if( seekAndWriteFd(pShmNode->h, iPg*pgsz + pgsz-1, "", 1, 0)!=1 ){
  27572. const char *zFile = pShmNode->zFilename;
  27573. rc = unixLogError(SQLITE_IOERR_SHMSIZE, "write", zFile);
  27574. goto shmpage_out;
  27575. }
  27576. }
  27577. }
  27578. }
  27579. }
  27580. /* Map the requested memory region into this processes address space. */
  27581. apNew = (char **)sqlite3_realloc(
  27582. pShmNode->apRegion, nReqRegion*sizeof(char *)
  27583. );
  27584. if( !apNew ){
  27585. rc = SQLITE_IOERR_NOMEM;
  27586. goto shmpage_out;
  27587. }
  27588. pShmNode->apRegion = apNew;
  27589. while( pShmNode->nRegion<nReqRegion ){
  27590. int nMap = szRegion*nShmPerMap;
  27591. int i;
  27592. void *pMem;
  27593. if( pShmNode->h>=0 ){
  27594. pMem = osMmap(0, nMap,
  27595. pShmNode->isReadonly ? PROT_READ : PROT_READ|PROT_WRITE,
  27596. MAP_SHARED, pShmNode->h, szRegion*(i64)pShmNode->nRegion
  27597. );
  27598. if( pMem==MAP_FAILED ){
  27599. rc = unixLogError(SQLITE_IOERR_SHMMAP, "mmap", pShmNode->zFilename);
  27600. goto shmpage_out;
  27601. }
  27602. }else{
  27603. pMem = sqlite3_malloc(szRegion);
  27604. if( pMem==0 ){
  27605. rc = SQLITE_NOMEM;
  27606. goto shmpage_out;
  27607. }
  27608. memset(pMem, 0, szRegion);
  27609. }
  27610. for(i=0; i<nShmPerMap; i++){
  27611. pShmNode->apRegion[pShmNode->nRegion+i] = &((char*)pMem)[szRegion*i];
  27612. }
  27613. pShmNode->nRegion += nShmPerMap;
  27614. }
  27615. }
  27616. shmpage_out:
  27617. if( pShmNode->nRegion>iRegion ){
  27618. *pp = pShmNode->apRegion[iRegion];
  27619. }else{
  27620. *pp = 0;
  27621. }
  27622. if( pShmNode->isReadonly && rc==SQLITE_OK ) rc = SQLITE_READONLY;
  27623. sqlite3_mutex_leave(pShmNode->mutex);
  27624. return rc;
  27625. }
  27626. /*
  27627. ** Change the lock state for a shared-memory segment.
  27628. **
  27629. ** Note that the relationship between SHAREd and EXCLUSIVE locks is a little
  27630. ** different here than in posix. In xShmLock(), one can go from unlocked
  27631. ** to shared and back or from unlocked to exclusive and back. But one may
  27632. ** not go from shared to exclusive or from exclusive to shared.
  27633. */
  27634. static int unixShmLock(
  27635. sqlite3_file *fd, /* Database file holding the shared memory */
  27636. int ofst, /* First lock to acquire or release */
  27637. int n, /* Number of locks to acquire or release */
  27638. int flags /* What to do with the lock */
  27639. ){
  27640. unixFile *pDbFd = (unixFile*)fd; /* Connection holding shared memory */
  27641. unixShm *p = pDbFd->pShm; /* The shared memory being locked */
  27642. unixShm *pX; /* For looping over all siblings */
  27643. unixShmNode *pShmNode = p->pShmNode; /* The underlying file iNode */
  27644. int rc = SQLITE_OK; /* Result code */
  27645. u16 mask; /* Mask of locks to take or release */
  27646. assert( pShmNode==pDbFd->pInode->pShmNode );
  27647. assert( pShmNode->pInode==pDbFd->pInode );
  27648. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  27649. assert( n>=1 );
  27650. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  27651. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  27652. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  27653. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  27654. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  27655. assert( pShmNode->h>=0 || pDbFd->pInode->bProcessLock==1 );
  27656. assert( pShmNode->h<0 || pDbFd->pInode->bProcessLock==0 );
  27657. mask = (1<<(ofst+n)) - (1<<ofst);
  27658. assert( n>1 || mask==(1<<ofst) );
  27659. sqlite3_mutex_enter(pShmNode->mutex);
  27660. if( flags & SQLITE_SHM_UNLOCK ){
  27661. u16 allMask = 0; /* Mask of locks held by siblings */
  27662. /* See if any siblings hold this same lock */
  27663. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  27664. if( pX==p ) continue;
  27665. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  27666. allMask |= pX->sharedMask;
  27667. }
  27668. /* Unlock the system-level locks */
  27669. if( (mask & allMask)==0 ){
  27670. rc = unixShmSystemLock(pShmNode, F_UNLCK, ofst+UNIX_SHM_BASE, n);
  27671. }else{
  27672. rc = SQLITE_OK;
  27673. }
  27674. /* Undo the local locks */
  27675. if( rc==SQLITE_OK ){
  27676. p->exclMask &= ~mask;
  27677. p->sharedMask &= ~mask;
  27678. }
  27679. }else if( flags & SQLITE_SHM_SHARED ){
  27680. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  27681. /* Find out which shared locks are already held by sibling connections.
  27682. ** If any sibling already holds an exclusive lock, go ahead and return
  27683. ** SQLITE_BUSY.
  27684. */
  27685. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  27686. if( (pX->exclMask & mask)!=0 ){
  27687. rc = SQLITE_BUSY;
  27688. break;
  27689. }
  27690. allShared |= pX->sharedMask;
  27691. }
  27692. /* Get shared locks at the system level, if necessary */
  27693. if( rc==SQLITE_OK ){
  27694. if( (allShared & mask)==0 ){
  27695. rc = unixShmSystemLock(pShmNode, F_RDLCK, ofst+UNIX_SHM_BASE, n);
  27696. }else{
  27697. rc = SQLITE_OK;
  27698. }
  27699. }
  27700. /* Get the local shared locks */
  27701. if( rc==SQLITE_OK ){
  27702. p->sharedMask |= mask;
  27703. }
  27704. }else{
  27705. /* Make sure no sibling connections hold locks that will block this
  27706. ** lock. If any do, return SQLITE_BUSY right away.
  27707. */
  27708. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  27709. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  27710. rc = SQLITE_BUSY;
  27711. break;
  27712. }
  27713. }
  27714. /* Get the exclusive locks at the system level. Then if successful
  27715. ** also mark the local connection as being locked.
  27716. */
  27717. if( rc==SQLITE_OK ){
  27718. rc = unixShmSystemLock(pShmNode, F_WRLCK, ofst+UNIX_SHM_BASE, n);
  27719. if( rc==SQLITE_OK ){
  27720. assert( (p->sharedMask & mask)==0 );
  27721. p->exclMask |= mask;
  27722. }
  27723. }
  27724. }
  27725. sqlite3_mutex_leave(pShmNode->mutex);
  27726. OSTRACE(("SHM-LOCK shmid-%d, pid-%d got %03x,%03x\n",
  27727. p->id, getpid(), p->sharedMask, p->exclMask));
  27728. return rc;
  27729. }
  27730. /*
  27731. ** Implement a memory barrier or memory fence on shared memory.
  27732. **
  27733. ** All loads and stores begun before the barrier must complete before
  27734. ** any load or store begun after the barrier.
  27735. */
  27736. static void unixShmBarrier(
  27737. sqlite3_file *fd /* Database file holding the shared memory */
  27738. ){
  27739. UNUSED_PARAMETER(fd);
  27740. unixEnterMutex();
  27741. unixLeaveMutex();
  27742. }
  27743. /*
  27744. ** Close a connection to shared-memory. Delete the underlying
  27745. ** storage if deleteFlag is true.
  27746. **
  27747. ** If there is no shared memory associated with the connection then this
  27748. ** routine is a harmless no-op.
  27749. */
  27750. static int unixShmUnmap(
  27751. sqlite3_file *fd, /* The underlying database file */
  27752. int deleteFlag /* Delete shared-memory if true */
  27753. ){
  27754. unixShm *p; /* The connection to be closed */
  27755. unixShmNode *pShmNode; /* The underlying shared-memory file */
  27756. unixShm **pp; /* For looping over sibling connections */
  27757. unixFile *pDbFd; /* The underlying database file */
  27758. pDbFd = (unixFile*)fd;
  27759. p = pDbFd->pShm;
  27760. if( p==0 ) return SQLITE_OK;
  27761. pShmNode = p->pShmNode;
  27762. assert( pShmNode==pDbFd->pInode->pShmNode );
  27763. assert( pShmNode->pInode==pDbFd->pInode );
  27764. /* Remove connection p from the set of connections associated
  27765. ** with pShmNode */
  27766. sqlite3_mutex_enter(pShmNode->mutex);
  27767. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  27768. *pp = p->pNext;
  27769. /* Free the connection p */
  27770. sqlite3_free(p);
  27771. pDbFd->pShm = 0;
  27772. sqlite3_mutex_leave(pShmNode->mutex);
  27773. /* If pShmNode->nRef has reached 0, then close the underlying
  27774. ** shared-memory file, too */
  27775. unixEnterMutex();
  27776. assert( pShmNode->nRef>0 );
  27777. pShmNode->nRef--;
  27778. if( pShmNode->nRef==0 ){
  27779. if( deleteFlag && pShmNode->h>=0 ) osUnlink(pShmNode->zFilename);
  27780. unixShmPurge(pDbFd);
  27781. }
  27782. unixLeaveMutex();
  27783. return SQLITE_OK;
  27784. }
  27785. #else
  27786. # define unixShmMap 0
  27787. # define unixShmLock 0
  27788. # define unixShmBarrier 0
  27789. # define unixShmUnmap 0
  27790. #endif /* #ifndef SQLITE_OMIT_WAL */
  27791. #if SQLITE_MAX_MMAP_SIZE>0
  27792. /*
  27793. ** If it is currently memory mapped, unmap file pFd.
  27794. */
  27795. static void unixUnmapfile(unixFile *pFd){
  27796. assert( pFd->nFetchOut==0 );
  27797. if( pFd->pMapRegion ){
  27798. osMunmap(pFd->pMapRegion, pFd->mmapSizeActual);
  27799. pFd->pMapRegion = 0;
  27800. pFd->mmapSize = 0;
  27801. pFd->mmapSizeActual = 0;
  27802. }
  27803. }
  27804. /*
  27805. ** Attempt to set the size of the memory mapping maintained by file
  27806. ** descriptor pFd to nNew bytes. Any existing mapping is discarded.
  27807. **
  27808. ** If successful, this function sets the following variables:
  27809. **
  27810. ** unixFile.pMapRegion
  27811. ** unixFile.mmapSize
  27812. ** unixFile.mmapSizeActual
  27813. **
  27814. ** If unsuccessful, an error message is logged via sqlite3_log() and
  27815. ** the three variables above are zeroed. In this case SQLite should
  27816. ** continue accessing the database using the xRead() and xWrite()
  27817. ** methods.
  27818. */
  27819. static void unixRemapfile(
  27820. unixFile *pFd, /* File descriptor object */
  27821. i64 nNew /* Required mapping size */
  27822. ){
  27823. const char *zErr = "mmap";
  27824. int h = pFd->h; /* File descriptor open on db file */
  27825. u8 *pOrig = (u8 *)pFd->pMapRegion; /* Pointer to current file mapping */
  27826. i64 nOrig = pFd->mmapSizeActual; /* Size of pOrig region in bytes */
  27827. u8 *pNew = 0; /* Location of new mapping */
  27828. int flags = PROT_READ; /* Flags to pass to mmap() */
  27829. assert( pFd->nFetchOut==0 );
  27830. assert( nNew>pFd->mmapSize );
  27831. assert( nNew<=pFd->mmapSizeMax );
  27832. assert( nNew>0 );
  27833. assert( pFd->mmapSizeActual>=pFd->mmapSize );
  27834. assert( MAP_FAILED!=0 );
  27835. if( (pFd->ctrlFlags & UNIXFILE_RDONLY)==0 ) flags |= PROT_WRITE;
  27836. if( pOrig ){
  27837. #if HAVE_MREMAP
  27838. i64 nReuse = pFd->mmapSize;
  27839. #else
  27840. const int szSyspage = osGetpagesize();
  27841. i64 nReuse = (pFd->mmapSize & ~(szSyspage-1));
  27842. #endif
  27843. u8 *pReq = &pOrig[nReuse];
  27844. /* Unmap any pages of the existing mapping that cannot be reused. */
  27845. if( nReuse!=nOrig ){
  27846. osMunmap(pReq, nOrig-nReuse);
  27847. }
  27848. #if HAVE_MREMAP
  27849. pNew = osMremap(pOrig, nReuse, nNew, MREMAP_MAYMOVE);
  27850. zErr = "mremap";
  27851. #else
  27852. pNew = osMmap(pReq, nNew-nReuse, flags, MAP_SHARED, h, nReuse);
  27853. if( pNew!=MAP_FAILED ){
  27854. if( pNew!=pReq ){
  27855. osMunmap(pNew, nNew - nReuse);
  27856. pNew = 0;
  27857. }else{
  27858. pNew = pOrig;
  27859. }
  27860. }
  27861. #endif
  27862. /* The attempt to extend the existing mapping failed. Free it. */
  27863. if( pNew==MAP_FAILED || pNew==0 ){
  27864. osMunmap(pOrig, nReuse);
  27865. }
  27866. }
  27867. /* If pNew is still NULL, try to create an entirely new mapping. */
  27868. if( pNew==0 ){
  27869. pNew = osMmap(0, nNew, flags, MAP_SHARED, h, 0);
  27870. }
  27871. if( pNew==MAP_FAILED ){
  27872. pNew = 0;
  27873. nNew = 0;
  27874. unixLogError(SQLITE_OK, zErr, pFd->zPath);
  27875. /* If the mmap() above failed, assume that all subsequent mmap() calls
  27876. ** will probably fail too. Fall back to using xRead/xWrite exclusively
  27877. ** in this case. */
  27878. pFd->mmapSizeMax = 0;
  27879. }
  27880. pFd->pMapRegion = (void *)pNew;
  27881. pFd->mmapSize = pFd->mmapSizeActual = nNew;
  27882. }
  27883. /*
  27884. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  27885. ** is already mapped, the existing mapping is replaced by the new). Or, if
  27886. ** there already exists a mapping for this file, and there are still
  27887. ** outstanding xFetch() references to it, this function is a no-op.
  27888. **
  27889. ** If parameter nByte is non-negative, then it is the requested size of
  27890. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  27891. ** requested size is the size of the file on disk. The actual size of the
  27892. ** created mapping is either the requested size or the value configured
  27893. ** using SQLITE_FCNTL_MMAP_LIMIT, whichever is smaller.
  27894. **
  27895. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  27896. ** recreated as a result of outstanding references) or an SQLite error
  27897. ** code otherwise.
  27898. */
  27899. static int unixMapfile(unixFile *pFd, i64 nByte){
  27900. i64 nMap = nByte;
  27901. int rc;
  27902. assert( nMap>=0 || pFd->nFetchOut==0 );
  27903. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  27904. if( nMap<0 ){
  27905. struct stat statbuf; /* Low-level file information */
  27906. rc = osFstat(pFd->h, &statbuf);
  27907. if( rc!=SQLITE_OK ){
  27908. return SQLITE_IOERR_FSTAT;
  27909. }
  27910. nMap = statbuf.st_size;
  27911. }
  27912. if( nMap>pFd->mmapSizeMax ){
  27913. nMap = pFd->mmapSizeMax;
  27914. }
  27915. if( nMap!=pFd->mmapSize ){
  27916. if( nMap>0 ){
  27917. unixRemapfile(pFd, nMap);
  27918. }else{
  27919. unixUnmapfile(pFd);
  27920. }
  27921. }
  27922. return SQLITE_OK;
  27923. }
  27924. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  27925. /*
  27926. ** If possible, return a pointer to a mapping of file fd starting at offset
  27927. ** iOff. The mapping must be valid for at least nAmt bytes.
  27928. **
  27929. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  27930. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  27931. ** Finally, if an error does occur, return an SQLite error code. The final
  27932. ** value of *pp is undefined in this case.
  27933. **
  27934. ** If this function does return a pointer, the caller must eventually
  27935. ** release the reference by calling unixUnfetch().
  27936. */
  27937. static int unixFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  27938. #if SQLITE_MAX_MMAP_SIZE>0
  27939. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  27940. #endif
  27941. *pp = 0;
  27942. #if SQLITE_MAX_MMAP_SIZE>0
  27943. if( pFd->mmapSizeMax>0 ){
  27944. if( pFd->pMapRegion==0 ){
  27945. int rc = unixMapfile(pFd, -1);
  27946. if( rc!=SQLITE_OK ) return rc;
  27947. }
  27948. if( pFd->mmapSize >= iOff+nAmt ){
  27949. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  27950. pFd->nFetchOut++;
  27951. }
  27952. }
  27953. #endif
  27954. return SQLITE_OK;
  27955. }
  27956. /*
  27957. ** If the third argument is non-NULL, then this function releases a
  27958. ** reference obtained by an earlier call to unixFetch(). The second
  27959. ** argument passed to this function must be the same as the corresponding
  27960. ** argument that was passed to the unixFetch() invocation.
  27961. **
  27962. ** Or, if the third argument is NULL, then this function is being called
  27963. ** to inform the VFS layer that, according to POSIX, any existing mapping
  27964. ** may now be invalid and should be unmapped.
  27965. */
  27966. static int unixUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  27967. #if SQLITE_MAX_MMAP_SIZE>0
  27968. unixFile *pFd = (unixFile *)fd; /* The underlying database file */
  27969. UNUSED_PARAMETER(iOff);
  27970. /* If p==0 (unmap the entire file) then there must be no outstanding
  27971. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  27972. ** then there must be at least one outstanding. */
  27973. assert( (p==0)==(pFd->nFetchOut==0) );
  27974. /* If p!=0, it must match the iOff value. */
  27975. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  27976. if( p ){
  27977. pFd->nFetchOut--;
  27978. }else{
  27979. unixUnmapfile(pFd);
  27980. }
  27981. assert( pFd->nFetchOut>=0 );
  27982. #else
  27983. UNUSED_PARAMETER(fd);
  27984. UNUSED_PARAMETER(p);
  27985. UNUSED_PARAMETER(iOff);
  27986. #endif
  27987. return SQLITE_OK;
  27988. }
  27989. /*
  27990. ** Here ends the implementation of all sqlite3_file methods.
  27991. **
  27992. ********************** End sqlite3_file Methods *******************************
  27993. ******************************************************************************/
  27994. /*
  27995. ** This division contains definitions of sqlite3_io_methods objects that
  27996. ** implement various file locking strategies. It also contains definitions
  27997. ** of "finder" functions. A finder-function is used to locate the appropriate
  27998. ** sqlite3_io_methods object for a particular database file. The pAppData
  27999. ** field of the sqlite3_vfs VFS objects are initialized to be pointers to
  28000. ** the correct finder-function for that VFS.
  28001. **
  28002. ** Most finder functions return a pointer to a fixed sqlite3_io_methods
  28003. ** object. The only interesting finder-function is autolockIoFinder, which
  28004. ** looks at the filesystem type and tries to guess the best locking
  28005. ** strategy from that.
  28006. **
  28007. ** For finder-function F, two objects are created:
  28008. **
  28009. ** (1) The real finder-function named "FImpt()".
  28010. **
  28011. ** (2) A constant pointer to this function named just "F".
  28012. **
  28013. **
  28014. ** A pointer to the F pointer is used as the pAppData value for VFS
  28015. ** objects. We have to do this instead of letting pAppData point
  28016. ** directly at the finder-function since C90 rules prevent a void*
  28017. ** from be cast into a function pointer.
  28018. **
  28019. **
  28020. ** Each instance of this macro generates two objects:
  28021. **
  28022. ** * A constant sqlite3_io_methods object call METHOD that has locking
  28023. ** methods CLOSE, LOCK, UNLOCK, CKRESLOCK.
  28024. **
  28025. ** * An I/O method finder function called FINDER that returns a pointer
  28026. ** to the METHOD object in the previous bullet.
  28027. */
  28028. #define IOMETHODS(FINDER, METHOD, VERSION, CLOSE, LOCK, UNLOCK, CKLOCK, SHMMAP) \
  28029. static const sqlite3_io_methods METHOD = { \
  28030. VERSION, /* iVersion */ \
  28031. CLOSE, /* xClose */ \
  28032. unixRead, /* xRead */ \
  28033. unixWrite, /* xWrite */ \
  28034. unixTruncate, /* xTruncate */ \
  28035. unixSync, /* xSync */ \
  28036. unixFileSize, /* xFileSize */ \
  28037. LOCK, /* xLock */ \
  28038. UNLOCK, /* xUnlock */ \
  28039. CKLOCK, /* xCheckReservedLock */ \
  28040. unixFileControl, /* xFileControl */ \
  28041. unixSectorSize, /* xSectorSize */ \
  28042. unixDeviceCharacteristics, /* xDeviceCapabilities */ \
  28043. SHMMAP, /* xShmMap */ \
  28044. unixShmLock, /* xShmLock */ \
  28045. unixShmBarrier, /* xShmBarrier */ \
  28046. unixShmUnmap, /* xShmUnmap */ \
  28047. unixFetch, /* xFetch */ \
  28048. unixUnfetch, /* xUnfetch */ \
  28049. }; \
  28050. static const sqlite3_io_methods *FINDER##Impl(const char *z, unixFile *p){ \
  28051. UNUSED_PARAMETER(z); UNUSED_PARAMETER(p); \
  28052. return &METHOD; \
  28053. } \
  28054. static const sqlite3_io_methods *(*const FINDER)(const char*,unixFile *p) \
  28055. = FINDER##Impl;
  28056. /*
  28057. ** Here are all of the sqlite3_io_methods objects for each of the
  28058. ** locking strategies. Functions that return pointers to these methods
  28059. ** are also created.
  28060. */
  28061. IOMETHODS(
  28062. posixIoFinder, /* Finder function name */
  28063. posixIoMethods, /* sqlite3_io_methods object name */
  28064. 3, /* shared memory and mmap are enabled */
  28065. unixClose, /* xClose method */
  28066. unixLock, /* xLock method */
  28067. unixUnlock, /* xUnlock method */
  28068. unixCheckReservedLock, /* xCheckReservedLock method */
  28069. unixShmMap /* xShmMap method */
  28070. )
  28071. IOMETHODS(
  28072. nolockIoFinder, /* Finder function name */
  28073. nolockIoMethods, /* sqlite3_io_methods object name */
  28074. 3, /* shared memory is disabled */
  28075. nolockClose, /* xClose method */
  28076. nolockLock, /* xLock method */
  28077. nolockUnlock, /* xUnlock method */
  28078. nolockCheckReservedLock, /* xCheckReservedLock method */
  28079. 0 /* xShmMap method */
  28080. )
  28081. IOMETHODS(
  28082. dotlockIoFinder, /* Finder function name */
  28083. dotlockIoMethods, /* sqlite3_io_methods object name */
  28084. 1, /* shared memory is disabled */
  28085. dotlockClose, /* xClose method */
  28086. dotlockLock, /* xLock method */
  28087. dotlockUnlock, /* xUnlock method */
  28088. dotlockCheckReservedLock, /* xCheckReservedLock method */
  28089. 0 /* xShmMap method */
  28090. )
  28091. #if SQLITE_ENABLE_LOCKING_STYLE && !OS_VXWORKS
  28092. IOMETHODS(
  28093. flockIoFinder, /* Finder function name */
  28094. flockIoMethods, /* sqlite3_io_methods object name */
  28095. 1, /* shared memory is disabled */
  28096. flockClose, /* xClose method */
  28097. flockLock, /* xLock method */
  28098. flockUnlock, /* xUnlock method */
  28099. flockCheckReservedLock, /* xCheckReservedLock method */
  28100. 0 /* xShmMap method */
  28101. )
  28102. #endif
  28103. #if OS_VXWORKS
  28104. IOMETHODS(
  28105. semIoFinder, /* Finder function name */
  28106. semIoMethods, /* sqlite3_io_methods object name */
  28107. 1, /* shared memory is disabled */
  28108. semClose, /* xClose method */
  28109. semLock, /* xLock method */
  28110. semUnlock, /* xUnlock method */
  28111. semCheckReservedLock, /* xCheckReservedLock method */
  28112. 0 /* xShmMap method */
  28113. )
  28114. #endif
  28115. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28116. IOMETHODS(
  28117. afpIoFinder, /* Finder function name */
  28118. afpIoMethods, /* sqlite3_io_methods object name */
  28119. 1, /* shared memory is disabled */
  28120. afpClose, /* xClose method */
  28121. afpLock, /* xLock method */
  28122. afpUnlock, /* xUnlock method */
  28123. afpCheckReservedLock, /* xCheckReservedLock method */
  28124. 0 /* xShmMap method */
  28125. )
  28126. #endif
  28127. /*
  28128. ** The proxy locking method is a "super-method" in the sense that it
  28129. ** opens secondary file descriptors for the conch and lock files and
  28130. ** it uses proxy, dot-file, AFP, and flock() locking methods on those
  28131. ** secondary files. For this reason, the division that implements
  28132. ** proxy locking is located much further down in the file. But we need
  28133. ** to go ahead and define the sqlite3_io_methods and finder function
  28134. ** for proxy locking here. So we forward declare the I/O methods.
  28135. */
  28136. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28137. static int proxyClose(sqlite3_file*);
  28138. static int proxyLock(sqlite3_file*, int);
  28139. static int proxyUnlock(sqlite3_file*, int);
  28140. static int proxyCheckReservedLock(sqlite3_file*, int*);
  28141. IOMETHODS(
  28142. proxyIoFinder, /* Finder function name */
  28143. proxyIoMethods, /* sqlite3_io_methods object name */
  28144. 1, /* shared memory is disabled */
  28145. proxyClose, /* xClose method */
  28146. proxyLock, /* xLock method */
  28147. proxyUnlock, /* xUnlock method */
  28148. proxyCheckReservedLock, /* xCheckReservedLock method */
  28149. 0 /* xShmMap method */
  28150. )
  28151. #endif
  28152. /* nfs lockd on OSX 10.3+ doesn't clear write locks when a read lock is set */
  28153. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28154. IOMETHODS(
  28155. nfsIoFinder, /* Finder function name */
  28156. nfsIoMethods, /* sqlite3_io_methods object name */
  28157. 1, /* shared memory is disabled */
  28158. unixClose, /* xClose method */
  28159. unixLock, /* xLock method */
  28160. nfsUnlock, /* xUnlock method */
  28161. unixCheckReservedLock, /* xCheckReservedLock method */
  28162. 0 /* xShmMap method */
  28163. )
  28164. #endif
  28165. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28166. /*
  28167. ** This "finder" function attempts to determine the best locking strategy
  28168. ** for the database file "filePath". It then returns the sqlite3_io_methods
  28169. ** object that implements that strategy.
  28170. **
  28171. ** This is for MacOSX only.
  28172. */
  28173. static const sqlite3_io_methods *autolockIoFinderImpl(
  28174. const char *filePath, /* name of the database file */
  28175. unixFile *pNew /* open file object for the database file */
  28176. ){
  28177. static const struct Mapping {
  28178. const char *zFilesystem; /* Filesystem type name */
  28179. const sqlite3_io_methods *pMethods; /* Appropriate locking method */
  28180. } aMap[] = {
  28181. { "hfs", &posixIoMethods },
  28182. { "ufs", &posixIoMethods },
  28183. { "afpfs", &afpIoMethods },
  28184. { "smbfs", &afpIoMethods },
  28185. { "webdav", &nolockIoMethods },
  28186. { 0, 0 }
  28187. };
  28188. int i;
  28189. struct statfs fsInfo;
  28190. struct flock lockInfo;
  28191. if( !filePath ){
  28192. /* If filePath==NULL that means we are dealing with a transient file
  28193. ** that does not need to be locked. */
  28194. return &nolockIoMethods;
  28195. }
  28196. if( statfs(filePath, &fsInfo) != -1 ){
  28197. if( fsInfo.f_flags & MNT_RDONLY ){
  28198. return &nolockIoMethods;
  28199. }
  28200. for(i=0; aMap[i].zFilesystem; i++){
  28201. if( strcmp(fsInfo.f_fstypename, aMap[i].zFilesystem)==0 ){
  28202. return aMap[i].pMethods;
  28203. }
  28204. }
  28205. }
  28206. /* Default case. Handles, amongst others, "nfs".
  28207. ** Test byte-range lock using fcntl(). If the call succeeds,
  28208. ** assume that the file-system supports POSIX style locks.
  28209. */
  28210. lockInfo.l_len = 1;
  28211. lockInfo.l_start = 0;
  28212. lockInfo.l_whence = SEEK_SET;
  28213. lockInfo.l_type = F_RDLCK;
  28214. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  28215. if( strcmp(fsInfo.f_fstypename, "nfs")==0 ){
  28216. return &nfsIoMethods;
  28217. } else {
  28218. return &posixIoMethods;
  28219. }
  28220. }else{
  28221. return &dotlockIoMethods;
  28222. }
  28223. }
  28224. static const sqlite3_io_methods
  28225. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  28226. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  28227. #if OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE
  28228. /*
  28229. ** This "finder" function attempts to determine the best locking strategy
  28230. ** for the database file "filePath". It then returns the sqlite3_io_methods
  28231. ** object that implements that strategy.
  28232. **
  28233. ** This is for VXWorks only.
  28234. */
  28235. static const sqlite3_io_methods *autolockIoFinderImpl(
  28236. const char *filePath, /* name of the database file */
  28237. unixFile *pNew /* the open file object */
  28238. ){
  28239. struct flock lockInfo;
  28240. if( !filePath ){
  28241. /* If filePath==NULL that means we are dealing with a transient file
  28242. ** that does not need to be locked. */
  28243. return &nolockIoMethods;
  28244. }
  28245. /* Test if fcntl() is supported and use POSIX style locks.
  28246. ** Otherwise fall back to the named semaphore method.
  28247. */
  28248. lockInfo.l_len = 1;
  28249. lockInfo.l_start = 0;
  28250. lockInfo.l_whence = SEEK_SET;
  28251. lockInfo.l_type = F_RDLCK;
  28252. if( osFcntl(pNew->h, F_GETLK, &lockInfo)!=-1 ) {
  28253. return &posixIoMethods;
  28254. }else{
  28255. return &semIoMethods;
  28256. }
  28257. }
  28258. static const sqlite3_io_methods
  28259. *(*const autolockIoFinder)(const char*,unixFile*) = autolockIoFinderImpl;
  28260. #endif /* OS_VXWORKS && SQLITE_ENABLE_LOCKING_STYLE */
  28261. /*
  28262. ** An abstract type for a pointer to an IO method finder function:
  28263. */
  28264. typedef const sqlite3_io_methods *(*finder_type)(const char*,unixFile*);
  28265. /****************************************************************************
  28266. **************************** sqlite3_vfs methods ****************************
  28267. **
  28268. ** This division contains the implementation of methods on the
  28269. ** sqlite3_vfs object.
  28270. */
  28271. /*
  28272. ** Initialize the contents of the unixFile structure pointed to by pId.
  28273. */
  28274. static int fillInUnixFile(
  28275. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  28276. int h, /* Open file descriptor of file being opened */
  28277. sqlite3_file *pId, /* Write to the unixFile structure here */
  28278. const char *zFilename, /* Name of the file being opened */
  28279. int ctrlFlags /* Zero or more UNIXFILE_* values */
  28280. ){
  28281. const sqlite3_io_methods *pLockingStyle;
  28282. unixFile *pNew = (unixFile *)pId;
  28283. int rc = SQLITE_OK;
  28284. assert( pNew->pInode==NULL );
  28285. /* Usually the path zFilename should not be a relative pathname. The
  28286. ** exception is when opening the proxy "conch" file in builds that
  28287. ** include the special Apple locking styles.
  28288. */
  28289. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28290. assert( zFilename==0 || zFilename[0]=='/'
  28291. || pVfs->pAppData==(void*)&autolockIoFinder );
  28292. #else
  28293. assert( zFilename==0 || zFilename[0]=='/' );
  28294. #endif
  28295. /* No locking occurs in temporary files */
  28296. assert( zFilename!=0 || (ctrlFlags & UNIXFILE_NOLOCK)!=0 );
  28297. OSTRACE(("OPEN %-3d %s\n", h, zFilename));
  28298. pNew->h = h;
  28299. pNew->pVfs = pVfs;
  28300. pNew->zPath = zFilename;
  28301. pNew->ctrlFlags = (u8)ctrlFlags;
  28302. #if SQLITE_MAX_MMAP_SIZE>0
  28303. pNew->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  28304. #endif
  28305. if( sqlite3_uri_boolean(((ctrlFlags & UNIXFILE_URI) ? zFilename : 0),
  28306. "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  28307. pNew->ctrlFlags |= UNIXFILE_PSOW;
  28308. }
  28309. if( strcmp(pVfs->zName,"unix-excl")==0 ){
  28310. pNew->ctrlFlags |= UNIXFILE_EXCL;
  28311. }
  28312. #if OS_VXWORKS
  28313. pNew->pId = vxworksFindFileId(zFilename);
  28314. if( pNew->pId==0 ){
  28315. ctrlFlags |= UNIXFILE_NOLOCK;
  28316. rc = SQLITE_NOMEM;
  28317. }
  28318. #endif
  28319. if( ctrlFlags & UNIXFILE_NOLOCK ){
  28320. pLockingStyle = &nolockIoMethods;
  28321. }else{
  28322. pLockingStyle = (**(finder_type*)pVfs->pAppData)(zFilename, pNew);
  28323. #if SQLITE_ENABLE_LOCKING_STYLE
  28324. /* Cache zFilename in the locking context (AFP and dotlock override) for
  28325. ** proxyLock activation is possible (remote proxy is based on db name)
  28326. ** zFilename remains valid until file is closed, to support */
  28327. pNew->lockingContext = (void*)zFilename;
  28328. #endif
  28329. }
  28330. if( pLockingStyle == &posixIoMethods
  28331. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  28332. || pLockingStyle == &nfsIoMethods
  28333. #endif
  28334. ){
  28335. unixEnterMutex();
  28336. rc = findInodeInfo(pNew, &pNew->pInode);
  28337. if( rc!=SQLITE_OK ){
  28338. /* If an error occurred in findInodeInfo(), close the file descriptor
  28339. ** immediately, before releasing the mutex. findInodeInfo() may fail
  28340. ** in two scenarios:
  28341. **
  28342. ** (a) A call to fstat() failed.
  28343. ** (b) A malloc failed.
  28344. **
  28345. ** Scenario (b) may only occur if the process is holding no other
  28346. ** file descriptors open on the same file. If there were other file
  28347. ** descriptors on this file, then no malloc would be required by
  28348. ** findInodeInfo(). If this is the case, it is quite safe to close
  28349. ** handle h - as it is guaranteed that no posix locks will be released
  28350. ** by doing so.
  28351. **
  28352. ** If scenario (a) caused the error then things are not so safe. The
  28353. ** implicit assumption here is that if fstat() fails, things are in
  28354. ** such bad shape that dropping a lock or two doesn't matter much.
  28355. */
  28356. robust_close(pNew, h, __LINE__);
  28357. h = -1;
  28358. }
  28359. unixLeaveMutex();
  28360. }
  28361. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28362. else if( pLockingStyle == &afpIoMethods ){
  28363. /* AFP locking uses the file path so it needs to be included in
  28364. ** the afpLockingContext.
  28365. */
  28366. afpLockingContext *pCtx;
  28367. pNew->lockingContext = pCtx = sqlite3_malloc( sizeof(*pCtx) );
  28368. if( pCtx==0 ){
  28369. rc = SQLITE_NOMEM;
  28370. }else{
  28371. /* NB: zFilename exists and remains valid until the file is closed
  28372. ** according to requirement F11141. So we do not need to make a
  28373. ** copy of the filename. */
  28374. pCtx->dbPath = zFilename;
  28375. pCtx->reserved = 0;
  28376. srandomdev();
  28377. unixEnterMutex();
  28378. rc = findInodeInfo(pNew, &pNew->pInode);
  28379. if( rc!=SQLITE_OK ){
  28380. sqlite3_free(pNew->lockingContext);
  28381. robust_close(pNew, h, __LINE__);
  28382. h = -1;
  28383. }
  28384. unixLeaveMutex();
  28385. }
  28386. }
  28387. #endif
  28388. else if( pLockingStyle == &dotlockIoMethods ){
  28389. /* Dotfile locking uses the file path so it needs to be included in
  28390. ** the dotlockLockingContext
  28391. */
  28392. char *zLockFile;
  28393. int nFilename;
  28394. assert( zFilename!=0 );
  28395. nFilename = (int)strlen(zFilename) + 6;
  28396. zLockFile = (char *)sqlite3_malloc(nFilename);
  28397. if( zLockFile==0 ){
  28398. rc = SQLITE_NOMEM;
  28399. }else{
  28400. sqlite3_snprintf(nFilename, zLockFile, "%s" DOTLOCK_SUFFIX, zFilename);
  28401. }
  28402. pNew->lockingContext = zLockFile;
  28403. }
  28404. #if OS_VXWORKS
  28405. else if( pLockingStyle == &semIoMethods ){
  28406. /* Named semaphore locking uses the file path so it needs to be
  28407. ** included in the semLockingContext
  28408. */
  28409. unixEnterMutex();
  28410. rc = findInodeInfo(pNew, &pNew->pInode);
  28411. if( (rc==SQLITE_OK) && (pNew->pInode->pSem==NULL) ){
  28412. char *zSemName = pNew->pInode->aSemName;
  28413. int n;
  28414. sqlite3_snprintf(MAX_PATHNAME, zSemName, "/%s.sem",
  28415. pNew->pId->zCanonicalName);
  28416. for( n=1; zSemName[n]; n++ )
  28417. if( zSemName[n]=='/' ) zSemName[n] = '_';
  28418. pNew->pInode->pSem = sem_open(zSemName, O_CREAT, 0666, 1);
  28419. if( pNew->pInode->pSem == SEM_FAILED ){
  28420. rc = SQLITE_NOMEM;
  28421. pNew->pInode->aSemName[0] = '\0';
  28422. }
  28423. }
  28424. unixLeaveMutex();
  28425. }
  28426. #endif
  28427. pNew->lastErrno = 0;
  28428. #if OS_VXWORKS
  28429. if( rc!=SQLITE_OK ){
  28430. if( h>=0 ) robust_close(pNew, h, __LINE__);
  28431. h = -1;
  28432. osUnlink(zFilename);
  28433. pNew->ctrlFlags |= UNIXFILE_DELETE;
  28434. }
  28435. #endif
  28436. if( rc!=SQLITE_OK ){
  28437. if( h>=0 ) robust_close(pNew, h, __LINE__);
  28438. }else{
  28439. pNew->pMethod = pLockingStyle;
  28440. OpenCounter(+1);
  28441. verifyDbFile(pNew);
  28442. }
  28443. return rc;
  28444. }
  28445. /*
  28446. ** Return the name of a directory in which to put temporary files.
  28447. ** If no suitable temporary file directory can be found, return NULL.
  28448. */
  28449. static const char *unixTempFileDir(void){
  28450. static const char *azDirs[] = {
  28451. 0,
  28452. 0,
  28453. 0,
  28454. "/var/tmp",
  28455. "/usr/tmp",
  28456. "/tmp",
  28457. 0 /* List terminator */
  28458. };
  28459. unsigned int i;
  28460. struct stat buf;
  28461. const char *zDir = 0;
  28462. azDirs[0] = sqlite3_temp_directory;
  28463. if( !azDirs[1] ) azDirs[1] = getenv("SQLITE_TMPDIR");
  28464. if( !azDirs[2] ) azDirs[2] = getenv("TMPDIR");
  28465. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  28466. if( zDir==0 ) continue;
  28467. if( osStat(zDir, &buf) ) continue;
  28468. if( !S_ISDIR(buf.st_mode) ) continue;
  28469. if( osAccess(zDir, 07) ) continue;
  28470. break;
  28471. }
  28472. return zDir;
  28473. }
  28474. /*
  28475. ** Create a temporary file name in zBuf. zBuf must be allocated
  28476. ** by the calling process and must be big enough to hold at least
  28477. ** pVfs->mxPathname bytes.
  28478. */
  28479. static int unixGetTempname(int nBuf, char *zBuf){
  28480. static const unsigned char zChars[] =
  28481. "abcdefghijklmnopqrstuvwxyz"
  28482. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  28483. "0123456789";
  28484. unsigned int i, j;
  28485. const char *zDir;
  28486. /* It's odd to simulate an io-error here, but really this is just
  28487. ** using the io-error infrastructure to test that SQLite handles this
  28488. ** function failing.
  28489. */
  28490. SimulateIOError( return SQLITE_IOERR );
  28491. zDir = unixTempFileDir();
  28492. if( zDir==0 ) zDir = ".";
  28493. /* Check that the output buffer is large enough for the temporary file
  28494. ** name. If it is not, return SQLITE_ERROR.
  28495. */
  28496. if( (strlen(zDir) + strlen(SQLITE_TEMP_FILE_PREFIX) + 18) >= (size_t)nBuf ){
  28497. return SQLITE_ERROR;
  28498. }
  28499. do{
  28500. sqlite3_snprintf(nBuf-18, zBuf, "%s/"SQLITE_TEMP_FILE_PREFIX, zDir);
  28501. j = (int)strlen(zBuf);
  28502. sqlite3_randomness(15, &zBuf[j]);
  28503. for(i=0; i<15; i++, j++){
  28504. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  28505. }
  28506. zBuf[j] = 0;
  28507. zBuf[j+1] = 0;
  28508. }while( osAccess(zBuf,0)==0 );
  28509. return SQLITE_OK;
  28510. }
  28511. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  28512. /*
  28513. ** Routine to transform a unixFile into a proxy-locking unixFile.
  28514. ** Implementation in the proxy-lock division, but used by unixOpen()
  28515. ** if SQLITE_PREFER_PROXY_LOCKING is defined.
  28516. */
  28517. static int proxyTransformUnixFile(unixFile*, const char*);
  28518. #endif
  28519. /*
  28520. ** Search for an unused file descriptor that was opened on the database
  28521. ** file (not a journal or master-journal file) identified by pathname
  28522. ** zPath with SQLITE_OPEN_XXX flags matching those passed as the second
  28523. ** argument to this function.
  28524. **
  28525. ** Such a file descriptor may exist if a database connection was closed
  28526. ** but the associated file descriptor could not be closed because some
  28527. ** other file descriptor open on the same file is holding a file-lock.
  28528. ** Refer to comments in the unixClose() function and the lengthy comment
  28529. ** describing "Posix Advisory Locking" at the start of this file for
  28530. ** further details. Also, ticket #4018.
  28531. **
  28532. ** If a suitable file descriptor is found, then it is returned. If no
  28533. ** such file descriptor is located, -1 is returned.
  28534. */
  28535. static UnixUnusedFd *findReusableFd(const char *zPath, int flags){
  28536. UnixUnusedFd *pUnused = 0;
  28537. /* Do not search for an unused file descriptor on vxworks. Not because
  28538. ** vxworks would not benefit from the change (it might, we're not sure),
  28539. ** but because no way to test it is currently available. It is better
  28540. ** not to risk breaking vxworks support for the sake of such an obscure
  28541. ** feature. */
  28542. #if !OS_VXWORKS
  28543. struct stat sStat; /* Results of stat() call */
  28544. /* A stat() call may fail for various reasons. If this happens, it is
  28545. ** almost certain that an open() call on the same path will also fail.
  28546. ** For this reason, if an error occurs in the stat() call here, it is
  28547. ** ignored and -1 is returned. The caller will try to open a new file
  28548. ** descriptor on the same path, fail, and return an error to SQLite.
  28549. **
  28550. ** Even if a subsequent open() call does succeed, the consequences of
  28551. ** not searching for a reusable file descriptor are not dire. */
  28552. if( 0==osStat(zPath, &sStat) ){
  28553. unixInodeInfo *pInode;
  28554. unixEnterMutex();
  28555. pInode = inodeList;
  28556. while( pInode && (pInode->fileId.dev!=sStat.st_dev
  28557. || pInode->fileId.ino!=sStat.st_ino) ){
  28558. pInode = pInode->pNext;
  28559. }
  28560. if( pInode ){
  28561. UnixUnusedFd **pp;
  28562. for(pp=&pInode->pUnused; *pp && (*pp)->flags!=flags; pp=&((*pp)->pNext));
  28563. pUnused = *pp;
  28564. if( pUnused ){
  28565. *pp = pUnused->pNext;
  28566. }
  28567. }
  28568. unixLeaveMutex();
  28569. }
  28570. #endif /* if !OS_VXWORKS */
  28571. return pUnused;
  28572. }
  28573. /*
  28574. ** This function is called by unixOpen() to determine the unix permissions
  28575. ** to create new files with. If no error occurs, then SQLITE_OK is returned
  28576. ** and a value suitable for passing as the third argument to open(2) is
  28577. ** written to *pMode. If an IO error occurs, an SQLite error code is
  28578. ** returned and the value of *pMode is not modified.
  28579. **
  28580. ** In most cases, this routine sets *pMode to 0, which will become
  28581. ** an indication to robust_open() to create the file using
  28582. ** SQLITE_DEFAULT_FILE_PERMISSIONS adjusted by the umask.
  28583. ** But if the file being opened is a WAL or regular journal file, then
  28584. ** this function queries the file-system for the permissions on the
  28585. ** corresponding database file and sets *pMode to this value. Whenever
  28586. ** possible, WAL and journal files are created using the same permissions
  28587. ** as the associated database file.
  28588. **
  28589. ** If the SQLITE_ENABLE_8_3_NAMES option is enabled, then the
  28590. ** original filename is unavailable. But 8_3_NAMES is only used for
  28591. ** FAT filesystems and permissions do not matter there, so just use
  28592. ** the default permissions.
  28593. */
  28594. static int findCreateFileMode(
  28595. const char *zPath, /* Path of file (possibly) being created */
  28596. int flags, /* Flags passed as 4th argument to xOpen() */
  28597. mode_t *pMode, /* OUT: Permissions to open file with */
  28598. uid_t *pUid, /* OUT: uid to set on the file */
  28599. gid_t *pGid /* OUT: gid to set on the file */
  28600. ){
  28601. int rc = SQLITE_OK; /* Return Code */
  28602. *pMode = 0;
  28603. *pUid = 0;
  28604. *pGid = 0;
  28605. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  28606. char zDb[MAX_PATHNAME+1]; /* Database file path */
  28607. int nDb; /* Number of valid bytes in zDb */
  28608. struct stat sStat; /* Output of stat() on database file */
  28609. /* zPath is a path to a WAL or journal file. The following block derives
  28610. ** the path to the associated database file from zPath. This block handles
  28611. ** the following naming conventions:
  28612. **
  28613. ** "<path to db>-journal"
  28614. ** "<path to db>-wal"
  28615. ** "<path to db>-journalNN"
  28616. ** "<path to db>-walNN"
  28617. **
  28618. ** where NN is a decimal number. The NN naming schemes are
  28619. ** used by the test_multiplex.c module.
  28620. */
  28621. nDb = sqlite3Strlen30(zPath) - 1;
  28622. #ifdef SQLITE_ENABLE_8_3_NAMES
  28623. while( nDb>0 && sqlite3Isalnum(zPath[nDb]) ) nDb--;
  28624. if( nDb==0 || zPath[nDb]!='-' ) return SQLITE_OK;
  28625. #else
  28626. while( zPath[nDb]!='-' ){
  28627. assert( nDb>0 );
  28628. assert( zPath[nDb]!='\n' );
  28629. nDb--;
  28630. }
  28631. #endif
  28632. memcpy(zDb, zPath, nDb);
  28633. zDb[nDb] = '\0';
  28634. if( 0==osStat(zDb, &sStat) ){
  28635. *pMode = sStat.st_mode & 0777;
  28636. *pUid = sStat.st_uid;
  28637. *pGid = sStat.st_gid;
  28638. }else{
  28639. rc = SQLITE_IOERR_FSTAT;
  28640. }
  28641. }else if( flags & SQLITE_OPEN_DELETEONCLOSE ){
  28642. *pMode = 0600;
  28643. }
  28644. return rc;
  28645. }
  28646. /*
  28647. ** Open the file zPath.
  28648. **
  28649. ** Previously, the SQLite OS layer used three functions in place of this
  28650. ** one:
  28651. **
  28652. ** sqlite3OsOpenReadWrite();
  28653. ** sqlite3OsOpenReadOnly();
  28654. ** sqlite3OsOpenExclusive();
  28655. **
  28656. ** These calls correspond to the following combinations of flags:
  28657. **
  28658. ** ReadWrite() -> (READWRITE | CREATE)
  28659. ** ReadOnly() -> (READONLY)
  28660. ** OpenExclusive() -> (READWRITE | CREATE | EXCLUSIVE)
  28661. **
  28662. ** The old OpenExclusive() accepted a boolean argument - "delFlag". If
  28663. ** true, the file was configured to be automatically deleted when the
  28664. ** file handle closed. To achieve the same effect using this new
  28665. ** interface, add the DELETEONCLOSE flag to those specified above for
  28666. ** OpenExclusive().
  28667. */
  28668. static int unixOpen(
  28669. sqlite3_vfs *pVfs, /* The VFS for which this is the xOpen method */
  28670. const char *zPath, /* Pathname of file to be opened */
  28671. sqlite3_file *pFile, /* The file descriptor to be filled in */
  28672. int flags, /* Input flags to control the opening */
  28673. int *pOutFlags /* Output flags returned to SQLite core */
  28674. ){
  28675. unixFile *p = (unixFile *)pFile;
  28676. int fd = -1; /* File descriptor returned by open() */
  28677. int openFlags = 0; /* Flags to pass to open() */
  28678. int eType = flags&0xFFFFFF00; /* Type of file to open */
  28679. int noLock; /* True to omit locking primitives */
  28680. int rc = SQLITE_OK; /* Function Return Code */
  28681. int ctrlFlags = 0; /* UNIXFILE_* flags */
  28682. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  28683. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  28684. int isCreate = (flags & SQLITE_OPEN_CREATE);
  28685. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  28686. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  28687. #if SQLITE_ENABLE_LOCKING_STYLE
  28688. int isAutoProxy = (flags & SQLITE_OPEN_AUTOPROXY);
  28689. #endif
  28690. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  28691. struct statfs fsInfo;
  28692. #endif
  28693. /* If creating a master or main-file journal, this function will open
  28694. ** a file-descriptor on the directory too. The first time unixSync()
  28695. ** is called the directory file descriptor will be fsync()ed and close()d.
  28696. */
  28697. int syncDir = (isCreate && (
  28698. eType==SQLITE_OPEN_MASTER_JOURNAL
  28699. || eType==SQLITE_OPEN_MAIN_JOURNAL
  28700. || eType==SQLITE_OPEN_WAL
  28701. ));
  28702. /* If argument zPath is a NULL pointer, this function is required to open
  28703. ** a temporary file. Use this buffer to store the file name in.
  28704. */
  28705. char zTmpname[MAX_PATHNAME+2];
  28706. const char *zName = zPath;
  28707. /* Check the following statements are true:
  28708. **
  28709. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  28710. ** (b) if CREATE is set, then READWRITE must also be set, and
  28711. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  28712. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  28713. */
  28714. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  28715. assert(isCreate==0 || isReadWrite);
  28716. assert(isExclusive==0 || isCreate);
  28717. assert(isDelete==0 || isCreate);
  28718. /* The main DB, main journal, WAL file and master journal are never
  28719. ** automatically deleted. Nor are they ever temporary files. */
  28720. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  28721. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  28722. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  28723. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  28724. /* Assert that the upper layer has set one of the "file-type" flags. */
  28725. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  28726. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  28727. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  28728. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  28729. );
  28730. /* Detect a pid change and reset the PRNG. There is a race condition
  28731. ** here such that two or more threads all trying to open databases at
  28732. ** the same instant might all reset the PRNG. But multiple resets
  28733. ** are harmless.
  28734. */
  28735. if( randomnessPid!=getpid() ){
  28736. randomnessPid = getpid();
  28737. sqlite3_randomness(0,0);
  28738. }
  28739. memset(p, 0, sizeof(unixFile));
  28740. if( eType==SQLITE_OPEN_MAIN_DB ){
  28741. UnixUnusedFd *pUnused;
  28742. pUnused = findReusableFd(zName, flags);
  28743. if( pUnused ){
  28744. fd = pUnused->fd;
  28745. }else{
  28746. pUnused = sqlite3_malloc(sizeof(*pUnused));
  28747. if( !pUnused ){
  28748. return SQLITE_NOMEM;
  28749. }
  28750. }
  28751. p->pUnused = pUnused;
  28752. /* Database filenames are double-zero terminated if they are not
  28753. ** URIs with parameters. Hence, they can always be passed into
  28754. ** sqlite3_uri_parameter(). */
  28755. assert( (flags & SQLITE_OPEN_URI) || zName[strlen(zName)+1]==0 );
  28756. }else if( !zName ){
  28757. /* If zName is NULL, the upper layer is requesting a temp file. */
  28758. assert(isDelete && !syncDir);
  28759. rc = unixGetTempname(MAX_PATHNAME+2, zTmpname);
  28760. if( rc!=SQLITE_OK ){
  28761. return rc;
  28762. }
  28763. zName = zTmpname;
  28764. /* Generated temporary filenames are always double-zero terminated
  28765. ** for use by sqlite3_uri_parameter(). */
  28766. assert( zName[strlen(zName)+1]==0 );
  28767. }
  28768. /* Determine the value of the flags parameter passed to POSIX function
  28769. ** open(). These must be calculated even if open() is not called, as
  28770. ** they may be stored as part of the file handle and used by the
  28771. ** 'conch file' locking functions later on. */
  28772. if( isReadonly ) openFlags |= O_RDONLY;
  28773. if( isReadWrite ) openFlags |= O_RDWR;
  28774. if( isCreate ) openFlags |= O_CREAT;
  28775. if( isExclusive ) openFlags |= (O_EXCL|O_NOFOLLOW);
  28776. openFlags |= (O_LARGEFILE|O_BINARY);
  28777. if( fd<0 ){
  28778. mode_t openMode; /* Permissions to create file with */
  28779. uid_t uid; /* Userid for the file */
  28780. gid_t gid; /* Groupid for the file */
  28781. rc = findCreateFileMode(zName, flags, &openMode, &uid, &gid);
  28782. if( rc!=SQLITE_OK ){
  28783. assert( !p->pUnused );
  28784. assert( eType==SQLITE_OPEN_WAL || eType==SQLITE_OPEN_MAIN_JOURNAL );
  28785. return rc;
  28786. }
  28787. fd = robust_open(zName, openFlags, openMode);
  28788. OSTRACE(("OPENX %-3d %s 0%o\n", fd, zName, openFlags));
  28789. if( fd<0 && errno!=EISDIR && isReadWrite && !isExclusive ){
  28790. /* Failed to open the file for read/write access. Try read-only. */
  28791. flags &= ~(SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE);
  28792. openFlags &= ~(O_RDWR|O_CREAT);
  28793. flags |= SQLITE_OPEN_READONLY;
  28794. openFlags |= O_RDONLY;
  28795. isReadonly = 1;
  28796. fd = robust_open(zName, openFlags, openMode);
  28797. }
  28798. if( fd<0 ){
  28799. rc = unixLogError(SQLITE_CANTOPEN_BKPT, "open", zName);
  28800. goto open_finished;
  28801. }
  28802. /* If this process is running as root and if creating a new rollback
  28803. ** journal or WAL file, set the ownership of the journal or WAL to be
  28804. ** the same as the original database.
  28805. */
  28806. if( flags & (SQLITE_OPEN_WAL|SQLITE_OPEN_MAIN_JOURNAL) ){
  28807. osFchown(fd, uid, gid);
  28808. }
  28809. }
  28810. assert( fd>=0 );
  28811. if( pOutFlags ){
  28812. *pOutFlags = flags;
  28813. }
  28814. if( p->pUnused ){
  28815. p->pUnused->fd = fd;
  28816. p->pUnused->flags = flags;
  28817. }
  28818. if( isDelete ){
  28819. #if OS_VXWORKS
  28820. zPath = zName;
  28821. #elif defined(SQLITE_UNLINK_AFTER_CLOSE)
  28822. zPath = sqlite3_mprintf("%s", zName);
  28823. if( zPath==0 ){
  28824. robust_close(p, fd, __LINE__);
  28825. return SQLITE_NOMEM;
  28826. }
  28827. #else
  28828. osUnlink(zName);
  28829. #endif
  28830. }
  28831. #if SQLITE_ENABLE_LOCKING_STYLE
  28832. else{
  28833. p->openFlags = openFlags;
  28834. }
  28835. #endif
  28836. noLock = eType!=SQLITE_OPEN_MAIN_DB;
  28837. #if defined(__APPLE__) || SQLITE_ENABLE_LOCKING_STYLE
  28838. if( fstatfs(fd, &fsInfo) == -1 ){
  28839. ((unixFile*)pFile)->lastErrno = errno;
  28840. robust_close(p, fd, __LINE__);
  28841. return SQLITE_IOERR_ACCESS;
  28842. }
  28843. if (0 == strncmp("msdos", fsInfo.f_fstypename, 5)) {
  28844. ((unixFile*)pFile)->fsFlags |= SQLITE_FSFLAGS_IS_MSDOS;
  28845. }
  28846. #endif
  28847. /* Set up appropriate ctrlFlags */
  28848. if( isDelete ) ctrlFlags |= UNIXFILE_DELETE;
  28849. if( isReadonly ) ctrlFlags |= UNIXFILE_RDONLY;
  28850. if( noLock ) ctrlFlags |= UNIXFILE_NOLOCK;
  28851. if( syncDir ) ctrlFlags |= UNIXFILE_DIRSYNC;
  28852. if( flags & SQLITE_OPEN_URI ) ctrlFlags |= UNIXFILE_URI;
  28853. #if SQLITE_ENABLE_LOCKING_STYLE
  28854. #if SQLITE_PREFER_PROXY_LOCKING
  28855. isAutoProxy = 1;
  28856. #endif
  28857. if( isAutoProxy && (zPath!=NULL) && (!noLock) && pVfs->xOpen ){
  28858. char *envforce = getenv("SQLITE_FORCE_PROXY_LOCKING");
  28859. int useProxy = 0;
  28860. /* SQLITE_FORCE_PROXY_LOCKING==1 means force always use proxy, 0 means
  28861. ** never use proxy, NULL means use proxy for non-local files only. */
  28862. if( envforce!=NULL ){
  28863. useProxy = atoi(envforce)>0;
  28864. }else{
  28865. if( statfs(zPath, &fsInfo) == -1 ){
  28866. /* In theory, the close(fd) call is sub-optimal. If the file opened
  28867. ** with fd is a database file, and there are other connections open
  28868. ** on that file that are currently holding advisory locks on it,
  28869. ** then the call to close() will cancel those locks. In practice,
  28870. ** we're assuming that statfs() doesn't fail very often. At least
  28871. ** not while other file descriptors opened by the same process on
  28872. ** the same file are working. */
  28873. p->lastErrno = errno;
  28874. robust_close(p, fd, __LINE__);
  28875. rc = SQLITE_IOERR_ACCESS;
  28876. goto open_finished;
  28877. }
  28878. useProxy = !(fsInfo.f_flags&MNT_LOCAL);
  28879. }
  28880. if( useProxy ){
  28881. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  28882. if( rc==SQLITE_OK ){
  28883. rc = proxyTransformUnixFile((unixFile*)pFile, ":auto:");
  28884. if( rc!=SQLITE_OK ){
  28885. /* Use unixClose to clean up the resources added in fillInUnixFile
  28886. ** and clear all the structure's references. Specifically,
  28887. ** pFile->pMethods will be NULL so sqlite3OsClose will be a no-op
  28888. */
  28889. unixClose(pFile);
  28890. return rc;
  28891. }
  28892. }
  28893. goto open_finished;
  28894. }
  28895. }
  28896. #endif
  28897. rc = fillInUnixFile(pVfs, fd, pFile, zPath, ctrlFlags);
  28898. open_finished:
  28899. if( rc!=SQLITE_OK ){
  28900. sqlite3_free(p->pUnused);
  28901. }
  28902. return rc;
  28903. }
  28904. /*
  28905. ** Delete the file at zPath. If the dirSync argument is true, fsync()
  28906. ** the directory after deleting the file.
  28907. */
  28908. static int unixDelete(
  28909. sqlite3_vfs *NotUsed, /* VFS containing this as the xDelete method */
  28910. const char *zPath, /* Name of file to be deleted */
  28911. int dirSync /* If true, fsync() directory after deleting file */
  28912. ){
  28913. int rc = SQLITE_OK;
  28914. UNUSED_PARAMETER(NotUsed);
  28915. SimulateIOError(return SQLITE_IOERR_DELETE);
  28916. if( osUnlink(zPath)==(-1) ){
  28917. if( errno==ENOENT
  28918. #if OS_VXWORKS
  28919. || osAccess(zPath,0)!=0
  28920. #endif
  28921. ){
  28922. rc = SQLITE_IOERR_DELETE_NOENT;
  28923. }else{
  28924. rc = unixLogError(SQLITE_IOERR_DELETE, "unlink", zPath);
  28925. }
  28926. return rc;
  28927. }
  28928. #ifndef SQLITE_DISABLE_DIRSYNC
  28929. if( (dirSync & 1)!=0 ){
  28930. int fd;
  28931. rc = osOpenDirectory(zPath, &fd);
  28932. if( rc==SQLITE_OK ){
  28933. #if OS_VXWORKS
  28934. if( fsync(fd)==-1 )
  28935. #else
  28936. if( fsync(fd) )
  28937. #endif
  28938. {
  28939. rc = unixLogError(SQLITE_IOERR_DIR_FSYNC, "fsync", zPath);
  28940. }
  28941. robust_close(0, fd, __LINE__);
  28942. }else if( rc==SQLITE_CANTOPEN ){
  28943. rc = SQLITE_OK;
  28944. }
  28945. }
  28946. #endif
  28947. return rc;
  28948. }
  28949. /*
  28950. ** Test the existence of or access permissions of file zPath. The
  28951. ** test performed depends on the value of flags:
  28952. **
  28953. ** SQLITE_ACCESS_EXISTS: Return 1 if the file exists
  28954. ** SQLITE_ACCESS_READWRITE: Return 1 if the file is read and writable.
  28955. ** SQLITE_ACCESS_READONLY: Return 1 if the file is readable.
  28956. **
  28957. ** Otherwise return 0.
  28958. */
  28959. static int unixAccess(
  28960. sqlite3_vfs *NotUsed, /* The VFS containing this xAccess method */
  28961. const char *zPath, /* Path of the file to examine */
  28962. int flags, /* What do we want to learn about the zPath file? */
  28963. int *pResOut /* Write result boolean here */
  28964. ){
  28965. int amode = 0;
  28966. UNUSED_PARAMETER(NotUsed);
  28967. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  28968. switch( flags ){
  28969. case SQLITE_ACCESS_EXISTS:
  28970. amode = F_OK;
  28971. break;
  28972. case SQLITE_ACCESS_READWRITE:
  28973. amode = W_OK|R_OK;
  28974. break;
  28975. case SQLITE_ACCESS_READ:
  28976. amode = R_OK;
  28977. break;
  28978. default:
  28979. assert(!"Invalid flags argument");
  28980. }
  28981. *pResOut = (osAccess(zPath, amode)==0);
  28982. if( flags==SQLITE_ACCESS_EXISTS && *pResOut ){
  28983. struct stat buf;
  28984. if( 0==osStat(zPath, &buf) && buf.st_size==0 ){
  28985. *pResOut = 0;
  28986. }
  28987. }
  28988. return SQLITE_OK;
  28989. }
  28990. /*
  28991. ** Turn a relative pathname into a full pathname. The relative path
  28992. ** is stored as a nul-terminated string in the buffer pointed to by
  28993. ** zPath.
  28994. **
  28995. ** zOut points to a buffer of at least sqlite3_vfs.mxPathname bytes
  28996. ** (in this case, MAX_PATHNAME bytes). The full-path is written to
  28997. ** this buffer before returning.
  28998. */
  28999. static int unixFullPathname(
  29000. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  29001. const char *zPath, /* Possibly relative input path */
  29002. int nOut, /* Size of output buffer in bytes */
  29003. char *zOut /* Output buffer */
  29004. ){
  29005. /* It's odd to simulate an io-error here, but really this is just
  29006. ** using the io-error infrastructure to test that SQLite handles this
  29007. ** function failing. This function could fail if, for example, the
  29008. ** current working directory has been unlinked.
  29009. */
  29010. SimulateIOError( return SQLITE_ERROR );
  29011. assert( pVfs->mxPathname==MAX_PATHNAME );
  29012. UNUSED_PARAMETER(pVfs);
  29013. zOut[nOut-1] = '\0';
  29014. if( zPath[0]=='/' ){
  29015. sqlite3_snprintf(nOut, zOut, "%s", zPath);
  29016. }else{
  29017. int nCwd;
  29018. if( osGetcwd(zOut, nOut-1)==0 ){
  29019. return unixLogError(SQLITE_CANTOPEN_BKPT, "getcwd", zPath);
  29020. }
  29021. nCwd = (int)strlen(zOut);
  29022. sqlite3_snprintf(nOut-nCwd, &zOut[nCwd], "/%s", zPath);
  29023. }
  29024. return SQLITE_OK;
  29025. }
  29026. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  29027. /*
  29028. ** Interfaces for opening a shared library, finding entry points
  29029. ** within the shared library, and closing the shared library.
  29030. */
  29031. #include <dlfcn.h>
  29032. static void *unixDlOpen(sqlite3_vfs *NotUsed, const char *zFilename){
  29033. UNUSED_PARAMETER(NotUsed);
  29034. return dlopen(zFilename, RTLD_NOW | RTLD_GLOBAL);
  29035. }
  29036. /*
  29037. ** SQLite calls this function immediately after a call to unixDlSym() or
  29038. ** unixDlOpen() fails (returns a null pointer). If a more detailed error
  29039. ** message is available, it is written to zBufOut. If no error message
  29040. ** is available, zBufOut is left unmodified and SQLite uses a default
  29041. ** error message.
  29042. */
  29043. static void unixDlError(sqlite3_vfs *NotUsed, int nBuf, char *zBufOut){
  29044. const char *zErr;
  29045. UNUSED_PARAMETER(NotUsed);
  29046. unixEnterMutex();
  29047. zErr = dlerror();
  29048. if( zErr ){
  29049. sqlite3_snprintf(nBuf, zBufOut, "%s", zErr);
  29050. }
  29051. unixLeaveMutex();
  29052. }
  29053. static void (*unixDlSym(sqlite3_vfs *NotUsed, void *p, const char*zSym))(void){
  29054. /*
  29055. ** GCC with -pedantic-errors says that C90 does not allow a void* to be
  29056. ** cast into a pointer to a function. And yet the library dlsym() routine
  29057. ** returns a void* which is really a pointer to a function. So how do we
  29058. ** use dlsym() with -pedantic-errors?
  29059. **
  29060. ** Variable x below is defined to be a pointer to a function taking
  29061. ** parameters void* and const char* and returning a pointer to a function.
  29062. ** We initialize x by assigning it a pointer to the dlsym() function.
  29063. ** (That assignment requires a cast.) Then we call the function that
  29064. ** x points to.
  29065. **
  29066. ** This work-around is unlikely to work correctly on any system where
  29067. ** you really cannot cast a function pointer into void*. But then, on the
  29068. ** other hand, dlsym() will not work on such a system either, so we have
  29069. ** not really lost anything.
  29070. */
  29071. void (*(*x)(void*,const char*))(void);
  29072. UNUSED_PARAMETER(NotUsed);
  29073. x = (void(*(*)(void*,const char*))(void))dlsym;
  29074. return (*x)(p, zSym);
  29075. }
  29076. static void unixDlClose(sqlite3_vfs *NotUsed, void *pHandle){
  29077. UNUSED_PARAMETER(NotUsed);
  29078. dlclose(pHandle);
  29079. }
  29080. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  29081. #define unixDlOpen 0
  29082. #define unixDlError 0
  29083. #define unixDlSym 0
  29084. #define unixDlClose 0
  29085. #endif
  29086. /*
  29087. ** Write nBuf bytes of random data to the supplied buffer zBuf.
  29088. */
  29089. static int unixRandomness(sqlite3_vfs *NotUsed, int nBuf, char *zBuf){
  29090. UNUSED_PARAMETER(NotUsed);
  29091. assert((size_t)nBuf>=(sizeof(time_t)+sizeof(int)));
  29092. /* We have to initialize zBuf to prevent valgrind from reporting
  29093. ** errors. The reports issued by valgrind are incorrect - we would
  29094. ** prefer that the randomness be increased by making use of the
  29095. ** uninitialized space in zBuf - but valgrind errors tend to worry
  29096. ** some users. Rather than argue, it seems easier just to initialize
  29097. ** the whole array and silence valgrind, even if that means less randomness
  29098. ** in the random seed.
  29099. **
  29100. ** When testing, initializing zBuf[] to zero is all we do. That means
  29101. ** that we always use the same random number sequence. This makes the
  29102. ** tests repeatable.
  29103. */
  29104. memset(zBuf, 0, nBuf);
  29105. randomnessPid = getpid();
  29106. #if !defined(SQLITE_TEST)
  29107. {
  29108. int fd, got;
  29109. fd = robust_open("/dev/urandom", O_RDONLY, 0);
  29110. if( fd<0 ){
  29111. time_t t;
  29112. time(&t);
  29113. memcpy(zBuf, &t, sizeof(t));
  29114. memcpy(&zBuf[sizeof(t)], &randomnessPid, sizeof(randomnessPid));
  29115. assert( sizeof(t)+sizeof(randomnessPid)<=(size_t)nBuf );
  29116. nBuf = sizeof(t) + sizeof(randomnessPid);
  29117. }else{
  29118. do{ got = osRead(fd, zBuf, nBuf); }while( got<0 && errno==EINTR );
  29119. robust_close(0, fd, __LINE__);
  29120. }
  29121. }
  29122. #endif
  29123. return nBuf;
  29124. }
  29125. /*
  29126. ** Sleep for a little while. Return the amount of time slept.
  29127. ** The argument is the number of microseconds we want to sleep.
  29128. ** The return value is the number of microseconds of sleep actually
  29129. ** requested from the underlying operating system, a number which
  29130. ** might be greater than or equal to the argument, but not less
  29131. ** than the argument.
  29132. */
  29133. static int unixSleep(sqlite3_vfs *NotUsed, int microseconds){
  29134. #if OS_VXWORKS
  29135. struct timespec sp;
  29136. sp.tv_sec = microseconds / 1000000;
  29137. sp.tv_nsec = (microseconds % 1000000) * 1000;
  29138. nanosleep(&sp, NULL);
  29139. UNUSED_PARAMETER(NotUsed);
  29140. return microseconds;
  29141. #elif defined(HAVE_USLEEP) && HAVE_USLEEP
  29142. usleep(microseconds);
  29143. UNUSED_PARAMETER(NotUsed);
  29144. return microseconds;
  29145. #else
  29146. int seconds = (microseconds+999999)/1000000;
  29147. sleep(seconds);
  29148. UNUSED_PARAMETER(NotUsed);
  29149. return seconds*1000000;
  29150. #endif
  29151. }
  29152. /*
  29153. ** The following variable, if set to a non-zero value, is interpreted as
  29154. ** the number of seconds since 1970 and is used to set the result of
  29155. ** sqlite3OsCurrentTime() during testing.
  29156. */
  29157. #ifdef SQLITE_TEST
  29158. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  29159. #endif
  29160. /*
  29161. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  29162. ** the current time and date as a Julian Day number times 86_400_000. In
  29163. ** other words, write into *piNow the number of milliseconds since the Julian
  29164. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  29165. ** proleptic Gregorian calendar.
  29166. **
  29167. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  29168. ** cannot be found.
  29169. */
  29170. static int unixCurrentTimeInt64(sqlite3_vfs *NotUsed, sqlite3_int64 *piNow){
  29171. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  29172. int rc = SQLITE_OK;
  29173. #if defined(NO_GETTOD)
  29174. time_t t;
  29175. time(&t);
  29176. *piNow = ((sqlite3_int64)t)*1000 + unixEpoch;
  29177. #elif OS_VXWORKS
  29178. struct timespec sNow;
  29179. clock_gettime(CLOCK_REALTIME, &sNow);
  29180. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_nsec/1000000;
  29181. #else
  29182. struct timeval sNow;
  29183. if( gettimeofday(&sNow, 0)==0 ){
  29184. *piNow = unixEpoch + 1000*(sqlite3_int64)sNow.tv_sec + sNow.tv_usec/1000;
  29185. }else{
  29186. rc = SQLITE_ERROR;
  29187. }
  29188. #endif
  29189. #ifdef SQLITE_TEST
  29190. if( sqlite3_current_time ){
  29191. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  29192. }
  29193. #endif
  29194. UNUSED_PARAMETER(NotUsed);
  29195. return rc;
  29196. }
  29197. /*
  29198. ** Find the current time (in Universal Coordinated Time). Write the
  29199. ** current time and date as a Julian Day number into *prNow and
  29200. ** return 0. Return 1 if the time and date cannot be found.
  29201. */
  29202. static int unixCurrentTime(sqlite3_vfs *NotUsed, double *prNow){
  29203. sqlite3_int64 i = 0;
  29204. int rc;
  29205. UNUSED_PARAMETER(NotUsed);
  29206. rc = unixCurrentTimeInt64(0, &i);
  29207. *prNow = i/86400000.0;
  29208. return rc;
  29209. }
  29210. /*
  29211. ** We added the xGetLastError() method with the intention of providing
  29212. ** better low-level error messages when operating-system problems come up
  29213. ** during SQLite operation. But so far, none of that has been implemented
  29214. ** in the core. So this routine is never called. For now, it is merely
  29215. ** a place-holder.
  29216. */
  29217. static int unixGetLastError(sqlite3_vfs *NotUsed, int NotUsed2, char *NotUsed3){
  29218. UNUSED_PARAMETER(NotUsed);
  29219. UNUSED_PARAMETER(NotUsed2);
  29220. UNUSED_PARAMETER(NotUsed3);
  29221. return 0;
  29222. }
  29223. /*
  29224. ************************ End of sqlite3_vfs methods ***************************
  29225. ******************************************************************************/
  29226. /******************************************************************************
  29227. ************************** Begin Proxy Locking ********************************
  29228. **
  29229. ** Proxy locking is a "uber-locking-method" in this sense: It uses the
  29230. ** other locking methods on secondary lock files. Proxy locking is a
  29231. ** meta-layer over top of the primitive locking implemented above. For
  29232. ** this reason, the division that implements of proxy locking is deferred
  29233. ** until late in the file (here) after all of the other I/O methods have
  29234. ** been defined - so that the primitive locking methods are available
  29235. ** as services to help with the implementation of proxy locking.
  29236. **
  29237. ****
  29238. **
  29239. ** The default locking schemes in SQLite use byte-range locks on the
  29240. ** database file to coordinate safe, concurrent access by multiple readers
  29241. ** and writers [http://sqlite.org/lockingv3.html]. The five file locking
  29242. ** states (UNLOCKED, PENDING, SHARED, RESERVED, EXCLUSIVE) are implemented
  29243. ** as POSIX read & write locks over fixed set of locations (via fsctl),
  29244. ** on AFP and SMB only exclusive byte-range locks are available via fsctl
  29245. ** with _IOWR('z', 23, struct ByteRangeLockPB2) to track the same 5 states.
  29246. ** To simulate a F_RDLCK on the shared range, on AFP a randomly selected
  29247. ** address in the shared range is taken for a SHARED lock, the entire
  29248. ** shared range is taken for an EXCLUSIVE lock):
  29249. **
  29250. ** PENDING_BYTE 0x40000000
  29251. ** RESERVED_BYTE 0x40000001
  29252. ** SHARED_RANGE 0x40000002 -> 0x40000200
  29253. **
  29254. ** This works well on the local file system, but shows a nearly 100x
  29255. ** slowdown in read performance on AFP because the AFP client disables
  29256. ** the read cache when byte-range locks are present. Enabling the read
  29257. ** cache exposes a cache coherency problem that is present on all OS X
  29258. ** supported network file systems. NFS and AFP both observe the
  29259. ** close-to-open semantics for ensuring cache coherency
  29260. ** [http://nfs.sourceforge.net/#faq_a8], which does not effectively
  29261. ** address the requirements for concurrent database access by multiple
  29262. ** readers and writers
  29263. ** [http://www.nabble.com/SQLite-on-NFS-cache-coherency-td15655701.html].
  29264. **
  29265. ** To address the performance and cache coherency issues, proxy file locking
  29266. ** changes the way database access is controlled by limiting access to a
  29267. ** single host at a time and moving file locks off of the database file
  29268. ** and onto a proxy file on the local file system.
  29269. **
  29270. **
  29271. ** Using proxy locks
  29272. ** -----------------
  29273. **
  29274. ** C APIs
  29275. **
  29276. ** sqlite3_file_control(db, dbname, SQLITE_SET_LOCKPROXYFILE,
  29277. ** <proxy_path> | ":auto:");
  29278. ** sqlite3_file_control(db, dbname, SQLITE_GET_LOCKPROXYFILE, &<proxy_path>);
  29279. **
  29280. **
  29281. ** SQL pragmas
  29282. **
  29283. ** PRAGMA [database.]lock_proxy_file=<proxy_path> | :auto:
  29284. ** PRAGMA [database.]lock_proxy_file
  29285. **
  29286. ** Specifying ":auto:" means that if there is a conch file with a matching
  29287. ** host ID in it, the proxy path in the conch file will be used, otherwise
  29288. ** a proxy path based on the user's temp dir
  29289. ** (via confstr(_CS_DARWIN_USER_TEMP_DIR,...)) will be used and the
  29290. ** actual proxy file name is generated from the name and path of the
  29291. ** database file. For example:
  29292. **
  29293. ** For database path "/Users/me/foo.db"
  29294. ** The lock path will be "<tmpdir>/sqliteplocks/_Users_me_foo.db:auto:")
  29295. **
  29296. ** Once a lock proxy is configured for a database connection, it can not
  29297. ** be removed, however it may be switched to a different proxy path via
  29298. ** the above APIs (assuming the conch file is not being held by another
  29299. ** connection or process).
  29300. **
  29301. **
  29302. ** How proxy locking works
  29303. ** -----------------------
  29304. **
  29305. ** Proxy file locking relies primarily on two new supporting files:
  29306. **
  29307. ** * conch file to limit access to the database file to a single host
  29308. ** at a time
  29309. **
  29310. ** * proxy file to act as a proxy for the advisory locks normally
  29311. ** taken on the database
  29312. **
  29313. ** The conch file - to use a proxy file, sqlite must first "hold the conch"
  29314. ** by taking an sqlite-style shared lock on the conch file, reading the
  29315. ** contents and comparing the host's unique host ID (see below) and lock
  29316. ** proxy path against the values stored in the conch. The conch file is
  29317. ** stored in the same directory as the database file and the file name
  29318. ** is patterned after the database file name as ".<databasename>-conch".
  29319. ** If the conch file does not exist, or its contents do not match the
  29320. ** host ID and/or proxy path, then the lock is escalated to an exclusive
  29321. ** lock and the conch file contents is updated with the host ID and proxy
  29322. ** path and the lock is downgraded to a shared lock again. If the conch
  29323. ** is held by another process (with a shared lock), the exclusive lock
  29324. ** will fail and SQLITE_BUSY is returned.
  29325. **
  29326. ** The proxy file - a single-byte file used for all advisory file locks
  29327. ** normally taken on the database file. This allows for safe sharing
  29328. ** of the database file for multiple readers and writers on the same
  29329. ** host (the conch ensures that they all use the same local lock file).
  29330. **
  29331. ** Requesting the lock proxy does not immediately take the conch, it is
  29332. ** only taken when the first request to lock database file is made.
  29333. ** This matches the semantics of the traditional locking behavior, where
  29334. ** opening a connection to a database file does not take a lock on it.
  29335. ** The shared lock and an open file descriptor are maintained until
  29336. ** the connection to the database is closed.
  29337. **
  29338. ** The proxy file and the lock file are never deleted so they only need
  29339. ** to be created the first time they are used.
  29340. **
  29341. ** Configuration options
  29342. ** ---------------------
  29343. **
  29344. ** SQLITE_PREFER_PROXY_LOCKING
  29345. **
  29346. ** Database files accessed on non-local file systems are
  29347. ** automatically configured for proxy locking, lock files are
  29348. ** named automatically using the same logic as
  29349. ** PRAGMA lock_proxy_file=":auto:"
  29350. **
  29351. ** SQLITE_PROXY_DEBUG
  29352. **
  29353. ** Enables the logging of error messages during host id file
  29354. ** retrieval and creation
  29355. **
  29356. ** LOCKPROXYDIR
  29357. **
  29358. ** Overrides the default directory used for lock proxy files that
  29359. ** are named automatically via the ":auto:" setting
  29360. **
  29361. ** SQLITE_DEFAULT_PROXYDIR_PERMISSIONS
  29362. **
  29363. ** Permissions to use when creating a directory for storing the
  29364. ** lock proxy files, only used when LOCKPROXYDIR is not set.
  29365. **
  29366. **
  29367. ** As mentioned above, when compiled with SQLITE_PREFER_PROXY_LOCKING,
  29368. ** setting the environment variable SQLITE_FORCE_PROXY_LOCKING to 1 will
  29369. ** force proxy locking to be used for every database file opened, and 0
  29370. ** will force automatic proxy locking to be disabled for all database
  29371. ** files (explicitly calling the SQLITE_SET_LOCKPROXYFILE pragma or
  29372. ** sqlite_file_control API is not affected by SQLITE_FORCE_PROXY_LOCKING).
  29373. */
  29374. /*
  29375. ** Proxy locking is only available on MacOSX
  29376. */
  29377. #if defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE
  29378. /*
  29379. ** The proxyLockingContext has the path and file structures for the remote
  29380. ** and local proxy files in it
  29381. */
  29382. typedef struct proxyLockingContext proxyLockingContext;
  29383. struct proxyLockingContext {
  29384. unixFile *conchFile; /* Open conch file */
  29385. char *conchFilePath; /* Name of the conch file */
  29386. unixFile *lockProxy; /* Open proxy lock file */
  29387. char *lockProxyPath; /* Name of the proxy lock file */
  29388. char *dbPath; /* Name of the open file */
  29389. int conchHeld; /* 1 if the conch is held, -1 if lockless */
  29390. void *oldLockingContext; /* Original lockingcontext to restore on close */
  29391. sqlite3_io_methods const *pOldMethod; /* Original I/O methods for close */
  29392. };
  29393. /*
  29394. ** The proxy lock file path for the database at dbPath is written into lPath,
  29395. ** which must point to valid, writable memory large enough for a maxLen length
  29396. ** file path.
  29397. */
  29398. static int proxyGetLockPath(const char *dbPath, char *lPath, size_t maxLen){
  29399. int len;
  29400. int dbLen;
  29401. int i;
  29402. #ifdef LOCKPROXYDIR
  29403. len = strlcpy(lPath, LOCKPROXYDIR, maxLen);
  29404. #else
  29405. # ifdef _CS_DARWIN_USER_TEMP_DIR
  29406. {
  29407. if( !confstr(_CS_DARWIN_USER_TEMP_DIR, lPath, maxLen) ){
  29408. OSTRACE(("GETLOCKPATH failed %s errno=%d pid=%d\n",
  29409. lPath, errno, getpid()));
  29410. return SQLITE_IOERR_LOCK;
  29411. }
  29412. len = strlcat(lPath, "sqliteplocks", maxLen);
  29413. }
  29414. # else
  29415. len = strlcpy(lPath, "/tmp/", maxLen);
  29416. # endif
  29417. #endif
  29418. if( lPath[len-1]!='/' ){
  29419. len = strlcat(lPath, "/", maxLen);
  29420. }
  29421. /* transform the db path to a unique cache name */
  29422. dbLen = (int)strlen(dbPath);
  29423. for( i=0; i<dbLen && (i+len+7)<(int)maxLen; i++){
  29424. char c = dbPath[i];
  29425. lPath[i+len] = (c=='/')?'_':c;
  29426. }
  29427. lPath[i+len]='\0';
  29428. strlcat(lPath, ":auto:", maxLen);
  29429. OSTRACE(("GETLOCKPATH proxy lock path=%s pid=%d\n", lPath, getpid()));
  29430. return SQLITE_OK;
  29431. }
  29432. /*
  29433. ** Creates the lock file and any missing directories in lockPath
  29434. */
  29435. static int proxyCreateLockPath(const char *lockPath){
  29436. int i, len;
  29437. char buf[MAXPATHLEN];
  29438. int start = 0;
  29439. assert(lockPath!=NULL);
  29440. /* try to create all the intermediate directories */
  29441. len = (int)strlen(lockPath);
  29442. buf[0] = lockPath[0];
  29443. for( i=1; i<len; i++ ){
  29444. if( lockPath[i] == '/' && (i - start > 0) ){
  29445. /* only mkdir if leaf dir != "." or "/" or ".." */
  29446. if( i-start>2 || (i-start==1 && buf[start] != '.' && buf[start] != '/')
  29447. || (i-start==2 && buf[start] != '.' && buf[start+1] != '.') ){
  29448. buf[i]='\0';
  29449. if( osMkdir(buf, SQLITE_DEFAULT_PROXYDIR_PERMISSIONS) ){
  29450. int err=errno;
  29451. if( err!=EEXIST ) {
  29452. OSTRACE(("CREATELOCKPATH FAILED creating %s, "
  29453. "'%s' proxy lock path=%s pid=%d\n",
  29454. buf, strerror(err), lockPath, getpid()));
  29455. return err;
  29456. }
  29457. }
  29458. }
  29459. start=i+1;
  29460. }
  29461. buf[i] = lockPath[i];
  29462. }
  29463. OSTRACE(("CREATELOCKPATH proxy lock path=%s pid=%d\n", lockPath, getpid()));
  29464. return 0;
  29465. }
  29466. /*
  29467. ** Create a new VFS file descriptor (stored in memory obtained from
  29468. ** sqlite3_malloc) and open the file named "path" in the file descriptor.
  29469. **
  29470. ** The caller is responsible not only for closing the file descriptor
  29471. ** but also for freeing the memory associated with the file descriptor.
  29472. */
  29473. static int proxyCreateUnixFile(
  29474. const char *path, /* path for the new unixFile */
  29475. unixFile **ppFile, /* unixFile created and returned by ref */
  29476. int islockfile /* if non zero missing dirs will be created */
  29477. ) {
  29478. int fd = -1;
  29479. unixFile *pNew;
  29480. int rc = SQLITE_OK;
  29481. int openFlags = O_RDWR | O_CREAT;
  29482. sqlite3_vfs dummyVfs;
  29483. int terrno = 0;
  29484. UnixUnusedFd *pUnused = NULL;
  29485. /* 1. first try to open/create the file
  29486. ** 2. if that fails, and this is a lock file (not-conch), try creating
  29487. ** the parent directories and then try again.
  29488. ** 3. if that fails, try to open the file read-only
  29489. ** otherwise return BUSY (if lock file) or CANTOPEN for the conch file
  29490. */
  29491. pUnused = findReusableFd(path, openFlags);
  29492. if( pUnused ){
  29493. fd = pUnused->fd;
  29494. }else{
  29495. pUnused = sqlite3_malloc(sizeof(*pUnused));
  29496. if( !pUnused ){
  29497. return SQLITE_NOMEM;
  29498. }
  29499. }
  29500. if( fd<0 ){
  29501. fd = robust_open(path, openFlags, 0);
  29502. terrno = errno;
  29503. if( fd<0 && errno==ENOENT && islockfile ){
  29504. if( proxyCreateLockPath(path) == SQLITE_OK ){
  29505. fd = robust_open(path, openFlags, 0);
  29506. }
  29507. }
  29508. }
  29509. if( fd<0 ){
  29510. openFlags = O_RDONLY;
  29511. fd = robust_open(path, openFlags, 0);
  29512. terrno = errno;
  29513. }
  29514. if( fd<0 ){
  29515. if( islockfile ){
  29516. return SQLITE_BUSY;
  29517. }
  29518. switch (terrno) {
  29519. case EACCES:
  29520. return SQLITE_PERM;
  29521. case EIO:
  29522. return SQLITE_IOERR_LOCK; /* even though it is the conch */
  29523. default:
  29524. return SQLITE_CANTOPEN_BKPT;
  29525. }
  29526. }
  29527. pNew = (unixFile *)sqlite3_malloc(sizeof(*pNew));
  29528. if( pNew==NULL ){
  29529. rc = SQLITE_NOMEM;
  29530. goto end_create_proxy;
  29531. }
  29532. memset(pNew, 0, sizeof(unixFile));
  29533. pNew->openFlags = openFlags;
  29534. memset(&dummyVfs, 0, sizeof(dummyVfs));
  29535. dummyVfs.pAppData = (void*)&autolockIoFinder;
  29536. dummyVfs.zName = "dummy";
  29537. pUnused->fd = fd;
  29538. pUnused->flags = openFlags;
  29539. pNew->pUnused = pUnused;
  29540. rc = fillInUnixFile(&dummyVfs, fd, (sqlite3_file*)pNew, path, 0);
  29541. if( rc==SQLITE_OK ){
  29542. *ppFile = pNew;
  29543. return SQLITE_OK;
  29544. }
  29545. end_create_proxy:
  29546. robust_close(pNew, fd, __LINE__);
  29547. sqlite3_free(pNew);
  29548. sqlite3_free(pUnused);
  29549. return rc;
  29550. }
  29551. #ifdef SQLITE_TEST
  29552. /* simulate multiple hosts by creating unique hostid file paths */
  29553. SQLITE_API int sqlite3_hostid_num = 0;
  29554. #endif
  29555. #define PROXY_HOSTIDLEN 16 /* conch file host id length */
  29556. /* Not always defined in the headers as it ought to be */
  29557. extern int gethostuuid(uuid_t id, const struct timespec *wait);
  29558. /* get the host ID via gethostuuid(), pHostID must point to PROXY_HOSTIDLEN
  29559. ** bytes of writable memory.
  29560. */
  29561. static int proxyGetHostID(unsigned char *pHostID, int *pError){
  29562. assert(PROXY_HOSTIDLEN == sizeof(uuid_t));
  29563. memset(pHostID, 0, PROXY_HOSTIDLEN);
  29564. #if defined(__MAX_OS_X_VERSION_MIN_REQUIRED)\
  29565. && __MAC_OS_X_VERSION_MIN_REQUIRED<1050
  29566. {
  29567. static const struct timespec timeout = {1, 0}; /* 1 sec timeout */
  29568. if( gethostuuid(pHostID, &timeout) ){
  29569. int err = errno;
  29570. if( pError ){
  29571. *pError = err;
  29572. }
  29573. return SQLITE_IOERR;
  29574. }
  29575. }
  29576. #else
  29577. UNUSED_PARAMETER(pError);
  29578. #endif
  29579. #ifdef SQLITE_TEST
  29580. /* simulate multiple hosts by creating unique hostid file paths */
  29581. if( sqlite3_hostid_num != 0){
  29582. pHostID[0] = (char)(pHostID[0] + (char)(sqlite3_hostid_num & 0xFF));
  29583. }
  29584. #endif
  29585. return SQLITE_OK;
  29586. }
  29587. /* The conch file contains the header, host id and lock file path
  29588. */
  29589. #define PROXY_CONCHVERSION 2 /* 1-byte header, 16-byte host id, path */
  29590. #define PROXY_HEADERLEN 1 /* conch file header length */
  29591. #define PROXY_PATHINDEX (PROXY_HEADERLEN+PROXY_HOSTIDLEN)
  29592. #define PROXY_MAXCONCHLEN (PROXY_HEADERLEN+PROXY_HOSTIDLEN+MAXPATHLEN)
  29593. /*
  29594. ** Takes an open conch file, copies the contents to a new path and then moves
  29595. ** it back. The newly created file's file descriptor is assigned to the
  29596. ** conch file structure and finally the original conch file descriptor is
  29597. ** closed. Returns zero if successful.
  29598. */
  29599. static int proxyBreakConchLock(unixFile *pFile, uuid_t myHostID){
  29600. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29601. unixFile *conchFile = pCtx->conchFile;
  29602. char tPath[MAXPATHLEN];
  29603. char buf[PROXY_MAXCONCHLEN];
  29604. char *cPath = pCtx->conchFilePath;
  29605. size_t readLen = 0;
  29606. size_t pathLen = 0;
  29607. char errmsg[64] = "";
  29608. int fd = -1;
  29609. int rc = -1;
  29610. UNUSED_PARAMETER(myHostID);
  29611. /* create a new path by replace the trailing '-conch' with '-break' */
  29612. pathLen = strlcpy(tPath, cPath, MAXPATHLEN);
  29613. if( pathLen>MAXPATHLEN || pathLen<6 ||
  29614. (strlcpy(&tPath[pathLen-5], "break", 6) != 5) ){
  29615. sqlite3_snprintf(sizeof(errmsg),errmsg,"path error (len %d)",(int)pathLen);
  29616. goto end_breaklock;
  29617. }
  29618. /* read the conch content */
  29619. readLen = osPread(conchFile->h, buf, PROXY_MAXCONCHLEN, 0);
  29620. if( readLen<PROXY_PATHINDEX ){
  29621. sqlite3_snprintf(sizeof(errmsg),errmsg,"read error (len %d)",(int)readLen);
  29622. goto end_breaklock;
  29623. }
  29624. /* write it out to the temporary break file */
  29625. fd = robust_open(tPath, (O_RDWR|O_CREAT|O_EXCL), 0);
  29626. if( fd<0 ){
  29627. sqlite3_snprintf(sizeof(errmsg), errmsg, "create failed (%d)", errno);
  29628. goto end_breaklock;
  29629. }
  29630. if( osPwrite(fd, buf, readLen, 0) != (ssize_t)readLen ){
  29631. sqlite3_snprintf(sizeof(errmsg), errmsg, "write failed (%d)", errno);
  29632. goto end_breaklock;
  29633. }
  29634. if( rename(tPath, cPath) ){
  29635. sqlite3_snprintf(sizeof(errmsg), errmsg, "rename failed (%d)", errno);
  29636. goto end_breaklock;
  29637. }
  29638. rc = 0;
  29639. fprintf(stderr, "broke stale lock on %s\n", cPath);
  29640. robust_close(pFile, conchFile->h, __LINE__);
  29641. conchFile->h = fd;
  29642. conchFile->openFlags = O_RDWR | O_CREAT;
  29643. end_breaklock:
  29644. if( rc ){
  29645. if( fd>=0 ){
  29646. osUnlink(tPath);
  29647. robust_close(pFile, fd, __LINE__);
  29648. }
  29649. fprintf(stderr, "failed to break stale lock on %s, %s\n", cPath, errmsg);
  29650. }
  29651. return rc;
  29652. }
  29653. /* Take the requested lock on the conch file and break a stale lock if the
  29654. ** host id matches.
  29655. */
  29656. static int proxyConchLock(unixFile *pFile, uuid_t myHostID, int lockType){
  29657. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29658. unixFile *conchFile = pCtx->conchFile;
  29659. int rc = SQLITE_OK;
  29660. int nTries = 0;
  29661. struct timespec conchModTime;
  29662. memset(&conchModTime, 0, sizeof(conchModTime));
  29663. do {
  29664. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  29665. nTries ++;
  29666. if( rc==SQLITE_BUSY ){
  29667. /* If the lock failed (busy):
  29668. * 1st try: get the mod time of the conch, wait 0.5s and try again.
  29669. * 2nd try: fail if the mod time changed or host id is different, wait
  29670. * 10 sec and try again
  29671. * 3rd try: break the lock unless the mod time has changed.
  29672. */
  29673. struct stat buf;
  29674. if( osFstat(conchFile->h, &buf) ){
  29675. pFile->lastErrno = errno;
  29676. return SQLITE_IOERR_LOCK;
  29677. }
  29678. if( nTries==1 ){
  29679. conchModTime = buf.st_mtimespec;
  29680. usleep(500000); /* wait 0.5 sec and try the lock again*/
  29681. continue;
  29682. }
  29683. assert( nTries>1 );
  29684. if( conchModTime.tv_sec != buf.st_mtimespec.tv_sec ||
  29685. conchModTime.tv_nsec != buf.st_mtimespec.tv_nsec ){
  29686. return SQLITE_BUSY;
  29687. }
  29688. if( nTries==2 ){
  29689. char tBuf[PROXY_MAXCONCHLEN];
  29690. int len = osPread(conchFile->h, tBuf, PROXY_MAXCONCHLEN, 0);
  29691. if( len<0 ){
  29692. pFile->lastErrno = errno;
  29693. return SQLITE_IOERR_LOCK;
  29694. }
  29695. if( len>PROXY_PATHINDEX && tBuf[0]==(char)PROXY_CONCHVERSION){
  29696. /* don't break the lock if the host id doesn't match */
  29697. if( 0!=memcmp(&tBuf[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN) ){
  29698. return SQLITE_BUSY;
  29699. }
  29700. }else{
  29701. /* don't break the lock on short read or a version mismatch */
  29702. return SQLITE_BUSY;
  29703. }
  29704. usleep(10000000); /* wait 10 sec and try the lock again */
  29705. continue;
  29706. }
  29707. assert( nTries==3 );
  29708. if( 0==proxyBreakConchLock(pFile, myHostID) ){
  29709. rc = SQLITE_OK;
  29710. if( lockType==EXCLUSIVE_LOCK ){
  29711. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, SHARED_LOCK);
  29712. }
  29713. if( !rc ){
  29714. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, lockType);
  29715. }
  29716. }
  29717. }
  29718. } while( rc==SQLITE_BUSY && nTries<3 );
  29719. return rc;
  29720. }
  29721. /* Takes the conch by taking a shared lock and read the contents conch, if
  29722. ** lockPath is non-NULL, the host ID and lock file path must match. A NULL
  29723. ** lockPath means that the lockPath in the conch file will be used if the
  29724. ** host IDs match, or a new lock path will be generated automatically
  29725. ** and written to the conch file.
  29726. */
  29727. static int proxyTakeConch(unixFile *pFile){
  29728. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  29729. if( pCtx->conchHeld!=0 ){
  29730. return SQLITE_OK;
  29731. }else{
  29732. unixFile *conchFile = pCtx->conchFile;
  29733. uuid_t myHostID;
  29734. int pError = 0;
  29735. char readBuf[PROXY_MAXCONCHLEN];
  29736. char lockPath[MAXPATHLEN];
  29737. char *tempLockPath = NULL;
  29738. int rc = SQLITE_OK;
  29739. int createConch = 0;
  29740. int hostIdMatch = 0;
  29741. int readLen = 0;
  29742. int tryOldLockPath = 0;
  29743. int forceNewLockPath = 0;
  29744. OSTRACE(("TAKECONCH %d for %s pid=%d\n", conchFile->h,
  29745. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"), getpid()));
  29746. rc = proxyGetHostID(myHostID, &pError);
  29747. if( (rc&0xff)==SQLITE_IOERR ){
  29748. pFile->lastErrno = pError;
  29749. goto end_takeconch;
  29750. }
  29751. rc = proxyConchLock(pFile, myHostID, SHARED_LOCK);
  29752. if( rc!=SQLITE_OK ){
  29753. goto end_takeconch;
  29754. }
  29755. /* read the existing conch file */
  29756. readLen = seekAndRead((unixFile*)conchFile, 0, readBuf, PROXY_MAXCONCHLEN);
  29757. if( readLen<0 ){
  29758. /* I/O error: lastErrno set by seekAndRead */
  29759. pFile->lastErrno = conchFile->lastErrno;
  29760. rc = SQLITE_IOERR_READ;
  29761. goto end_takeconch;
  29762. }else if( readLen<=(PROXY_HEADERLEN+PROXY_HOSTIDLEN) ||
  29763. readBuf[0]!=(char)PROXY_CONCHVERSION ){
  29764. /* a short read or version format mismatch means we need to create a new
  29765. ** conch file.
  29766. */
  29767. createConch = 1;
  29768. }
  29769. /* if the host id matches and the lock path already exists in the conch
  29770. ** we'll try to use the path there, if we can't open that path, we'll
  29771. ** retry with a new auto-generated path
  29772. */
  29773. do { /* in case we need to try again for an :auto: named lock file */
  29774. if( !createConch && !forceNewLockPath ){
  29775. hostIdMatch = !memcmp(&readBuf[PROXY_HEADERLEN], myHostID,
  29776. PROXY_HOSTIDLEN);
  29777. /* if the conch has data compare the contents */
  29778. if( !pCtx->lockProxyPath ){
  29779. /* for auto-named local lock file, just check the host ID and we'll
  29780. ** use the local lock file path that's already in there
  29781. */
  29782. if( hostIdMatch ){
  29783. size_t pathLen = (readLen - PROXY_PATHINDEX);
  29784. if( pathLen>=MAXPATHLEN ){
  29785. pathLen=MAXPATHLEN-1;
  29786. }
  29787. memcpy(lockPath, &readBuf[PROXY_PATHINDEX], pathLen);
  29788. lockPath[pathLen] = 0;
  29789. tempLockPath = lockPath;
  29790. tryOldLockPath = 1;
  29791. /* create a copy of the lock path if the conch is taken */
  29792. goto end_takeconch;
  29793. }
  29794. }else if( hostIdMatch
  29795. && !strncmp(pCtx->lockProxyPath, &readBuf[PROXY_PATHINDEX],
  29796. readLen-PROXY_PATHINDEX)
  29797. ){
  29798. /* conch host and lock path match */
  29799. goto end_takeconch;
  29800. }
  29801. }
  29802. /* if the conch isn't writable and doesn't match, we can't take it */
  29803. if( (conchFile->openFlags&O_RDWR) == 0 ){
  29804. rc = SQLITE_BUSY;
  29805. goto end_takeconch;
  29806. }
  29807. /* either the conch didn't match or we need to create a new one */
  29808. if( !pCtx->lockProxyPath ){
  29809. proxyGetLockPath(pCtx->dbPath, lockPath, MAXPATHLEN);
  29810. tempLockPath = lockPath;
  29811. /* create a copy of the lock path _only_ if the conch is taken */
  29812. }
  29813. /* update conch with host and path (this will fail if other process
  29814. ** has a shared lock already), if the host id matches, use the big
  29815. ** stick.
  29816. */
  29817. futimes(conchFile->h, NULL);
  29818. if( hostIdMatch && !createConch ){
  29819. if( conchFile->pInode && conchFile->pInode->nShared>1 ){
  29820. /* We are trying for an exclusive lock but another thread in this
  29821. ** same process is still holding a shared lock. */
  29822. rc = SQLITE_BUSY;
  29823. } else {
  29824. rc = proxyConchLock(pFile, myHostID, EXCLUSIVE_LOCK);
  29825. }
  29826. }else{
  29827. rc = conchFile->pMethod->xLock((sqlite3_file*)conchFile, EXCLUSIVE_LOCK);
  29828. }
  29829. if( rc==SQLITE_OK ){
  29830. char writeBuffer[PROXY_MAXCONCHLEN];
  29831. int writeSize = 0;
  29832. writeBuffer[0] = (char)PROXY_CONCHVERSION;
  29833. memcpy(&writeBuffer[PROXY_HEADERLEN], myHostID, PROXY_HOSTIDLEN);
  29834. if( pCtx->lockProxyPath!=NULL ){
  29835. strlcpy(&writeBuffer[PROXY_PATHINDEX], pCtx->lockProxyPath, MAXPATHLEN);
  29836. }else{
  29837. strlcpy(&writeBuffer[PROXY_PATHINDEX], tempLockPath, MAXPATHLEN);
  29838. }
  29839. writeSize = PROXY_PATHINDEX + strlen(&writeBuffer[PROXY_PATHINDEX]);
  29840. robust_ftruncate(conchFile->h, writeSize);
  29841. rc = unixWrite((sqlite3_file *)conchFile, writeBuffer, writeSize, 0);
  29842. fsync(conchFile->h);
  29843. /* If we created a new conch file (not just updated the contents of a
  29844. ** valid conch file), try to match the permissions of the database
  29845. */
  29846. if( rc==SQLITE_OK && createConch ){
  29847. struct stat buf;
  29848. int err = osFstat(pFile->h, &buf);
  29849. if( err==0 ){
  29850. mode_t cmode = buf.st_mode&(S_IRUSR|S_IWUSR | S_IRGRP|S_IWGRP |
  29851. S_IROTH|S_IWOTH);
  29852. /* try to match the database file R/W permissions, ignore failure */
  29853. #ifndef SQLITE_PROXY_DEBUG
  29854. osFchmod(conchFile->h, cmode);
  29855. #else
  29856. do{
  29857. rc = osFchmod(conchFile->h, cmode);
  29858. }while( rc==(-1) && errno==EINTR );
  29859. if( rc!=0 ){
  29860. int code = errno;
  29861. fprintf(stderr, "fchmod %o FAILED with %d %s\n",
  29862. cmode, code, strerror(code));
  29863. } else {
  29864. fprintf(stderr, "fchmod %o SUCCEDED\n",cmode);
  29865. }
  29866. }else{
  29867. int code = errno;
  29868. fprintf(stderr, "STAT FAILED[%d] with %d %s\n",
  29869. err, code, strerror(code));
  29870. #endif
  29871. }
  29872. }
  29873. }
  29874. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, SHARED_LOCK);
  29875. end_takeconch:
  29876. OSTRACE(("TRANSPROXY: CLOSE %d\n", pFile->h));
  29877. if( rc==SQLITE_OK && pFile->openFlags ){
  29878. int fd;
  29879. if( pFile->h>=0 ){
  29880. robust_close(pFile, pFile->h, __LINE__);
  29881. }
  29882. pFile->h = -1;
  29883. fd = robust_open(pCtx->dbPath, pFile->openFlags, 0);
  29884. OSTRACE(("TRANSPROXY: OPEN %d\n", fd));
  29885. if( fd>=0 ){
  29886. pFile->h = fd;
  29887. }else{
  29888. rc=SQLITE_CANTOPEN_BKPT; /* SQLITE_BUSY? proxyTakeConch called
  29889. during locking */
  29890. }
  29891. }
  29892. if( rc==SQLITE_OK && !pCtx->lockProxy ){
  29893. char *path = tempLockPath ? tempLockPath : pCtx->lockProxyPath;
  29894. rc = proxyCreateUnixFile(path, &pCtx->lockProxy, 1);
  29895. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM && tryOldLockPath ){
  29896. /* we couldn't create the proxy lock file with the old lock file path
  29897. ** so try again via auto-naming
  29898. */
  29899. forceNewLockPath = 1;
  29900. tryOldLockPath = 0;
  29901. continue; /* go back to the do {} while start point, try again */
  29902. }
  29903. }
  29904. if( rc==SQLITE_OK ){
  29905. /* Need to make a copy of path if we extracted the value
  29906. ** from the conch file or the path was allocated on the stack
  29907. */
  29908. if( tempLockPath ){
  29909. pCtx->lockProxyPath = sqlite3DbStrDup(0, tempLockPath);
  29910. if( !pCtx->lockProxyPath ){
  29911. rc = SQLITE_NOMEM;
  29912. }
  29913. }
  29914. }
  29915. if( rc==SQLITE_OK ){
  29916. pCtx->conchHeld = 1;
  29917. if( pCtx->lockProxy->pMethod == &afpIoMethods ){
  29918. afpLockingContext *afpCtx;
  29919. afpCtx = (afpLockingContext *)pCtx->lockProxy->lockingContext;
  29920. afpCtx->dbPath = pCtx->lockProxyPath;
  29921. }
  29922. } else {
  29923. conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  29924. }
  29925. OSTRACE(("TAKECONCH %d %s\n", conchFile->h,
  29926. rc==SQLITE_OK?"ok":"failed"));
  29927. return rc;
  29928. } while (1); /* in case we need to retry the :auto: lock file -
  29929. ** we should never get here except via the 'continue' call. */
  29930. }
  29931. }
  29932. /*
  29933. ** If pFile holds a lock on a conch file, then release that lock.
  29934. */
  29935. static int proxyReleaseConch(unixFile *pFile){
  29936. int rc = SQLITE_OK; /* Subroutine return code */
  29937. proxyLockingContext *pCtx; /* The locking context for the proxy lock */
  29938. unixFile *conchFile; /* Name of the conch file */
  29939. pCtx = (proxyLockingContext *)pFile->lockingContext;
  29940. conchFile = pCtx->conchFile;
  29941. OSTRACE(("RELEASECONCH %d for %s pid=%d\n", conchFile->h,
  29942. (pCtx->lockProxyPath ? pCtx->lockProxyPath : ":auto:"),
  29943. getpid()));
  29944. if( pCtx->conchHeld>0 ){
  29945. rc = conchFile->pMethod->xUnlock((sqlite3_file*)conchFile, NO_LOCK);
  29946. }
  29947. pCtx->conchHeld = 0;
  29948. OSTRACE(("RELEASECONCH %d %s\n", conchFile->h,
  29949. (rc==SQLITE_OK ? "ok" : "failed")));
  29950. return rc;
  29951. }
  29952. /*
  29953. ** Given the name of a database file, compute the name of its conch file.
  29954. ** Store the conch filename in memory obtained from sqlite3_malloc().
  29955. ** Make *pConchPath point to the new name. Return SQLITE_OK on success
  29956. ** or SQLITE_NOMEM if unable to obtain memory.
  29957. **
  29958. ** The caller is responsible for ensuring that the allocated memory
  29959. ** space is eventually freed.
  29960. **
  29961. ** *pConchPath is set to NULL if a memory allocation error occurs.
  29962. */
  29963. static int proxyCreateConchPathname(char *dbPath, char **pConchPath){
  29964. int i; /* Loop counter */
  29965. int len = (int)strlen(dbPath); /* Length of database filename - dbPath */
  29966. char *conchPath; /* buffer in which to construct conch name */
  29967. /* Allocate space for the conch filename and initialize the name to
  29968. ** the name of the original database file. */
  29969. *pConchPath = conchPath = (char *)sqlite3_malloc(len + 8);
  29970. if( conchPath==0 ){
  29971. return SQLITE_NOMEM;
  29972. }
  29973. memcpy(conchPath, dbPath, len+1);
  29974. /* now insert a "." before the last / character */
  29975. for( i=(len-1); i>=0; i-- ){
  29976. if( conchPath[i]=='/' ){
  29977. i++;
  29978. break;
  29979. }
  29980. }
  29981. conchPath[i]='.';
  29982. while ( i<len ){
  29983. conchPath[i+1]=dbPath[i];
  29984. i++;
  29985. }
  29986. /* append the "-conch" suffix to the file */
  29987. memcpy(&conchPath[i+1], "-conch", 7);
  29988. assert( (int)strlen(conchPath) == len+7 );
  29989. return SQLITE_OK;
  29990. }
  29991. /* Takes a fully configured proxy locking-style unix file and switches
  29992. ** the local lock file path
  29993. */
  29994. static int switchLockProxyPath(unixFile *pFile, const char *path) {
  29995. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  29996. char *oldPath = pCtx->lockProxyPath;
  29997. int rc = SQLITE_OK;
  29998. if( pFile->eFileLock!=NO_LOCK ){
  29999. return SQLITE_BUSY;
  30000. }
  30001. /* nothing to do if the path is NULL, :auto: or matches the existing path */
  30002. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ||
  30003. (oldPath && !strncmp(oldPath, path, MAXPATHLEN)) ){
  30004. return SQLITE_OK;
  30005. }else{
  30006. unixFile *lockProxy = pCtx->lockProxy;
  30007. pCtx->lockProxy=NULL;
  30008. pCtx->conchHeld = 0;
  30009. if( lockProxy!=NULL ){
  30010. rc=lockProxy->pMethod->xClose((sqlite3_file *)lockProxy);
  30011. if( rc ) return rc;
  30012. sqlite3_free(lockProxy);
  30013. }
  30014. sqlite3_free(oldPath);
  30015. pCtx->lockProxyPath = sqlite3DbStrDup(0, path);
  30016. }
  30017. return rc;
  30018. }
  30019. /*
  30020. ** pFile is a file that has been opened by a prior xOpen call. dbPath
  30021. ** is a string buffer at least MAXPATHLEN+1 characters in size.
  30022. **
  30023. ** This routine find the filename associated with pFile and writes it
  30024. ** int dbPath.
  30025. */
  30026. static int proxyGetDbPathForUnixFile(unixFile *pFile, char *dbPath){
  30027. #if defined(__APPLE__)
  30028. if( pFile->pMethod == &afpIoMethods ){
  30029. /* afp style keeps a reference to the db path in the filePath field
  30030. ** of the struct */
  30031. assert( (int)strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  30032. strlcpy(dbPath, ((afpLockingContext *)pFile->lockingContext)->dbPath, MAXPATHLEN);
  30033. } else
  30034. #endif
  30035. if( pFile->pMethod == &dotlockIoMethods ){
  30036. /* dot lock style uses the locking context to store the dot lock
  30037. ** file path */
  30038. int len = strlen((char *)pFile->lockingContext) - strlen(DOTLOCK_SUFFIX);
  30039. memcpy(dbPath, (char *)pFile->lockingContext, len + 1);
  30040. }else{
  30041. /* all other styles use the locking context to store the db file path */
  30042. assert( strlen((char*)pFile->lockingContext)<=MAXPATHLEN );
  30043. strlcpy(dbPath, (char *)pFile->lockingContext, MAXPATHLEN);
  30044. }
  30045. return SQLITE_OK;
  30046. }
  30047. /*
  30048. ** Takes an already filled in unix file and alters it so all file locking
  30049. ** will be performed on the local proxy lock file. The following fields
  30050. ** are preserved in the locking context so that they can be restored and
  30051. ** the unix structure properly cleaned up at close time:
  30052. ** ->lockingContext
  30053. ** ->pMethod
  30054. */
  30055. static int proxyTransformUnixFile(unixFile *pFile, const char *path) {
  30056. proxyLockingContext *pCtx;
  30057. char dbPath[MAXPATHLEN+1]; /* Name of the database file */
  30058. char *lockPath=NULL;
  30059. int rc = SQLITE_OK;
  30060. if( pFile->eFileLock!=NO_LOCK ){
  30061. return SQLITE_BUSY;
  30062. }
  30063. proxyGetDbPathForUnixFile(pFile, dbPath);
  30064. if( !path || path[0]=='\0' || !strcmp(path, ":auto:") ){
  30065. lockPath=NULL;
  30066. }else{
  30067. lockPath=(char *)path;
  30068. }
  30069. OSTRACE(("TRANSPROXY %d for %s pid=%d\n", pFile->h,
  30070. (lockPath ? lockPath : ":auto:"), getpid()));
  30071. pCtx = sqlite3_malloc( sizeof(*pCtx) );
  30072. if( pCtx==0 ){
  30073. return SQLITE_NOMEM;
  30074. }
  30075. memset(pCtx, 0, sizeof(*pCtx));
  30076. rc = proxyCreateConchPathname(dbPath, &pCtx->conchFilePath);
  30077. if( rc==SQLITE_OK ){
  30078. rc = proxyCreateUnixFile(pCtx->conchFilePath, &pCtx->conchFile, 0);
  30079. if( rc==SQLITE_CANTOPEN && ((pFile->openFlags&O_RDWR) == 0) ){
  30080. /* if (a) the open flags are not O_RDWR, (b) the conch isn't there, and
  30081. ** (c) the file system is read-only, then enable no-locking access.
  30082. ** Ugh, since O_RDONLY==0x0000 we test for !O_RDWR since unixOpen asserts
  30083. ** that openFlags will have only one of O_RDONLY or O_RDWR.
  30084. */
  30085. struct statfs fsInfo;
  30086. struct stat conchInfo;
  30087. int goLockless = 0;
  30088. if( osStat(pCtx->conchFilePath, &conchInfo) == -1 ) {
  30089. int err = errno;
  30090. if( (err==ENOENT) && (statfs(dbPath, &fsInfo) != -1) ){
  30091. goLockless = (fsInfo.f_flags&MNT_RDONLY) == MNT_RDONLY;
  30092. }
  30093. }
  30094. if( goLockless ){
  30095. pCtx->conchHeld = -1; /* read only FS/ lockless */
  30096. rc = SQLITE_OK;
  30097. }
  30098. }
  30099. }
  30100. if( rc==SQLITE_OK && lockPath ){
  30101. pCtx->lockProxyPath = sqlite3DbStrDup(0, lockPath);
  30102. }
  30103. if( rc==SQLITE_OK ){
  30104. pCtx->dbPath = sqlite3DbStrDup(0, dbPath);
  30105. if( pCtx->dbPath==NULL ){
  30106. rc = SQLITE_NOMEM;
  30107. }
  30108. }
  30109. if( rc==SQLITE_OK ){
  30110. /* all memory is allocated, proxys are created and assigned,
  30111. ** switch the locking context and pMethod then return.
  30112. */
  30113. pCtx->oldLockingContext = pFile->lockingContext;
  30114. pFile->lockingContext = pCtx;
  30115. pCtx->pOldMethod = pFile->pMethod;
  30116. pFile->pMethod = &proxyIoMethods;
  30117. }else{
  30118. if( pCtx->conchFile ){
  30119. pCtx->conchFile->pMethod->xClose((sqlite3_file *)pCtx->conchFile);
  30120. sqlite3_free(pCtx->conchFile);
  30121. }
  30122. sqlite3DbFree(0, pCtx->lockProxyPath);
  30123. sqlite3_free(pCtx->conchFilePath);
  30124. sqlite3_free(pCtx);
  30125. }
  30126. OSTRACE(("TRANSPROXY %d %s\n", pFile->h,
  30127. (rc==SQLITE_OK ? "ok" : "failed")));
  30128. return rc;
  30129. }
  30130. /*
  30131. ** This routine handles sqlite3_file_control() calls that are specific
  30132. ** to proxy locking.
  30133. */
  30134. static int proxyFileControl(sqlite3_file *id, int op, void *pArg){
  30135. switch( op ){
  30136. case SQLITE_GET_LOCKPROXYFILE: {
  30137. unixFile *pFile = (unixFile*)id;
  30138. if( pFile->pMethod == &proxyIoMethods ){
  30139. proxyLockingContext *pCtx = (proxyLockingContext*)pFile->lockingContext;
  30140. proxyTakeConch(pFile);
  30141. if( pCtx->lockProxyPath ){
  30142. *(const char **)pArg = pCtx->lockProxyPath;
  30143. }else{
  30144. *(const char **)pArg = ":auto: (not held)";
  30145. }
  30146. } else {
  30147. *(const char **)pArg = NULL;
  30148. }
  30149. return SQLITE_OK;
  30150. }
  30151. case SQLITE_SET_LOCKPROXYFILE: {
  30152. unixFile *pFile = (unixFile*)id;
  30153. int rc = SQLITE_OK;
  30154. int isProxyStyle = (pFile->pMethod == &proxyIoMethods);
  30155. if( pArg==NULL || (const char *)pArg==0 ){
  30156. if( isProxyStyle ){
  30157. /* turn off proxy locking - not supported */
  30158. rc = SQLITE_ERROR /*SQLITE_PROTOCOL? SQLITE_MISUSE?*/;
  30159. }else{
  30160. /* turn off proxy locking - already off - NOOP */
  30161. rc = SQLITE_OK;
  30162. }
  30163. }else{
  30164. const char *proxyPath = (const char *)pArg;
  30165. if( isProxyStyle ){
  30166. proxyLockingContext *pCtx =
  30167. (proxyLockingContext*)pFile->lockingContext;
  30168. if( !strcmp(pArg, ":auto:")
  30169. || (pCtx->lockProxyPath &&
  30170. !strncmp(pCtx->lockProxyPath, proxyPath, MAXPATHLEN))
  30171. ){
  30172. rc = SQLITE_OK;
  30173. }else{
  30174. rc = switchLockProxyPath(pFile, proxyPath);
  30175. }
  30176. }else{
  30177. /* turn on proxy file locking */
  30178. rc = proxyTransformUnixFile(pFile, proxyPath);
  30179. }
  30180. }
  30181. return rc;
  30182. }
  30183. default: {
  30184. assert( 0 ); /* The call assures that only valid opcodes are sent */
  30185. }
  30186. }
  30187. /*NOTREACHED*/
  30188. return SQLITE_ERROR;
  30189. }
  30190. /*
  30191. ** Within this division (the proxying locking implementation) the procedures
  30192. ** above this point are all utilities. The lock-related methods of the
  30193. ** proxy-locking sqlite3_io_method object follow.
  30194. */
  30195. /*
  30196. ** This routine checks if there is a RESERVED lock held on the specified
  30197. ** file by this or any other process. If such a lock is held, set *pResOut
  30198. ** to a non-zero value otherwise *pResOut is set to zero. The return value
  30199. ** is set to SQLITE_OK unless an I/O error occurs during lock checking.
  30200. */
  30201. static int proxyCheckReservedLock(sqlite3_file *id, int *pResOut) {
  30202. unixFile *pFile = (unixFile*)id;
  30203. int rc = proxyTakeConch(pFile);
  30204. if( rc==SQLITE_OK ){
  30205. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30206. if( pCtx->conchHeld>0 ){
  30207. unixFile *proxy = pCtx->lockProxy;
  30208. return proxy->pMethod->xCheckReservedLock((sqlite3_file*)proxy, pResOut);
  30209. }else{ /* conchHeld < 0 is lockless */
  30210. pResOut=0;
  30211. }
  30212. }
  30213. return rc;
  30214. }
  30215. /*
  30216. ** Lock the file with the lock specified by parameter eFileLock - one
  30217. ** of the following:
  30218. **
  30219. ** (1) SHARED_LOCK
  30220. ** (2) RESERVED_LOCK
  30221. ** (3) PENDING_LOCK
  30222. ** (4) EXCLUSIVE_LOCK
  30223. **
  30224. ** Sometimes when requesting one lock state, additional lock states
  30225. ** are inserted in between. The locking might fail on one of the later
  30226. ** transitions leaving the lock state different from what it started but
  30227. ** still short of its goal. The following chart shows the allowed
  30228. ** transitions and the inserted intermediate states:
  30229. **
  30230. ** UNLOCKED -> SHARED
  30231. ** SHARED -> RESERVED
  30232. ** SHARED -> (PENDING) -> EXCLUSIVE
  30233. ** RESERVED -> (PENDING) -> EXCLUSIVE
  30234. ** PENDING -> EXCLUSIVE
  30235. **
  30236. ** This routine will only increase a lock. Use the sqlite3OsUnlock()
  30237. ** routine to lower a locking level.
  30238. */
  30239. static int proxyLock(sqlite3_file *id, int eFileLock) {
  30240. unixFile *pFile = (unixFile*)id;
  30241. int rc = proxyTakeConch(pFile);
  30242. if( rc==SQLITE_OK ){
  30243. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30244. if( pCtx->conchHeld>0 ){
  30245. unixFile *proxy = pCtx->lockProxy;
  30246. rc = proxy->pMethod->xLock((sqlite3_file*)proxy, eFileLock);
  30247. pFile->eFileLock = proxy->eFileLock;
  30248. }else{
  30249. /* conchHeld < 0 is lockless */
  30250. }
  30251. }
  30252. return rc;
  30253. }
  30254. /*
  30255. ** Lower the locking level on file descriptor pFile to eFileLock. eFileLock
  30256. ** must be either NO_LOCK or SHARED_LOCK.
  30257. **
  30258. ** If the locking level of the file descriptor is already at or below
  30259. ** the requested locking level, this routine is a no-op.
  30260. */
  30261. static int proxyUnlock(sqlite3_file *id, int eFileLock) {
  30262. unixFile *pFile = (unixFile*)id;
  30263. int rc = proxyTakeConch(pFile);
  30264. if( rc==SQLITE_OK ){
  30265. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30266. if( pCtx->conchHeld>0 ){
  30267. unixFile *proxy = pCtx->lockProxy;
  30268. rc = proxy->pMethod->xUnlock((sqlite3_file*)proxy, eFileLock);
  30269. pFile->eFileLock = proxy->eFileLock;
  30270. }else{
  30271. /* conchHeld < 0 is lockless */
  30272. }
  30273. }
  30274. return rc;
  30275. }
  30276. /*
  30277. ** Close a file that uses proxy locks.
  30278. */
  30279. static int proxyClose(sqlite3_file *id) {
  30280. if( id ){
  30281. unixFile *pFile = (unixFile*)id;
  30282. proxyLockingContext *pCtx = (proxyLockingContext *)pFile->lockingContext;
  30283. unixFile *lockProxy = pCtx->lockProxy;
  30284. unixFile *conchFile = pCtx->conchFile;
  30285. int rc = SQLITE_OK;
  30286. if( lockProxy ){
  30287. rc = lockProxy->pMethod->xUnlock((sqlite3_file*)lockProxy, NO_LOCK);
  30288. if( rc ) return rc;
  30289. rc = lockProxy->pMethod->xClose((sqlite3_file*)lockProxy);
  30290. if( rc ) return rc;
  30291. sqlite3_free(lockProxy);
  30292. pCtx->lockProxy = 0;
  30293. }
  30294. if( conchFile ){
  30295. if( pCtx->conchHeld ){
  30296. rc = proxyReleaseConch(pFile);
  30297. if( rc ) return rc;
  30298. }
  30299. rc = conchFile->pMethod->xClose((sqlite3_file*)conchFile);
  30300. if( rc ) return rc;
  30301. sqlite3_free(conchFile);
  30302. }
  30303. sqlite3DbFree(0, pCtx->lockProxyPath);
  30304. sqlite3_free(pCtx->conchFilePath);
  30305. sqlite3DbFree(0, pCtx->dbPath);
  30306. /* restore the original locking context and pMethod then close it */
  30307. pFile->lockingContext = pCtx->oldLockingContext;
  30308. pFile->pMethod = pCtx->pOldMethod;
  30309. sqlite3_free(pCtx);
  30310. return pFile->pMethod->xClose(id);
  30311. }
  30312. return SQLITE_OK;
  30313. }
  30314. #endif /* defined(__APPLE__) && SQLITE_ENABLE_LOCKING_STYLE */
  30315. /*
  30316. ** The proxy locking style is intended for use with AFP filesystems.
  30317. ** And since AFP is only supported on MacOSX, the proxy locking is also
  30318. ** restricted to MacOSX.
  30319. **
  30320. **
  30321. ******************* End of the proxy lock implementation **********************
  30322. ******************************************************************************/
  30323. /*
  30324. ** Initialize the operating system interface.
  30325. **
  30326. ** This routine registers all VFS implementations for unix-like operating
  30327. ** systems. This routine, and the sqlite3_os_end() routine that follows,
  30328. ** should be the only routines in this file that are visible from other
  30329. ** files.
  30330. **
  30331. ** This routine is called once during SQLite initialization and by a
  30332. ** single thread. The memory allocation and mutex subsystems have not
  30333. ** necessarily been initialized when this routine is called, and so they
  30334. ** should not be used.
  30335. */
  30336. SQLITE_API int sqlite3_os_init(void){
  30337. /*
  30338. ** The following macro defines an initializer for an sqlite3_vfs object.
  30339. ** The name of the VFS is NAME. The pAppData is a pointer to a pointer
  30340. ** to the "finder" function. (pAppData is a pointer to a pointer because
  30341. ** silly C90 rules prohibit a void* from being cast to a function pointer
  30342. ** and so we have to go through the intermediate pointer to avoid problems
  30343. ** when compiling with -pedantic-errors on GCC.)
  30344. **
  30345. ** The FINDER parameter to this macro is the name of the pointer to the
  30346. ** finder-function. The finder-function returns a pointer to the
  30347. ** sqlite_io_methods object that implements the desired locking
  30348. ** behaviors. See the division above that contains the IOMETHODS
  30349. ** macro for addition information on finder-functions.
  30350. **
  30351. ** Most finders simply return a pointer to a fixed sqlite3_io_methods
  30352. ** object. But the "autolockIoFinder" available on MacOSX does a little
  30353. ** more than that; it looks at the filesystem type that hosts the
  30354. ** database file and tries to choose an locking method appropriate for
  30355. ** that filesystem time.
  30356. */
  30357. #define UNIXVFS(VFSNAME, FINDER) { \
  30358. 3, /* iVersion */ \
  30359. sizeof(unixFile), /* szOsFile */ \
  30360. MAX_PATHNAME, /* mxPathname */ \
  30361. 0, /* pNext */ \
  30362. VFSNAME, /* zName */ \
  30363. (void*)&FINDER, /* pAppData */ \
  30364. unixOpen, /* xOpen */ \
  30365. unixDelete, /* xDelete */ \
  30366. unixAccess, /* xAccess */ \
  30367. unixFullPathname, /* xFullPathname */ \
  30368. unixDlOpen, /* xDlOpen */ \
  30369. unixDlError, /* xDlError */ \
  30370. unixDlSym, /* xDlSym */ \
  30371. unixDlClose, /* xDlClose */ \
  30372. unixRandomness, /* xRandomness */ \
  30373. unixSleep, /* xSleep */ \
  30374. unixCurrentTime, /* xCurrentTime */ \
  30375. unixGetLastError, /* xGetLastError */ \
  30376. unixCurrentTimeInt64, /* xCurrentTimeInt64 */ \
  30377. unixSetSystemCall, /* xSetSystemCall */ \
  30378. unixGetSystemCall, /* xGetSystemCall */ \
  30379. unixNextSystemCall, /* xNextSystemCall */ \
  30380. }
  30381. /*
  30382. ** All default VFSes for unix are contained in the following array.
  30383. **
  30384. ** Note that the sqlite3_vfs.pNext field of the VFS object is modified
  30385. ** by the SQLite core when the VFS is registered. So the following
  30386. ** array cannot be const.
  30387. */
  30388. static sqlite3_vfs aVfs[] = {
  30389. #if SQLITE_ENABLE_LOCKING_STYLE && (OS_VXWORKS || defined(__APPLE__))
  30390. UNIXVFS("unix", autolockIoFinder ),
  30391. #else
  30392. UNIXVFS("unix", posixIoFinder ),
  30393. #endif
  30394. UNIXVFS("unix-none", nolockIoFinder ),
  30395. UNIXVFS("unix-dotfile", dotlockIoFinder ),
  30396. UNIXVFS("unix-excl", posixIoFinder ),
  30397. #if OS_VXWORKS
  30398. UNIXVFS("unix-namedsem", semIoFinder ),
  30399. #endif
  30400. #if SQLITE_ENABLE_LOCKING_STYLE
  30401. UNIXVFS("unix-posix", posixIoFinder ),
  30402. #if !OS_VXWORKS
  30403. UNIXVFS("unix-flock", flockIoFinder ),
  30404. #endif
  30405. #endif
  30406. #if SQLITE_ENABLE_LOCKING_STYLE && defined(__APPLE__)
  30407. UNIXVFS("unix-afp", afpIoFinder ),
  30408. UNIXVFS("unix-nfs", nfsIoFinder ),
  30409. UNIXVFS("unix-proxy", proxyIoFinder ),
  30410. #endif
  30411. };
  30412. unsigned int i; /* Loop counter */
  30413. /* Double-check that the aSyscall[] array has been constructed
  30414. ** correctly. See ticket [bb3a86e890c8e96ab] */
  30415. assert( ArraySize(aSyscall)==25 );
  30416. /* Register all VFSes defined in the aVfs[] array */
  30417. for(i=0; i<(sizeof(aVfs)/sizeof(sqlite3_vfs)); i++){
  30418. sqlite3_vfs_register(&aVfs[i], i==0);
  30419. }
  30420. return SQLITE_OK;
  30421. }
  30422. /*
  30423. ** Shutdown the operating system interface.
  30424. **
  30425. ** Some operating systems might need to do some cleanup in this routine,
  30426. ** to release dynamically allocated objects. But not on unix.
  30427. ** This routine is a no-op for unix.
  30428. */
  30429. SQLITE_API int sqlite3_os_end(void){
  30430. return SQLITE_OK;
  30431. }
  30432. #endif /* SQLITE_OS_UNIX */
  30433. /************** End of os_unix.c *********************************************/
  30434. /************** Begin file os_win.c ******************************************/
  30435. /*
  30436. ** 2004 May 22
  30437. **
  30438. ** The author disclaims copyright to this source code. In place of
  30439. ** a legal notice, here is a blessing:
  30440. **
  30441. ** May you do good and not evil.
  30442. ** May you find forgiveness for yourself and forgive others.
  30443. ** May you share freely, never taking more than you give.
  30444. **
  30445. ******************************************************************************
  30446. **
  30447. ** This file contains code that is specific to Windows.
  30448. */
  30449. #if SQLITE_OS_WIN /* This file is used for Windows only */
  30450. /*
  30451. ** Include code that is common to all os_*.c files
  30452. */
  30453. /************** Include os_common.h in the middle of os_win.c ****************/
  30454. /************** Begin file os_common.h ***************************************/
  30455. /*
  30456. ** 2004 May 22
  30457. **
  30458. ** The author disclaims copyright to this source code. In place of
  30459. ** a legal notice, here is a blessing:
  30460. **
  30461. ** May you do good and not evil.
  30462. ** May you find forgiveness for yourself and forgive others.
  30463. ** May you share freely, never taking more than you give.
  30464. **
  30465. ******************************************************************************
  30466. **
  30467. ** This file contains macros and a little bit of code that is common to
  30468. ** all of the platform-specific files (os_*.c) and is #included into those
  30469. ** files.
  30470. **
  30471. ** This file should be #included by the os_*.c files only. It is not a
  30472. ** general purpose header file.
  30473. */
  30474. #ifndef _OS_COMMON_H_
  30475. #define _OS_COMMON_H_
  30476. /*
  30477. ** At least two bugs have slipped in because we changed the MEMORY_DEBUG
  30478. ** macro to SQLITE_DEBUG and some older makefiles have not yet made the
  30479. ** switch. The following code should catch this problem at compile-time.
  30480. */
  30481. #ifdef MEMORY_DEBUG
  30482. # error "The MEMORY_DEBUG macro is obsolete. Use SQLITE_DEBUG instead."
  30483. #endif
  30484. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  30485. # ifndef SQLITE_DEBUG_OS_TRACE
  30486. # define SQLITE_DEBUG_OS_TRACE 0
  30487. # endif
  30488. int sqlite3OSTrace = SQLITE_DEBUG_OS_TRACE;
  30489. # define OSTRACE(X) if( sqlite3OSTrace ) sqlite3DebugPrintf X
  30490. #else
  30491. # define OSTRACE(X)
  30492. #endif
  30493. /*
  30494. ** Macros for performance tracing. Normally turned off. Only works
  30495. ** on i486 hardware.
  30496. */
  30497. #ifdef SQLITE_PERFORMANCE_TRACE
  30498. /*
  30499. ** hwtime.h contains inline assembler code for implementing
  30500. ** high-performance timing routines.
  30501. */
  30502. /************** Include hwtime.h in the middle of os_common.h ****************/
  30503. /************** Begin file hwtime.h ******************************************/
  30504. /*
  30505. ** 2008 May 27
  30506. **
  30507. ** The author disclaims copyright to this source code. In place of
  30508. ** a legal notice, here is a blessing:
  30509. **
  30510. ** May you do good and not evil.
  30511. ** May you find forgiveness for yourself and forgive others.
  30512. ** May you share freely, never taking more than you give.
  30513. **
  30514. ******************************************************************************
  30515. **
  30516. ** This file contains inline asm code for retrieving "high-performance"
  30517. ** counters for x86 class CPUs.
  30518. */
  30519. #ifndef _HWTIME_H_
  30520. #define _HWTIME_H_
  30521. /*
  30522. ** The following routine only works on pentium-class (or newer) processors.
  30523. ** It uses the RDTSC opcode to read the cycle count value out of the
  30524. ** processor and returns that value. This can be used for high-res
  30525. ** profiling.
  30526. */
  30527. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  30528. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  30529. #if defined(__GNUC__)
  30530. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30531. unsigned int lo, hi;
  30532. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  30533. return (sqlite_uint64)hi << 32 | lo;
  30534. }
  30535. #elif defined(_MSC_VER)
  30536. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  30537. __asm {
  30538. rdtsc
  30539. ret ; return value at EDX:EAX
  30540. }
  30541. }
  30542. #endif
  30543. #elif (defined(__GNUC__) && defined(__x86_64__))
  30544. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30545. unsigned long val;
  30546. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  30547. return val;
  30548. }
  30549. #elif (defined(__GNUC__) && defined(__ppc__))
  30550. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  30551. unsigned long long retval;
  30552. unsigned long junk;
  30553. __asm__ __volatile__ ("\n\
  30554. 1: mftbu %1\n\
  30555. mftb %L0\n\
  30556. mftbu %0\n\
  30557. cmpw %0,%1\n\
  30558. bne 1b"
  30559. : "=r" (retval), "=r" (junk));
  30560. return retval;
  30561. }
  30562. #else
  30563. #error Need implementation of sqlite3Hwtime() for your platform.
  30564. /*
  30565. ** To compile without implementing sqlite3Hwtime() for your platform,
  30566. ** you can remove the above #error and use the following
  30567. ** stub function. You will lose timing support for many
  30568. ** of the debugging and testing utilities, but it should at
  30569. ** least compile and run.
  30570. */
  30571. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  30572. #endif
  30573. #endif /* !defined(_HWTIME_H_) */
  30574. /************** End of hwtime.h **********************************************/
  30575. /************** Continuing where we left off in os_common.h ******************/
  30576. static sqlite_uint64 g_start;
  30577. static sqlite_uint64 g_elapsed;
  30578. #define TIMER_START g_start=sqlite3Hwtime()
  30579. #define TIMER_END g_elapsed=sqlite3Hwtime()-g_start
  30580. #define TIMER_ELAPSED g_elapsed
  30581. #else
  30582. #define TIMER_START
  30583. #define TIMER_END
  30584. #define TIMER_ELAPSED ((sqlite_uint64)0)
  30585. #endif
  30586. /*
  30587. ** If we compile with the SQLITE_TEST macro set, then the following block
  30588. ** of code will give us the ability to simulate a disk I/O error. This
  30589. ** is used for testing the I/O recovery logic.
  30590. */
  30591. #ifdef SQLITE_TEST
  30592. SQLITE_API int sqlite3_io_error_hit = 0; /* Total number of I/O Errors */
  30593. SQLITE_API int sqlite3_io_error_hardhit = 0; /* Number of non-benign errors */
  30594. SQLITE_API int sqlite3_io_error_pending = 0; /* Count down to first I/O error */
  30595. SQLITE_API int sqlite3_io_error_persist = 0; /* True if I/O errors persist */
  30596. SQLITE_API int sqlite3_io_error_benign = 0; /* True if errors are benign */
  30597. SQLITE_API int sqlite3_diskfull_pending = 0;
  30598. SQLITE_API int sqlite3_diskfull = 0;
  30599. #define SimulateIOErrorBenign(X) sqlite3_io_error_benign=(X)
  30600. #define SimulateIOError(CODE) \
  30601. if( (sqlite3_io_error_persist && sqlite3_io_error_hit) \
  30602. || sqlite3_io_error_pending-- == 1 ) \
  30603. { local_ioerr(); CODE; }
  30604. static void local_ioerr(){
  30605. IOTRACE(("IOERR\n"));
  30606. sqlite3_io_error_hit++;
  30607. if( !sqlite3_io_error_benign ) sqlite3_io_error_hardhit++;
  30608. }
  30609. #define SimulateDiskfullError(CODE) \
  30610. if( sqlite3_diskfull_pending ){ \
  30611. if( sqlite3_diskfull_pending == 1 ){ \
  30612. local_ioerr(); \
  30613. sqlite3_diskfull = 1; \
  30614. sqlite3_io_error_hit = 1; \
  30615. CODE; \
  30616. }else{ \
  30617. sqlite3_diskfull_pending--; \
  30618. } \
  30619. }
  30620. #else
  30621. #define SimulateIOErrorBenign(X)
  30622. #define SimulateIOError(A)
  30623. #define SimulateDiskfullError(A)
  30624. #endif
  30625. /*
  30626. ** When testing, keep a count of the number of open files.
  30627. */
  30628. #ifdef SQLITE_TEST
  30629. SQLITE_API int sqlite3_open_file_count = 0;
  30630. #define OpenCounter(X) sqlite3_open_file_count+=(X)
  30631. #else
  30632. #define OpenCounter(X)
  30633. #endif
  30634. #endif /* !defined(_OS_COMMON_H_) */
  30635. /************** End of os_common.h *******************************************/
  30636. /************** Continuing where we left off in os_win.c *********************/
  30637. /*
  30638. ** Include the header file for the Windows VFS.
  30639. */
  30640. /*
  30641. ** Compiling and using WAL mode requires several APIs that are only
  30642. ** available in Windows platforms based on the NT kernel.
  30643. */
  30644. #if !SQLITE_OS_WINNT && !defined(SQLITE_OMIT_WAL)
  30645. # error "WAL mode requires support from the Windows NT kernel, compile\
  30646. with SQLITE_OMIT_WAL."
  30647. #endif
  30648. /*
  30649. ** Are most of the Win32 ANSI APIs available (i.e. with certain exceptions
  30650. ** based on the sub-platform)?
  30651. */
  30652. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(SQLITE_WIN32_NO_ANSI)
  30653. # define SQLITE_WIN32_HAS_ANSI
  30654. #endif
  30655. /*
  30656. ** Are most of the Win32 Unicode APIs available (i.e. with certain exceptions
  30657. ** based on the sub-platform)?
  30658. */
  30659. #if (SQLITE_OS_WINCE || SQLITE_OS_WINNT || SQLITE_OS_WINRT) && \
  30660. !defined(SQLITE_WIN32_NO_WIDE)
  30661. # define SQLITE_WIN32_HAS_WIDE
  30662. #endif
  30663. /*
  30664. ** Make sure at least one set of Win32 APIs is available.
  30665. */
  30666. #if !defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_WIN32_HAS_WIDE)
  30667. # error "At least one of SQLITE_WIN32_HAS_ANSI and SQLITE_WIN32_HAS_WIDE\
  30668. must be defined."
  30669. #endif
  30670. /*
  30671. ** Define the required Windows SDK version constants if they are not
  30672. ** already available.
  30673. */
  30674. #ifndef NTDDI_WIN8
  30675. # define NTDDI_WIN8 0x06020000
  30676. #endif
  30677. #ifndef NTDDI_WINBLUE
  30678. # define NTDDI_WINBLUE 0x06030000
  30679. #endif
  30680. /*
  30681. ** Check to see if the GetVersionEx[AW] functions are deprecated on the
  30682. ** target system. GetVersionEx was first deprecated in Win8.1.
  30683. */
  30684. #ifndef SQLITE_WIN32_GETVERSIONEX
  30685. # if defined(NTDDI_VERSION) && NTDDI_VERSION >= NTDDI_WINBLUE
  30686. # define SQLITE_WIN32_GETVERSIONEX 0 /* GetVersionEx() is deprecated */
  30687. # else
  30688. # define SQLITE_WIN32_GETVERSIONEX 1 /* GetVersionEx() is current */
  30689. # endif
  30690. #endif
  30691. /*
  30692. ** This constant should already be defined (in the "WinDef.h" SDK file).
  30693. */
  30694. #ifndef MAX_PATH
  30695. # define MAX_PATH (260)
  30696. #endif
  30697. /*
  30698. ** Maximum pathname length (in chars) for Win32. This should normally be
  30699. ** MAX_PATH.
  30700. */
  30701. #ifndef SQLITE_WIN32_MAX_PATH_CHARS
  30702. # define SQLITE_WIN32_MAX_PATH_CHARS (MAX_PATH)
  30703. #endif
  30704. /*
  30705. ** This constant should already be defined (in the "WinNT.h" SDK file).
  30706. */
  30707. #ifndef UNICODE_STRING_MAX_CHARS
  30708. # define UNICODE_STRING_MAX_CHARS (32767)
  30709. #endif
  30710. /*
  30711. ** Maximum pathname length (in chars) for WinNT. This should normally be
  30712. ** UNICODE_STRING_MAX_CHARS.
  30713. */
  30714. #ifndef SQLITE_WINNT_MAX_PATH_CHARS
  30715. # define SQLITE_WINNT_MAX_PATH_CHARS (UNICODE_STRING_MAX_CHARS)
  30716. #endif
  30717. /*
  30718. ** Maximum pathname length (in bytes) for Win32. The MAX_PATH macro is in
  30719. ** characters, so we allocate 4 bytes per character assuming worst-case of
  30720. ** 4-bytes-per-character for UTF8.
  30721. */
  30722. #ifndef SQLITE_WIN32_MAX_PATH_BYTES
  30723. # define SQLITE_WIN32_MAX_PATH_BYTES (SQLITE_WIN32_MAX_PATH_CHARS*4)
  30724. #endif
  30725. /*
  30726. ** Maximum pathname length (in bytes) for WinNT. This should normally be
  30727. ** UNICODE_STRING_MAX_CHARS * sizeof(WCHAR).
  30728. */
  30729. #ifndef SQLITE_WINNT_MAX_PATH_BYTES
  30730. # define SQLITE_WINNT_MAX_PATH_BYTES \
  30731. (sizeof(WCHAR) * SQLITE_WINNT_MAX_PATH_CHARS)
  30732. #endif
  30733. /*
  30734. ** Maximum error message length (in chars) for WinRT.
  30735. */
  30736. #ifndef SQLITE_WIN32_MAX_ERRMSG_CHARS
  30737. # define SQLITE_WIN32_MAX_ERRMSG_CHARS (1024)
  30738. #endif
  30739. /*
  30740. ** Returns non-zero if the character should be treated as a directory
  30741. ** separator.
  30742. */
  30743. #ifndef winIsDirSep
  30744. # define winIsDirSep(a) (((a) == '/') || ((a) == '\\'))
  30745. #endif
  30746. /*
  30747. ** This macro is used when a local variable is set to a value that is
  30748. ** [sometimes] not used by the code (e.g. via conditional compilation).
  30749. */
  30750. #ifndef UNUSED_VARIABLE_VALUE
  30751. # define UNUSED_VARIABLE_VALUE(x) (void)(x)
  30752. #endif
  30753. /*
  30754. ** Returns the character that should be used as the directory separator.
  30755. */
  30756. #ifndef winGetDirSep
  30757. # define winGetDirSep() '\\'
  30758. #endif
  30759. /*
  30760. ** Do we need to manually define the Win32 file mapping APIs for use with WAL
  30761. ** mode (e.g. these APIs are available in the Windows CE SDK; however, they
  30762. ** are not present in the header file)?
  30763. */
  30764. #if SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL)
  30765. /*
  30766. ** Two of the file mapping APIs are different under WinRT. Figure out which
  30767. ** set we need.
  30768. */
  30769. #if SQLITE_OS_WINRT
  30770. WINBASEAPI HANDLE WINAPI CreateFileMappingFromApp(HANDLE, \
  30771. LPSECURITY_ATTRIBUTES, ULONG, ULONG64, LPCWSTR);
  30772. WINBASEAPI LPVOID WINAPI MapViewOfFileFromApp(HANDLE, ULONG, ULONG64, SIZE_T);
  30773. #else
  30774. #if defined(SQLITE_WIN32_HAS_ANSI)
  30775. WINBASEAPI HANDLE WINAPI CreateFileMappingA(HANDLE, LPSECURITY_ATTRIBUTES, \
  30776. DWORD, DWORD, DWORD, LPCSTR);
  30777. #endif /* defined(SQLITE_WIN32_HAS_ANSI) */
  30778. #if defined(SQLITE_WIN32_HAS_WIDE)
  30779. WINBASEAPI HANDLE WINAPI CreateFileMappingW(HANDLE, LPSECURITY_ATTRIBUTES, \
  30780. DWORD, DWORD, DWORD, LPCWSTR);
  30781. #endif /* defined(SQLITE_WIN32_HAS_WIDE) */
  30782. WINBASEAPI LPVOID WINAPI MapViewOfFile(HANDLE, DWORD, DWORD, DWORD, SIZE_T);
  30783. #endif /* SQLITE_OS_WINRT */
  30784. /*
  30785. ** This file mapping API is common to both Win32 and WinRT.
  30786. */
  30787. WINBASEAPI BOOL WINAPI UnmapViewOfFile(LPCVOID);
  30788. #endif /* SQLITE_WIN32_FILEMAPPING_API && !defined(SQLITE_OMIT_WAL) */
  30789. /*
  30790. ** Some Microsoft compilers lack this definition.
  30791. */
  30792. #ifndef INVALID_FILE_ATTRIBUTES
  30793. # define INVALID_FILE_ATTRIBUTES ((DWORD)-1)
  30794. #endif
  30795. #ifndef FILE_FLAG_MASK
  30796. # define FILE_FLAG_MASK (0xFF3C0000)
  30797. #endif
  30798. #ifndef FILE_ATTRIBUTE_MASK
  30799. # define FILE_ATTRIBUTE_MASK (0x0003FFF7)
  30800. #endif
  30801. #ifndef SQLITE_OMIT_WAL
  30802. /* Forward references to structures used for WAL */
  30803. typedef struct winShm winShm; /* A connection to shared-memory */
  30804. typedef struct winShmNode winShmNode; /* A region of shared-memory */
  30805. #endif
  30806. /*
  30807. ** WinCE lacks native support for file locking so we have to fake it
  30808. ** with some code of our own.
  30809. */
  30810. #if SQLITE_OS_WINCE
  30811. typedef struct winceLock {
  30812. int nReaders; /* Number of reader locks obtained */
  30813. BOOL bPending; /* Indicates a pending lock has been obtained */
  30814. BOOL bReserved; /* Indicates a reserved lock has been obtained */
  30815. BOOL bExclusive; /* Indicates an exclusive lock has been obtained */
  30816. } winceLock;
  30817. #endif
  30818. /*
  30819. ** The winFile structure is a subclass of sqlite3_file* specific to the win32
  30820. ** portability layer.
  30821. */
  30822. typedef struct winFile winFile;
  30823. struct winFile {
  30824. const sqlite3_io_methods *pMethod; /*** Must be first ***/
  30825. sqlite3_vfs *pVfs; /* The VFS used to open this file */
  30826. HANDLE h; /* Handle for accessing the file */
  30827. u8 locktype; /* Type of lock currently held on this file */
  30828. short sharedLockByte; /* Randomly chosen byte used as a shared lock */
  30829. u8 ctrlFlags; /* Flags. See WINFILE_* below */
  30830. DWORD lastErrno; /* The Windows errno from the last I/O error */
  30831. #ifndef SQLITE_OMIT_WAL
  30832. winShm *pShm; /* Instance of shared memory on this file */
  30833. #endif
  30834. const char *zPath; /* Full pathname of this file */
  30835. int szChunk; /* Chunk size configured by FCNTL_CHUNK_SIZE */
  30836. #if SQLITE_OS_WINCE
  30837. LPWSTR zDeleteOnClose; /* Name of file to delete when closing */
  30838. HANDLE hMutex; /* Mutex used to control access to shared lock */
  30839. HANDLE hShared; /* Shared memory segment used for locking */
  30840. winceLock local; /* Locks obtained by this instance of winFile */
  30841. winceLock *shared; /* Global shared lock memory for the file */
  30842. #endif
  30843. #if SQLITE_MAX_MMAP_SIZE>0
  30844. int nFetchOut; /* Number of outstanding xFetch references */
  30845. HANDLE hMap; /* Handle for accessing memory mapping */
  30846. void *pMapRegion; /* Area memory mapped */
  30847. sqlite3_int64 mmapSize; /* Usable size of mapped region */
  30848. sqlite3_int64 mmapSizeActual; /* Actual size of mapped region */
  30849. sqlite3_int64 mmapSizeMax; /* Configured FCNTL_MMAP_SIZE value */
  30850. #endif
  30851. };
  30852. /*
  30853. ** Allowed values for winFile.ctrlFlags
  30854. */
  30855. #define WINFILE_RDONLY 0x02 /* Connection is read only */
  30856. #define WINFILE_PERSIST_WAL 0x04 /* Persistent WAL mode */
  30857. #define WINFILE_PSOW 0x10 /* SQLITE_IOCAP_POWERSAFE_OVERWRITE */
  30858. /*
  30859. * The size of the buffer used by sqlite3_win32_write_debug().
  30860. */
  30861. #ifndef SQLITE_WIN32_DBG_BUF_SIZE
  30862. # define SQLITE_WIN32_DBG_BUF_SIZE ((int)(4096-sizeof(DWORD)))
  30863. #endif
  30864. /*
  30865. * The value used with sqlite3_win32_set_directory() to specify that
  30866. * the data directory should be changed.
  30867. */
  30868. #ifndef SQLITE_WIN32_DATA_DIRECTORY_TYPE
  30869. # define SQLITE_WIN32_DATA_DIRECTORY_TYPE (1)
  30870. #endif
  30871. /*
  30872. * The value used with sqlite3_win32_set_directory() to specify that
  30873. * the temporary directory should be changed.
  30874. */
  30875. #ifndef SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  30876. # define SQLITE_WIN32_TEMP_DIRECTORY_TYPE (2)
  30877. #endif
  30878. /*
  30879. * If compiled with SQLITE_WIN32_MALLOC on Windows, we will use the
  30880. * various Win32 API heap functions instead of our own.
  30881. */
  30882. #ifdef SQLITE_WIN32_MALLOC
  30883. /*
  30884. * If this is non-zero, an isolated heap will be created by the native Win32
  30885. * allocator subsystem; otherwise, the default process heap will be used. This
  30886. * setting has no effect when compiling for WinRT. By default, this is enabled
  30887. * and an isolated heap will be created to store all allocated data.
  30888. *
  30889. ******************************************************************************
  30890. * WARNING: It is important to note that when this setting is non-zero and the
  30891. * winMemShutdown function is called (e.g. by the sqlite3_shutdown
  30892. * function), all data that was allocated using the isolated heap will
  30893. * be freed immediately and any attempt to access any of that freed
  30894. * data will almost certainly result in an immediate access violation.
  30895. ******************************************************************************
  30896. */
  30897. #ifndef SQLITE_WIN32_HEAP_CREATE
  30898. # define SQLITE_WIN32_HEAP_CREATE (TRUE)
  30899. #endif
  30900. /*
  30901. * The initial size of the Win32-specific heap. This value may be zero.
  30902. */
  30903. #ifndef SQLITE_WIN32_HEAP_INIT_SIZE
  30904. # define SQLITE_WIN32_HEAP_INIT_SIZE ((SQLITE_DEFAULT_CACHE_SIZE) * \
  30905. (SQLITE_DEFAULT_PAGE_SIZE) + 4194304)
  30906. #endif
  30907. /*
  30908. * The maximum size of the Win32-specific heap. This value may be zero.
  30909. */
  30910. #ifndef SQLITE_WIN32_HEAP_MAX_SIZE
  30911. # define SQLITE_WIN32_HEAP_MAX_SIZE (0)
  30912. #endif
  30913. /*
  30914. * The extra flags to use in calls to the Win32 heap APIs. This value may be
  30915. * zero for the default behavior.
  30916. */
  30917. #ifndef SQLITE_WIN32_HEAP_FLAGS
  30918. # define SQLITE_WIN32_HEAP_FLAGS (0)
  30919. #endif
  30920. /*
  30921. ** The winMemData structure stores information required by the Win32-specific
  30922. ** sqlite3_mem_methods implementation.
  30923. */
  30924. typedef struct winMemData winMemData;
  30925. struct winMemData {
  30926. #ifndef NDEBUG
  30927. u32 magic1; /* Magic number to detect structure corruption. */
  30928. #endif
  30929. HANDLE hHeap; /* The handle to our heap. */
  30930. BOOL bOwned; /* Do we own the heap (i.e. destroy it on shutdown)? */
  30931. #ifndef NDEBUG
  30932. u32 magic2; /* Magic number to detect structure corruption. */
  30933. #endif
  30934. };
  30935. #ifndef NDEBUG
  30936. #define WINMEM_MAGIC1 0x42b2830b
  30937. #define WINMEM_MAGIC2 0xbd4d7cf4
  30938. #endif
  30939. static struct winMemData win_mem_data = {
  30940. #ifndef NDEBUG
  30941. WINMEM_MAGIC1,
  30942. #endif
  30943. NULL, FALSE
  30944. #ifndef NDEBUG
  30945. ,WINMEM_MAGIC2
  30946. #endif
  30947. };
  30948. #ifndef NDEBUG
  30949. #define winMemAssertMagic1() assert( win_mem_data.magic1==WINMEM_MAGIC1 )
  30950. #define winMemAssertMagic2() assert( win_mem_data.magic2==WINMEM_MAGIC2 )
  30951. #define winMemAssertMagic() winMemAssertMagic1(); winMemAssertMagic2();
  30952. #else
  30953. #define winMemAssertMagic()
  30954. #endif
  30955. #define winMemGetDataPtr() &win_mem_data
  30956. #define winMemGetHeap() win_mem_data.hHeap
  30957. #define winMemGetOwned() win_mem_data.bOwned
  30958. static void *winMemMalloc(int nBytes);
  30959. static void winMemFree(void *pPrior);
  30960. static void *winMemRealloc(void *pPrior, int nBytes);
  30961. static int winMemSize(void *p);
  30962. static int winMemRoundup(int n);
  30963. static int winMemInit(void *pAppData);
  30964. static void winMemShutdown(void *pAppData);
  30965. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void);
  30966. #endif /* SQLITE_WIN32_MALLOC */
  30967. /*
  30968. ** The following variable is (normally) set once and never changes
  30969. ** thereafter. It records whether the operating system is Win9x
  30970. ** or WinNT.
  30971. **
  30972. ** 0: Operating system unknown.
  30973. ** 1: Operating system is Win9x.
  30974. ** 2: Operating system is WinNT.
  30975. **
  30976. ** In order to facilitate testing on a WinNT system, the test fixture
  30977. ** can manually set this value to 1 to emulate Win98 behavior.
  30978. */
  30979. #ifdef SQLITE_TEST
  30980. SQLITE_API LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  30981. #else
  30982. static LONG SQLITE_WIN32_VOLATILE sqlite3_os_type = 0;
  30983. #endif
  30984. #ifndef SYSCALL
  30985. # define SYSCALL sqlite3_syscall_ptr
  30986. #endif
  30987. /*
  30988. ** This function is not available on Windows CE or WinRT.
  30989. */
  30990. #if SQLITE_OS_WINCE || SQLITE_OS_WINRT
  30991. # define osAreFileApisANSI() 1
  30992. #endif
  30993. /*
  30994. ** Many system calls are accessed through pointer-to-functions so that
  30995. ** they may be overridden at runtime to facilitate fault injection during
  30996. ** testing and sandboxing. The following array holds the names and pointers
  30997. ** to all overrideable system calls.
  30998. */
  30999. static struct win_syscall {
  31000. const char *zName; /* Name of the system call */
  31001. sqlite3_syscall_ptr pCurrent; /* Current value of the system call */
  31002. sqlite3_syscall_ptr pDefault; /* Default value */
  31003. } aSyscall[] = {
  31004. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31005. { "AreFileApisANSI", (SYSCALL)AreFileApisANSI, 0 },
  31006. #else
  31007. { "AreFileApisANSI", (SYSCALL)0, 0 },
  31008. #endif
  31009. #ifndef osAreFileApisANSI
  31010. #define osAreFileApisANSI ((BOOL(WINAPI*)(VOID))aSyscall[0].pCurrent)
  31011. #endif
  31012. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  31013. { "CharLowerW", (SYSCALL)CharLowerW, 0 },
  31014. #else
  31015. { "CharLowerW", (SYSCALL)0, 0 },
  31016. #endif
  31017. #define osCharLowerW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[1].pCurrent)
  31018. #if SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_WIDE)
  31019. { "CharUpperW", (SYSCALL)CharUpperW, 0 },
  31020. #else
  31021. { "CharUpperW", (SYSCALL)0, 0 },
  31022. #endif
  31023. #define osCharUpperW ((LPWSTR(WINAPI*)(LPWSTR))aSyscall[2].pCurrent)
  31024. { "CloseHandle", (SYSCALL)CloseHandle, 0 },
  31025. #define osCloseHandle ((BOOL(WINAPI*)(HANDLE))aSyscall[3].pCurrent)
  31026. #if defined(SQLITE_WIN32_HAS_ANSI)
  31027. { "CreateFileA", (SYSCALL)CreateFileA, 0 },
  31028. #else
  31029. { "CreateFileA", (SYSCALL)0, 0 },
  31030. #endif
  31031. #define osCreateFileA ((HANDLE(WINAPI*)(LPCSTR,DWORD,DWORD, \
  31032. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[4].pCurrent)
  31033. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31034. { "CreateFileW", (SYSCALL)CreateFileW, 0 },
  31035. #else
  31036. { "CreateFileW", (SYSCALL)0, 0 },
  31037. #endif
  31038. #define osCreateFileW ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD, \
  31039. LPSECURITY_ATTRIBUTES,DWORD,DWORD,HANDLE))aSyscall[5].pCurrent)
  31040. #if (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_ANSI) && \
  31041. !defined(SQLITE_OMIT_WAL))
  31042. { "CreateFileMappingA", (SYSCALL)CreateFileMappingA, 0 },
  31043. #else
  31044. { "CreateFileMappingA", (SYSCALL)0, 0 },
  31045. #endif
  31046. #define osCreateFileMappingA ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  31047. DWORD,DWORD,DWORD,LPCSTR))aSyscall[6].pCurrent)
  31048. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31049. !defined(SQLITE_OMIT_WAL))
  31050. { "CreateFileMappingW", (SYSCALL)CreateFileMappingW, 0 },
  31051. #else
  31052. { "CreateFileMappingW", (SYSCALL)0, 0 },
  31053. #endif
  31054. #define osCreateFileMappingW ((HANDLE(WINAPI*)(HANDLE,LPSECURITY_ATTRIBUTES, \
  31055. DWORD,DWORD,DWORD,LPCWSTR))aSyscall[7].pCurrent)
  31056. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31057. { "CreateMutexW", (SYSCALL)CreateMutexW, 0 },
  31058. #else
  31059. { "CreateMutexW", (SYSCALL)0, 0 },
  31060. #endif
  31061. #define osCreateMutexW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,BOOL, \
  31062. LPCWSTR))aSyscall[8].pCurrent)
  31063. #if defined(SQLITE_WIN32_HAS_ANSI)
  31064. { "DeleteFileA", (SYSCALL)DeleteFileA, 0 },
  31065. #else
  31066. { "DeleteFileA", (SYSCALL)0, 0 },
  31067. #endif
  31068. #define osDeleteFileA ((BOOL(WINAPI*)(LPCSTR))aSyscall[9].pCurrent)
  31069. #if defined(SQLITE_WIN32_HAS_WIDE)
  31070. { "DeleteFileW", (SYSCALL)DeleteFileW, 0 },
  31071. #else
  31072. { "DeleteFileW", (SYSCALL)0, 0 },
  31073. #endif
  31074. #define osDeleteFileW ((BOOL(WINAPI*)(LPCWSTR))aSyscall[10].pCurrent)
  31075. #if SQLITE_OS_WINCE
  31076. { "FileTimeToLocalFileTime", (SYSCALL)FileTimeToLocalFileTime, 0 },
  31077. #else
  31078. { "FileTimeToLocalFileTime", (SYSCALL)0, 0 },
  31079. #endif
  31080. #define osFileTimeToLocalFileTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  31081. LPFILETIME))aSyscall[11].pCurrent)
  31082. #if SQLITE_OS_WINCE
  31083. { "FileTimeToSystemTime", (SYSCALL)FileTimeToSystemTime, 0 },
  31084. #else
  31085. { "FileTimeToSystemTime", (SYSCALL)0, 0 },
  31086. #endif
  31087. #define osFileTimeToSystemTime ((BOOL(WINAPI*)(CONST FILETIME*, \
  31088. LPSYSTEMTIME))aSyscall[12].pCurrent)
  31089. { "FlushFileBuffers", (SYSCALL)FlushFileBuffers, 0 },
  31090. #define osFlushFileBuffers ((BOOL(WINAPI*)(HANDLE))aSyscall[13].pCurrent)
  31091. #if defined(SQLITE_WIN32_HAS_ANSI)
  31092. { "FormatMessageA", (SYSCALL)FormatMessageA, 0 },
  31093. #else
  31094. { "FormatMessageA", (SYSCALL)0, 0 },
  31095. #endif
  31096. #define osFormatMessageA ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPSTR, \
  31097. DWORD,va_list*))aSyscall[14].pCurrent)
  31098. #if defined(SQLITE_WIN32_HAS_WIDE)
  31099. { "FormatMessageW", (SYSCALL)FormatMessageW, 0 },
  31100. #else
  31101. { "FormatMessageW", (SYSCALL)0, 0 },
  31102. #endif
  31103. #define osFormatMessageW ((DWORD(WINAPI*)(DWORD,LPCVOID,DWORD,DWORD,LPWSTR, \
  31104. DWORD,va_list*))aSyscall[15].pCurrent)
  31105. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31106. { "FreeLibrary", (SYSCALL)FreeLibrary, 0 },
  31107. #else
  31108. { "FreeLibrary", (SYSCALL)0, 0 },
  31109. #endif
  31110. #define osFreeLibrary ((BOOL(WINAPI*)(HMODULE))aSyscall[16].pCurrent)
  31111. { "GetCurrentProcessId", (SYSCALL)GetCurrentProcessId, 0 },
  31112. #define osGetCurrentProcessId ((DWORD(WINAPI*)(VOID))aSyscall[17].pCurrent)
  31113. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  31114. { "GetDiskFreeSpaceA", (SYSCALL)GetDiskFreeSpaceA, 0 },
  31115. #else
  31116. { "GetDiskFreeSpaceA", (SYSCALL)0, 0 },
  31117. #endif
  31118. #define osGetDiskFreeSpaceA ((BOOL(WINAPI*)(LPCSTR,LPDWORD,LPDWORD,LPDWORD, \
  31119. LPDWORD))aSyscall[18].pCurrent)
  31120. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31121. { "GetDiskFreeSpaceW", (SYSCALL)GetDiskFreeSpaceW, 0 },
  31122. #else
  31123. { "GetDiskFreeSpaceW", (SYSCALL)0, 0 },
  31124. #endif
  31125. #define osGetDiskFreeSpaceW ((BOOL(WINAPI*)(LPCWSTR,LPDWORD,LPDWORD,LPDWORD, \
  31126. LPDWORD))aSyscall[19].pCurrent)
  31127. #if defined(SQLITE_WIN32_HAS_ANSI)
  31128. { "GetFileAttributesA", (SYSCALL)GetFileAttributesA, 0 },
  31129. #else
  31130. { "GetFileAttributesA", (SYSCALL)0, 0 },
  31131. #endif
  31132. #define osGetFileAttributesA ((DWORD(WINAPI*)(LPCSTR))aSyscall[20].pCurrent)
  31133. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31134. { "GetFileAttributesW", (SYSCALL)GetFileAttributesW, 0 },
  31135. #else
  31136. { "GetFileAttributesW", (SYSCALL)0, 0 },
  31137. #endif
  31138. #define osGetFileAttributesW ((DWORD(WINAPI*)(LPCWSTR))aSyscall[21].pCurrent)
  31139. #if defined(SQLITE_WIN32_HAS_WIDE)
  31140. { "GetFileAttributesExW", (SYSCALL)GetFileAttributesExW, 0 },
  31141. #else
  31142. { "GetFileAttributesExW", (SYSCALL)0, 0 },
  31143. #endif
  31144. #define osGetFileAttributesExW ((BOOL(WINAPI*)(LPCWSTR,GET_FILEEX_INFO_LEVELS, \
  31145. LPVOID))aSyscall[22].pCurrent)
  31146. #if !SQLITE_OS_WINRT
  31147. { "GetFileSize", (SYSCALL)GetFileSize, 0 },
  31148. #else
  31149. { "GetFileSize", (SYSCALL)0, 0 },
  31150. #endif
  31151. #define osGetFileSize ((DWORD(WINAPI*)(HANDLE,LPDWORD))aSyscall[23].pCurrent)
  31152. #if !SQLITE_OS_WINCE && defined(SQLITE_WIN32_HAS_ANSI)
  31153. { "GetFullPathNameA", (SYSCALL)GetFullPathNameA, 0 },
  31154. #else
  31155. { "GetFullPathNameA", (SYSCALL)0, 0 },
  31156. #endif
  31157. #define osGetFullPathNameA ((DWORD(WINAPI*)(LPCSTR,DWORD,LPSTR, \
  31158. LPSTR*))aSyscall[24].pCurrent)
  31159. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31160. { "GetFullPathNameW", (SYSCALL)GetFullPathNameW, 0 },
  31161. #else
  31162. { "GetFullPathNameW", (SYSCALL)0, 0 },
  31163. #endif
  31164. #define osGetFullPathNameW ((DWORD(WINAPI*)(LPCWSTR,DWORD,LPWSTR, \
  31165. LPWSTR*))aSyscall[25].pCurrent)
  31166. { "GetLastError", (SYSCALL)GetLastError, 0 },
  31167. #define osGetLastError ((DWORD(WINAPI*)(VOID))aSyscall[26].pCurrent)
  31168. #if !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31169. #if SQLITE_OS_WINCE
  31170. /* The GetProcAddressA() routine is only available on Windows CE. */
  31171. { "GetProcAddressA", (SYSCALL)GetProcAddressA, 0 },
  31172. #else
  31173. /* All other Windows platforms expect GetProcAddress() to take
  31174. ** an ANSI string regardless of the _UNICODE setting */
  31175. { "GetProcAddressA", (SYSCALL)GetProcAddress, 0 },
  31176. #endif
  31177. #else
  31178. { "GetProcAddressA", (SYSCALL)0, 0 },
  31179. #endif
  31180. #define osGetProcAddressA ((FARPROC(WINAPI*)(HMODULE, \
  31181. LPCSTR))aSyscall[27].pCurrent)
  31182. #if !SQLITE_OS_WINRT
  31183. { "GetSystemInfo", (SYSCALL)GetSystemInfo, 0 },
  31184. #else
  31185. { "GetSystemInfo", (SYSCALL)0, 0 },
  31186. #endif
  31187. #define osGetSystemInfo ((VOID(WINAPI*)(LPSYSTEM_INFO))aSyscall[28].pCurrent)
  31188. { "GetSystemTime", (SYSCALL)GetSystemTime, 0 },
  31189. #define osGetSystemTime ((VOID(WINAPI*)(LPSYSTEMTIME))aSyscall[29].pCurrent)
  31190. #if !SQLITE_OS_WINCE
  31191. { "GetSystemTimeAsFileTime", (SYSCALL)GetSystemTimeAsFileTime, 0 },
  31192. #else
  31193. { "GetSystemTimeAsFileTime", (SYSCALL)0, 0 },
  31194. #endif
  31195. #define osGetSystemTimeAsFileTime ((VOID(WINAPI*)( \
  31196. LPFILETIME))aSyscall[30].pCurrent)
  31197. #if defined(SQLITE_WIN32_HAS_ANSI)
  31198. { "GetTempPathA", (SYSCALL)GetTempPathA, 0 },
  31199. #else
  31200. { "GetTempPathA", (SYSCALL)0, 0 },
  31201. #endif
  31202. #define osGetTempPathA ((DWORD(WINAPI*)(DWORD,LPSTR))aSyscall[31].pCurrent)
  31203. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE)
  31204. { "GetTempPathW", (SYSCALL)GetTempPathW, 0 },
  31205. #else
  31206. { "GetTempPathW", (SYSCALL)0, 0 },
  31207. #endif
  31208. #define osGetTempPathW ((DWORD(WINAPI*)(DWORD,LPWSTR))aSyscall[32].pCurrent)
  31209. #if !SQLITE_OS_WINRT
  31210. { "GetTickCount", (SYSCALL)GetTickCount, 0 },
  31211. #else
  31212. { "GetTickCount", (SYSCALL)0, 0 },
  31213. #endif
  31214. #define osGetTickCount ((DWORD(WINAPI*)(VOID))aSyscall[33].pCurrent)
  31215. #if defined(SQLITE_WIN32_HAS_ANSI) && defined(SQLITE_WIN32_GETVERSIONEX) && \
  31216. SQLITE_WIN32_GETVERSIONEX
  31217. { "GetVersionExA", (SYSCALL)GetVersionExA, 0 },
  31218. #else
  31219. { "GetVersionExA", (SYSCALL)0, 0 },
  31220. #endif
  31221. #define osGetVersionExA ((BOOL(WINAPI*)( \
  31222. LPOSVERSIONINFOA))aSyscall[34].pCurrent)
  31223. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31224. defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  31225. { "GetVersionExW", (SYSCALL)GetVersionExW, 0 },
  31226. #else
  31227. { "GetVersionExW", (SYSCALL)0, 0 },
  31228. #endif
  31229. #define osGetVersionExW ((BOOL(WINAPI*)( \
  31230. LPOSVERSIONINFOW))aSyscall[35].pCurrent)
  31231. { "HeapAlloc", (SYSCALL)HeapAlloc, 0 },
  31232. #define osHeapAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD, \
  31233. SIZE_T))aSyscall[36].pCurrent)
  31234. #if !SQLITE_OS_WINRT
  31235. { "HeapCreate", (SYSCALL)HeapCreate, 0 },
  31236. #else
  31237. { "HeapCreate", (SYSCALL)0, 0 },
  31238. #endif
  31239. #define osHeapCreate ((HANDLE(WINAPI*)(DWORD,SIZE_T, \
  31240. SIZE_T))aSyscall[37].pCurrent)
  31241. #if !SQLITE_OS_WINRT
  31242. { "HeapDestroy", (SYSCALL)HeapDestroy, 0 },
  31243. #else
  31244. { "HeapDestroy", (SYSCALL)0, 0 },
  31245. #endif
  31246. #define osHeapDestroy ((BOOL(WINAPI*)(HANDLE))aSyscall[38].pCurrent)
  31247. { "HeapFree", (SYSCALL)HeapFree, 0 },
  31248. #define osHeapFree ((BOOL(WINAPI*)(HANDLE,DWORD,LPVOID))aSyscall[39].pCurrent)
  31249. { "HeapReAlloc", (SYSCALL)HeapReAlloc, 0 },
  31250. #define osHeapReAlloc ((LPVOID(WINAPI*)(HANDLE,DWORD,LPVOID, \
  31251. SIZE_T))aSyscall[40].pCurrent)
  31252. { "HeapSize", (SYSCALL)HeapSize, 0 },
  31253. #define osHeapSize ((SIZE_T(WINAPI*)(HANDLE,DWORD, \
  31254. LPCVOID))aSyscall[41].pCurrent)
  31255. #if !SQLITE_OS_WINRT
  31256. { "HeapValidate", (SYSCALL)HeapValidate, 0 },
  31257. #else
  31258. { "HeapValidate", (SYSCALL)0, 0 },
  31259. #endif
  31260. #define osHeapValidate ((BOOL(WINAPI*)(HANDLE,DWORD, \
  31261. LPCVOID))aSyscall[42].pCurrent)
  31262. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31263. { "HeapCompact", (SYSCALL)HeapCompact, 0 },
  31264. #else
  31265. { "HeapCompact", (SYSCALL)0, 0 },
  31266. #endif
  31267. #define osHeapCompact ((UINT(WINAPI*)(HANDLE,DWORD))aSyscall[43].pCurrent)
  31268. #if defined(SQLITE_WIN32_HAS_ANSI) && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31269. { "LoadLibraryA", (SYSCALL)LoadLibraryA, 0 },
  31270. #else
  31271. { "LoadLibraryA", (SYSCALL)0, 0 },
  31272. #endif
  31273. #define osLoadLibraryA ((HMODULE(WINAPI*)(LPCSTR))aSyscall[44].pCurrent)
  31274. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_HAS_WIDE) && \
  31275. !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31276. { "LoadLibraryW", (SYSCALL)LoadLibraryW, 0 },
  31277. #else
  31278. { "LoadLibraryW", (SYSCALL)0, 0 },
  31279. #endif
  31280. #define osLoadLibraryW ((HMODULE(WINAPI*)(LPCWSTR))aSyscall[45].pCurrent)
  31281. #if !SQLITE_OS_WINRT
  31282. { "LocalFree", (SYSCALL)LocalFree, 0 },
  31283. #else
  31284. { "LocalFree", (SYSCALL)0, 0 },
  31285. #endif
  31286. #define osLocalFree ((HLOCAL(WINAPI*)(HLOCAL))aSyscall[46].pCurrent)
  31287. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31288. { "LockFile", (SYSCALL)LockFile, 0 },
  31289. #else
  31290. { "LockFile", (SYSCALL)0, 0 },
  31291. #endif
  31292. #ifndef osLockFile
  31293. #define osLockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31294. DWORD))aSyscall[47].pCurrent)
  31295. #endif
  31296. #if !SQLITE_OS_WINCE
  31297. { "LockFileEx", (SYSCALL)LockFileEx, 0 },
  31298. #else
  31299. { "LockFileEx", (SYSCALL)0, 0 },
  31300. #endif
  31301. #ifndef osLockFileEx
  31302. #define osLockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD,DWORD, \
  31303. LPOVERLAPPED))aSyscall[48].pCurrent)
  31304. #endif
  31305. #if SQLITE_OS_WINCE || (!SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL))
  31306. { "MapViewOfFile", (SYSCALL)MapViewOfFile, 0 },
  31307. #else
  31308. { "MapViewOfFile", (SYSCALL)0, 0 },
  31309. #endif
  31310. #define osMapViewOfFile ((LPVOID(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31311. SIZE_T))aSyscall[49].pCurrent)
  31312. { "MultiByteToWideChar", (SYSCALL)MultiByteToWideChar, 0 },
  31313. #define osMultiByteToWideChar ((int(WINAPI*)(UINT,DWORD,LPCSTR,int,LPWSTR, \
  31314. int))aSyscall[50].pCurrent)
  31315. { "QueryPerformanceCounter", (SYSCALL)QueryPerformanceCounter, 0 },
  31316. #define osQueryPerformanceCounter ((BOOL(WINAPI*)( \
  31317. LARGE_INTEGER*))aSyscall[51].pCurrent)
  31318. { "ReadFile", (SYSCALL)ReadFile, 0 },
  31319. #define osReadFile ((BOOL(WINAPI*)(HANDLE,LPVOID,DWORD,LPDWORD, \
  31320. LPOVERLAPPED))aSyscall[52].pCurrent)
  31321. { "SetEndOfFile", (SYSCALL)SetEndOfFile, 0 },
  31322. #define osSetEndOfFile ((BOOL(WINAPI*)(HANDLE))aSyscall[53].pCurrent)
  31323. #if !SQLITE_OS_WINRT
  31324. { "SetFilePointer", (SYSCALL)SetFilePointer, 0 },
  31325. #else
  31326. { "SetFilePointer", (SYSCALL)0, 0 },
  31327. #endif
  31328. #define osSetFilePointer ((DWORD(WINAPI*)(HANDLE,LONG,PLONG, \
  31329. DWORD))aSyscall[54].pCurrent)
  31330. #if !SQLITE_OS_WINRT
  31331. { "Sleep", (SYSCALL)Sleep, 0 },
  31332. #else
  31333. { "Sleep", (SYSCALL)0, 0 },
  31334. #endif
  31335. #define osSleep ((VOID(WINAPI*)(DWORD))aSyscall[55].pCurrent)
  31336. { "SystemTimeToFileTime", (SYSCALL)SystemTimeToFileTime, 0 },
  31337. #define osSystemTimeToFileTime ((BOOL(WINAPI*)(CONST SYSTEMTIME*, \
  31338. LPFILETIME))aSyscall[56].pCurrent)
  31339. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31340. { "UnlockFile", (SYSCALL)UnlockFile, 0 },
  31341. #else
  31342. { "UnlockFile", (SYSCALL)0, 0 },
  31343. #endif
  31344. #ifndef osUnlockFile
  31345. #define osUnlockFile ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31346. DWORD))aSyscall[57].pCurrent)
  31347. #endif
  31348. #if !SQLITE_OS_WINCE
  31349. { "UnlockFileEx", (SYSCALL)UnlockFileEx, 0 },
  31350. #else
  31351. { "UnlockFileEx", (SYSCALL)0, 0 },
  31352. #endif
  31353. #define osUnlockFileEx ((BOOL(WINAPI*)(HANDLE,DWORD,DWORD,DWORD, \
  31354. LPOVERLAPPED))aSyscall[58].pCurrent)
  31355. #if SQLITE_OS_WINCE || !defined(SQLITE_OMIT_WAL)
  31356. { "UnmapViewOfFile", (SYSCALL)UnmapViewOfFile, 0 },
  31357. #else
  31358. { "UnmapViewOfFile", (SYSCALL)0, 0 },
  31359. #endif
  31360. #define osUnmapViewOfFile ((BOOL(WINAPI*)(LPCVOID))aSyscall[59].pCurrent)
  31361. { "WideCharToMultiByte", (SYSCALL)WideCharToMultiByte, 0 },
  31362. #define osWideCharToMultiByte ((int(WINAPI*)(UINT,DWORD,LPCWSTR,int,LPSTR,int, \
  31363. LPCSTR,LPBOOL))aSyscall[60].pCurrent)
  31364. { "WriteFile", (SYSCALL)WriteFile, 0 },
  31365. #define osWriteFile ((BOOL(WINAPI*)(HANDLE,LPCVOID,DWORD,LPDWORD, \
  31366. LPOVERLAPPED))aSyscall[61].pCurrent)
  31367. #if SQLITE_OS_WINRT
  31368. { "CreateEventExW", (SYSCALL)CreateEventExW, 0 },
  31369. #else
  31370. { "CreateEventExW", (SYSCALL)0, 0 },
  31371. #endif
  31372. #define osCreateEventExW ((HANDLE(WINAPI*)(LPSECURITY_ATTRIBUTES,LPCWSTR, \
  31373. DWORD,DWORD))aSyscall[62].pCurrent)
  31374. #if !SQLITE_OS_WINRT
  31375. { "WaitForSingleObject", (SYSCALL)WaitForSingleObject, 0 },
  31376. #else
  31377. { "WaitForSingleObject", (SYSCALL)0, 0 },
  31378. #endif
  31379. #define osWaitForSingleObject ((DWORD(WINAPI*)(HANDLE, \
  31380. DWORD))aSyscall[63].pCurrent)
  31381. #if !SQLITE_OS_WINCE
  31382. { "WaitForSingleObjectEx", (SYSCALL)WaitForSingleObjectEx, 0 },
  31383. #else
  31384. { "WaitForSingleObjectEx", (SYSCALL)0, 0 },
  31385. #endif
  31386. #define osWaitForSingleObjectEx ((DWORD(WINAPI*)(HANDLE,DWORD, \
  31387. BOOL))aSyscall[64].pCurrent)
  31388. #if SQLITE_OS_WINRT
  31389. { "SetFilePointerEx", (SYSCALL)SetFilePointerEx, 0 },
  31390. #else
  31391. { "SetFilePointerEx", (SYSCALL)0, 0 },
  31392. #endif
  31393. #define osSetFilePointerEx ((BOOL(WINAPI*)(HANDLE,LARGE_INTEGER, \
  31394. PLARGE_INTEGER,DWORD))aSyscall[65].pCurrent)
  31395. #if SQLITE_OS_WINRT
  31396. { "GetFileInformationByHandleEx", (SYSCALL)GetFileInformationByHandleEx, 0 },
  31397. #else
  31398. { "GetFileInformationByHandleEx", (SYSCALL)0, 0 },
  31399. #endif
  31400. #define osGetFileInformationByHandleEx ((BOOL(WINAPI*)(HANDLE, \
  31401. FILE_INFO_BY_HANDLE_CLASS,LPVOID,DWORD))aSyscall[66].pCurrent)
  31402. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  31403. { "MapViewOfFileFromApp", (SYSCALL)MapViewOfFileFromApp, 0 },
  31404. #else
  31405. { "MapViewOfFileFromApp", (SYSCALL)0, 0 },
  31406. #endif
  31407. #define osMapViewOfFileFromApp ((LPVOID(WINAPI*)(HANDLE,ULONG,ULONG64, \
  31408. SIZE_T))aSyscall[67].pCurrent)
  31409. #if SQLITE_OS_WINRT
  31410. { "CreateFile2", (SYSCALL)CreateFile2, 0 },
  31411. #else
  31412. { "CreateFile2", (SYSCALL)0, 0 },
  31413. #endif
  31414. #define osCreateFile2 ((HANDLE(WINAPI*)(LPCWSTR,DWORD,DWORD,DWORD, \
  31415. LPCREATEFILE2_EXTENDED_PARAMETERS))aSyscall[68].pCurrent)
  31416. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_LOAD_EXTENSION)
  31417. { "LoadPackagedLibrary", (SYSCALL)LoadPackagedLibrary, 0 },
  31418. #else
  31419. { "LoadPackagedLibrary", (SYSCALL)0, 0 },
  31420. #endif
  31421. #define osLoadPackagedLibrary ((HMODULE(WINAPI*)(LPCWSTR, \
  31422. DWORD))aSyscall[69].pCurrent)
  31423. #if SQLITE_OS_WINRT
  31424. { "GetTickCount64", (SYSCALL)GetTickCount64, 0 },
  31425. #else
  31426. { "GetTickCount64", (SYSCALL)0, 0 },
  31427. #endif
  31428. #define osGetTickCount64 ((ULONGLONG(WINAPI*)(VOID))aSyscall[70].pCurrent)
  31429. #if SQLITE_OS_WINRT
  31430. { "GetNativeSystemInfo", (SYSCALL)GetNativeSystemInfo, 0 },
  31431. #else
  31432. { "GetNativeSystemInfo", (SYSCALL)0, 0 },
  31433. #endif
  31434. #define osGetNativeSystemInfo ((VOID(WINAPI*)( \
  31435. LPSYSTEM_INFO))aSyscall[71].pCurrent)
  31436. #if defined(SQLITE_WIN32_HAS_ANSI)
  31437. { "OutputDebugStringA", (SYSCALL)OutputDebugStringA, 0 },
  31438. #else
  31439. { "OutputDebugStringA", (SYSCALL)0, 0 },
  31440. #endif
  31441. #define osOutputDebugStringA ((VOID(WINAPI*)(LPCSTR))aSyscall[72].pCurrent)
  31442. #if defined(SQLITE_WIN32_HAS_WIDE)
  31443. { "OutputDebugStringW", (SYSCALL)OutputDebugStringW, 0 },
  31444. #else
  31445. { "OutputDebugStringW", (SYSCALL)0, 0 },
  31446. #endif
  31447. #define osOutputDebugStringW ((VOID(WINAPI*)(LPCWSTR))aSyscall[73].pCurrent)
  31448. { "GetProcessHeap", (SYSCALL)GetProcessHeap, 0 },
  31449. #define osGetProcessHeap ((HANDLE(WINAPI*)(VOID))aSyscall[74].pCurrent)
  31450. #if SQLITE_OS_WINRT && !defined(SQLITE_OMIT_WAL)
  31451. { "CreateFileMappingFromApp", (SYSCALL)CreateFileMappingFromApp, 0 },
  31452. #else
  31453. { "CreateFileMappingFromApp", (SYSCALL)0, 0 },
  31454. #endif
  31455. #define osCreateFileMappingFromApp ((HANDLE(WINAPI*)(HANDLE, \
  31456. LPSECURITY_ATTRIBUTES,ULONG,ULONG64,LPCWSTR))aSyscall[75].pCurrent)
  31457. /*
  31458. ** NOTE: On some sub-platforms, the InterlockedCompareExchange "function"
  31459. ** is really just a macro that uses a compiler intrinsic (e.g. x64).
  31460. ** So do not try to make this is into a redefinable interface.
  31461. */
  31462. #if defined(InterlockedCompareExchange)
  31463. { "InterlockedCompareExchange", (SYSCALL)0, 0 },
  31464. #define osInterlockedCompareExchange InterlockedCompareExchange
  31465. #else
  31466. { "InterlockedCompareExchange", (SYSCALL)InterlockedCompareExchange, 0 },
  31467. #define osInterlockedCompareExchange ((LONG(WINAPI*)(LONG \
  31468. SQLITE_WIN32_VOLATILE*, LONG,LONG))aSyscall[76].pCurrent)
  31469. #endif /* defined(InterlockedCompareExchange) */
  31470. }; /* End of the overrideable system calls */
  31471. /*
  31472. ** This is the xSetSystemCall() method of sqlite3_vfs for all of the
  31473. ** "win32" VFSes. Return SQLITE_OK opon successfully updating the
  31474. ** system call pointer, or SQLITE_NOTFOUND if there is no configurable
  31475. ** system call named zName.
  31476. */
  31477. static int winSetSystemCall(
  31478. sqlite3_vfs *pNotUsed, /* The VFS pointer. Not used */
  31479. const char *zName, /* Name of system call to override */
  31480. sqlite3_syscall_ptr pNewFunc /* Pointer to new system call value */
  31481. ){
  31482. unsigned int i;
  31483. int rc = SQLITE_NOTFOUND;
  31484. UNUSED_PARAMETER(pNotUsed);
  31485. if( zName==0 ){
  31486. /* If no zName is given, restore all system calls to their default
  31487. ** settings and return NULL
  31488. */
  31489. rc = SQLITE_OK;
  31490. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31491. if( aSyscall[i].pDefault ){
  31492. aSyscall[i].pCurrent = aSyscall[i].pDefault;
  31493. }
  31494. }
  31495. }else{
  31496. /* If zName is specified, operate on only the one system call
  31497. ** specified.
  31498. */
  31499. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31500. if( strcmp(zName, aSyscall[i].zName)==0 ){
  31501. if( aSyscall[i].pDefault==0 ){
  31502. aSyscall[i].pDefault = aSyscall[i].pCurrent;
  31503. }
  31504. rc = SQLITE_OK;
  31505. if( pNewFunc==0 ) pNewFunc = aSyscall[i].pDefault;
  31506. aSyscall[i].pCurrent = pNewFunc;
  31507. break;
  31508. }
  31509. }
  31510. }
  31511. return rc;
  31512. }
  31513. /*
  31514. ** Return the value of a system call. Return NULL if zName is not a
  31515. ** recognized system call name. NULL is also returned if the system call
  31516. ** is currently undefined.
  31517. */
  31518. static sqlite3_syscall_ptr winGetSystemCall(
  31519. sqlite3_vfs *pNotUsed,
  31520. const char *zName
  31521. ){
  31522. unsigned int i;
  31523. UNUSED_PARAMETER(pNotUsed);
  31524. for(i=0; i<sizeof(aSyscall)/sizeof(aSyscall[0]); i++){
  31525. if( strcmp(zName, aSyscall[i].zName)==0 ) return aSyscall[i].pCurrent;
  31526. }
  31527. return 0;
  31528. }
  31529. /*
  31530. ** Return the name of the first system call after zName. If zName==NULL
  31531. ** then return the name of the first system call. Return NULL if zName
  31532. ** is the last system call or if zName is not the name of a valid
  31533. ** system call.
  31534. */
  31535. static const char *winNextSystemCall(sqlite3_vfs *p, const char *zName){
  31536. int i = -1;
  31537. UNUSED_PARAMETER(p);
  31538. if( zName ){
  31539. for(i=0; i<ArraySize(aSyscall)-1; i++){
  31540. if( strcmp(zName, aSyscall[i].zName)==0 ) break;
  31541. }
  31542. }
  31543. for(i++; i<ArraySize(aSyscall); i++){
  31544. if( aSyscall[i].pCurrent!=0 ) return aSyscall[i].zName;
  31545. }
  31546. return 0;
  31547. }
  31548. #ifdef SQLITE_WIN32_MALLOC
  31549. /*
  31550. ** If a Win32 native heap has been configured, this function will attempt to
  31551. ** compact it. Upon success, SQLITE_OK will be returned. Upon failure, one
  31552. ** of SQLITE_NOMEM, SQLITE_ERROR, or SQLITE_NOTFOUND will be returned. The
  31553. ** "pnLargest" argument, if non-zero, will be used to return the size of the
  31554. ** largest committed free block in the heap, in bytes.
  31555. */
  31556. SQLITE_API int sqlite3_win32_compact_heap(LPUINT pnLargest){
  31557. int rc = SQLITE_OK;
  31558. UINT nLargest = 0;
  31559. HANDLE hHeap;
  31560. winMemAssertMagic();
  31561. hHeap = winMemGetHeap();
  31562. assert( hHeap!=0 );
  31563. assert( hHeap!=INVALID_HANDLE_VALUE );
  31564. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31565. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  31566. #endif
  31567. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT
  31568. if( (nLargest=osHeapCompact(hHeap, SQLITE_WIN32_HEAP_FLAGS))==0 ){
  31569. DWORD lastErrno = osGetLastError();
  31570. if( lastErrno==NO_ERROR ){
  31571. sqlite3_log(SQLITE_NOMEM, "failed to HeapCompact (no space), heap=%p",
  31572. (void*)hHeap);
  31573. rc = SQLITE_NOMEM;
  31574. }else{
  31575. sqlite3_log(SQLITE_ERROR, "failed to HeapCompact (%lu), heap=%p",
  31576. osGetLastError(), (void*)hHeap);
  31577. rc = SQLITE_ERROR;
  31578. }
  31579. }
  31580. #else
  31581. sqlite3_log(SQLITE_NOTFOUND, "failed to HeapCompact, heap=%p",
  31582. (void*)hHeap);
  31583. rc = SQLITE_NOTFOUND;
  31584. #endif
  31585. if( pnLargest ) *pnLargest = nLargest;
  31586. return rc;
  31587. }
  31588. /*
  31589. ** If a Win32 native heap has been configured, this function will attempt to
  31590. ** destroy and recreate it. If the Win32 native heap is not isolated and/or
  31591. ** the sqlite3_memory_used() function does not return zero, SQLITE_BUSY will
  31592. ** be returned and no changes will be made to the Win32 native heap.
  31593. */
  31594. SQLITE_API int sqlite3_win32_reset_heap(){
  31595. int rc;
  31596. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  31597. MUTEX_LOGIC( sqlite3_mutex *pMem; ) /* The memsys static mutex */
  31598. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  31599. MUTEX_LOGIC( pMem = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MEM); )
  31600. sqlite3_mutex_enter(pMaster);
  31601. sqlite3_mutex_enter(pMem);
  31602. winMemAssertMagic();
  31603. if( winMemGetHeap()!=NULL && winMemGetOwned() && sqlite3_memory_used()==0 ){
  31604. /*
  31605. ** At this point, there should be no outstanding memory allocations on
  31606. ** the heap. Also, since both the master and memsys locks are currently
  31607. ** being held by us, no other function (i.e. from another thread) should
  31608. ** be able to even access the heap. Attempt to destroy and recreate our
  31609. ** isolated Win32 native heap now.
  31610. */
  31611. assert( winMemGetHeap()!=NULL );
  31612. assert( winMemGetOwned() );
  31613. assert( sqlite3_memory_used()==0 );
  31614. winMemShutdown(winMemGetDataPtr());
  31615. assert( winMemGetHeap()==NULL );
  31616. assert( !winMemGetOwned() );
  31617. assert( sqlite3_memory_used()==0 );
  31618. rc = winMemInit(winMemGetDataPtr());
  31619. assert( rc!=SQLITE_OK || winMemGetHeap()!=NULL );
  31620. assert( rc!=SQLITE_OK || winMemGetOwned() );
  31621. assert( rc!=SQLITE_OK || sqlite3_memory_used()==0 );
  31622. }else{
  31623. /*
  31624. ** The Win32 native heap cannot be modified because it may be in use.
  31625. */
  31626. rc = SQLITE_BUSY;
  31627. }
  31628. sqlite3_mutex_leave(pMem);
  31629. sqlite3_mutex_leave(pMaster);
  31630. return rc;
  31631. }
  31632. #endif /* SQLITE_WIN32_MALLOC */
  31633. /*
  31634. ** This function outputs the specified (ANSI) string to the Win32 debugger
  31635. ** (if available).
  31636. */
  31637. SQLITE_API void sqlite3_win32_write_debug(const char *zBuf, int nBuf){
  31638. char zDbgBuf[SQLITE_WIN32_DBG_BUF_SIZE];
  31639. int nMin = MIN(nBuf, (SQLITE_WIN32_DBG_BUF_SIZE - 1)); /* may be negative. */
  31640. if( nMin<-1 ) nMin = -1; /* all negative values become -1. */
  31641. assert( nMin==-1 || nMin==0 || nMin<SQLITE_WIN32_DBG_BUF_SIZE );
  31642. #if defined(SQLITE_WIN32_HAS_ANSI)
  31643. if( nMin>0 ){
  31644. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  31645. memcpy(zDbgBuf, zBuf, nMin);
  31646. osOutputDebugStringA(zDbgBuf);
  31647. }else{
  31648. osOutputDebugStringA(zBuf);
  31649. }
  31650. #elif defined(SQLITE_WIN32_HAS_WIDE)
  31651. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  31652. if ( osMultiByteToWideChar(
  31653. osAreFileApisANSI() ? CP_ACP : CP_OEMCP, 0, zBuf,
  31654. nMin, (LPWSTR)zDbgBuf, SQLITE_WIN32_DBG_BUF_SIZE/sizeof(WCHAR))<=0 ){
  31655. return;
  31656. }
  31657. osOutputDebugStringW((LPCWSTR)zDbgBuf);
  31658. #else
  31659. if( nMin>0 ){
  31660. memset(zDbgBuf, 0, SQLITE_WIN32_DBG_BUF_SIZE);
  31661. memcpy(zDbgBuf, zBuf, nMin);
  31662. fprintf(stderr, "%s", zDbgBuf);
  31663. }else{
  31664. fprintf(stderr, "%s", zBuf);
  31665. }
  31666. #endif
  31667. }
  31668. /*
  31669. ** The following routine suspends the current thread for at least ms
  31670. ** milliseconds. This is equivalent to the Win32 Sleep() interface.
  31671. */
  31672. #if SQLITE_OS_WINRT
  31673. static HANDLE sleepObj = NULL;
  31674. #endif
  31675. SQLITE_API void sqlite3_win32_sleep(DWORD milliseconds){
  31676. #if SQLITE_OS_WINRT
  31677. if ( sleepObj==NULL ){
  31678. sleepObj = osCreateEventExW(NULL, NULL, CREATE_EVENT_MANUAL_RESET,
  31679. SYNCHRONIZE);
  31680. }
  31681. assert( sleepObj!=NULL );
  31682. osWaitForSingleObjectEx(sleepObj, milliseconds, FALSE);
  31683. #else
  31684. osSleep(milliseconds);
  31685. #endif
  31686. }
  31687. #if SQLITE_MAX_WORKER_THREADS>0 && !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && \
  31688. SQLITE_THREADSAFE>0
  31689. SQLITE_PRIVATE DWORD sqlite3Win32Wait(HANDLE hObject){
  31690. DWORD rc;
  31691. while( (rc = osWaitForSingleObjectEx(hObject, INFINITE,
  31692. TRUE))==WAIT_IO_COMPLETION ){}
  31693. return rc;
  31694. }
  31695. #endif
  31696. /*
  31697. ** Return true (non-zero) if we are running under WinNT, Win2K, WinXP,
  31698. ** or WinCE. Return false (zero) for Win95, Win98, or WinME.
  31699. **
  31700. ** Here is an interesting observation: Win95, Win98, and WinME lack
  31701. ** the LockFileEx() API. But we can still statically link against that
  31702. ** API as long as we don't call it when running Win95/98/ME. A call to
  31703. ** this routine is used to determine if the host is Win95/98/ME or
  31704. ** WinNT/2K/XP so that we will know whether or not we can safely call
  31705. ** the LockFileEx() API.
  31706. */
  31707. #if !defined(SQLITE_WIN32_GETVERSIONEX) || !SQLITE_WIN32_GETVERSIONEX
  31708. # define osIsNT() (1)
  31709. #elif SQLITE_OS_WINCE || SQLITE_OS_WINRT || !defined(SQLITE_WIN32_HAS_ANSI)
  31710. # define osIsNT() (1)
  31711. #elif !defined(SQLITE_WIN32_HAS_WIDE)
  31712. # define osIsNT() (0)
  31713. #else
  31714. # define osIsNT() ((sqlite3_os_type==2) || sqlite3_win32_is_nt())
  31715. #endif
  31716. /*
  31717. ** This function determines if the machine is running a version of Windows
  31718. ** based on the NT kernel.
  31719. */
  31720. SQLITE_API int sqlite3_win32_is_nt(void){
  31721. #if SQLITE_OS_WINRT
  31722. /*
  31723. ** NOTE: The WinRT sub-platform is always assumed to be based on the NT
  31724. ** kernel.
  31725. */
  31726. return 1;
  31727. #elif defined(SQLITE_WIN32_GETVERSIONEX) && SQLITE_WIN32_GETVERSIONEX
  31728. if( osInterlockedCompareExchange(&sqlite3_os_type, 0, 0)==0 ){
  31729. #if defined(SQLITE_WIN32_HAS_ANSI)
  31730. OSVERSIONINFOA sInfo;
  31731. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  31732. osGetVersionExA(&sInfo);
  31733. osInterlockedCompareExchange(&sqlite3_os_type,
  31734. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  31735. #elif defined(SQLITE_WIN32_HAS_WIDE)
  31736. OSVERSIONINFOW sInfo;
  31737. sInfo.dwOSVersionInfoSize = sizeof(sInfo);
  31738. osGetVersionExW(&sInfo);
  31739. osInterlockedCompareExchange(&sqlite3_os_type,
  31740. (sInfo.dwPlatformId == VER_PLATFORM_WIN32_NT) ? 2 : 1, 0);
  31741. #endif
  31742. }
  31743. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  31744. #elif SQLITE_TEST
  31745. return osInterlockedCompareExchange(&sqlite3_os_type, 2, 2)==2;
  31746. #else
  31747. /*
  31748. ** NOTE: All sub-platforms where the GetVersionEx[AW] functions are
  31749. ** deprecated are always assumed to be based on the NT kernel.
  31750. */
  31751. return 1;
  31752. #endif
  31753. }
  31754. #ifdef SQLITE_WIN32_MALLOC
  31755. /*
  31756. ** Allocate nBytes of memory.
  31757. */
  31758. static void *winMemMalloc(int nBytes){
  31759. HANDLE hHeap;
  31760. void *p;
  31761. winMemAssertMagic();
  31762. hHeap = winMemGetHeap();
  31763. assert( hHeap!=0 );
  31764. assert( hHeap!=INVALID_HANDLE_VALUE );
  31765. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31766. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  31767. #endif
  31768. assert( nBytes>=0 );
  31769. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  31770. if( !p ){
  31771. sqlite3_log(SQLITE_NOMEM, "failed to HeapAlloc %u bytes (%lu), heap=%p",
  31772. nBytes, osGetLastError(), (void*)hHeap);
  31773. }
  31774. return p;
  31775. }
  31776. /*
  31777. ** Free memory.
  31778. */
  31779. static void winMemFree(void *pPrior){
  31780. HANDLE hHeap;
  31781. winMemAssertMagic();
  31782. hHeap = winMemGetHeap();
  31783. assert( hHeap!=0 );
  31784. assert( hHeap!=INVALID_HANDLE_VALUE );
  31785. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31786. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  31787. #endif
  31788. if( !pPrior ) return; /* Passing NULL to HeapFree is undefined. */
  31789. if( !osHeapFree(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) ){
  31790. sqlite3_log(SQLITE_NOMEM, "failed to HeapFree block %p (%lu), heap=%p",
  31791. pPrior, osGetLastError(), (void*)hHeap);
  31792. }
  31793. }
  31794. /*
  31795. ** Change the size of an existing memory allocation
  31796. */
  31797. static void *winMemRealloc(void *pPrior, int nBytes){
  31798. HANDLE hHeap;
  31799. void *p;
  31800. winMemAssertMagic();
  31801. hHeap = winMemGetHeap();
  31802. assert( hHeap!=0 );
  31803. assert( hHeap!=INVALID_HANDLE_VALUE );
  31804. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31805. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior) );
  31806. #endif
  31807. assert( nBytes>=0 );
  31808. if( !pPrior ){
  31809. p = osHeapAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, (SIZE_T)nBytes);
  31810. }else{
  31811. p = osHeapReAlloc(hHeap, SQLITE_WIN32_HEAP_FLAGS, pPrior, (SIZE_T)nBytes);
  31812. }
  31813. if( !p ){
  31814. sqlite3_log(SQLITE_NOMEM, "failed to %s %u bytes (%lu), heap=%p",
  31815. pPrior ? "HeapReAlloc" : "HeapAlloc", nBytes, osGetLastError(),
  31816. (void*)hHeap);
  31817. }
  31818. return p;
  31819. }
  31820. /*
  31821. ** Return the size of an outstanding allocation, in bytes.
  31822. */
  31823. static int winMemSize(void *p){
  31824. HANDLE hHeap;
  31825. SIZE_T n;
  31826. winMemAssertMagic();
  31827. hHeap = winMemGetHeap();
  31828. assert( hHeap!=0 );
  31829. assert( hHeap!=INVALID_HANDLE_VALUE );
  31830. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31831. assert( osHeapValidate(hHeap, SQLITE_WIN32_HEAP_FLAGS, p) );
  31832. #endif
  31833. if( !p ) return 0;
  31834. n = osHeapSize(hHeap, SQLITE_WIN32_HEAP_FLAGS, p);
  31835. if( n==(SIZE_T)-1 ){
  31836. sqlite3_log(SQLITE_NOMEM, "failed to HeapSize block %p (%lu), heap=%p",
  31837. p, osGetLastError(), (void*)hHeap);
  31838. return 0;
  31839. }
  31840. return (int)n;
  31841. }
  31842. /*
  31843. ** Round up a request size to the next valid allocation size.
  31844. */
  31845. static int winMemRoundup(int n){
  31846. return n;
  31847. }
  31848. /*
  31849. ** Initialize this module.
  31850. */
  31851. static int winMemInit(void *pAppData){
  31852. winMemData *pWinMemData = (winMemData *)pAppData;
  31853. if( !pWinMemData ) return SQLITE_ERROR;
  31854. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  31855. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  31856. #if !SQLITE_OS_WINRT && SQLITE_WIN32_HEAP_CREATE
  31857. if( !pWinMemData->hHeap ){
  31858. DWORD dwInitialSize = SQLITE_WIN32_HEAP_INIT_SIZE;
  31859. DWORD dwMaximumSize = (DWORD)sqlite3GlobalConfig.nHeap;
  31860. if( dwMaximumSize==0 ){
  31861. dwMaximumSize = SQLITE_WIN32_HEAP_MAX_SIZE;
  31862. }else if( dwInitialSize>dwMaximumSize ){
  31863. dwInitialSize = dwMaximumSize;
  31864. }
  31865. pWinMemData->hHeap = osHeapCreate(SQLITE_WIN32_HEAP_FLAGS,
  31866. dwInitialSize, dwMaximumSize);
  31867. if( !pWinMemData->hHeap ){
  31868. sqlite3_log(SQLITE_NOMEM,
  31869. "failed to HeapCreate (%lu), flags=%u, initSize=%lu, maxSize=%lu",
  31870. osGetLastError(), SQLITE_WIN32_HEAP_FLAGS, dwInitialSize,
  31871. dwMaximumSize);
  31872. return SQLITE_NOMEM;
  31873. }
  31874. pWinMemData->bOwned = TRUE;
  31875. assert( pWinMemData->bOwned );
  31876. }
  31877. #else
  31878. pWinMemData->hHeap = osGetProcessHeap();
  31879. if( !pWinMemData->hHeap ){
  31880. sqlite3_log(SQLITE_NOMEM,
  31881. "failed to GetProcessHeap (%lu)", osGetLastError());
  31882. return SQLITE_NOMEM;
  31883. }
  31884. pWinMemData->bOwned = FALSE;
  31885. assert( !pWinMemData->bOwned );
  31886. #endif
  31887. assert( pWinMemData->hHeap!=0 );
  31888. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  31889. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31890. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  31891. #endif
  31892. return SQLITE_OK;
  31893. }
  31894. /*
  31895. ** Deinitialize this module.
  31896. */
  31897. static void winMemShutdown(void *pAppData){
  31898. winMemData *pWinMemData = (winMemData *)pAppData;
  31899. if( !pWinMemData ) return;
  31900. assert( pWinMemData->magic1==WINMEM_MAGIC1 );
  31901. assert( pWinMemData->magic2==WINMEM_MAGIC2 );
  31902. if( pWinMemData->hHeap ){
  31903. assert( pWinMemData->hHeap!=INVALID_HANDLE_VALUE );
  31904. #if !SQLITE_OS_WINRT && defined(SQLITE_WIN32_MALLOC_VALIDATE)
  31905. assert( osHeapValidate(pWinMemData->hHeap, SQLITE_WIN32_HEAP_FLAGS, NULL) );
  31906. #endif
  31907. if( pWinMemData->bOwned ){
  31908. if( !osHeapDestroy(pWinMemData->hHeap) ){
  31909. sqlite3_log(SQLITE_NOMEM, "failed to HeapDestroy (%lu), heap=%p",
  31910. osGetLastError(), (void*)pWinMemData->hHeap);
  31911. }
  31912. pWinMemData->bOwned = FALSE;
  31913. }
  31914. pWinMemData->hHeap = NULL;
  31915. }
  31916. }
  31917. /*
  31918. ** Populate the low-level memory allocation function pointers in
  31919. ** sqlite3GlobalConfig.m with pointers to the routines in this file. The
  31920. ** arguments specify the block of memory to manage.
  31921. **
  31922. ** This routine is only called by sqlite3_config(), and therefore
  31923. ** is not required to be threadsafe (it is not).
  31924. */
  31925. SQLITE_PRIVATE const sqlite3_mem_methods *sqlite3MemGetWin32(void){
  31926. static const sqlite3_mem_methods winMemMethods = {
  31927. winMemMalloc,
  31928. winMemFree,
  31929. winMemRealloc,
  31930. winMemSize,
  31931. winMemRoundup,
  31932. winMemInit,
  31933. winMemShutdown,
  31934. &win_mem_data
  31935. };
  31936. return &winMemMethods;
  31937. }
  31938. SQLITE_PRIVATE void sqlite3MemSetDefault(void){
  31939. sqlite3_config(SQLITE_CONFIG_MALLOC, sqlite3MemGetWin32());
  31940. }
  31941. #endif /* SQLITE_WIN32_MALLOC */
  31942. /*
  31943. ** Convert a UTF-8 string to Microsoft Unicode (UTF-16?).
  31944. **
  31945. ** Space to hold the returned string is obtained from malloc.
  31946. */
  31947. static LPWSTR winUtf8ToUnicode(const char *zFilename){
  31948. int nChar;
  31949. LPWSTR zWideFilename;
  31950. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, NULL, 0);
  31951. if( nChar==0 ){
  31952. return 0;
  31953. }
  31954. zWideFilename = sqlite3MallocZero( nChar*sizeof(zWideFilename[0]) );
  31955. if( zWideFilename==0 ){
  31956. return 0;
  31957. }
  31958. nChar = osMultiByteToWideChar(CP_UTF8, 0, zFilename, -1, zWideFilename,
  31959. nChar);
  31960. if( nChar==0 ){
  31961. sqlite3_free(zWideFilename);
  31962. zWideFilename = 0;
  31963. }
  31964. return zWideFilename;
  31965. }
  31966. /*
  31967. ** Convert Microsoft Unicode to UTF-8. Space to hold the returned string is
  31968. ** obtained from sqlite3_malloc().
  31969. */
  31970. static char *winUnicodeToUtf8(LPCWSTR zWideFilename){
  31971. int nByte;
  31972. char *zFilename;
  31973. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, 0, 0, 0, 0);
  31974. if( nByte == 0 ){
  31975. return 0;
  31976. }
  31977. zFilename = sqlite3MallocZero( nByte );
  31978. if( zFilename==0 ){
  31979. return 0;
  31980. }
  31981. nByte = osWideCharToMultiByte(CP_UTF8, 0, zWideFilename, -1, zFilename, nByte,
  31982. 0, 0);
  31983. if( nByte == 0 ){
  31984. sqlite3_free(zFilename);
  31985. zFilename = 0;
  31986. }
  31987. return zFilename;
  31988. }
  31989. /*
  31990. ** Convert an ANSI string to Microsoft Unicode, based on the
  31991. ** current codepage settings for file apis.
  31992. **
  31993. ** Space to hold the returned string is obtained
  31994. ** from sqlite3_malloc.
  31995. */
  31996. static LPWSTR winMbcsToUnicode(const char *zFilename){
  31997. int nByte;
  31998. LPWSTR zMbcsFilename;
  31999. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  32000. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, NULL,
  32001. 0)*sizeof(WCHAR);
  32002. if( nByte==0 ){
  32003. return 0;
  32004. }
  32005. zMbcsFilename = sqlite3MallocZero( nByte*sizeof(zMbcsFilename[0]) );
  32006. if( zMbcsFilename==0 ){
  32007. return 0;
  32008. }
  32009. nByte = osMultiByteToWideChar(codepage, 0, zFilename, -1, zMbcsFilename,
  32010. nByte);
  32011. if( nByte==0 ){
  32012. sqlite3_free(zMbcsFilename);
  32013. zMbcsFilename = 0;
  32014. }
  32015. return zMbcsFilename;
  32016. }
  32017. /*
  32018. ** Convert Microsoft Unicode to multi-byte character string, based on the
  32019. ** user's ANSI codepage.
  32020. **
  32021. ** Space to hold the returned string is obtained from
  32022. ** sqlite3_malloc().
  32023. */
  32024. static char *winUnicodeToMbcs(LPCWSTR zWideFilename){
  32025. int nByte;
  32026. char *zFilename;
  32027. int codepage = osAreFileApisANSI() ? CP_ACP : CP_OEMCP;
  32028. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, 0, 0, 0, 0);
  32029. if( nByte == 0 ){
  32030. return 0;
  32031. }
  32032. zFilename = sqlite3MallocZero( nByte );
  32033. if( zFilename==0 ){
  32034. return 0;
  32035. }
  32036. nByte = osWideCharToMultiByte(codepage, 0, zWideFilename, -1, zFilename,
  32037. nByte, 0, 0);
  32038. if( nByte == 0 ){
  32039. sqlite3_free(zFilename);
  32040. zFilename = 0;
  32041. }
  32042. return zFilename;
  32043. }
  32044. /*
  32045. ** Convert multibyte character string to UTF-8. Space to hold the
  32046. ** returned string is obtained from sqlite3_malloc().
  32047. */
  32048. SQLITE_API char *sqlite3_win32_mbcs_to_utf8(const char *zFilename){
  32049. char *zFilenameUtf8;
  32050. LPWSTR zTmpWide;
  32051. zTmpWide = winMbcsToUnicode(zFilename);
  32052. if( zTmpWide==0 ){
  32053. return 0;
  32054. }
  32055. zFilenameUtf8 = winUnicodeToUtf8(zTmpWide);
  32056. sqlite3_free(zTmpWide);
  32057. return zFilenameUtf8;
  32058. }
  32059. /*
  32060. ** Convert UTF-8 to multibyte character string. Space to hold the
  32061. ** returned string is obtained from sqlite3_malloc().
  32062. */
  32063. SQLITE_API char *sqlite3_win32_utf8_to_mbcs(const char *zFilename){
  32064. char *zFilenameMbcs;
  32065. LPWSTR zTmpWide;
  32066. zTmpWide = winUtf8ToUnicode(zFilename);
  32067. if( zTmpWide==0 ){
  32068. return 0;
  32069. }
  32070. zFilenameMbcs = winUnicodeToMbcs(zTmpWide);
  32071. sqlite3_free(zTmpWide);
  32072. return zFilenameMbcs;
  32073. }
  32074. /*
  32075. ** This function sets the data directory or the temporary directory based on
  32076. ** the provided arguments. The type argument must be 1 in order to set the
  32077. ** data directory or 2 in order to set the temporary directory. The zValue
  32078. ** argument is the name of the directory to use. The return value will be
  32079. ** SQLITE_OK if successful.
  32080. */
  32081. SQLITE_API int sqlite3_win32_set_directory(DWORD type, LPCWSTR zValue){
  32082. char **ppDirectory = 0;
  32083. #ifndef SQLITE_OMIT_AUTOINIT
  32084. int rc = sqlite3_initialize();
  32085. if( rc ) return rc;
  32086. #endif
  32087. if( type==SQLITE_WIN32_DATA_DIRECTORY_TYPE ){
  32088. ppDirectory = &sqlite3_data_directory;
  32089. }else if( type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE ){
  32090. ppDirectory = &sqlite3_temp_directory;
  32091. }
  32092. assert( !ppDirectory || type==SQLITE_WIN32_DATA_DIRECTORY_TYPE
  32093. || type==SQLITE_WIN32_TEMP_DIRECTORY_TYPE
  32094. );
  32095. assert( !ppDirectory || sqlite3MemdebugHasType(*ppDirectory, MEMTYPE_HEAP) );
  32096. if( ppDirectory ){
  32097. char *zValueUtf8 = 0;
  32098. if( zValue && zValue[0] ){
  32099. zValueUtf8 = winUnicodeToUtf8(zValue);
  32100. if ( zValueUtf8==0 ){
  32101. return SQLITE_NOMEM;
  32102. }
  32103. }
  32104. sqlite3_free(*ppDirectory);
  32105. *ppDirectory = zValueUtf8;
  32106. return SQLITE_OK;
  32107. }
  32108. return SQLITE_ERROR;
  32109. }
  32110. /*
  32111. ** The return value of winGetLastErrorMsg
  32112. ** is zero if the error message fits in the buffer, or non-zero
  32113. ** otherwise (if the message was truncated).
  32114. */
  32115. static int winGetLastErrorMsg(DWORD lastErrno, int nBuf, char *zBuf){
  32116. /* FormatMessage returns 0 on failure. Otherwise it
  32117. ** returns the number of TCHARs written to the output
  32118. ** buffer, excluding the terminating null char.
  32119. */
  32120. DWORD dwLen = 0;
  32121. char *zOut = 0;
  32122. if( osIsNT() ){
  32123. #if SQLITE_OS_WINRT
  32124. WCHAR zTempWide[SQLITE_WIN32_MAX_ERRMSG_CHARS+1];
  32125. dwLen = osFormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM |
  32126. FORMAT_MESSAGE_IGNORE_INSERTS,
  32127. NULL,
  32128. lastErrno,
  32129. 0,
  32130. zTempWide,
  32131. SQLITE_WIN32_MAX_ERRMSG_CHARS,
  32132. 0);
  32133. #else
  32134. LPWSTR zTempWide = NULL;
  32135. dwLen = osFormatMessageW(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  32136. FORMAT_MESSAGE_FROM_SYSTEM |
  32137. FORMAT_MESSAGE_IGNORE_INSERTS,
  32138. NULL,
  32139. lastErrno,
  32140. 0,
  32141. (LPWSTR) &zTempWide,
  32142. 0,
  32143. 0);
  32144. #endif
  32145. if( dwLen > 0 ){
  32146. /* allocate a buffer and convert to UTF8 */
  32147. sqlite3BeginBenignMalloc();
  32148. zOut = winUnicodeToUtf8(zTempWide);
  32149. sqlite3EndBenignMalloc();
  32150. #if !SQLITE_OS_WINRT
  32151. /* free the system buffer allocated by FormatMessage */
  32152. osLocalFree(zTempWide);
  32153. #endif
  32154. }
  32155. }
  32156. #ifdef SQLITE_WIN32_HAS_ANSI
  32157. else{
  32158. char *zTemp = NULL;
  32159. dwLen = osFormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
  32160. FORMAT_MESSAGE_FROM_SYSTEM |
  32161. FORMAT_MESSAGE_IGNORE_INSERTS,
  32162. NULL,
  32163. lastErrno,
  32164. 0,
  32165. (LPSTR) &zTemp,
  32166. 0,
  32167. 0);
  32168. if( dwLen > 0 ){
  32169. /* allocate a buffer and convert to UTF8 */
  32170. sqlite3BeginBenignMalloc();
  32171. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  32172. sqlite3EndBenignMalloc();
  32173. /* free the system buffer allocated by FormatMessage */
  32174. osLocalFree(zTemp);
  32175. }
  32176. }
  32177. #endif
  32178. if( 0 == dwLen ){
  32179. sqlite3_snprintf(nBuf, zBuf, "OsError 0x%lx (%lu)", lastErrno, lastErrno);
  32180. }else{
  32181. /* copy a maximum of nBuf chars to output buffer */
  32182. sqlite3_snprintf(nBuf, zBuf, "%s", zOut);
  32183. /* free the UTF8 buffer */
  32184. sqlite3_free(zOut);
  32185. }
  32186. return 0;
  32187. }
  32188. /*
  32189. **
  32190. ** This function - winLogErrorAtLine() - is only ever called via the macro
  32191. ** winLogError().
  32192. **
  32193. ** This routine is invoked after an error occurs in an OS function.
  32194. ** It logs a message using sqlite3_log() containing the current value of
  32195. ** error code and, if possible, the human-readable equivalent from
  32196. ** FormatMessage.
  32197. **
  32198. ** The first argument passed to the macro should be the error code that
  32199. ** will be returned to SQLite (e.g. SQLITE_IOERR_DELETE, SQLITE_CANTOPEN).
  32200. ** The two subsequent arguments should be the name of the OS function that
  32201. ** failed and the associated file-system path, if any.
  32202. */
  32203. #define winLogError(a,b,c,d) winLogErrorAtLine(a,b,c,d,__LINE__)
  32204. static int winLogErrorAtLine(
  32205. int errcode, /* SQLite error code */
  32206. DWORD lastErrno, /* Win32 last error */
  32207. const char *zFunc, /* Name of OS function that failed */
  32208. const char *zPath, /* File path associated with error */
  32209. int iLine /* Source line number where error occurred */
  32210. ){
  32211. char zMsg[500]; /* Human readable error text */
  32212. int i; /* Loop counter */
  32213. zMsg[0] = 0;
  32214. winGetLastErrorMsg(lastErrno, sizeof(zMsg), zMsg);
  32215. assert( errcode!=SQLITE_OK );
  32216. if( zPath==0 ) zPath = "";
  32217. for(i=0; zMsg[i] && zMsg[i]!='\r' && zMsg[i]!='\n'; i++){}
  32218. zMsg[i] = 0;
  32219. sqlite3_log(errcode,
  32220. "os_win.c:%d: (%lu) %s(%s) - %s",
  32221. iLine, lastErrno, zFunc, zPath, zMsg
  32222. );
  32223. return errcode;
  32224. }
  32225. /*
  32226. ** The number of times that a ReadFile(), WriteFile(), and DeleteFile()
  32227. ** will be retried following a locking error - probably caused by
  32228. ** antivirus software. Also the initial delay before the first retry.
  32229. ** The delay increases linearly with each retry.
  32230. */
  32231. #ifndef SQLITE_WIN32_IOERR_RETRY
  32232. # define SQLITE_WIN32_IOERR_RETRY 10
  32233. #endif
  32234. #ifndef SQLITE_WIN32_IOERR_RETRY_DELAY
  32235. # define SQLITE_WIN32_IOERR_RETRY_DELAY 25
  32236. #endif
  32237. static int winIoerrRetry = SQLITE_WIN32_IOERR_RETRY;
  32238. static int winIoerrRetryDelay = SQLITE_WIN32_IOERR_RETRY_DELAY;
  32239. /*
  32240. ** The "winIoerrCanRetry1" macro is used to determine if a particular I/O
  32241. ** error code obtained via GetLastError() is eligible to be retried. It
  32242. ** must accept the error code DWORD as its only argument and should return
  32243. ** non-zero if the error code is transient in nature and the operation
  32244. ** responsible for generating the original error might succeed upon being
  32245. ** retried. The argument to this macro should be a variable.
  32246. **
  32247. ** Additionally, a macro named "winIoerrCanRetry2" may be defined. If it
  32248. ** is defined, it will be consulted only when the macro "winIoerrCanRetry1"
  32249. ** returns zero. The "winIoerrCanRetry2" macro is completely optional and
  32250. ** may be used to include additional error codes in the set that should
  32251. ** result in the failing I/O operation being retried by the caller. If
  32252. ** defined, the "winIoerrCanRetry2" macro must exhibit external semantics
  32253. ** identical to those of the "winIoerrCanRetry1" macro.
  32254. */
  32255. #if !defined(winIoerrCanRetry1)
  32256. #define winIoerrCanRetry1(a) (((a)==ERROR_ACCESS_DENIED) || \
  32257. ((a)==ERROR_SHARING_VIOLATION) || \
  32258. ((a)==ERROR_LOCK_VIOLATION) || \
  32259. ((a)==ERROR_DEV_NOT_EXIST) || \
  32260. ((a)==ERROR_NETNAME_DELETED) || \
  32261. ((a)==ERROR_SEM_TIMEOUT) || \
  32262. ((a)==ERROR_NETWORK_UNREACHABLE))
  32263. #endif
  32264. /*
  32265. ** If a ReadFile() or WriteFile() error occurs, invoke this routine
  32266. ** to see if it should be retried. Return TRUE to retry. Return FALSE
  32267. ** to give up with an error.
  32268. */
  32269. static int winRetryIoerr(int *pnRetry, DWORD *pError){
  32270. DWORD e = osGetLastError();
  32271. if( *pnRetry>=winIoerrRetry ){
  32272. if( pError ){
  32273. *pError = e;
  32274. }
  32275. return 0;
  32276. }
  32277. if( winIoerrCanRetry1(e) ){
  32278. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  32279. ++*pnRetry;
  32280. return 1;
  32281. }
  32282. #if defined(winIoerrCanRetry2)
  32283. else if( winIoerrCanRetry2(e) ){
  32284. sqlite3_win32_sleep(winIoerrRetryDelay*(1+*pnRetry));
  32285. ++*pnRetry;
  32286. return 1;
  32287. }
  32288. #endif
  32289. if( pError ){
  32290. *pError = e;
  32291. }
  32292. return 0;
  32293. }
  32294. /*
  32295. ** Log a I/O error retry episode.
  32296. */
  32297. static void winLogIoerr(int nRetry){
  32298. if( nRetry ){
  32299. sqlite3_log(SQLITE_IOERR,
  32300. "delayed %dms for lock/sharing conflict",
  32301. winIoerrRetryDelay*nRetry*(nRetry+1)/2
  32302. );
  32303. }
  32304. }
  32305. #if SQLITE_OS_WINCE
  32306. /*************************************************************************
  32307. ** This section contains code for WinCE only.
  32308. */
  32309. #if !defined(SQLITE_MSVC_LOCALTIME_API) || !SQLITE_MSVC_LOCALTIME_API
  32310. /*
  32311. ** The MSVC CRT on Windows CE may not have a localtime() function. So
  32312. ** create a substitute.
  32313. */
  32314. /* #include <time.h> */
  32315. struct tm *__cdecl localtime(const time_t *t)
  32316. {
  32317. static struct tm y;
  32318. FILETIME uTm, lTm;
  32319. SYSTEMTIME pTm;
  32320. sqlite3_int64 t64;
  32321. t64 = *t;
  32322. t64 = (t64 + 11644473600)*10000000;
  32323. uTm.dwLowDateTime = (DWORD)(t64 & 0xFFFFFFFF);
  32324. uTm.dwHighDateTime= (DWORD)(t64 >> 32);
  32325. osFileTimeToLocalFileTime(&uTm,&lTm);
  32326. osFileTimeToSystemTime(&lTm,&pTm);
  32327. y.tm_year = pTm.wYear - 1900;
  32328. y.tm_mon = pTm.wMonth - 1;
  32329. y.tm_wday = pTm.wDayOfWeek;
  32330. y.tm_mday = pTm.wDay;
  32331. y.tm_hour = pTm.wHour;
  32332. y.tm_min = pTm.wMinute;
  32333. y.tm_sec = pTm.wSecond;
  32334. return &y;
  32335. }
  32336. #endif
  32337. #define HANDLE_TO_WINFILE(a) (winFile*)&((char*)a)[-(int)offsetof(winFile,h)]
  32338. /*
  32339. ** Acquire a lock on the handle h
  32340. */
  32341. static void winceMutexAcquire(HANDLE h){
  32342. DWORD dwErr;
  32343. do {
  32344. dwErr = osWaitForSingleObject(h, INFINITE);
  32345. } while (dwErr != WAIT_OBJECT_0 && dwErr != WAIT_ABANDONED);
  32346. }
  32347. /*
  32348. ** Release a lock acquired by winceMutexAcquire()
  32349. */
  32350. #define winceMutexRelease(h) ReleaseMutex(h)
  32351. /*
  32352. ** Create the mutex and shared memory used for locking in the file
  32353. ** descriptor pFile
  32354. */
  32355. static int winceCreateLock(const char *zFilename, winFile *pFile){
  32356. LPWSTR zTok;
  32357. LPWSTR zName;
  32358. DWORD lastErrno;
  32359. BOOL bLogged = FALSE;
  32360. BOOL bInit = TRUE;
  32361. zName = winUtf8ToUnicode(zFilename);
  32362. if( zName==0 ){
  32363. /* out of memory */
  32364. return SQLITE_IOERR_NOMEM;
  32365. }
  32366. /* Initialize the local lockdata */
  32367. memset(&pFile->local, 0, sizeof(pFile->local));
  32368. /* Replace the backslashes from the filename and lowercase it
  32369. ** to derive a mutex name. */
  32370. zTok = osCharLowerW(zName);
  32371. for (;*zTok;zTok++){
  32372. if (*zTok == '\\') *zTok = '_';
  32373. }
  32374. /* Create/open the named mutex */
  32375. pFile->hMutex = osCreateMutexW(NULL, FALSE, zName);
  32376. if (!pFile->hMutex){
  32377. pFile->lastErrno = osGetLastError();
  32378. sqlite3_free(zName);
  32379. return winLogError(SQLITE_IOERR, pFile->lastErrno,
  32380. "winceCreateLock1", zFilename);
  32381. }
  32382. /* Acquire the mutex before continuing */
  32383. winceMutexAcquire(pFile->hMutex);
  32384. /* Since the names of named mutexes, semaphores, file mappings etc are
  32385. ** case-sensitive, take advantage of that by uppercasing the mutex name
  32386. ** and using that as the shared filemapping name.
  32387. */
  32388. osCharUpperW(zName);
  32389. pFile->hShared = osCreateFileMappingW(INVALID_HANDLE_VALUE, NULL,
  32390. PAGE_READWRITE, 0, sizeof(winceLock),
  32391. zName);
  32392. /* Set a flag that indicates we're the first to create the memory so it
  32393. ** must be zero-initialized */
  32394. lastErrno = osGetLastError();
  32395. if (lastErrno == ERROR_ALREADY_EXISTS){
  32396. bInit = FALSE;
  32397. }
  32398. sqlite3_free(zName);
  32399. /* If we succeeded in making the shared memory handle, map it. */
  32400. if( pFile->hShared ){
  32401. pFile->shared = (winceLock*)osMapViewOfFile(pFile->hShared,
  32402. FILE_MAP_READ|FILE_MAP_WRITE, 0, 0, sizeof(winceLock));
  32403. /* If mapping failed, close the shared memory handle and erase it */
  32404. if( !pFile->shared ){
  32405. pFile->lastErrno = osGetLastError();
  32406. winLogError(SQLITE_IOERR, pFile->lastErrno,
  32407. "winceCreateLock2", zFilename);
  32408. bLogged = TRUE;
  32409. osCloseHandle(pFile->hShared);
  32410. pFile->hShared = NULL;
  32411. }
  32412. }
  32413. /* If shared memory could not be created, then close the mutex and fail */
  32414. if( pFile->hShared==NULL ){
  32415. if( !bLogged ){
  32416. pFile->lastErrno = lastErrno;
  32417. winLogError(SQLITE_IOERR, pFile->lastErrno,
  32418. "winceCreateLock3", zFilename);
  32419. bLogged = TRUE;
  32420. }
  32421. winceMutexRelease(pFile->hMutex);
  32422. osCloseHandle(pFile->hMutex);
  32423. pFile->hMutex = NULL;
  32424. return SQLITE_IOERR;
  32425. }
  32426. /* Initialize the shared memory if we're supposed to */
  32427. if( bInit ){
  32428. memset(pFile->shared, 0, sizeof(winceLock));
  32429. }
  32430. winceMutexRelease(pFile->hMutex);
  32431. return SQLITE_OK;
  32432. }
  32433. /*
  32434. ** Destroy the part of winFile that deals with wince locks
  32435. */
  32436. static void winceDestroyLock(winFile *pFile){
  32437. if (pFile->hMutex){
  32438. /* Acquire the mutex */
  32439. winceMutexAcquire(pFile->hMutex);
  32440. /* The following blocks should probably assert in debug mode, but they
  32441. are to cleanup in case any locks remained open */
  32442. if (pFile->local.nReaders){
  32443. pFile->shared->nReaders --;
  32444. }
  32445. if (pFile->local.bReserved){
  32446. pFile->shared->bReserved = FALSE;
  32447. }
  32448. if (pFile->local.bPending){
  32449. pFile->shared->bPending = FALSE;
  32450. }
  32451. if (pFile->local.bExclusive){
  32452. pFile->shared->bExclusive = FALSE;
  32453. }
  32454. /* De-reference and close our copy of the shared memory handle */
  32455. osUnmapViewOfFile(pFile->shared);
  32456. osCloseHandle(pFile->hShared);
  32457. /* Done with the mutex */
  32458. winceMutexRelease(pFile->hMutex);
  32459. osCloseHandle(pFile->hMutex);
  32460. pFile->hMutex = NULL;
  32461. }
  32462. }
  32463. /*
  32464. ** An implementation of the LockFile() API of Windows for CE
  32465. */
  32466. static BOOL winceLockFile(
  32467. LPHANDLE phFile,
  32468. DWORD dwFileOffsetLow,
  32469. DWORD dwFileOffsetHigh,
  32470. DWORD nNumberOfBytesToLockLow,
  32471. DWORD nNumberOfBytesToLockHigh
  32472. ){
  32473. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  32474. BOOL bReturn = FALSE;
  32475. UNUSED_PARAMETER(dwFileOffsetHigh);
  32476. UNUSED_PARAMETER(nNumberOfBytesToLockHigh);
  32477. if (!pFile->hMutex) return TRUE;
  32478. winceMutexAcquire(pFile->hMutex);
  32479. /* Wanting an exclusive lock? */
  32480. if (dwFileOffsetLow == (DWORD)SHARED_FIRST
  32481. && nNumberOfBytesToLockLow == (DWORD)SHARED_SIZE){
  32482. if (pFile->shared->nReaders == 0 && pFile->shared->bExclusive == 0){
  32483. pFile->shared->bExclusive = TRUE;
  32484. pFile->local.bExclusive = TRUE;
  32485. bReturn = TRUE;
  32486. }
  32487. }
  32488. /* Want a read-only lock? */
  32489. else if (dwFileOffsetLow == (DWORD)SHARED_FIRST &&
  32490. nNumberOfBytesToLockLow == 1){
  32491. if (pFile->shared->bExclusive == 0){
  32492. pFile->local.nReaders ++;
  32493. if (pFile->local.nReaders == 1){
  32494. pFile->shared->nReaders ++;
  32495. }
  32496. bReturn = TRUE;
  32497. }
  32498. }
  32499. /* Want a pending lock? */
  32500. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  32501. && nNumberOfBytesToLockLow == 1){
  32502. /* If no pending lock has been acquired, then acquire it */
  32503. if (pFile->shared->bPending == 0) {
  32504. pFile->shared->bPending = TRUE;
  32505. pFile->local.bPending = TRUE;
  32506. bReturn = TRUE;
  32507. }
  32508. }
  32509. /* Want a reserved lock? */
  32510. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  32511. && nNumberOfBytesToLockLow == 1){
  32512. if (pFile->shared->bReserved == 0) {
  32513. pFile->shared->bReserved = TRUE;
  32514. pFile->local.bReserved = TRUE;
  32515. bReturn = TRUE;
  32516. }
  32517. }
  32518. winceMutexRelease(pFile->hMutex);
  32519. return bReturn;
  32520. }
  32521. /*
  32522. ** An implementation of the UnlockFile API of Windows for CE
  32523. */
  32524. static BOOL winceUnlockFile(
  32525. LPHANDLE phFile,
  32526. DWORD dwFileOffsetLow,
  32527. DWORD dwFileOffsetHigh,
  32528. DWORD nNumberOfBytesToUnlockLow,
  32529. DWORD nNumberOfBytesToUnlockHigh
  32530. ){
  32531. winFile *pFile = HANDLE_TO_WINFILE(phFile);
  32532. BOOL bReturn = FALSE;
  32533. UNUSED_PARAMETER(dwFileOffsetHigh);
  32534. UNUSED_PARAMETER(nNumberOfBytesToUnlockHigh);
  32535. if (!pFile->hMutex) return TRUE;
  32536. winceMutexAcquire(pFile->hMutex);
  32537. /* Releasing a reader lock or an exclusive lock */
  32538. if (dwFileOffsetLow == (DWORD)SHARED_FIRST){
  32539. /* Did we have an exclusive lock? */
  32540. if (pFile->local.bExclusive){
  32541. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE);
  32542. pFile->local.bExclusive = FALSE;
  32543. pFile->shared->bExclusive = FALSE;
  32544. bReturn = TRUE;
  32545. }
  32546. /* Did we just have a reader lock? */
  32547. else if (pFile->local.nReaders){
  32548. assert(nNumberOfBytesToUnlockLow == (DWORD)SHARED_SIZE
  32549. || nNumberOfBytesToUnlockLow == 1);
  32550. pFile->local.nReaders --;
  32551. if (pFile->local.nReaders == 0)
  32552. {
  32553. pFile->shared->nReaders --;
  32554. }
  32555. bReturn = TRUE;
  32556. }
  32557. }
  32558. /* Releasing a pending lock */
  32559. else if (dwFileOffsetLow == (DWORD)PENDING_BYTE
  32560. && nNumberOfBytesToUnlockLow == 1){
  32561. if (pFile->local.bPending){
  32562. pFile->local.bPending = FALSE;
  32563. pFile->shared->bPending = FALSE;
  32564. bReturn = TRUE;
  32565. }
  32566. }
  32567. /* Releasing a reserved lock */
  32568. else if (dwFileOffsetLow == (DWORD)RESERVED_BYTE
  32569. && nNumberOfBytesToUnlockLow == 1){
  32570. if (pFile->local.bReserved) {
  32571. pFile->local.bReserved = FALSE;
  32572. pFile->shared->bReserved = FALSE;
  32573. bReturn = TRUE;
  32574. }
  32575. }
  32576. winceMutexRelease(pFile->hMutex);
  32577. return bReturn;
  32578. }
  32579. /*
  32580. ** End of the special code for wince
  32581. *****************************************************************************/
  32582. #endif /* SQLITE_OS_WINCE */
  32583. /*
  32584. ** Lock a file region.
  32585. */
  32586. static BOOL winLockFile(
  32587. LPHANDLE phFile,
  32588. DWORD flags,
  32589. DWORD offsetLow,
  32590. DWORD offsetHigh,
  32591. DWORD numBytesLow,
  32592. DWORD numBytesHigh
  32593. ){
  32594. #if SQLITE_OS_WINCE
  32595. /*
  32596. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  32597. ** API LockFile.
  32598. */
  32599. return winceLockFile(phFile, offsetLow, offsetHigh,
  32600. numBytesLow, numBytesHigh);
  32601. #else
  32602. if( osIsNT() ){
  32603. OVERLAPPED ovlp;
  32604. memset(&ovlp, 0, sizeof(OVERLAPPED));
  32605. ovlp.Offset = offsetLow;
  32606. ovlp.OffsetHigh = offsetHigh;
  32607. return osLockFileEx(*phFile, flags, 0, numBytesLow, numBytesHigh, &ovlp);
  32608. }else{
  32609. return osLockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  32610. numBytesHigh);
  32611. }
  32612. #endif
  32613. }
  32614. /*
  32615. ** Unlock a file region.
  32616. */
  32617. static BOOL winUnlockFile(
  32618. LPHANDLE phFile,
  32619. DWORD offsetLow,
  32620. DWORD offsetHigh,
  32621. DWORD numBytesLow,
  32622. DWORD numBytesHigh
  32623. ){
  32624. #if SQLITE_OS_WINCE
  32625. /*
  32626. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  32627. ** API UnlockFile.
  32628. */
  32629. return winceUnlockFile(phFile, offsetLow, offsetHigh,
  32630. numBytesLow, numBytesHigh);
  32631. #else
  32632. if( osIsNT() ){
  32633. OVERLAPPED ovlp;
  32634. memset(&ovlp, 0, sizeof(OVERLAPPED));
  32635. ovlp.Offset = offsetLow;
  32636. ovlp.OffsetHigh = offsetHigh;
  32637. return osUnlockFileEx(*phFile, 0, numBytesLow, numBytesHigh, &ovlp);
  32638. }else{
  32639. return osUnlockFile(*phFile, offsetLow, offsetHigh, numBytesLow,
  32640. numBytesHigh);
  32641. }
  32642. #endif
  32643. }
  32644. /*****************************************************************************
  32645. ** The next group of routines implement the I/O methods specified
  32646. ** by the sqlite3_io_methods object.
  32647. ******************************************************************************/
  32648. /*
  32649. ** Some Microsoft compilers lack this definition.
  32650. */
  32651. #ifndef INVALID_SET_FILE_POINTER
  32652. # define INVALID_SET_FILE_POINTER ((DWORD)-1)
  32653. #endif
  32654. /*
  32655. ** Move the current position of the file handle passed as the first
  32656. ** argument to offset iOffset within the file. If successful, return 0.
  32657. ** Otherwise, set pFile->lastErrno and return non-zero.
  32658. */
  32659. static int winSeekFile(winFile *pFile, sqlite3_int64 iOffset){
  32660. #if !SQLITE_OS_WINRT
  32661. LONG upperBits; /* Most sig. 32 bits of new offset */
  32662. LONG lowerBits; /* Least sig. 32 bits of new offset */
  32663. DWORD dwRet; /* Value returned by SetFilePointer() */
  32664. DWORD lastErrno; /* Value returned by GetLastError() */
  32665. OSTRACE(("SEEK file=%p, offset=%lld\n", pFile->h, iOffset));
  32666. upperBits = (LONG)((iOffset>>32) & 0x7fffffff);
  32667. lowerBits = (LONG)(iOffset & 0xffffffff);
  32668. /* API oddity: If successful, SetFilePointer() returns a dword
  32669. ** containing the lower 32-bits of the new file-offset. Or, if it fails,
  32670. ** it returns INVALID_SET_FILE_POINTER. However according to MSDN,
  32671. ** INVALID_SET_FILE_POINTER may also be a valid new offset. So to determine
  32672. ** whether an error has actually occurred, it is also necessary to call
  32673. ** GetLastError().
  32674. */
  32675. dwRet = osSetFilePointer(pFile->h, lowerBits, &upperBits, FILE_BEGIN);
  32676. if( (dwRet==INVALID_SET_FILE_POINTER
  32677. && ((lastErrno = osGetLastError())!=NO_ERROR)) ){
  32678. pFile->lastErrno = lastErrno;
  32679. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  32680. "winSeekFile", pFile->zPath);
  32681. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  32682. return 1;
  32683. }
  32684. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  32685. return 0;
  32686. #else
  32687. /*
  32688. ** Same as above, except that this implementation works for WinRT.
  32689. */
  32690. LARGE_INTEGER x; /* The new offset */
  32691. BOOL bRet; /* Value returned by SetFilePointerEx() */
  32692. x.QuadPart = iOffset;
  32693. bRet = osSetFilePointerEx(pFile->h, x, 0, FILE_BEGIN);
  32694. if(!bRet){
  32695. pFile->lastErrno = osGetLastError();
  32696. winLogError(SQLITE_IOERR_SEEK, pFile->lastErrno,
  32697. "winSeekFile", pFile->zPath);
  32698. OSTRACE(("SEEK file=%p, rc=SQLITE_IOERR_SEEK\n", pFile->h));
  32699. return 1;
  32700. }
  32701. OSTRACE(("SEEK file=%p, rc=SQLITE_OK\n", pFile->h));
  32702. return 0;
  32703. #endif
  32704. }
  32705. #if SQLITE_MAX_MMAP_SIZE>0
  32706. /* Forward references to VFS helper methods used for memory mapped files */
  32707. static int winMapfile(winFile*, sqlite3_int64);
  32708. static int winUnmapfile(winFile*);
  32709. #endif
  32710. /*
  32711. ** Close a file.
  32712. **
  32713. ** It is reported that an attempt to close a handle might sometimes
  32714. ** fail. This is a very unreasonable result, but Windows is notorious
  32715. ** for being unreasonable so I do not doubt that it might happen. If
  32716. ** the close fails, we pause for 100 milliseconds and try again. As
  32717. ** many as MX_CLOSE_ATTEMPT attempts to close the handle are made before
  32718. ** giving up and returning an error.
  32719. */
  32720. #define MX_CLOSE_ATTEMPT 3
  32721. static int winClose(sqlite3_file *id){
  32722. int rc, cnt = 0;
  32723. winFile *pFile = (winFile*)id;
  32724. assert( id!=0 );
  32725. #ifndef SQLITE_OMIT_WAL
  32726. assert( pFile->pShm==0 );
  32727. #endif
  32728. assert( pFile->h!=NULL && pFile->h!=INVALID_HANDLE_VALUE );
  32729. OSTRACE(("CLOSE file=%p\n", pFile->h));
  32730. #if SQLITE_MAX_MMAP_SIZE>0
  32731. winUnmapfile(pFile);
  32732. #endif
  32733. do{
  32734. rc = osCloseHandle(pFile->h);
  32735. /* SimulateIOError( rc=0; cnt=MX_CLOSE_ATTEMPT; ); */
  32736. }while( rc==0 && ++cnt < MX_CLOSE_ATTEMPT && (sqlite3_win32_sleep(100), 1) );
  32737. #if SQLITE_OS_WINCE
  32738. #define WINCE_DELETION_ATTEMPTS 3
  32739. winceDestroyLock(pFile);
  32740. if( pFile->zDeleteOnClose ){
  32741. int cnt = 0;
  32742. while(
  32743. osDeleteFileW(pFile->zDeleteOnClose)==0
  32744. && osGetFileAttributesW(pFile->zDeleteOnClose)!=0xffffffff
  32745. && cnt++ < WINCE_DELETION_ATTEMPTS
  32746. ){
  32747. sqlite3_win32_sleep(100); /* Wait a little before trying again */
  32748. }
  32749. sqlite3_free(pFile->zDeleteOnClose);
  32750. }
  32751. #endif
  32752. if( rc ){
  32753. pFile->h = NULL;
  32754. }
  32755. OpenCounter(-1);
  32756. OSTRACE(("CLOSE file=%p, rc=%s\n", pFile->h, rc ? "ok" : "failed"));
  32757. return rc ? SQLITE_OK
  32758. : winLogError(SQLITE_IOERR_CLOSE, osGetLastError(),
  32759. "winClose", pFile->zPath);
  32760. }
  32761. /*
  32762. ** Read data from a file into a buffer. Return SQLITE_OK if all
  32763. ** bytes were read successfully and SQLITE_IOERR if anything goes
  32764. ** wrong.
  32765. */
  32766. static int winRead(
  32767. sqlite3_file *id, /* File to read from */
  32768. void *pBuf, /* Write content into this buffer */
  32769. int amt, /* Number of bytes to read */
  32770. sqlite3_int64 offset /* Begin reading at this offset */
  32771. ){
  32772. #if !SQLITE_OS_WINCE
  32773. OVERLAPPED overlapped; /* The offset for ReadFile. */
  32774. #endif
  32775. winFile *pFile = (winFile*)id; /* file handle */
  32776. DWORD nRead; /* Number of bytes actually read from file */
  32777. int nRetry = 0; /* Number of retrys */
  32778. assert( id!=0 );
  32779. assert( amt>0 );
  32780. assert( offset>=0 );
  32781. SimulateIOError(return SQLITE_IOERR_READ);
  32782. OSTRACE(("READ file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  32783. pFile->h, pBuf, amt, offset, pFile->locktype));
  32784. #if SQLITE_MAX_MMAP_SIZE>0
  32785. /* Deal with as much of this read request as possible by transfering
  32786. ** data from the memory mapping using memcpy(). */
  32787. if( offset<pFile->mmapSize ){
  32788. if( offset+amt <= pFile->mmapSize ){
  32789. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], amt);
  32790. OSTRACE(("READ-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  32791. return SQLITE_OK;
  32792. }else{
  32793. int nCopy = (int)(pFile->mmapSize - offset);
  32794. memcpy(pBuf, &((u8 *)(pFile->pMapRegion))[offset], nCopy);
  32795. pBuf = &((u8 *)pBuf)[nCopy];
  32796. amt -= nCopy;
  32797. offset += nCopy;
  32798. }
  32799. }
  32800. #endif
  32801. #if SQLITE_OS_WINCE
  32802. if( winSeekFile(pFile, offset) ){
  32803. OSTRACE(("READ file=%p, rc=SQLITE_FULL\n", pFile->h));
  32804. return SQLITE_FULL;
  32805. }
  32806. while( !osReadFile(pFile->h, pBuf, amt, &nRead, 0) ){
  32807. #else
  32808. memset(&overlapped, 0, sizeof(OVERLAPPED));
  32809. overlapped.Offset = (LONG)(offset & 0xffffffff);
  32810. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  32811. while( !osReadFile(pFile->h, pBuf, amt, &nRead, &overlapped) &&
  32812. osGetLastError()!=ERROR_HANDLE_EOF ){
  32813. #endif
  32814. DWORD lastErrno;
  32815. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  32816. pFile->lastErrno = lastErrno;
  32817. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_READ\n", pFile->h));
  32818. return winLogError(SQLITE_IOERR_READ, pFile->lastErrno,
  32819. "winRead", pFile->zPath);
  32820. }
  32821. winLogIoerr(nRetry);
  32822. if( nRead<(DWORD)amt ){
  32823. /* Unread parts of the buffer must be zero-filled */
  32824. memset(&((char*)pBuf)[nRead], 0, amt-nRead);
  32825. OSTRACE(("READ file=%p, rc=SQLITE_IOERR_SHORT_READ\n", pFile->h));
  32826. return SQLITE_IOERR_SHORT_READ;
  32827. }
  32828. OSTRACE(("READ file=%p, rc=SQLITE_OK\n", pFile->h));
  32829. return SQLITE_OK;
  32830. }
  32831. /*
  32832. ** Write data from a buffer into a file. Return SQLITE_OK on success
  32833. ** or some other error code on failure.
  32834. */
  32835. static int winWrite(
  32836. sqlite3_file *id, /* File to write into */
  32837. const void *pBuf, /* The bytes to be written */
  32838. int amt, /* Number of bytes to write */
  32839. sqlite3_int64 offset /* Offset into the file to begin writing at */
  32840. ){
  32841. int rc = 0; /* True if error has occurred, else false */
  32842. winFile *pFile = (winFile*)id; /* File handle */
  32843. int nRetry = 0; /* Number of retries */
  32844. assert( amt>0 );
  32845. assert( pFile );
  32846. SimulateIOError(return SQLITE_IOERR_WRITE);
  32847. SimulateDiskfullError(return SQLITE_FULL);
  32848. OSTRACE(("WRITE file=%p, buffer=%p, amount=%d, offset=%lld, lock=%d\n",
  32849. pFile->h, pBuf, amt, offset, pFile->locktype));
  32850. #if SQLITE_MAX_MMAP_SIZE>0
  32851. /* Deal with as much of this write request as possible by transfering
  32852. ** data from the memory mapping using memcpy(). */
  32853. if( offset<pFile->mmapSize ){
  32854. if( offset+amt <= pFile->mmapSize ){
  32855. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, amt);
  32856. OSTRACE(("WRITE-MMAP file=%p, rc=SQLITE_OK\n", pFile->h));
  32857. return SQLITE_OK;
  32858. }else{
  32859. int nCopy = (int)(pFile->mmapSize - offset);
  32860. memcpy(&((u8 *)(pFile->pMapRegion))[offset], pBuf, nCopy);
  32861. pBuf = &((u8 *)pBuf)[nCopy];
  32862. amt -= nCopy;
  32863. offset += nCopy;
  32864. }
  32865. }
  32866. #endif
  32867. #if SQLITE_OS_WINCE
  32868. rc = winSeekFile(pFile, offset);
  32869. if( rc==0 ){
  32870. #else
  32871. {
  32872. #endif
  32873. #if !SQLITE_OS_WINCE
  32874. OVERLAPPED overlapped; /* The offset for WriteFile. */
  32875. #endif
  32876. u8 *aRem = (u8 *)pBuf; /* Data yet to be written */
  32877. int nRem = amt; /* Number of bytes yet to be written */
  32878. DWORD nWrite; /* Bytes written by each WriteFile() call */
  32879. DWORD lastErrno = NO_ERROR; /* Value returned by GetLastError() */
  32880. #if !SQLITE_OS_WINCE
  32881. memset(&overlapped, 0, sizeof(OVERLAPPED));
  32882. overlapped.Offset = (LONG)(offset & 0xffffffff);
  32883. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  32884. #endif
  32885. while( nRem>0 ){
  32886. #if SQLITE_OS_WINCE
  32887. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, 0) ){
  32888. #else
  32889. if( !osWriteFile(pFile->h, aRem, nRem, &nWrite, &overlapped) ){
  32890. #endif
  32891. if( winRetryIoerr(&nRetry, &lastErrno) ) continue;
  32892. break;
  32893. }
  32894. assert( nWrite==0 || nWrite<=(DWORD)nRem );
  32895. if( nWrite==0 || nWrite>(DWORD)nRem ){
  32896. lastErrno = osGetLastError();
  32897. break;
  32898. }
  32899. #if !SQLITE_OS_WINCE
  32900. offset += nWrite;
  32901. overlapped.Offset = (LONG)(offset & 0xffffffff);
  32902. overlapped.OffsetHigh = (LONG)((offset>>32) & 0x7fffffff);
  32903. #endif
  32904. aRem += nWrite;
  32905. nRem -= nWrite;
  32906. }
  32907. if( nRem>0 ){
  32908. pFile->lastErrno = lastErrno;
  32909. rc = 1;
  32910. }
  32911. }
  32912. if( rc ){
  32913. if( ( pFile->lastErrno==ERROR_HANDLE_DISK_FULL )
  32914. || ( pFile->lastErrno==ERROR_DISK_FULL )){
  32915. OSTRACE(("WRITE file=%p, rc=SQLITE_FULL\n", pFile->h));
  32916. return winLogError(SQLITE_FULL, pFile->lastErrno,
  32917. "winWrite1", pFile->zPath);
  32918. }
  32919. OSTRACE(("WRITE file=%p, rc=SQLITE_IOERR_WRITE\n", pFile->h));
  32920. return winLogError(SQLITE_IOERR_WRITE, pFile->lastErrno,
  32921. "winWrite2", pFile->zPath);
  32922. }else{
  32923. winLogIoerr(nRetry);
  32924. }
  32925. OSTRACE(("WRITE file=%p, rc=SQLITE_OK\n", pFile->h));
  32926. return SQLITE_OK;
  32927. }
  32928. /*
  32929. ** Truncate an open file to a specified size
  32930. */
  32931. static int winTruncate(sqlite3_file *id, sqlite3_int64 nByte){
  32932. winFile *pFile = (winFile*)id; /* File handle object */
  32933. int rc = SQLITE_OK; /* Return code for this function */
  32934. DWORD lastErrno;
  32935. assert( pFile );
  32936. SimulateIOError(return SQLITE_IOERR_TRUNCATE);
  32937. OSTRACE(("TRUNCATE file=%p, size=%lld, lock=%d\n",
  32938. pFile->h, nByte, pFile->locktype));
  32939. /* If the user has configured a chunk-size for this file, truncate the
  32940. ** file so that it consists of an integer number of chunks (i.e. the
  32941. ** actual file size after the operation may be larger than the requested
  32942. ** size).
  32943. */
  32944. if( pFile->szChunk>0 ){
  32945. nByte = ((nByte + pFile->szChunk - 1)/pFile->szChunk) * pFile->szChunk;
  32946. }
  32947. /* SetEndOfFile() returns non-zero when successful, or zero when it fails. */
  32948. if( winSeekFile(pFile, nByte) ){
  32949. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  32950. "winTruncate1", pFile->zPath);
  32951. }else if( 0==osSetEndOfFile(pFile->h) &&
  32952. ((lastErrno = osGetLastError())!=ERROR_USER_MAPPED_FILE) ){
  32953. pFile->lastErrno = lastErrno;
  32954. rc = winLogError(SQLITE_IOERR_TRUNCATE, pFile->lastErrno,
  32955. "winTruncate2", pFile->zPath);
  32956. }
  32957. #if SQLITE_MAX_MMAP_SIZE>0
  32958. /* If the file was truncated to a size smaller than the currently
  32959. ** mapped region, reduce the effective mapping size as well. SQLite will
  32960. ** use read() and write() to access data beyond this point from now on.
  32961. */
  32962. if( pFile->pMapRegion && nByte<pFile->mmapSize ){
  32963. pFile->mmapSize = nByte;
  32964. }
  32965. #endif
  32966. OSTRACE(("TRUNCATE file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  32967. return rc;
  32968. }
  32969. #ifdef SQLITE_TEST
  32970. /*
  32971. ** Count the number of fullsyncs and normal syncs. This is used to test
  32972. ** that syncs and fullsyncs are occuring at the right times.
  32973. */
  32974. SQLITE_API int sqlite3_sync_count = 0;
  32975. SQLITE_API int sqlite3_fullsync_count = 0;
  32976. #endif
  32977. /*
  32978. ** Make sure all writes to a particular file are committed to disk.
  32979. */
  32980. static int winSync(sqlite3_file *id, int flags){
  32981. #ifndef SQLITE_NO_SYNC
  32982. /*
  32983. ** Used only when SQLITE_NO_SYNC is not defined.
  32984. */
  32985. BOOL rc;
  32986. #endif
  32987. #if !defined(NDEBUG) || !defined(SQLITE_NO_SYNC) || \
  32988. (defined(SQLITE_TEST) && defined(SQLITE_DEBUG))
  32989. /*
  32990. ** Used when SQLITE_NO_SYNC is not defined and by the assert() and/or
  32991. ** OSTRACE() macros.
  32992. */
  32993. winFile *pFile = (winFile*)id;
  32994. #else
  32995. UNUSED_PARAMETER(id);
  32996. #endif
  32997. assert( pFile );
  32998. /* Check that one of SQLITE_SYNC_NORMAL or FULL was passed */
  32999. assert((flags&0x0F)==SQLITE_SYNC_NORMAL
  33000. || (flags&0x0F)==SQLITE_SYNC_FULL
  33001. );
  33002. /* Unix cannot, but some systems may return SQLITE_FULL from here. This
  33003. ** line is to test that doing so does not cause any problems.
  33004. */
  33005. SimulateDiskfullError( return SQLITE_FULL );
  33006. OSTRACE(("SYNC file=%p, flags=%x, lock=%d\n",
  33007. pFile->h, flags, pFile->locktype));
  33008. #ifndef SQLITE_TEST
  33009. UNUSED_PARAMETER(flags);
  33010. #else
  33011. if( (flags&0x0F)==SQLITE_SYNC_FULL ){
  33012. sqlite3_fullsync_count++;
  33013. }
  33014. sqlite3_sync_count++;
  33015. #endif
  33016. /* If we compiled with the SQLITE_NO_SYNC flag, then syncing is a
  33017. ** no-op
  33018. */
  33019. #ifdef SQLITE_NO_SYNC
  33020. OSTRACE(("SYNC-NOP file=%p, rc=SQLITE_OK\n", pFile->h));
  33021. return SQLITE_OK;
  33022. #else
  33023. rc = osFlushFileBuffers(pFile->h);
  33024. SimulateIOError( rc=FALSE );
  33025. if( rc ){
  33026. OSTRACE(("SYNC file=%p, rc=SQLITE_OK\n", pFile->h));
  33027. return SQLITE_OK;
  33028. }else{
  33029. pFile->lastErrno = osGetLastError();
  33030. OSTRACE(("SYNC file=%p, rc=SQLITE_IOERR_FSYNC\n", pFile->h));
  33031. return winLogError(SQLITE_IOERR_FSYNC, pFile->lastErrno,
  33032. "winSync", pFile->zPath);
  33033. }
  33034. #endif
  33035. }
  33036. /*
  33037. ** Determine the current size of a file in bytes
  33038. */
  33039. static int winFileSize(sqlite3_file *id, sqlite3_int64 *pSize){
  33040. winFile *pFile = (winFile*)id;
  33041. int rc = SQLITE_OK;
  33042. assert( id!=0 );
  33043. assert( pSize!=0 );
  33044. SimulateIOError(return SQLITE_IOERR_FSTAT);
  33045. OSTRACE(("SIZE file=%p, pSize=%p\n", pFile->h, pSize));
  33046. #if SQLITE_OS_WINRT
  33047. {
  33048. FILE_STANDARD_INFO info;
  33049. if( osGetFileInformationByHandleEx(pFile->h, FileStandardInfo,
  33050. &info, sizeof(info)) ){
  33051. *pSize = info.EndOfFile.QuadPart;
  33052. }else{
  33053. pFile->lastErrno = osGetLastError();
  33054. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  33055. "winFileSize", pFile->zPath);
  33056. }
  33057. }
  33058. #else
  33059. {
  33060. DWORD upperBits;
  33061. DWORD lowerBits;
  33062. DWORD lastErrno;
  33063. lowerBits = osGetFileSize(pFile->h, &upperBits);
  33064. *pSize = (((sqlite3_int64)upperBits)<<32) + lowerBits;
  33065. if( (lowerBits == INVALID_FILE_SIZE)
  33066. && ((lastErrno = osGetLastError())!=NO_ERROR) ){
  33067. pFile->lastErrno = lastErrno;
  33068. rc = winLogError(SQLITE_IOERR_FSTAT, pFile->lastErrno,
  33069. "winFileSize", pFile->zPath);
  33070. }
  33071. }
  33072. #endif
  33073. OSTRACE(("SIZE file=%p, pSize=%p, *pSize=%lld, rc=%s\n",
  33074. pFile->h, pSize, *pSize, sqlite3ErrName(rc)));
  33075. return rc;
  33076. }
  33077. /*
  33078. ** LOCKFILE_FAIL_IMMEDIATELY is undefined on some Windows systems.
  33079. */
  33080. #ifndef LOCKFILE_FAIL_IMMEDIATELY
  33081. # define LOCKFILE_FAIL_IMMEDIATELY 1
  33082. #endif
  33083. #ifndef LOCKFILE_EXCLUSIVE_LOCK
  33084. # define LOCKFILE_EXCLUSIVE_LOCK 2
  33085. #endif
  33086. /*
  33087. ** Historically, SQLite has used both the LockFile and LockFileEx functions.
  33088. ** When the LockFile function was used, it was always expected to fail
  33089. ** immediately if the lock could not be obtained. Also, it always expected to
  33090. ** obtain an exclusive lock. These flags are used with the LockFileEx function
  33091. ** and reflect those expectations; therefore, they should not be changed.
  33092. */
  33093. #ifndef SQLITE_LOCKFILE_FLAGS
  33094. # define SQLITE_LOCKFILE_FLAGS (LOCKFILE_FAIL_IMMEDIATELY | \
  33095. LOCKFILE_EXCLUSIVE_LOCK)
  33096. #endif
  33097. /*
  33098. ** Currently, SQLite never calls the LockFileEx function without wanting the
  33099. ** call to fail immediately if the lock cannot be obtained.
  33100. */
  33101. #ifndef SQLITE_LOCKFILEEX_FLAGS
  33102. # define SQLITE_LOCKFILEEX_FLAGS (LOCKFILE_FAIL_IMMEDIATELY)
  33103. #endif
  33104. /*
  33105. ** Acquire a reader lock.
  33106. ** Different API routines are called depending on whether or not this
  33107. ** is Win9x or WinNT.
  33108. */
  33109. static int winGetReadLock(winFile *pFile){
  33110. int res;
  33111. OSTRACE(("READ-LOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  33112. if( osIsNT() ){
  33113. #if SQLITE_OS_WINCE
  33114. /*
  33115. ** NOTE: Windows CE is handled differently here due its lack of the Win32
  33116. ** API LockFileEx.
  33117. */
  33118. res = winceLockFile(&pFile->h, SHARED_FIRST, 0, 1, 0);
  33119. #else
  33120. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS, SHARED_FIRST, 0,
  33121. SHARED_SIZE, 0);
  33122. #endif
  33123. }
  33124. #ifdef SQLITE_WIN32_HAS_ANSI
  33125. else{
  33126. int lk;
  33127. sqlite3_randomness(sizeof(lk), &lk);
  33128. pFile->sharedLockByte = (short)((lk & 0x7fffffff)%(SHARED_SIZE - 1));
  33129. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  33130. SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  33131. }
  33132. #endif
  33133. if( res == 0 ){
  33134. pFile->lastErrno = osGetLastError();
  33135. /* No need to log a failure to lock */
  33136. }
  33137. OSTRACE(("READ-LOCK file=%p, result=%d\n", pFile->h, res));
  33138. return res;
  33139. }
  33140. /*
  33141. ** Undo a readlock
  33142. */
  33143. static int winUnlockReadLock(winFile *pFile){
  33144. int res;
  33145. DWORD lastErrno;
  33146. OSTRACE(("READ-UNLOCK file=%p, lock=%d\n", pFile->h, pFile->locktype));
  33147. if( osIsNT() ){
  33148. res = winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  33149. }
  33150. #ifdef SQLITE_WIN32_HAS_ANSI
  33151. else{
  33152. res = winUnlockFile(&pFile->h, SHARED_FIRST+pFile->sharedLockByte, 0, 1, 0);
  33153. }
  33154. #endif
  33155. if( res==0 && ((lastErrno = osGetLastError())!=ERROR_NOT_LOCKED) ){
  33156. pFile->lastErrno = lastErrno;
  33157. winLogError(SQLITE_IOERR_UNLOCK, pFile->lastErrno,
  33158. "winUnlockReadLock", pFile->zPath);
  33159. }
  33160. OSTRACE(("READ-UNLOCK file=%p, result=%d\n", pFile->h, res));
  33161. return res;
  33162. }
  33163. /*
  33164. ** Lock the file with the lock specified by parameter locktype - one
  33165. ** of the following:
  33166. **
  33167. ** (1) SHARED_LOCK
  33168. ** (2) RESERVED_LOCK
  33169. ** (3) PENDING_LOCK
  33170. ** (4) EXCLUSIVE_LOCK
  33171. **
  33172. ** Sometimes when requesting one lock state, additional lock states
  33173. ** are inserted in between. The locking might fail on one of the later
  33174. ** transitions leaving the lock state different from what it started but
  33175. ** still short of its goal. The following chart shows the allowed
  33176. ** transitions and the inserted intermediate states:
  33177. **
  33178. ** UNLOCKED -> SHARED
  33179. ** SHARED -> RESERVED
  33180. ** SHARED -> (PENDING) -> EXCLUSIVE
  33181. ** RESERVED -> (PENDING) -> EXCLUSIVE
  33182. ** PENDING -> EXCLUSIVE
  33183. **
  33184. ** This routine will only increase a lock. The winUnlock() routine
  33185. ** erases all locks at once and returns us immediately to locking level 0.
  33186. ** It is not possible to lower the locking level one step at a time. You
  33187. ** must go straight to locking level 0.
  33188. */
  33189. static int winLock(sqlite3_file *id, int locktype){
  33190. int rc = SQLITE_OK; /* Return code from subroutines */
  33191. int res = 1; /* Result of a Windows lock call */
  33192. int newLocktype; /* Set pFile->locktype to this value before exiting */
  33193. int gotPendingLock = 0;/* True if we acquired a PENDING lock this time */
  33194. winFile *pFile = (winFile*)id;
  33195. DWORD lastErrno = NO_ERROR;
  33196. assert( id!=0 );
  33197. OSTRACE(("LOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  33198. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  33199. /* If there is already a lock of this type or more restrictive on the
  33200. ** OsFile, do nothing. Don't use the end_lock: exit path, as
  33201. ** sqlite3OsEnterMutex() hasn't been called yet.
  33202. */
  33203. if( pFile->locktype>=locktype ){
  33204. OSTRACE(("LOCK-HELD file=%p, rc=SQLITE_OK\n", pFile->h));
  33205. return SQLITE_OK;
  33206. }
  33207. /* Make sure the locking sequence is correct
  33208. */
  33209. assert( pFile->locktype!=NO_LOCK || locktype==SHARED_LOCK );
  33210. assert( locktype!=PENDING_LOCK );
  33211. assert( locktype!=RESERVED_LOCK || pFile->locktype==SHARED_LOCK );
  33212. /* Lock the PENDING_LOCK byte if we need to acquire a PENDING lock or
  33213. ** a SHARED lock. If we are acquiring a SHARED lock, the acquisition of
  33214. ** the PENDING_LOCK byte is temporary.
  33215. */
  33216. newLocktype = pFile->locktype;
  33217. if( (pFile->locktype==NO_LOCK)
  33218. || ( (locktype==EXCLUSIVE_LOCK)
  33219. && (pFile->locktype==RESERVED_LOCK))
  33220. ){
  33221. int cnt = 3;
  33222. while( cnt-->0 && (res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS,
  33223. PENDING_BYTE, 0, 1, 0))==0 ){
  33224. /* Try 3 times to get the pending lock. This is needed to work
  33225. ** around problems caused by indexing and/or anti-virus software on
  33226. ** Windows systems.
  33227. ** If you are using this code as a model for alternative VFSes, do not
  33228. ** copy this retry logic. It is a hack intended for Windows only.
  33229. */
  33230. lastErrno = osGetLastError();
  33231. OSTRACE(("LOCK-PENDING-FAIL file=%p, count=%d, result=%d\n",
  33232. pFile->h, cnt, res));
  33233. if( lastErrno==ERROR_INVALID_HANDLE ){
  33234. pFile->lastErrno = lastErrno;
  33235. rc = SQLITE_IOERR_LOCK;
  33236. OSTRACE(("LOCK-FAIL file=%p, count=%d, rc=%s\n",
  33237. pFile->h, cnt, sqlite3ErrName(rc)));
  33238. return rc;
  33239. }
  33240. if( cnt ) sqlite3_win32_sleep(1);
  33241. }
  33242. gotPendingLock = res;
  33243. if( !res ){
  33244. lastErrno = osGetLastError();
  33245. }
  33246. }
  33247. /* Acquire a shared lock
  33248. */
  33249. if( locktype==SHARED_LOCK && res ){
  33250. assert( pFile->locktype==NO_LOCK );
  33251. res = winGetReadLock(pFile);
  33252. if( res ){
  33253. newLocktype = SHARED_LOCK;
  33254. }else{
  33255. lastErrno = osGetLastError();
  33256. }
  33257. }
  33258. /* Acquire a RESERVED lock
  33259. */
  33260. if( locktype==RESERVED_LOCK && res ){
  33261. assert( pFile->locktype==SHARED_LOCK );
  33262. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, RESERVED_BYTE, 0, 1, 0);
  33263. if( res ){
  33264. newLocktype = RESERVED_LOCK;
  33265. }else{
  33266. lastErrno = osGetLastError();
  33267. }
  33268. }
  33269. /* Acquire a PENDING lock
  33270. */
  33271. if( locktype==EXCLUSIVE_LOCK && res ){
  33272. newLocktype = PENDING_LOCK;
  33273. gotPendingLock = 0;
  33274. }
  33275. /* Acquire an EXCLUSIVE lock
  33276. */
  33277. if( locktype==EXCLUSIVE_LOCK && res ){
  33278. assert( pFile->locktype>=SHARED_LOCK );
  33279. res = winUnlockReadLock(pFile);
  33280. res = winLockFile(&pFile->h, SQLITE_LOCKFILE_FLAGS, SHARED_FIRST, 0,
  33281. SHARED_SIZE, 0);
  33282. if( res ){
  33283. newLocktype = EXCLUSIVE_LOCK;
  33284. }else{
  33285. lastErrno = osGetLastError();
  33286. winGetReadLock(pFile);
  33287. }
  33288. }
  33289. /* If we are holding a PENDING lock that ought to be released, then
  33290. ** release it now.
  33291. */
  33292. if( gotPendingLock && locktype==SHARED_LOCK ){
  33293. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  33294. }
  33295. /* Update the state of the lock has held in the file descriptor then
  33296. ** return the appropriate result code.
  33297. */
  33298. if( res ){
  33299. rc = SQLITE_OK;
  33300. }else{
  33301. pFile->lastErrno = lastErrno;
  33302. rc = SQLITE_BUSY;
  33303. OSTRACE(("LOCK-FAIL file=%p, wanted=%d, got=%d\n",
  33304. pFile->h, locktype, newLocktype));
  33305. }
  33306. pFile->locktype = (u8)newLocktype;
  33307. OSTRACE(("LOCK file=%p, lock=%d, rc=%s\n",
  33308. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  33309. return rc;
  33310. }
  33311. /*
  33312. ** This routine checks if there is a RESERVED lock held on the specified
  33313. ** file by this or any other process. If such a lock is held, return
  33314. ** non-zero, otherwise zero.
  33315. */
  33316. static int winCheckReservedLock(sqlite3_file *id, int *pResOut){
  33317. int res;
  33318. winFile *pFile = (winFile*)id;
  33319. SimulateIOError( return SQLITE_IOERR_CHECKRESERVEDLOCK; );
  33320. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p\n", pFile->h, pResOut));
  33321. assert( id!=0 );
  33322. if( pFile->locktype>=RESERVED_LOCK ){
  33323. res = 1;
  33324. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (local)\n", pFile->h, res));
  33325. }else{
  33326. res = winLockFile(&pFile->h, SQLITE_LOCKFILEEX_FLAGS,RESERVED_BYTE, 0, 1, 0);
  33327. if( res ){
  33328. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  33329. }
  33330. res = !res;
  33331. OSTRACE(("TEST-WR-LOCK file=%p, result=%d (remote)\n", pFile->h, res));
  33332. }
  33333. *pResOut = res;
  33334. OSTRACE(("TEST-WR-LOCK file=%p, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  33335. pFile->h, pResOut, *pResOut));
  33336. return SQLITE_OK;
  33337. }
  33338. /*
  33339. ** Lower the locking level on file descriptor id to locktype. locktype
  33340. ** must be either NO_LOCK or SHARED_LOCK.
  33341. **
  33342. ** If the locking level of the file descriptor is already at or below
  33343. ** the requested locking level, this routine is a no-op.
  33344. **
  33345. ** It is not possible for this routine to fail if the second argument
  33346. ** is NO_LOCK. If the second argument is SHARED_LOCK then this routine
  33347. ** might return SQLITE_IOERR;
  33348. */
  33349. static int winUnlock(sqlite3_file *id, int locktype){
  33350. int type;
  33351. winFile *pFile = (winFile*)id;
  33352. int rc = SQLITE_OK;
  33353. assert( pFile!=0 );
  33354. assert( locktype<=SHARED_LOCK );
  33355. OSTRACE(("UNLOCK file=%p, oldLock=%d(%d), newLock=%d\n",
  33356. pFile->h, pFile->locktype, pFile->sharedLockByte, locktype));
  33357. type = pFile->locktype;
  33358. if( type>=EXCLUSIVE_LOCK ){
  33359. winUnlockFile(&pFile->h, SHARED_FIRST, 0, SHARED_SIZE, 0);
  33360. if( locktype==SHARED_LOCK && !winGetReadLock(pFile) ){
  33361. /* This should never happen. We should always be able to
  33362. ** reacquire the read lock */
  33363. rc = winLogError(SQLITE_IOERR_UNLOCK, osGetLastError(),
  33364. "winUnlock", pFile->zPath);
  33365. }
  33366. }
  33367. if( type>=RESERVED_LOCK ){
  33368. winUnlockFile(&pFile->h, RESERVED_BYTE, 0, 1, 0);
  33369. }
  33370. if( locktype==NO_LOCK && type>=SHARED_LOCK ){
  33371. winUnlockReadLock(pFile);
  33372. }
  33373. if( type>=PENDING_LOCK ){
  33374. winUnlockFile(&pFile->h, PENDING_BYTE, 0, 1, 0);
  33375. }
  33376. pFile->locktype = (u8)locktype;
  33377. OSTRACE(("UNLOCK file=%p, lock=%d, rc=%s\n",
  33378. pFile->h, pFile->locktype, sqlite3ErrName(rc)));
  33379. return rc;
  33380. }
  33381. /*
  33382. ** If *pArg is initially negative then this is a query. Set *pArg to
  33383. ** 1 or 0 depending on whether or not bit mask of pFile->ctrlFlags is set.
  33384. **
  33385. ** If *pArg is 0 or 1, then clear or set the mask bit of pFile->ctrlFlags.
  33386. */
  33387. static void winModeBit(winFile *pFile, unsigned char mask, int *pArg){
  33388. if( *pArg<0 ){
  33389. *pArg = (pFile->ctrlFlags & mask)!=0;
  33390. }else if( (*pArg)==0 ){
  33391. pFile->ctrlFlags &= ~mask;
  33392. }else{
  33393. pFile->ctrlFlags |= mask;
  33394. }
  33395. }
  33396. /* Forward references to VFS helper methods used for temporary files */
  33397. static int winGetTempname(sqlite3_vfs *, char **);
  33398. static int winIsDir(const void *);
  33399. static BOOL winIsDriveLetterAndColon(const char *);
  33400. /*
  33401. ** Control and query of the open file handle.
  33402. */
  33403. static int winFileControl(sqlite3_file *id, int op, void *pArg){
  33404. winFile *pFile = (winFile*)id;
  33405. OSTRACE(("FCNTL file=%p, op=%d, pArg=%p\n", pFile->h, op, pArg));
  33406. switch( op ){
  33407. case SQLITE_FCNTL_LOCKSTATE: {
  33408. *(int*)pArg = pFile->locktype;
  33409. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33410. return SQLITE_OK;
  33411. }
  33412. case SQLITE_LAST_ERRNO: {
  33413. *(int*)pArg = (int)pFile->lastErrno;
  33414. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33415. return SQLITE_OK;
  33416. }
  33417. case SQLITE_FCNTL_CHUNK_SIZE: {
  33418. pFile->szChunk = *(int *)pArg;
  33419. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33420. return SQLITE_OK;
  33421. }
  33422. case SQLITE_FCNTL_SIZE_HINT: {
  33423. if( pFile->szChunk>0 ){
  33424. sqlite3_int64 oldSz;
  33425. int rc = winFileSize(id, &oldSz);
  33426. if( rc==SQLITE_OK ){
  33427. sqlite3_int64 newSz = *(sqlite3_int64*)pArg;
  33428. if( newSz>oldSz ){
  33429. SimulateIOErrorBenign(1);
  33430. rc = winTruncate(id, newSz);
  33431. SimulateIOErrorBenign(0);
  33432. }
  33433. }
  33434. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  33435. return rc;
  33436. }
  33437. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33438. return SQLITE_OK;
  33439. }
  33440. case SQLITE_FCNTL_PERSIST_WAL: {
  33441. winModeBit(pFile, WINFILE_PERSIST_WAL, (int*)pArg);
  33442. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33443. return SQLITE_OK;
  33444. }
  33445. case SQLITE_FCNTL_POWERSAFE_OVERWRITE: {
  33446. winModeBit(pFile, WINFILE_PSOW, (int*)pArg);
  33447. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33448. return SQLITE_OK;
  33449. }
  33450. case SQLITE_FCNTL_VFSNAME: {
  33451. *(char**)pArg = sqlite3_mprintf("%s", pFile->pVfs->zName);
  33452. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33453. return SQLITE_OK;
  33454. }
  33455. case SQLITE_FCNTL_WIN32_AV_RETRY: {
  33456. int *a = (int*)pArg;
  33457. if( a[0]>0 ){
  33458. winIoerrRetry = a[0];
  33459. }else{
  33460. a[0] = winIoerrRetry;
  33461. }
  33462. if( a[1]>0 ){
  33463. winIoerrRetryDelay = a[1];
  33464. }else{
  33465. a[1] = winIoerrRetryDelay;
  33466. }
  33467. OSTRACE(("FCNTL file=%p, rc=SQLITE_OK\n", pFile->h));
  33468. return SQLITE_OK;
  33469. }
  33470. #ifdef SQLITE_TEST
  33471. case SQLITE_FCNTL_WIN32_SET_HANDLE: {
  33472. LPHANDLE phFile = (LPHANDLE)pArg;
  33473. HANDLE hOldFile = pFile->h;
  33474. pFile->h = *phFile;
  33475. *phFile = hOldFile;
  33476. OSTRACE(("FCNTL oldFile=%p, newFile=%p, rc=SQLITE_OK\n",
  33477. hOldFile, pFile->h));
  33478. return SQLITE_OK;
  33479. }
  33480. #endif
  33481. case SQLITE_FCNTL_TEMPFILENAME: {
  33482. char *zTFile = 0;
  33483. int rc = winGetTempname(pFile->pVfs, &zTFile);
  33484. if( rc==SQLITE_OK ){
  33485. *(char**)pArg = zTFile;
  33486. }
  33487. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  33488. return rc;
  33489. }
  33490. #if SQLITE_MAX_MMAP_SIZE>0
  33491. case SQLITE_FCNTL_MMAP_SIZE: {
  33492. i64 newLimit = *(i64*)pArg;
  33493. int rc = SQLITE_OK;
  33494. if( newLimit>sqlite3GlobalConfig.mxMmap ){
  33495. newLimit = sqlite3GlobalConfig.mxMmap;
  33496. }
  33497. *(i64*)pArg = pFile->mmapSizeMax;
  33498. if( newLimit>=0 && newLimit!=pFile->mmapSizeMax && pFile->nFetchOut==0 ){
  33499. pFile->mmapSizeMax = newLimit;
  33500. if( pFile->mmapSize>0 ){
  33501. winUnmapfile(pFile);
  33502. rc = winMapfile(pFile, -1);
  33503. }
  33504. }
  33505. OSTRACE(("FCNTL file=%p, rc=%s\n", pFile->h, sqlite3ErrName(rc)));
  33506. return rc;
  33507. }
  33508. #endif
  33509. }
  33510. OSTRACE(("FCNTL file=%p, rc=SQLITE_NOTFOUND\n", pFile->h));
  33511. return SQLITE_NOTFOUND;
  33512. }
  33513. /*
  33514. ** Return the sector size in bytes of the underlying block device for
  33515. ** the specified file. This is almost always 512 bytes, but may be
  33516. ** larger for some devices.
  33517. **
  33518. ** SQLite code assumes this function cannot fail. It also assumes that
  33519. ** if two files are created in the same file-system directory (i.e.
  33520. ** a database and its journal file) that the sector size will be the
  33521. ** same for both.
  33522. */
  33523. static int winSectorSize(sqlite3_file *id){
  33524. (void)id;
  33525. return SQLITE_DEFAULT_SECTOR_SIZE;
  33526. }
  33527. /*
  33528. ** Return a vector of device characteristics.
  33529. */
  33530. static int winDeviceCharacteristics(sqlite3_file *id){
  33531. winFile *p = (winFile*)id;
  33532. return SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN |
  33533. ((p->ctrlFlags & WINFILE_PSOW)?SQLITE_IOCAP_POWERSAFE_OVERWRITE:0);
  33534. }
  33535. /*
  33536. ** Windows will only let you create file view mappings
  33537. ** on allocation size granularity boundaries.
  33538. ** During sqlite3_os_init() we do a GetSystemInfo()
  33539. ** to get the granularity size.
  33540. */
  33541. static SYSTEM_INFO winSysInfo;
  33542. #ifndef SQLITE_OMIT_WAL
  33543. /*
  33544. ** Helper functions to obtain and relinquish the global mutex. The
  33545. ** global mutex is used to protect the winLockInfo objects used by
  33546. ** this file, all of which may be shared by multiple threads.
  33547. **
  33548. ** Function winShmMutexHeld() is used to assert() that the global mutex
  33549. ** is held when required. This function is only used as part of assert()
  33550. ** statements. e.g.
  33551. **
  33552. ** winShmEnterMutex()
  33553. ** assert( winShmMutexHeld() );
  33554. ** winShmLeaveMutex()
  33555. */
  33556. static void winShmEnterMutex(void){
  33557. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  33558. }
  33559. static void winShmLeaveMutex(void){
  33560. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  33561. }
  33562. #ifndef NDEBUG
  33563. static int winShmMutexHeld(void) {
  33564. return sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  33565. }
  33566. #endif
  33567. /*
  33568. ** Object used to represent a single file opened and mmapped to provide
  33569. ** shared memory. When multiple threads all reference the same
  33570. ** log-summary, each thread has its own winFile object, but they all
  33571. ** point to a single instance of this object. In other words, each
  33572. ** log-summary is opened only once per process.
  33573. **
  33574. ** winShmMutexHeld() must be true when creating or destroying
  33575. ** this object or while reading or writing the following fields:
  33576. **
  33577. ** nRef
  33578. ** pNext
  33579. **
  33580. ** The following fields are read-only after the object is created:
  33581. **
  33582. ** fid
  33583. ** zFilename
  33584. **
  33585. ** Either winShmNode.mutex must be held or winShmNode.nRef==0 and
  33586. ** winShmMutexHeld() is true when reading or writing any other field
  33587. ** in this structure.
  33588. **
  33589. */
  33590. struct winShmNode {
  33591. sqlite3_mutex *mutex; /* Mutex to access this object */
  33592. char *zFilename; /* Name of the file */
  33593. winFile hFile; /* File handle from winOpen */
  33594. int szRegion; /* Size of shared-memory regions */
  33595. int nRegion; /* Size of array apRegion */
  33596. struct ShmRegion {
  33597. HANDLE hMap; /* File handle from CreateFileMapping */
  33598. void *pMap;
  33599. } *aRegion;
  33600. DWORD lastErrno; /* The Windows errno from the last I/O error */
  33601. int nRef; /* Number of winShm objects pointing to this */
  33602. winShm *pFirst; /* All winShm objects pointing to this */
  33603. winShmNode *pNext; /* Next in list of all winShmNode objects */
  33604. #ifdef SQLITE_DEBUG
  33605. u8 nextShmId; /* Next available winShm.id value */
  33606. #endif
  33607. };
  33608. /*
  33609. ** A global array of all winShmNode objects.
  33610. **
  33611. ** The winShmMutexHeld() must be true while reading or writing this list.
  33612. */
  33613. static winShmNode *winShmNodeList = 0;
  33614. /*
  33615. ** Structure used internally by this VFS to record the state of an
  33616. ** open shared memory connection.
  33617. **
  33618. ** The following fields are initialized when this object is created and
  33619. ** are read-only thereafter:
  33620. **
  33621. ** winShm.pShmNode
  33622. ** winShm.id
  33623. **
  33624. ** All other fields are read/write. The winShm.pShmNode->mutex must be held
  33625. ** while accessing any read/write fields.
  33626. */
  33627. struct winShm {
  33628. winShmNode *pShmNode; /* The underlying winShmNode object */
  33629. winShm *pNext; /* Next winShm with the same winShmNode */
  33630. u8 hasMutex; /* True if holding the winShmNode mutex */
  33631. u16 sharedMask; /* Mask of shared locks held */
  33632. u16 exclMask; /* Mask of exclusive locks held */
  33633. #ifdef SQLITE_DEBUG
  33634. u8 id; /* Id of this connection with its winShmNode */
  33635. #endif
  33636. };
  33637. /*
  33638. ** Constants used for locking
  33639. */
  33640. #define WIN_SHM_BASE ((22+SQLITE_SHM_NLOCK)*4) /* first lock byte */
  33641. #define WIN_SHM_DMS (WIN_SHM_BASE+SQLITE_SHM_NLOCK) /* deadman switch */
  33642. /*
  33643. ** Apply advisory locks for all n bytes beginning at ofst.
  33644. */
  33645. #define _SHM_UNLCK 1
  33646. #define _SHM_RDLCK 2
  33647. #define _SHM_WRLCK 3
  33648. static int winShmSystemLock(
  33649. winShmNode *pFile, /* Apply locks to this open shared-memory segment */
  33650. int lockType, /* _SHM_UNLCK, _SHM_RDLCK, or _SHM_WRLCK */
  33651. int ofst, /* Offset to first byte to be locked/unlocked */
  33652. int nByte /* Number of bytes to lock or unlock */
  33653. ){
  33654. int rc = 0; /* Result code form Lock/UnlockFileEx() */
  33655. /* Access to the winShmNode object is serialized by the caller */
  33656. assert( sqlite3_mutex_held(pFile->mutex) || pFile->nRef==0 );
  33657. OSTRACE(("SHM-LOCK file=%p, lock=%d, offset=%d, size=%d\n",
  33658. pFile->hFile.h, lockType, ofst, nByte));
  33659. /* Release/Acquire the system-level lock */
  33660. if( lockType==_SHM_UNLCK ){
  33661. rc = winUnlockFile(&pFile->hFile.h, ofst, 0, nByte, 0);
  33662. }else{
  33663. /* Initialize the locking parameters */
  33664. DWORD dwFlags = LOCKFILE_FAIL_IMMEDIATELY;
  33665. if( lockType == _SHM_WRLCK ) dwFlags |= LOCKFILE_EXCLUSIVE_LOCK;
  33666. rc = winLockFile(&pFile->hFile.h, dwFlags, ofst, 0, nByte, 0);
  33667. }
  33668. if( rc!= 0 ){
  33669. rc = SQLITE_OK;
  33670. }else{
  33671. pFile->lastErrno = osGetLastError();
  33672. rc = SQLITE_BUSY;
  33673. }
  33674. OSTRACE(("SHM-LOCK file=%p, func=%s, errno=%lu, rc=%s\n",
  33675. pFile->hFile.h, (lockType == _SHM_UNLCK) ? "winUnlockFile" :
  33676. "winLockFile", pFile->lastErrno, sqlite3ErrName(rc)));
  33677. return rc;
  33678. }
  33679. /* Forward references to VFS methods */
  33680. static int winOpen(sqlite3_vfs*,const char*,sqlite3_file*,int,int*);
  33681. static int winDelete(sqlite3_vfs *,const char*,int);
  33682. /*
  33683. ** Purge the winShmNodeList list of all entries with winShmNode.nRef==0.
  33684. **
  33685. ** This is not a VFS shared-memory method; it is a utility function called
  33686. ** by VFS shared-memory methods.
  33687. */
  33688. static void winShmPurge(sqlite3_vfs *pVfs, int deleteFlag){
  33689. winShmNode **pp;
  33690. winShmNode *p;
  33691. assert( winShmMutexHeld() );
  33692. OSTRACE(("SHM-PURGE pid=%lu, deleteFlag=%d\n",
  33693. osGetCurrentProcessId(), deleteFlag));
  33694. pp = &winShmNodeList;
  33695. while( (p = *pp)!=0 ){
  33696. if( p->nRef==0 ){
  33697. int i;
  33698. if( p->mutex ){ sqlite3_mutex_free(p->mutex); }
  33699. for(i=0; i<p->nRegion; i++){
  33700. BOOL bRc = osUnmapViewOfFile(p->aRegion[i].pMap);
  33701. OSTRACE(("SHM-PURGE-UNMAP pid=%lu, region=%d, rc=%s\n",
  33702. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  33703. UNUSED_VARIABLE_VALUE(bRc);
  33704. bRc = osCloseHandle(p->aRegion[i].hMap);
  33705. OSTRACE(("SHM-PURGE-CLOSE pid=%lu, region=%d, rc=%s\n",
  33706. osGetCurrentProcessId(), i, bRc ? "ok" : "failed"));
  33707. UNUSED_VARIABLE_VALUE(bRc);
  33708. }
  33709. if( p->hFile.h!=NULL && p->hFile.h!=INVALID_HANDLE_VALUE ){
  33710. SimulateIOErrorBenign(1);
  33711. winClose((sqlite3_file *)&p->hFile);
  33712. SimulateIOErrorBenign(0);
  33713. }
  33714. if( deleteFlag ){
  33715. SimulateIOErrorBenign(1);
  33716. sqlite3BeginBenignMalloc();
  33717. winDelete(pVfs, p->zFilename, 0);
  33718. sqlite3EndBenignMalloc();
  33719. SimulateIOErrorBenign(0);
  33720. }
  33721. *pp = p->pNext;
  33722. sqlite3_free(p->aRegion);
  33723. sqlite3_free(p);
  33724. }else{
  33725. pp = &p->pNext;
  33726. }
  33727. }
  33728. }
  33729. /*
  33730. ** Open the shared-memory area associated with database file pDbFd.
  33731. **
  33732. ** When opening a new shared-memory file, if no other instances of that
  33733. ** file are currently open, in this process or in other processes, then
  33734. ** the file must be truncated to zero length or have its header cleared.
  33735. */
  33736. static int winOpenSharedMemory(winFile *pDbFd){
  33737. struct winShm *p; /* The connection to be opened */
  33738. struct winShmNode *pShmNode = 0; /* The underlying mmapped file */
  33739. int rc; /* Result code */
  33740. struct winShmNode *pNew; /* Newly allocated winShmNode */
  33741. int nName; /* Size of zName in bytes */
  33742. assert( pDbFd->pShm==0 ); /* Not previously opened */
  33743. /* Allocate space for the new sqlite3_shm object. Also speculatively
  33744. ** allocate space for a new winShmNode and filename.
  33745. */
  33746. p = sqlite3MallocZero( sizeof(*p) );
  33747. if( p==0 ) return SQLITE_IOERR_NOMEM;
  33748. nName = sqlite3Strlen30(pDbFd->zPath);
  33749. pNew = sqlite3MallocZero( sizeof(*pShmNode) + nName + 17 );
  33750. if( pNew==0 ){
  33751. sqlite3_free(p);
  33752. return SQLITE_IOERR_NOMEM;
  33753. }
  33754. pNew->zFilename = (char*)&pNew[1];
  33755. sqlite3_snprintf(nName+15, pNew->zFilename, "%s-shm", pDbFd->zPath);
  33756. sqlite3FileSuffix3(pDbFd->zPath, pNew->zFilename);
  33757. /* Look to see if there is an existing winShmNode that can be used.
  33758. ** If no matching winShmNode currently exists, create a new one.
  33759. */
  33760. winShmEnterMutex();
  33761. for(pShmNode = winShmNodeList; pShmNode; pShmNode=pShmNode->pNext){
  33762. /* TBD need to come up with better match here. Perhaps
  33763. ** use FILE_ID_BOTH_DIR_INFO Structure.
  33764. */
  33765. if( sqlite3StrICmp(pShmNode->zFilename, pNew->zFilename)==0 ) break;
  33766. }
  33767. if( pShmNode ){
  33768. sqlite3_free(pNew);
  33769. }else{
  33770. pShmNode = pNew;
  33771. pNew = 0;
  33772. ((winFile*)(&pShmNode->hFile))->h = INVALID_HANDLE_VALUE;
  33773. pShmNode->pNext = winShmNodeList;
  33774. winShmNodeList = pShmNode;
  33775. pShmNode->mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_FAST);
  33776. if( pShmNode->mutex==0 ){
  33777. rc = SQLITE_IOERR_NOMEM;
  33778. goto shm_open_err;
  33779. }
  33780. rc = winOpen(pDbFd->pVfs,
  33781. pShmNode->zFilename, /* Name of the file (UTF-8) */
  33782. (sqlite3_file*)&pShmNode->hFile, /* File handle here */
  33783. SQLITE_OPEN_WAL | SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE,
  33784. 0);
  33785. if( SQLITE_OK!=rc ){
  33786. goto shm_open_err;
  33787. }
  33788. /* Check to see if another process is holding the dead-man switch.
  33789. ** If not, truncate the file to zero length.
  33790. */
  33791. if( winShmSystemLock(pShmNode, _SHM_WRLCK, WIN_SHM_DMS, 1)==SQLITE_OK ){
  33792. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, 0);
  33793. if( rc!=SQLITE_OK ){
  33794. rc = winLogError(SQLITE_IOERR_SHMOPEN, osGetLastError(),
  33795. "winOpenShm", pDbFd->zPath);
  33796. }
  33797. }
  33798. if( rc==SQLITE_OK ){
  33799. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  33800. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, WIN_SHM_DMS, 1);
  33801. }
  33802. if( rc ) goto shm_open_err;
  33803. }
  33804. /* Make the new connection a child of the winShmNode */
  33805. p->pShmNode = pShmNode;
  33806. #ifdef SQLITE_DEBUG
  33807. p->id = pShmNode->nextShmId++;
  33808. #endif
  33809. pShmNode->nRef++;
  33810. pDbFd->pShm = p;
  33811. winShmLeaveMutex();
  33812. /* The reference count on pShmNode has already been incremented under
  33813. ** the cover of the winShmEnterMutex() mutex and the pointer from the
  33814. ** new (struct winShm) object to the pShmNode has been set. All that is
  33815. ** left to do is to link the new object into the linked list starting
  33816. ** at pShmNode->pFirst. This must be done while holding the pShmNode->mutex
  33817. ** mutex.
  33818. */
  33819. sqlite3_mutex_enter(pShmNode->mutex);
  33820. p->pNext = pShmNode->pFirst;
  33821. pShmNode->pFirst = p;
  33822. sqlite3_mutex_leave(pShmNode->mutex);
  33823. return SQLITE_OK;
  33824. /* Jump here on any error */
  33825. shm_open_err:
  33826. winShmSystemLock(pShmNode, _SHM_UNLCK, WIN_SHM_DMS, 1);
  33827. winShmPurge(pDbFd->pVfs, 0); /* This call frees pShmNode if required */
  33828. sqlite3_free(p);
  33829. sqlite3_free(pNew);
  33830. winShmLeaveMutex();
  33831. return rc;
  33832. }
  33833. /*
  33834. ** Close a connection to shared-memory. Delete the underlying
  33835. ** storage if deleteFlag is true.
  33836. */
  33837. static int winShmUnmap(
  33838. sqlite3_file *fd, /* Database holding shared memory */
  33839. int deleteFlag /* Delete after closing if true */
  33840. ){
  33841. winFile *pDbFd; /* Database holding shared-memory */
  33842. winShm *p; /* The connection to be closed */
  33843. winShmNode *pShmNode; /* The underlying shared-memory file */
  33844. winShm **pp; /* For looping over sibling connections */
  33845. pDbFd = (winFile*)fd;
  33846. p = pDbFd->pShm;
  33847. if( p==0 ) return SQLITE_OK;
  33848. pShmNode = p->pShmNode;
  33849. /* Remove connection p from the set of connections associated
  33850. ** with pShmNode */
  33851. sqlite3_mutex_enter(pShmNode->mutex);
  33852. for(pp=&pShmNode->pFirst; (*pp)!=p; pp = &(*pp)->pNext){}
  33853. *pp = p->pNext;
  33854. /* Free the connection p */
  33855. sqlite3_free(p);
  33856. pDbFd->pShm = 0;
  33857. sqlite3_mutex_leave(pShmNode->mutex);
  33858. /* If pShmNode->nRef has reached 0, then close the underlying
  33859. ** shared-memory file, too */
  33860. winShmEnterMutex();
  33861. assert( pShmNode->nRef>0 );
  33862. pShmNode->nRef--;
  33863. if( pShmNode->nRef==0 ){
  33864. winShmPurge(pDbFd->pVfs, deleteFlag);
  33865. }
  33866. winShmLeaveMutex();
  33867. return SQLITE_OK;
  33868. }
  33869. /*
  33870. ** Change the lock state for a shared-memory segment.
  33871. */
  33872. static int winShmLock(
  33873. sqlite3_file *fd, /* Database file holding the shared memory */
  33874. int ofst, /* First lock to acquire or release */
  33875. int n, /* Number of locks to acquire or release */
  33876. int flags /* What to do with the lock */
  33877. ){
  33878. winFile *pDbFd = (winFile*)fd; /* Connection holding shared memory */
  33879. winShm *p = pDbFd->pShm; /* The shared memory being locked */
  33880. winShm *pX; /* For looping over all siblings */
  33881. winShmNode *pShmNode = p->pShmNode;
  33882. int rc = SQLITE_OK; /* Result code */
  33883. u16 mask; /* Mask of locks to take or release */
  33884. assert( ofst>=0 && ofst+n<=SQLITE_SHM_NLOCK );
  33885. assert( n>=1 );
  33886. assert( flags==(SQLITE_SHM_LOCK | SQLITE_SHM_SHARED)
  33887. || flags==(SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE)
  33888. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED)
  33889. || flags==(SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE) );
  33890. assert( n==1 || (flags & SQLITE_SHM_EXCLUSIVE)!=0 );
  33891. mask = (u16)((1U<<(ofst+n)) - (1U<<ofst));
  33892. assert( n>1 || mask==(1<<ofst) );
  33893. sqlite3_mutex_enter(pShmNode->mutex);
  33894. if( flags & SQLITE_SHM_UNLOCK ){
  33895. u16 allMask = 0; /* Mask of locks held by siblings */
  33896. /* See if any siblings hold this same lock */
  33897. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  33898. if( pX==p ) continue;
  33899. assert( (pX->exclMask & (p->exclMask|p->sharedMask))==0 );
  33900. allMask |= pX->sharedMask;
  33901. }
  33902. /* Unlock the system-level locks */
  33903. if( (mask & allMask)==0 ){
  33904. rc = winShmSystemLock(pShmNode, _SHM_UNLCK, ofst+WIN_SHM_BASE, n);
  33905. }else{
  33906. rc = SQLITE_OK;
  33907. }
  33908. /* Undo the local locks */
  33909. if( rc==SQLITE_OK ){
  33910. p->exclMask &= ~mask;
  33911. p->sharedMask &= ~mask;
  33912. }
  33913. }else if( flags & SQLITE_SHM_SHARED ){
  33914. u16 allShared = 0; /* Union of locks held by connections other than "p" */
  33915. /* Find out which shared locks are already held by sibling connections.
  33916. ** If any sibling already holds an exclusive lock, go ahead and return
  33917. ** SQLITE_BUSY.
  33918. */
  33919. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  33920. if( (pX->exclMask & mask)!=0 ){
  33921. rc = SQLITE_BUSY;
  33922. break;
  33923. }
  33924. allShared |= pX->sharedMask;
  33925. }
  33926. /* Get shared locks at the system level, if necessary */
  33927. if( rc==SQLITE_OK ){
  33928. if( (allShared & mask)==0 ){
  33929. rc = winShmSystemLock(pShmNode, _SHM_RDLCK, ofst+WIN_SHM_BASE, n);
  33930. }else{
  33931. rc = SQLITE_OK;
  33932. }
  33933. }
  33934. /* Get the local shared locks */
  33935. if( rc==SQLITE_OK ){
  33936. p->sharedMask |= mask;
  33937. }
  33938. }else{
  33939. /* Make sure no sibling connections hold locks that will block this
  33940. ** lock. If any do, return SQLITE_BUSY right away.
  33941. */
  33942. for(pX=pShmNode->pFirst; pX; pX=pX->pNext){
  33943. if( (pX->exclMask & mask)!=0 || (pX->sharedMask & mask)!=0 ){
  33944. rc = SQLITE_BUSY;
  33945. break;
  33946. }
  33947. }
  33948. /* Get the exclusive locks at the system level. Then if successful
  33949. ** also mark the local connection as being locked.
  33950. */
  33951. if( rc==SQLITE_OK ){
  33952. rc = winShmSystemLock(pShmNode, _SHM_WRLCK, ofst+WIN_SHM_BASE, n);
  33953. if( rc==SQLITE_OK ){
  33954. assert( (p->sharedMask & mask)==0 );
  33955. p->exclMask |= mask;
  33956. }
  33957. }
  33958. }
  33959. sqlite3_mutex_leave(pShmNode->mutex);
  33960. OSTRACE(("SHM-LOCK pid=%lu, id=%d, sharedMask=%03x, exclMask=%03x, rc=%s\n",
  33961. osGetCurrentProcessId(), p->id, p->sharedMask, p->exclMask,
  33962. sqlite3ErrName(rc)));
  33963. return rc;
  33964. }
  33965. /*
  33966. ** Implement a memory barrier or memory fence on shared memory.
  33967. **
  33968. ** All loads and stores begun before the barrier must complete before
  33969. ** any load or store begun after the barrier.
  33970. */
  33971. static void winShmBarrier(
  33972. sqlite3_file *fd /* Database holding the shared memory */
  33973. ){
  33974. UNUSED_PARAMETER(fd);
  33975. /* MemoryBarrier(); // does not work -- do not know why not */
  33976. winShmEnterMutex();
  33977. winShmLeaveMutex();
  33978. }
  33979. /*
  33980. ** This function is called to obtain a pointer to region iRegion of the
  33981. ** shared-memory associated with the database file fd. Shared-memory regions
  33982. ** are numbered starting from zero. Each shared-memory region is szRegion
  33983. ** bytes in size.
  33984. **
  33985. ** If an error occurs, an error code is returned and *pp is set to NULL.
  33986. **
  33987. ** Otherwise, if the isWrite parameter is 0 and the requested shared-memory
  33988. ** region has not been allocated (by any client, including one running in a
  33989. ** separate process), then *pp is set to NULL and SQLITE_OK returned. If
  33990. ** isWrite is non-zero and the requested shared-memory region has not yet
  33991. ** been allocated, it is allocated by this function.
  33992. **
  33993. ** If the shared-memory region has already been allocated or is allocated by
  33994. ** this call as described above, then it is mapped into this processes
  33995. ** address space (if it is not already), *pp is set to point to the mapped
  33996. ** memory and SQLITE_OK returned.
  33997. */
  33998. static int winShmMap(
  33999. sqlite3_file *fd, /* Handle open on database file */
  34000. int iRegion, /* Region to retrieve */
  34001. int szRegion, /* Size of regions */
  34002. int isWrite, /* True to extend file if necessary */
  34003. void volatile **pp /* OUT: Mapped memory */
  34004. ){
  34005. winFile *pDbFd = (winFile*)fd;
  34006. winShm *p = pDbFd->pShm;
  34007. winShmNode *pShmNode;
  34008. int rc = SQLITE_OK;
  34009. if( !p ){
  34010. rc = winOpenSharedMemory(pDbFd);
  34011. if( rc!=SQLITE_OK ) return rc;
  34012. p = pDbFd->pShm;
  34013. }
  34014. pShmNode = p->pShmNode;
  34015. sqlite3_mutex_enter(pShmNode->mutex);
  34016. assert( szRegion==pShmNode->szRegion || pShmNode->nRegion==0 );
  34017. if( pShmNode->nRegion<=iRegion ){
  34018. struct ShmRegion *apNew; /* New aRegion[] array */
  34019. int nByte = (iRegion+1)*szRegion; /* Minimum required file size */
  34020. sqlite3_int64 sz; /* Current size of wal-index file */
  34021. pShmNode->szRegion = szRegion;
  34022. /* The requested region is not mapped into this processes address space.
  34023. ** Check to see if it has been allocated (i.e. if the wal-index file is
  34024. ** large enough to contain the requested region).
  34025. */
  34026. rc = winFileSize((sqlite3_file *)&pShmNode->hFile, &sz);
  34027. if( rc!=SQLITE_OK ){
  34028. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  34029. "winShmMap1", pDbFd->zPath);
  34030. goto shmpage_out;
  34031. }
  34032. if( sz<nByte ){
  34033. /* The requested memory region does not exist. If isWrite is set to
  34034. ** zero, exit early. *pp will be set to NULL and SQLITE_OK returned.
  34035. **
  34036. ** Alternatively, if isWrite is non-zero, use ftruncate() to allocate
  34037. ** the requested memory region.
  34038. */
  34039. if( !isWrite ) goto shmpage_out;
  34040. rc = winTruncate((sqlite3_file *)&pShmNode->hFile, nByte);
  34041. if( rc!=SQLITE_OK ){
  34042. rc = winLogError(SQLITE_IOERR_SHMSIZE, osGetLastError(),
  34043. "winShmMap2", pDbFd->zPath);
  34044. goto shmpage_out;
  34045. }
  34046. }
  34047. /* Map the requested memory region into this processes address space. */
  34048. apNew = (struct ShmRegion *)sqlite3_realloc(
  34049. pShmNode->aRegion, (iRegion+1)*sizeof(apNew[0])
  34050. );
  34051. if( !apNew ){
  34052. rc = SQLITE_IOERR_NOMEM;
  34053. goto shmpage_out;
  34054. }
  34055. pShmNode->aRegion = apNew;
  34056. while( pShmNode->nRegion<=iRegion ){
  34057. HANDLE hMap = NULL; /* file-mapping handle */
  34058. void *pMap = 0; /* Mapped memory region */
  34059. #if SQLITE_OS_WINRT
  34060. hMap = osCreateFileMappingFromApp(pShmNode->hFile.h,
  34061. NULL, PAGE_READWRITE, nByte, NULL
  34062. );
  34063. #elif defined(SQLITE_WIN32_HAS_WIDE)
  34064. hMap = osCreateFileMappingW(pShmNode->hFile.h,
  34065. NULL, PAGE_READWRITE, 0, nByte, NULL
  34066. );
  34067. #elif defined(SQLITE_WIN32_HAS_ANSI)
  34068. hMap = osCreateFileMappingA(pShmNode->hFile.h,
  34069. NULL, PAGE_READWRITE, 0, nByte, NULL
  34070. );
  34071. #endif
  34072. OSTRACE(("SHM-MAP-CREATE pid=%lu, region=%d, size=%d, rc=%s\n",
  34073. osGetCurrentProcessId(), pShmNode->nRegion, nByte,
  34074. hMap ? "ok" : "failed"));
  34075. if( hMap ){
  34076. int iOffset = pShmNode->nRegion*szRegion;
  34077. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  34078. #if SQLITE_OS_WINRT
  34079. pMap = osMapViewOfFileFromApp(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  34080. iOffset - iOffsetShift, szRegion + iOffsetShift
  34081. );
  34082. #else
  34083. pMap = osMapViewOfFile(hMap, FILE_MAP_WRITE | FILE_MAP_READ,
  34084. 0, iOffset - iOffsetShift, szRegion + iOffsetShift
  34085. );
  34086. #endif
  34087. OSTRACE(("SHM-MAP-MAP pid=%lu, region=%d, offset=%d, size=%d, rc=%s\n",
  34088. osGetCurrentProcessId(), pShmNode->nRegion, iOffset,
  34089. szRegion, pMap ? "ok" : "failed"));
  34090. }
  34091. if( !pMap ){
  34092. pShmNode->lastErrno = osGetLastError();
  34093. rc = winLogError(SQLITE_IOERR_SHMMAP, pShmNode->lastErrno,
  34094. "winShmMap3", pDbFd->zPath);
  34095. if( hMap ) osCloseHandle(hMap);
  34096. goto shmpage_out;
  34097. }
  34098. pShmNode->aRegion[pShmNode->nRegion].pMap = pMap;
  34099. pShmNode->aRegion[pShmNode->nRegion].hMap = hMap;
  34100. pShmNode->nRegion++;
  34101. }
  34102. }
  34103. shmpage_out:
  34104. if( pShmNode->nRegion>iRegion ){
  34105. int iOffset = iRegion*szRegion;
  34106. int iOffsetShift = iOffset % winSysInfo.dwAllocationGranularity;
  34107. char *p = (char *)pShmNode->aRegion[iRegion].pMap;
  34108. *pp = (void *)&p[iOffsetShift];
  34109. }else{
  34110. *pp = 0;
  34111. }
  34112. sqlite3_mutex_leave(pShmNode->mutex);
  34113. return rc;
  34114. }
  34115. #else
  34116. # define winShmMap 0
  34117. # define winShmLock 0
  34118. # define winShmBarrier 0
  34119. # define winShmUnmap 0
  34120. #endif /* #ifndef SQLITE_OMIT_WAL */
  34121. /*
  34122. ** Cleans up the mapped region of the specified file, if any.
  34123. */
  34124. #if SQLITE_MAX_MMAP_SIZE>0
  34125. static int winUnmapfile(winFile *pFile){
  34126. assert( pFile!=0 );
  34127. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, pMapRegion=%p, "
  34128. "mmapSize=%lld, mmapSizeActual=%lld, mmapSizeMax=%lld\n",
  34129. osGetCurrentProcessId(), pFile, pFile->hMap, pFile->pMapRegion,
  34130. pFile->mmapSize, pFile->mmapSizeActual, pFile->mmapSizeMax));
  34131. if( pFile->pMapRegion ){
  34132. if( !osUnmapViewOfFile(pFile->pMapRegion) ){
  34133. pFile->lastErrno = osGetLastError();
  34134. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, pMapRegion=%p, "
  34135. "rc=SQLITE_IOERR_MMAP\n", osGetCurrentProcessId(), pFile,
  34136. pFile->pMapRegion));
  34137. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  34138. "winUnmapfile1", pFile->zPath);
  34139. }
  34140. pFile->pMapRegion = 0;
  34141. pFile->mmapSize = 0;
  34142. pFile->mmapSizeActual = 0;
  34143. }
  34144. if( pFile->hMap!=NULL ){
  34145. if( !osCloseHandle(pFile->hMap) ){
  34146. pFile->lastErrno = osGetLastError();
  34147. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, hMap=%p, rc=SQLITE_IOERR_MMAP\n",
  34148. osGetCurrentProcessId(), pFile, pFile->hMap));
  34149. return winLogError(SQLITE_IOERR_MMAP, pFile->lastErrno,
  34150. "winUnmapfile2", pFile->zPath);
  34151. }
  34152. pFile->hMap = NULL;
  34153. }
  34154. OSTRACE(("UNMAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  34155. osGetCurrentProcessId(), pFile));
  34156. return SQLITE_OK;
  34157. }
  34158. /*
  34159. ** Memory map or remap the file opened by file-descriptor pFd (if the file
  34160. ** is already mapped, the existing mapping is replaced by the new). Or, if
  34161. ** there already exists a mapping for this file, and there are still
  34162. ** outstanding xFetch() references to it, this function is a no-op.
  34163. **
  34164. ** If parameter nByte is non-negative, then it is the requested size of
  34165. ** the mapping to create. Otherwise, if nByte is less than zero, then the
  34166. ** requested size is the size of the file on disk. The actual size of the
  34167. ** created mapping is either the requested size or the value configured
  34168. ** using SQLITE_FCNTL_MMAP_SIZE, whichever is smaller.
  34169. **
  34170. ** SQLITE_OK is returned if no error occurs (even if the mapping is not
  34171. ** recreated as a result of outstanding references) or an SQLite error
  34172. ** code otherwise.
  34173. */
  34174. static int winMapfile(winFile *pFd, sqlite3_int64 nByte){
  34175. sqlite3_int64 nMap = nByte;
  34176. int rc;
  34177. assert( nMap>=0 || pFd->nFetchOut==0 );
  34178. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, size=%lld\n",
  34179. osGetCurrentProcessId(), pFd, nByte));
  34180. if( pFd->nFetchOut>0 ) return SQLITE_OK;
  34181. if( nMap<0 ){
  34182. rc = winFileSize((sqlite3_file*)pFd, &nMap);
  34183. if( rc ){
  34184. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_IOERR_FSTAT\n",
  34185. osGetCurrentProcessId(), pFd));
  34186. return SQLITE_IOERR_FSTAT;
  34187. }
  34188. }
  34189. if( nMap>pFd->mmapSizeMax ){
  34190. nMap = pFd->mmapSizeMax;
  34191. }
  34192. nMap &= ~(sqlite3_int64)(winSysInfo.dwPageSize - 1);
  34193. if( nMap==0 && pFd->mmapSize>0 ){
  34194. winUnmapfile(pFd);
  34195. }
  34196. if( nMap!=pFd->mmapSize ){
  34197. void *pNew = 0;
  34198. DWORD protect = PAGE_READONLY;
  34199. DWORD flags = FILE_MAP_READ;
  34200. winUnmapfile(pFd);
  34201. if( (pFd->ctrlFlags & WINFILE_RDONLY)==0 ){
  34202. protect = PAGE_READWRITE;
  34203. flags |= FILE_MAP_WRITE;
  34204. }
  34205. #if SQLITE_OS_WINRT
  34206. pFd->hMap = osCreateFileMappingFromApp(pFd->h, NULL, protect, nMap, NULL);
  34207. #elif defined(SQLITE_WIN32_HAS_WIDE)
  34208. pFd->hMap = osCreateFileMappingW(pFd->h, NULL, protect,
  34209. (DWORD)((nMap>>32) & 0xffffffff),
  34210. (DWORD)(nMap & 0xffffffff), NULL);
  34211. #elif defined(SQLITE_WIN32_HAS_ANSI)
  34212. pFd->hMap = osCreateFileMappingA(pFd->h, NULL, protect,
  34213. (DWORD)((nMap>>32) & 0xffffffff),
  34214. (DWORD)(nMap & 0xffffffff), NULL);
  34215. #endif
  34216. if( pFd->hMap==NULL ){
  34217. pFd->lastErrno = osGetLastError();
  34218. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  34219. "winMapfile1", pFd->zPath);
  34220. /* Log the error, but continue normal operation using xRead/xWrite */
  34221. OSTRACE(("MAP-FILE-CREATE pid=%lu, pFile=%p, rc=%s\n",
  34222. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34223. return SQLITE_OK;
  34224. }
  34225. assert( (nMap % winSysInfo.dwPageSize)==0 );
  34226. assert( sizeof(SIZE_T)==sizeof(sqlite3_int64) || nMap<=0xffffffff );
  34227. #if SQLITE_OS_WINRT
  34228. pNew = osMapViewOfFileFromApp(pFd->hMap, flags, 0, (SIZE_T)nMap);
  34229. #else
  34230. pNew = osMapViewOfFile(pFd->hMap, flags, 0, 0, (SIZE_T)nMap);
  34231. #endif
  34232. if( pNew==NULL ){
  34233. osCloseHandle(pFd->hMap);
  34234. pFd->hMap = NULL;
  34235. pFd->lastErrno = osGetLastError();
  34236. rc = winLogError(SQLITE_IOERR_MMAP, pFd->lastErrno,
  34237. "winMapfile2", pFd->zPath);
  34238. /* Log the error, but continue normal operation using xRead/xWrite */
  34239. OSTRACE(("MAP-FILE-MAP pid=%lu, pFile=%p, rc=%s\n",
  34240. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34241. return SQLITE_OK;
  34242. }
  34243. pFd->pMapRegion = pNew;
  34244. pFd->mmapSize = nMap;
  34245. pFd->mmapSizeActual = nMap;
  34246. }
  34247. OSTRACE(("MAP-FILE pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  34248. osGetCurrentProcessId(), pFd));
  34249. return SQLITE_OK;
  34250. }
  34251. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  34252. /*
  34253. ** If possible, return a pointer to a mapping of file fd starting at offset
  34254. ** iOff. The mapping must be valid for at least nAmt bytes.
  34255. **
  34256. ** If such a pointer can be obtained, store it in *pp and return SQLITE_OK.
  34257. ** Or, if one cannot but no error occurs, set *pp to 0 and return SQLITE_OK.
  34258. ** Finally, if an error does occur, return an SQLite error code. The final
  34259. ** value of *pp is undefined in this case.
  34260. **
  34261. ** If this function does return a pointer, the caller must eventually
  34262. ** release the reference by calling winUnfetch().
  34263. */
  34264. static int winFetch(sqlite3_file *fd, i64 iOff, int nAmt, void **pp){
  34265. #if SQLITE_MAX_MMAP_SIZE>0
  34266. winFile *pFd = (winFile*)fd; /* The underlying database file */
  34267. #endif
  34268. *pp = 0;
  34269. OSTRACE(("FETCH pid=%lu, pFile=%p, offset=%lld, amount=%d, pp=%p\n",
  34270. osGetCurrentProcessId(), fd, iOff, nAmt, pp));
  34271. #if SQLITE_MAX_MMAP_SIZE>0
  34272. if( pFd->mmapSizeMax>0 ){
  34273. if( pFd->pMapRegion==0 ){
  34274. int rc = winMapfile(pFd, -1);
  34275. if( rc!=SQLITE_OK ){
  34276. OSTRACE(("FETCH pid=%lu, pFile=%p, rc=%s\n",
  34277. osGetCurrentProcessId(), pFd, sqlite3ErrName(rc)));
  34278. return rc;
  34279. }
  34280. }
  34281. if( pFd->mmapSize >= iOff+nAmt ){
  34282. *pp = &((u8 *)pFd->pMapRegion)[iOff];
  34283. pFd->nFetchOut++;
  34284. }
  34285. }
  34286. #endif
  34287. OSTRACE(("FETCH pid=%lu, pFile=%p, pp=%p, *pp=%p, rc=SQLITE_OK\n",
  34288. osGetCurrentProcessId(), fd, pp, *pp));
  34289. return SQLITE_OK;
  34290. }
  34291. /*
  34292. ** If the third argument is non-NULL, then this function releases a
  34293. ** reference obtained by an earlier call to winFetch(). The second
  34294. ** argument passed to this function must be the same as the corresponding
  34295. ** argument that was passed to the winFetch() invocation.
  34296. **
  34297. ** Or, if the third argument is NULL, then this function is being called
  34298. ** to inform the VFS layer that, according to POSIX, any existing mapping
  34299. ** may now be invalid and should be unmapped.
  34300. */
  34301. static int winUnfetch(sqlite3_file *fd, i64 iOff, void *p){
  34302. #if SQLITE_MAX_MMAP_SIZE>0
  34303. winFile *pFd = (winFile*)fd; /* The underlying database file */
  34304. /* If p==0 (unmap the entire file) then there must be no outstanding
  34305. ** xFetch references. Or, if p!=0 (meaning it is an xFetch reference),
  34306. ** then there must be at least one outstanding. */
  34307. assert( (p==0)==(pFd->nFetchOut==0) );
  34308. /* If p!=0, it must match the iOff value. */
  34309. assert( p==0 || p==&((u8 *)pFd->pMapRegion)[iOff] );
  34310. OSTRACE(("UNFETCH pid=%lu, pFile=%p, offset=%lld, p=%p\n",
  34311. osGetCurrentProcessId(), pFd, iOff, p));
  34312. if( p ){
  34313. pFd->nFetchOut--;
  34314. }else{
  34315. /* FIXME: If Windows truly always prevents truncating or deleting a
  34316. ** file while a mapping is held, then the following winUnmapfile() call
  34317. ** is unnecessary can be omitted - potentially improving
  34318. ** performance. */
  34319. winUnmapfile(pFd);
  34320. }
  34321. assert( pFd->nFetchOut>=0 );
  34322. #endif
  34323. OSTRACE(("UNFETCH pid=%lu, pFile=%p, rc=SQLITE_OK\n",
  34324. osGetCurrentProcessId(), fd));
  34325. return SQLITE_OK;
  34326. }
  34327. /*
  34328. ** Here ends the implementation of all sqlite3_file methods.
  34329. **
  34330. ********************** End sqlite3_file Methods *******************************
  34331. ******************************************************************************/
  34332. /*
  34333. ** This vector defines all the methods that can operate on an
  34334. ** sqlite3_file for win32.
  34335. */
  34336. static const sqlite3_io_methods winIoMethod = {
  34337. 3, /* iVersion */
  34338. winClose, /* xClose */
  34339. winRead, /* xRead */
  34340. winWrite, /* xWrite */
  34341. winTruncate, /* xTruncate */
  34342. winSync, /* xSync */
  34343. winFileSize, /* xFileSize */
  34344. winLock, /* xLock */
  34345. winUnlock, /* xUnlock */
  34346. winCheckReservedLock, /* xCheckReservedLock */
  34347. winFileControl, /* xFileControl */
  34348. winSectorSize, /* xSectorSize */
  34349. winDeviceCharacteristics, /* xDeviceCharacteristics */
  34350. winShmMap, /* xShmMap */
  34351. winShmLock, /* xShmLock */
  34352. winShmBarrier, /* xShmBarrier */
  34353. winShmUnmap, /* xShmUnmap */
  34354. winFetch, /* xFetch */
  34355. winUnfetch /* xUnfetch */
  34356. };
  34357. /****************************************************************************
  34358. **************************** sqlite3_vfs methods ****************************
  34359. **
  34360. ** This division contains the implementation of methods on the
  34361. ** sqlite3_vfs object.
  34362. */
  34363. #if defined(__CYGWIN__)
  34364. /*
  34365. ** Convert a filename from whatever the underlying operating system
  34366. ** supports for filenames into UTF-8. Space to hold the result is
  34367. ** obtained from malloc and must be freed by the calling function.
  34368. */
  34369. static char *winConvertToUtf8Filename(const void *zFilename){
  34370. char *zConverted = 0;
  34371. if( osIsNT() ){
  34372. zConverted = winUnicodeToUtf8(zFilename);
  34373. }
  34374. #ifdef SQLITE_WIN32_HAS_ANSI
  34375. else{
  34376. zConverted = sqlite3_win32_mbcs_to_utf8(zFilename);
  34377. }
  34378. #endif
  34379. /* caller will handle out of memory */
  34380. return zConverted;
  34381. }
  34382. #endif
  34383. /*
  34384. ** Convert a UTF-8 filename into whatever form the underlying
  34385. ** operating system wants filenames in. Space to hold the result
  34386. ** is obtained from malloc and must be freed by the calling
  34387. ** function.
  34388. */
  34389. static void *winConvertFromUtf8Filename(const char *zFilename){
  34390. void *zConverted = 0;
  34391. if( osIsNT() ){
  34392. zConverted = winUtf8ToUnicode(zFilename);
  34393. }
  34394. #ifdef SQLITE_WIN32_HAS_ANSI
  34395. else{
  34396. zConverted = sqlite3_win32_utf8_to_mbcs(zFilename);
  34397. }
  34398. #endif
  34399. /* caller will handle out of memory */
  34400. return zConverted;
  34401. }
  34402. /*
  34403. ** This function returns non-zero if the specified UTF-8 string buffer
  34404. ** ends with a directory separator character or one was successfully
  34405. ** added to it.
  34406. */
  34407. static int winMakeEndInDirSep(int nBuf, char *zBuf){
  34408. if( zBuf ){
  34409. int nLen = sqlite3Strlen30(zBuf);
  34410. if( nLen>0 ){
  34411. if( winIsDirSep(zBuf[nLen-1]) ){
  34412. return 1;
  34413. }else if( nLen+1<nBuf ){
  34414. zBuf[nLen] = winGetDirSep();
  34415. zBuf[nLen+1] = '\0';
  34416. return 1;
  34417. }
  34418. }
  34419. }
  34420. return 0;
  34421. }
  34422. /*
  34423. ** Create a temporary file name and store the resulting pointer into pzBuf.
  34424. ** The pointer returned in pzBuf must be freed via sqlite3_free().
  34425. */
  34426. static int winGetTempname(sqlite3_vfs *pVfs, char **pzBuf){
  34427. static char zChars[] =
  34428. "abcdefghijklmnopqrstuvwxyz"
  34429. "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
  34430. "0123456789";
  34431. size_t i, j;
  34432. int nPre = sqlite3Strlen30(SQLITE_TEMP_FILE_PREFIX);
  34433. int nMax, nBuf, nDir, nLen;
  34434. char *zBuf;
  34435. /* It's odd to simulate an io-error here, but really this is just
  34436. ** using the io-error infrastructure to test that SQLite handles this
  34437. ** function failing.
  34438. */
  34439. SimulateIOError( return SQLITE_IOERR );
  34440. /* Allocate a temporary buffer to store the fully qualified file
  34441. ** name for the temporary file. If this fails, we cannot continue.
  34442. */
  34443. nMax = pVfs->mxPathname; nBuf = nMax + 2;
  34444. zBuf = sqlite3MallocZero( nBuf );
  34445. if( !zBuf ){
  34446. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34447. return SQLITE_IOERR_NOMEM;
  34448. }
  34449. /* Figure out the effective temporary directory. First, check if one
  34450. ** has been explicitly set by the application; otherwise, use the one
  34451. ** configured by the operating system.
  34452. */
  34453. nDir = nMax - (nPre + 15);
  34454. assert( nDir>0 );
  34455. if( sqlite3_temp_directory ){
  34456. int nDirLen = sqlite3Strlen30(sqlite3_temp_directory);
  34457. if( nDirLen>0 ){
  34458. if( !winIsDirSep(sqlite3_temp_directory[nDirLen-1]) ){
  34459. nDirLen++;
  34460. }
  34461. if( nDirLen>nDir ){
  34462. sqlite3_free(zBuf);
  34463. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  34464. return winLogError(SQLITE_ERROR, 0, "winGetTempname1", 0);
  34465. }
  34466. sqlite3_snprintf(nMax, zBuf, "%s", sqlite3_temp_directory);
  34467. }
  34468. }
  34469. #if defined(__CYGWIN__)
  34470. else{
  34471. static const char *azDirs[] = {
  34472. 0, /* getenv("SQLITE_TMPDIR") */
  34473. 0, /* getenv("TMPDIR") */
  34474. 0, /* getenv("TMP") */
  34475. 0, /* getenv("TEMP") */
  34476. 0, /* getenv("USERPROFILE") */
  34477. "/var/tmp",
  34478. "/usr/tmp",
  34479. "/tmp",
  34480. ".",
  34481. 0 /* List terminator */
  34482. };
  34483. unsigned int i;
  34484. const char *zDir = 0;
  34485. if( !azDirs[0] ) azDirs[0] = getenv("SQLITE_TMPDIR");
  34486. if( !azDirs[1] ) azDirs[1] = getenv("TMPDIR");
  34487. if( !azDirs[2] ) azDirs[2] = getenv("TMP");
  34488. if( !azDirs[3] ) azDirs[3] = getenv("TEMP");
  34489. if( !azDirs[4] ) azDirs[4] = getenv("USERPROFILE");
  34490. for(i=0; i<sizeof(azDirs)/sizeof(azDirs[0]); zDir=azDirs[i++]){
  34491. void *zConverted;
  34492. if( zDir==0 ) continue;
  34493. /* If the path starts with a drive letter followed by the colon
  34494. ** character, assume it is already a native Win32 path; otherwise,
  34495. ** it must be converted to a native Win32 path via the Cygwin API
  34496. ** prior to using it.
  34497. */
  34498. if( winIsDriveLetterAndColon(zDir) ){
  34499. zConverted = winConvertFromUtf8Filename(zDir);
  34500. if( !zConverted ){
  34501. sqlite3_free(zBuf);
  34502. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34503. return SQLITE_IOERR_NOMEM;
  34504. }
  34505. if( winIsDir(zConverted) ){
  34506. sqlite3_snprintf(nMax, zBuf, "%s", zDir);
  34507. sqlite3_free(zConverted);
  34508. break;
  34509. }
  34510. sqlite3_free(zConverted);
  34511. }else{
  34512. zConverted = sqlite3MallocZero( nMax+1 );
  34513. if( !zConverted ){
  34514. sqlite3_free(zBuf);
  34515. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34516. return SQLITE_IOERR_NOMEM;
  34517. }
  34518. if( cygwin_conv_path(
  34519. osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A, zDir,
  34520. zConverted, nMax+1)<0 ){
  34521. sqlite3_free(zConverted);
  34522. sqlite3_free(zBuf);
  34523. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_CONVPATH\n"));
  34524. return winLogError(SQLITE_IOERR_CONVPATH, (DWORD)errno,
  34525. "winGetTempname2", zDir);
  34526. }
  34527. if( winIsDir(zConverted) ){
  34528. /* At this point, we know the candidate directory exists and should
  34529. ** be used. However, we may need to convert the string containing
  34530. ** its name into UTF-8 (i.e. if it is UTF-16 right now).
  34531. */
  34532. char *zUtf8 = winConvertToUtf8Filename(zConverted);
  34533. if( !zUtf8 ){
  34534. sqlite3_free(zConverted);
  34535. sqlite3_free(zBuf);
  34536. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34537. return SQLITE_IOERR_NOMEM;
  34538. }
  34539. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  34540. sqlite3_free(zUtf8);
  34541. sqlite3_free(zConverted);
  34542. break;
  34543. }
  34544. sqlite3_free(zConverted);
  34545. }
  34546. }
  34547. }
  34548. #elif !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  34549. else if( osIsNT() ){
  34550. char *zMulti;
  34551. LPWSTR zWidePath = sqlite3MallocZero( nMax*sizeof(WCHAR) );
  34552. if( !zWidePath ){
  34553. sqlite3_free(zBuf);
  34554. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34555. return SQLITE_IOERR_NOMEM;
  34556. }
  34557. if( osGetTempPathW(nMax, zWidePath)==0 ){
  34558. sqlite3_free(zWidePath);
  34559. sqlite3_free(zBuf);
  34560. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  34561. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  34562. "winGetTempname2", 0);
  34563. }
  34564. zMulti = winUnicodeToUtf8(zWidePath);
  34565. if( zMulti ){
  34566. sqlite3_snprintf(nMax, zBuf, "%s", zMulti);
  34567. sqlite3_free(zMulti);
  34568. sqlite3_free(zWidePath);
  34569. }else{
  34570. sqlite3_free(zWidePath);
  34571. sqlite3_free(zBuf);
  34572. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34573. return SQLITE_IOERR_NOMEM;
  34574. }
  34575. }
  34576. #ifdef SQLITE_WIN32_HAS_ANSI
  34577. else{
  34578. char *zUtf8;
  34579. char *zMbcsPath = sqlite3MallocZero( nMax );
  34580. if( !zMbcsPath ){
  34581. sqlite3_free(zBuf);
  34582. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34583. return SQLITE_IOERR_NOMEM;
  34584. }
  34585. if( osGetTempPathA(nMax, zMbcsPath)==0 ){
  34586. sqlite3_free(zBuf);
  34587. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_GETTEMPPATH\n"));
  34588. return winLogError(SQLITE_IOERR_GETTEMPPATH, osGetLastError(),
  34589. "winGetTempname3", 0);
  34590. }
  34591. zUtf8 = sqlite3_win32_mbcs_to_utf8(zMbcsPath);
  34592. if( zUtf8 ){
  34593. sqlite3_snprintf(nMax, zBuf, "%s", zUtf8);
  34594. sqlite3_free(zUtf8);
  34595. }else{
  34596. sqlite3_free(zBuf);
  34597. OSTRACE(("TEMP-FILENAME rc=SQLITE_IOERR_NOMEM\n"));
  34598. return SQLITE_IOERR_NOMEM;
  34599. }
  34600. }
  34601. #endif /* SQLITE_WIN32_HAS_ANSI */
  34602. #endif /* !SQLITE_OS_WINRT */
  34603. /*
  34604. ** Check to make sure the temporary directory ends with an appropriate
  34605. ** separator. If it does not and there is not enough space left to add
  34606. ** one, fail.
  34607. */
  34608. if( !winMakeEndInDirSep(nDir+1, zBuf) ){
  34609. sqlite3_free(zBuf);
  34610. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  34611. return winLogError(SQLITE_ERROR, 0, "winGetTempname4", 0);
  34612. }
  34613. /*
  34614. ** Check that the output buffer is large enough for the temporary file
  34615. ** name in the following format:
  34616. **
  34617. ** "<temporary_directory>/etilqs_XXXXXXXXXXXXXXX\0\0"
  34618. **
  34619. ** If not, return SQLITE_ERROR. The number 17 is used here in order to
  34620. ** account for the space used by the 15 character random suffix and the
  34621. ** two trailing NUL characters. The final directory separator character
  34622. ** has already added if it was not already present.
  34623. */
  34624. nLen = sqlite3Strlen30(zBuf);
  34625. if( (nLen + nPre + 17) > nBuf ){
  34626. sqlite3_free(zBuf);
  34627. OSTRACE(("TEMP-FILENAME rc=SQLITE_ERROR\n"));
  34628. return winLogError(SQLITE_ERROR, 0, "winGetTempname5", 0);
  34629. }
  34630. sqlite3_snprintf(nBuf-16-nLen, zBuf+nLen, SQLITE_TEMP_FILE_PREFIX);
  34631. j = sqlite3Strlen30(zBuf);
  34632. sqlite3_randomness(15, &zBuf[j]);
  34633. for(i=0; i<15; i++, j++){
  34634. zBuf[j] = (char)zChars[ ((unsigned char)zBuf[j])%(sizeof(zChars)-1) ];
  34635. }
  34636. zBuf[j] = 0;
  34637. zBuf[j+1] = 0;
  34638. *pzBuf = zBuf;
  34639. OSTRACE(("TEMP-FILENAME name=%s, rc=SQLITE_OK\n", zBuf));
  34640. return SQLITE_OK;
  34641. }
  34642. /*
  34643. ** Return TRUE if the named file is really a directory. Return false if
  34644. ** it is something other than a directory, or if there is any kind of memory
  34645. ** allocation failure.
  34646. */
  34647. static int winIsDir(const void *zConverted){
  34648. DWORD attr;
  34649. int rc = 0;
  34650. DWORD lastErrno;
  34651. if( osIsNT() ){
  34652. int cnt = 0;
  34653. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  34654. memset(&sAttrData, 0, sizeof(sAttrData));
  34655. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  34656. GetFileExInfoStandard,
  34657. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  34658. if( !rc ){
  34659. return 0; /* Invalid name? */
  34660. }
  34661. attr = sAttrData.dwFileAttributes;
  34662. #if SQLITE_OS_WINCE==0
  34663. }else{
  34664. attr = osGetFileAttributesA((char*)zConverted);
  34665. #endif
  34666. }
  34667. return (attr!=INVALID_FILE_ATTRIBUTES) && (attr&FILE_ATTRIBUTE_DIRECTORY);
  34668. }
  34669. /*
  34670. ** Open a file.
  34671. */
  34672. static int winOpen(
  34673. sqlite3_vfs *pVfs, /* Used to get maximum path name length */
  34674. const char *zName, /* Name of the file (UTF-8) */
  34675. sqlite3_file *id, /* Write the SQLite file handle here */
  34676. int flags, /* Open mode flags */
  34677. int *pOutFlags /* Status return flags */
  34678. ){
  34679. HANDLE h;
  34680. DWORD lastErrno = 0;
  34681. DWORD dwDesiredAccess;
  34682. DWORD dwShareMode;
  34683. DWORD dwCreationDisposition;
  34684. DWORD dwFlagsAndAttributes = 0;
  34685. #if SQLITE_OS_WINCE
  34686. int isTemp = 0;
  34687. #endif
  34688. winFile *pFile = (winFile*)id;
  34689. void *zConverted; /* Filename in OS encoding */
  34690. const char *zUtf8Name = zName; /* Filename in UTF-8 encoding */
  34691. int cnt = 0;
  34692. /* If argument zPath is a NULL pointer, this function is required to open
  34693. ** a temporary file. Use this buffer to store the file name in.
  34694. */
  34695. char *zTmpname = 0; /* For temporary filename, if necessary. */
  34696. int rc = SQLITE_OK; /* Function Return Code */
  34697. #if !defined(NDEBUG) || SQLITE_OS_WINCE
  34698. int eType = flags&0xFFFFFF00; /* Type of file to open */
  34699. #endif
  34700. int isExclusive = (flags & SQLITE_OPEN_EXCLUSIVE);
  34701. int isDelete = (flags & SQLITE_OPEN_DELETEONCLOSE);
  34702. int isCreate = (flags & SQLITE_OPEN_CREATE);
  34703. int isReadonly = (flags & SQLITE_OPEN_READONLY);
  34704. int isReadWrite = (flags & SQLITE_OPEN_READWRITE);
  34705. #ifndef NDEBUG
  34706. int isOpenJournal = (isCreate && (
  34707. eType==SQLITE_OPEN_MASTER_JOURNAL
  34708. || eType==SQLITE_OPEN_MAIN_JOURNAL
  34709. || eType==SQLITE_OPEN_WAL
  34710. ));
  34711. #endif
  34712. OSTRACE(("OPEN name=%s, pFile=%p, flags=%x, pOutFlags=%p\n",
  34713. zUtf8Name, id, flags, pOutFlags));
  34714. /* Check the following statements are true:
  34715. **
  34716. ** (a) Exactly one of the READWRITE and READONLY flags must be set, and
  34717. ** (b) if CREATE is set, then READWRITE must also be set, and
  34718. ** (c) if EXCLUSIVE is set, then CREATE must also be set.
  34719. ** (d) if DELETEONCLOSE is set, then CREATE must also be set.
  34720. */
  34721. assert((isReadonly==0 || isReadWrite==0) && (isReadWrite || isReadonly));
  34722. assert(isCreate==0 || isReadWrite);
  34723. assert(isExclusive==0 || isCreate);
  34724. assert(isDelete==0 || isCreate);
  34725. /* The main DB, main journal, WAL file and master journal are never
  34726. ** automatically deleted. Nor are they ever temporary files. */
  34727. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_DB );
  34728. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MAIN_JOURNAL );
  34729. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_MASTER_JOURNAL );
  34730. assert( (!isDelete && zName) || eType!=SQLITE_OPEN_WAL );
  34731. /* Assert that the upper layer has set one of the "file-type" flags. */
  34732. assert( eType==SQLITE_OPEN_MAIN_DB || eType==SQLITE_OPEN_TEMP_DB
  34733. || eType==SQLITE_OPEN_MAIN_JOURNAL || eType==SQLITE_OPEN_TEMP_JOURNAL
  34734. || eType==SQLITE_OPEN_SUBJOURNAL || eType==SQLITE_OPEN_MASTER_JOURNAL
  34735. || eType==SQLITE_OPEN_TRANSIENT_DB || eType==SQLITE_OPEN_WAL
  34736. );
  34737. assert( pFile!=0 );
  34738. memset(pFile, 0, sizeof(winFile));
  34739. pFile->h = INVALID_HANDLE_VALUE;
  34740. #if SQLITE_OS_WINRT
  34741. if( !zUtf8Name && !sqlite3_temp_directory ){
  34742. sqlite3_log(SQLITE_ERROR,
  34743. "sqlite3_temp_directory variable should be set for WinRT");
  34744. }
  34745. #endif
  34746. /* If the second argument to this function is NULL, generate a
  34747. ** temporary file name to use
  34748. */
  34749. if( !zUtf8Name ){
  34750. assert( isDelete && !isOpenJournal );
  34751. rc = winGetTempname(pVfs, &zTmpname);
  34752. if( rc!=SQLITE_OK ){
  34753. OSTRACE(("OPEN name=%s, rc=%s", zUtf8Name, sqlite3ErrName(rc)));
  34754. return rc;
  34755. }
  34756. zUtf8Name = zTmpname;
  34757. }
  34758. /* Database filenames are double-zero terminated if they are not
  34759. ** URIs with parameters. Hence, they can always be passed into
  34760. ** sqlite3_uri_parameter().
  34761. */
  34762. assert( (eType!=SQLITE_OPEN_MAIN_DB) || (flags & SQLITE_OPEN_URI) ||
  34763. zUtf8Name[sqlite3Strlen30(zUtf8Name)+1]==0 );
  34764. /* Convert the filename to the system encoding. */
  34765. zConverted = winConvertFromUtf8Filename(zUtf8Name);
  34766. if( zConverted==0 ){
  34767. sqlite3_free(zTmpname);
  34768. OSTRACE(("OPEN name=%s, rc=SQLITE_IOERR_NOMEM", zUtf8Name));
  34769. return SQLITE_IOERR_NOMEM;
  34770. }
  34771. if( winIsDir(zConverted) ){
  34772. sqlite3_free(zConverted);
  34773. sqlite3_free(zTmpname);
  34774. OSTRACE(("OPEN name=%s, rc=SQLITE_CANTOPEN_ISDIR", zUtf8Name));
  34775. return SQLITE_CANTOPEN_ISDIR;
  34776. }
  34777. if( isReadWrite ){
  34778. dwDesiredAccess = GENERIC_READ | GENERIC_WRITE;
  34779. }else{
  34780. dwDesiredAccess = GENERIC_READ;
  34781. }
  34782. /* SQLITE_OPEN_EXCLUSIVE is used to make sure that a new file is
  34783. ** created. SQLite doesn't use it to indicate "exclusive access"
  34784. ** as it is usually understood.
  34785. */
  34786. if( isExclusive ){
  34787. /* Creates a new file, only if it does not already exist. */
  34788. /* If the file exists, it fails. */
  34789. dwCreationDisposition = CREATE_NEW;
  34790. }else if( isCreate ){
  34791. /* Open existing file, or create if it doesn't exist */
  34792. dwCreationDisposition = OPEN_ALWAYS;
  34793. }else{
  34794. /* Opens a file, only if it exists. */
  34795. dwCreationDisposition = OPEN_EXISTING;
  34796. }
  34797. dwShareMode = FILE_SHARE_READ | FILE_SHARE_WRITE;
  34798. if( isDelete ){
  34799. #if SQLITE_OS_WINCE
  34800. dwFlagsAndAttributes = FILE_ATTRIBUTE_HIDDEN;
  34801. isTemp = 1;
  34802. #else
  34803. dwFlagsAndAttributes = FILE_ATTRIBUTE_TEMPORARY
  34804. | FILE_ATTRIBUTE_HIDDEN
  34805. | FILE_FLAG_DELETE_ON_CLOSE;
  34806. #endif
  34807. }else{
  34808. dwFlagsAndAttributes = FILE_ATTRIBUTE_NORMAL;
  34809. }
  34810. /* Reports from the internet are that performance is always
  34811. ** better if FILE_FLAG_RANDOM_ACCESS is used. Ticket #2699. */
  34812. #if SQLITE_OS_WINCE
  34813. dwFlagsAndAttributes |= FILE_FLAG_RANDOM_ACCESS;
  34814. #endif
  34815. if( osIsNT() ){
  34816. #if SQLITE_OS_WINRT
  34817. CREATEFILE2_EXTENDED_PARAMETERS extendedParameters;
  34818. extendedParameters.dwSize = sizeof(CREATEFILE2_EXTENDED_PARAMETERS);
  34819. extendedParameters.dwFileAttributes =
  34820. dwFlagsAndAttributes & FILE_ATTRIBUTE_MASK;
  34821. extendedParameters.dwFileFlags = dwFlagsAndAttributes & FILE_FLAG_MASK;
  34822. extendedParameters.dwSecurityQosFlags = SECURITY_ANONYMOUS;
  34823. extendedParameters.lpSecurityAttributes = NULL;
  34824. extendedParameters.hTemplateFile = NULL;
  34825. while( (h = osCreateFile2((LPCWSTR)zConverted,
  34826. dwDesiredAccess,
  34827. dwShareMode,
  34828. dwCreationDisposition,
  34829. &extendedParameters))==INVALID_HANDLE_VALUE &&
  34830. winRetryIoerr(&cnt, &lastErrno) ){
  34831. /* Noop */
  34832. }
  34833. #else
  34834. while( (h = osCreateFileW((LPCWSTR)zConverted,
  34835. dwDesiredAccess,
  34836. dwShareMode, NULL,
  34837. dwCreationDisposition,
  34838. dwFlagsAndAttributes,
  34839. NULL))==INVALID_HANDLE_VALUE &&
  34840. winRetryIoerr(&cnt, &lastErrno) ){
  34841. /* Noop */
  34842. }
  34843. #endif
  34844. }
  34845. #ifdef SQLITE_WIN32_HAS_ANSI
  34846. else{
  34847. while( (h = osCreateFileA((LPCSTR)zConverted,
  34848. dwDesiredAccess,
  34849. dwShareMode, NULL,
  34850. dwCreationDisposition,
  34851. dwFlagsAndAttributes,
  34852. NULL))==INVALID_HANDLE_VALUE &&
  34853. winRetryIoerr(&cnt, &lastErrno) ){
  34854. /* Noop */
  34855. }
  34856. }
  34857. #endif
  34858. winLogIoerr(cnt);
  34859. OSTRACE(("OPEN file=%p, name=%s, access=%lx, rc=%s\n", h, zUtf8Name,
  34860. dwDesiredAccess, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  34861. if( h==INVALID_HANDLE_VALUE ){
  34862. pFile->lastErrno = lastErrno;
  34863. winLogError(SQLITE_CANTOPEN, pFile->lastErrno, "winOpen", zUtf8Name);
  34864. sqlite3_free(zConverted);
  34865. sqlite3_free(zTmpname);
  34866. if( isReadWrite && !isExclusive ){
  34867. return winOpen(pVfs, zName, id,
  34868. ((flags|SQLITE_OPEN_READONLY) &
  34869. ~(SQLITE_OPEN_CREATE|SQLITE_OPEN_READWRITE)),
  34870. pOutFlags);
  34871. }else{
  34872. return SQLITE_CANTOPEN_BKPT;
  34873. }
  34874. }
  34875. if( pOutFlags ){
  34876. if( isReadWrite ){
  34877. *pOutFlags = SQLITE_OPEN_READWRITE;
  34878. }else{
  34879. *pOutFlags = SQLITE_OPEN_READONLY;
  34880. }
  34881. }
  34882. OSTRACE(("OPEN file=%p, name=%s, access=%lx, pOutFlags=%p, *pOutFlags=%d, "
  34883. "rc=%s\n", h, zUtf8Name, dwDesiredAccess, pOutFlags, pOutFlags ?
  34884. *pOutFlags : 0, (h==INVALID_HANDLE_VALUE) ? "failed" : "ok"));
  34885. #if SQLITE_OS_WINCE
  34886. if( isReadWrite && eType==SQLITE_OPEN_MAIN_DB
  34887. && (rc = winceCreateLock(zName, pFile))!=SQLITE_OK
  34888. ){
  34889. osCloseHandle(h);
  34890. sqlite3_free(zConverted);
  34891. sqlite3_free(zTmpname);
  34892. OSTRACE(("OPEN-CE-LOCK name=%s, rc=%s\n", zName, sqlite3ErrName(rc)));
  34893. return rc;
  34894. }
  34895. if( isTemp ){
  34896. pFile->zDeleteOnClose = zConverted;
  34897. }else
  34898. #endif
  34899. {
  34900. sqlite3_free(zConverted);
  34901. }
  34902. sqlite3_free(zTmpname);
  34903. pFile->pMethod = &winIoMethod;
  34904. pFile->pVfs = pVfs;
  34905. pFile->h = h;
  34906. if( isReadonly ){
  34907. pFile->ctrlFlags |= WINFILE_RDONLY;
  34908. }
  34909. if( sqlite3_uri_boolean(zName, "psow", SQLITE_POWERSAFE_OVERWRITE) ){
  34910. pFile->ctrlFlags |= WINFILE_PSOW;
  34911. }
  34912. pFile->lastErrno = NO_ERROR;
  34913. pFile->zPath = zName;
  34914. #if SQLITE_MAX_MMAP_SIZE>0
  34915. pFile->hMap = NULL;
  34916. pFile->pMapRegion = 0;
  34917. pFile->mmapSize = 0;
  34918. pFile->mmapSizeActual = 0;
  34919. pFile->mmapSizeMax = sqlite3GlobalConfig.szMmap;
  34920. #endif
  34921. OpenCounter(+1);
  34922. return rc;
  34923. }
  34924. /*
  34925. ** Delete the named file.
  34926. **
  34927. ** Note that Windows does not allow a file to be deleted if some other
  34928. ** process has it open. Sometimes a virus scanner or indexing program
  34929. ** will open a journal file shortly after it is created in order to do
  34930. ** whatever it does. While this other process is holding the
  34931. ** file open, we will be unable to delete it. To work around this
  34932. ** problem, we delay 100 milliseconds and try to delete again. Up
  34933. ** to MX_DELETION_ATTEMPTs deletion attempts are run before giving
  34934. ** up and returning an error.
  34935. */
  34936. static int winDelete(
  34937. sqlite3_vfs *pVfs, /* Not used on win32 */
  34938. const char *zFilename, /* Name of file to delete */
  34939. int syncDir /* Not used on win32 */
  34940. ){
  34941. int cnt = 0;
  34942. int rc;
  34943. DWORD attr;
  34944. DWORD lastErrno = 0;
  34945. void *zConverted;
  34946. UNUSED_PARAMETER(pVfs);
  34947. UNUSED_PARAMETER(syncDir);
  34948. SimulateIOError(return SQLITE_IOERR_DELETE);
  34949. OSTRACE(("DELETE name=%s, syncDir=%d\n", zFilename, syncDir));
  34950. zConverted = winConvertFromUtf8Filename(zFilename);
  34951. if( zConverted==0 ){
  34952. OSTRACE(("DELETE name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  34953. return SQLITE_IOERR_NOMEM;
  34954. }
  34955. if( osIsNT() ){
  34956. do {
  34957. #if SQLITE_OS_WINRT
  34958. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  34959. memset(&sAttrData, 0, sizeof(sAttrData));
  34960. if ( osGetFileAttributesExW(zConverted, GetFileExInfoStandard,
  34961. &sAttrData) ){
  34962. attr = sAttrData.dwFileAttributes;
  34963. }else{
  34964. lastErrno = osGetLastError();
  34965. if( lastErrno==ERROR_FILE_NOT_FOUND
  34966. || lastErrno==ERROR_PATH_NOT_FOUND ){
  34967. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  34968. }else{
  34969. rc = SQLITE_ERROR;
  34970. }
  34971. break;
  34972. }
  34973. #else
  34974. attr = osGetFileAttributesW(zConverted);
  34975. #endif
  34976. if ( attr==INVALID_FILE_ATTRIBUTES ){
  34977. lastErrno = osGetLastError();
  34978. if( lastErrno==ERROR_FILE_NOT_FOUND
  34979. || lastErrno==ERROR_PATH_NOT_FOUND ){
  34980. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  34981. }else{
  34982. rc = SQLITE_ERROR;
  34983. }
  34984. break;
  34985. }
  34986. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  34987. rc = SQLITE_ERROR; /* Files only. */
  34988. break;
  34989. }
  34990. if ( osDeleteFileW(zConverted) ){
  34991. rc = SQLITE_OK; /* Deleted OK. */
  34992. break;
  34993. }
  34994. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  34995. rc = SQLITE_ERROR; /* No more retries. */
  34996. break;
  34997. }
  34998. } while(1);
  34999. }
  35000. #ifdef SQLITE_WIN32_HAS_ANSI
  35001. else{
  35002. do {
  35003. attr = osGetFileAttributesA(zConverted);
  35004. if ( attr==INVALID_FILE_ATTRIBUTES ){
  35005. lastErrno = osGetLastError();
  35006. if( lastErrno==ERROR_FILE_NOT_FOUND
  35007. || lastErrno==ERROR_PATH_NOT_FOUND ){
  35008. rc = SQLITE_IOERR_DELETE_NOENT; /* Already gone? */
  35009. }else{
  35010. rc = SQLITE_ERROR;
  35011. }
  35012. break;
  35013. }
  35014. if ( attr&FILE_ATTRIBUTE_DIRECTORY ){
  35015. rc = SQLITE_ERROR; /* Files only. */
  35016. break;
  35017. }
  35018. if ( osDeleteFileA(zConverted) ){
  35019. rc = SQLITE_OK; /* Deleted OK. */
  35020. break;
  35021. }
  35022. if ( !winRetryIoerr(&cnt, &lastErrno) ){
  35023. rc = SQLITE_ERROR; /* No more retries. */
  35024. break;
  35025. }
  35026. } while(1);
  35027. }
  35028. #endif
  35029. if( rc && rc!=SQLITE_IOERR_DELETE_NOENT ){
  35030. rc = winLogError(SQLITE_IOERR_DELETE, lastErrno, "winDelete", zFilename);
  35031. }else{
  35032. winLogIoerr(cnt);
  35033. }
  35034. sqlite3_free(zConverted);
  35035. OSTRACE(("DELETE name=%s, rc=%s\n", zFilename, sqlite3ErrName(rc)));
  35036. return rc;
  35037. }
  35038. /*
  35039. ** Check the existence and status of a file.
  35040. */
  35041. static int winAccess(
  35042. sqlite3_vfs *pVfs, /* Not used on win32 */
  35043. const char *zFilename, /* Name of file to check */
  35044. int flags, /* Type of test to make on this file */
  35045. int *pResOut /* OUT: Result */
  35046. ){
  35047. DWORD attr;
  35048. int rc = 0;
  35049. DWORD lastErrno = 0;
  35050. void *zConverted;
  35051. UNUSED_PARAMETER(pVfs);
  35052. SimulateIOError( return SQLITE_IOERR_ACCESS; );
  35053. OSTRACE(("ACCESS name=%s, flags=%x, pResOut=%p\n",
  35054. zFilename, flags, pResOut));
  35055. zConverted = winConvertFromUtf8Filename(zFilename);
  35056. if( zConverted==0 ){
  35057. OSTRACE(("ACCESS name=%s, rc=SQLITE_IOERR_NOMEM\n", zFilename));
  35058. return SQLITE_IOERR_NOMEM;
  35059. }
  35060. if( osIsNT() ){
  35061. int cnt = 0;
  35062. WIN32_FILE_ATTRIBUTE_DATA sAttrData;
  35063. memset(&sAttrData, 0, sizeof(sAttrData));
  35064. while( !(rc = osGetFileAttributesExW((LPCWSTR)zConverted,
  35065. GetFileExInfoStandard,
  35066. &sAttrData)) && winRetryIoerr(&cnt, &lastErrno) ){}
  35067. if( rc ){
  35068. /* For an SQLITE_ACCESS_EXISTS query, treat a zero-length file
  35069. ** as if it does not exist.
  35070. */
  35071. if( flags==SQLITE_ACCESS_EXISTS
  35072. && sAttrData.nFileSizeHigh==0
  35073. && sAttrData.nFileSizeLow==0 ){
  35074. attr = INVALID_FILE_ATTRIBUTES;
  35075. }else{
  35076. attr = sAttrData.dwFileAttributes;
  35077. }
  35078. }else{
  35079. winLogIoerr(cnt);
  35080. if( lastErrno!=ERROR_FILE_NOT_FOUND && lastErrno!=ERROR_PATH_NOT_FOUND ){
  35081. sqlite3_free(zConverted);
  35082. return winLogError(SQLITE_IOERR_ACCESS, lastErrno, "winAccess",
  35083. zFilename);
  35084. }else{
  35085. attr = INVALID_FILE_ATTRIBUTES;
  35086. }
  35087. }
  35088. }
  35089. #ifdef SQLITE_WIN32_HAS_ANSI
  35090. else{
  35091. attr = osGetFileAttributesA((char*)zConverted);
  35092. }
  35093. #endif
  35094. sqlite3_free(zConverted);
  35095. switch( flags ){
  35096. case SQLITE_ACCESS_READ:
  35097. case SQLITE_ACCESS_EXISTS:
  35098. rc = attr!=INVALID_FILE_ATTRIBUTES;
  35099. break;
  35100. case SQLITE_ACCESS_READWRITE:
  35101. rc = attr!=INVALID_FILE_ATTRIBUTES &&
  35102. (attr & FILE_ATTRIBUTE_READONLY)==0;
  35103. break;
  35104. default:
  35105. assert(!"Invalid flags argument");
  35106. }
  35107. *pResOut = rc;
  35108. OSTRACE(("ACCESS name=%s, pResOut=%p, *pResOut=%d, rc=SQLITE_OK\n",
  35109. zFilename, pResOut, *pResOut));
  35110. return SQLITE_OK;
  35111. }
  35112. /*
  35113. ** Returns non-zero if the specified path name starts with a drive letter
  35114. ** followed by a colon character.
  35115. */
  35116. static BOOL winIsDriveLetterAndColon(
  35117. const char *zPathname
  35118. ){
  35119. return ( sqlite3Isalpha(zPathname[0]) && zPathname[1]==':' );
  35120. }
  35121. /*
  35122. ** Returns non-zero if the specified path name should be used verbatim. If
  35123. ** non-zero is returned from this function, the calling function must simply
  35124. ** use the provided path name verbatim -OR- resolve it into a full path name
  35125. ** using the GetFullPathName Win32 API function (if available).
  35126. */
  35127. static BOOL winIsVerbatimPathname(
  35128. const char *zPathname
  35129. ){
  35130. /*
  35131. ** If the path name starts with a forward slash or a backslash, it is either
  35132. ** a legal UNC name, a volume relative path, or an absolute path name in the
  35133. ** "Unix" format on Windows. There is no easy way to differentiate between
  35134. ** the final two cases; therefore, we return the safer return value of TRUE
  35135. ** so that callers of this function will simply use it verbatim.
  35136. */
  35137. if ( winIsDirSep(zPathname[0]) ){
  35138. return TRUE;
  35139. }
  35140. /*
  35141. ** If the path name starts with a letter and a colon it is either a volume
  35142. ** relative path or an absolute path. Callers of this function must not
  35143. ** attempt to treat it as a relative path name (i.e. they should simply use
  35144. ** it verbatim).
  35145. */
  35146. if ( winIsDriveLetterAndColon(zPathname) ){
  35147. return TRUE;
  35148. }
  35149. /*
  35150. ** If we get to this point, the path name should almost certainly be a purely
  35151. ** relative one (i.e. not a UNC name, not absolute, and not volume relative).
  35152. */
  35153. return FALSE;
  35154. }
  35155. /*
  35156. ** Turn a relative pathname into a full pathname. Write the full
  35157. ** pathname into zOut[]. zOut[] will be at least pVfs->mxPathname
  35158. ** bytes in size.
  35159. */
  35160. static int winFullPathname(
  35161. sqlite3_vfs *pVfs, /* Pointer to vfs object */
  35162. const char *zRelative, /* Possibly relative input path */
  35163. int nFull, /* Size of output buffer in bytes */
  35164. char *zFull /* Output buffer */
  35165. ){
  35166. #if defined(__CYGWIN__)
  35167. SimulateIOError( return SQLITE_ERROR );
  35168. UNUSED_PARAMETER(nFull);
  35169. assert( nFull>=pVfs->mxPathname );
  35170. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35171. /*
  35172. ** NOTE: We are dealing with a relative path name and the data
  35173. ** directory has been set. Therefore, use it as the basis
  35174. ** for converting the relative path name to an absolute
  35175. ** one by prepending the data directory and a slash.
  35176. */
  35177. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  35178. if( !zOut ){
  35179. return SQLITE_IOERR_NOMEM;
  35180. }
  35181. if( cygwin_conv_path(
  35182. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A) |
  35183. CCP_RELATIVE, zRelative, zOut, pVfs->mxPathname+1)<0 ){
  35184. sqlite3_free(zOut);
  35185. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  35186. "winFullPathname1", zRelative);
  35187. }else{
  35188. char *zUtf8 = winConvertToUtf8Filename(zOut);
  35189. if( !zUtf8 ){
  35190. sqlite3_free(zOut);
  35191. return SQLITE_IOERR_NOMEM;
  35192. }
  35193. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35194. sqlite3_data_directory, winGetDirSep(), zUtf8);
  35195. sqlite3_free(zUtf8);
  35196. sqlite3_free(zOut);
  35197. }
  35198. }else{
  35199. char *zOut = sqlite3MallocZero( pVfs->mxPathname+1 );
  35200. if( !zOut ){
  35201. return SQLITE_IOERR_NOMEM;
  35202. }
  35203. if( cygwin_conv_path(
  35204. (osIsNT() ? CCP_POSIX_TO_WIN_W : CCP_POSIX_TO_WIN_A),
  35205. zRelative, zOut, pVfs->mxPathname+1)<0 ){
  35206. sqlite3_free(zOut);
  35207. return winLogError(SQLITE_CANTOPEN_CONVPATH, (DWORD)errno,
  35208. "winFullPathname2", zRelative);
  35209. }else{
  35210. char *zUtf8 = winConvertToUtf8Filename(zOut);
  35211. if( !zUtf8 ){
  35212. sqlite3_free(zOut);
  35213. return SQLITE_IOERR_NOMEM;
  35214. }
  35215. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zUtf8);
  35216. sqlite3_free(zUtf8);
  35217. sqlite3_free(zOut);
  35218. }
  35219. }
  35220. return SQLITE_OK;
  35221. #endif
  35222. #if (SQLITE_OS_WINCE || SQLITE_OS_WINRT) && !defined(__CYGWIN__)
  35223. SimulateIOError( return SQLITE_ERROR );
  35224. /* WinCE has no concept of a relative pathname, or so I am told. */
  35225. /* WinRT has no way to convert a relative path to an absolute one. */
  35226. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35227. /*
  35228. ** NOTE: We are dealing with a relative path name and the data
  35229. ** directory has been set. Therefore, use it as the basis
  35230. ** for converting the relative path name to an absolute
  35231. ** one by prepending the data directory and a backslash.
  35232. */
  35233. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35234. sqlite3_data_directory, winGetDirSep(), zRelative);
  35235. }else{
  35236. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zRelative);
  35237. }
  35238. return SQLITE_OK;
  35239. #endif
  35240. #if !SQLITE_OS_WINCE && !SQLITE_OS_WINRT && !defined(__CYGWIN__)
  35241. DWORD nByte;
  35242. void *zConverted;
  35243. char *zOut;
  35244. /* If this path name begins with "/X:", where "X" is any alphabetic
  35245. ** character, discard the initial "/" from the pathname.
  35246. */
  35247. if( zRelative[0]=='/' && winIsDriveLetterAndColon(zRelative+1) ){
  35248. zRelative++;
  35249. }
  35250. /* It's odd to simulate an io-error here, but really this is just
  35251. ** using the io-error infrastructure to test that SQLite handles this
  35252. ** function failing. This function could fail if, for example, the
  35253. ** current working directory has been unlinked.
  35254. */
  35255. SimulateIOError( return SQLITE_ERROR );
  35256. if ( sqlite3_data_directory && !winIsVerbatimPathname(zRelative) ){
  35257. /*
  35258. ** NOTE: We are dealing with a relative path name and the data
  35259. ** directory has been set. Therefore, use it as the basis
  35260. ** for converting the relative path name to an absolute
  35261. ** one by prepending the data directory and a backslash.
  35262. */
  35263. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s%c%s",
  35264. sqlite3_data_directory, winGetDirSep(), zRelative);
  35265. return SQLITE_OK;
  35266. }
  35267. zConverted = winConvertFromUtf8Filename(zRelative);
  35268. if( zConverted==0 ){
  35269. return SQLITE_IOERR_NOMEM;
  35270. }
  35271. if( osIsNT() ){
  35272. LPWSTR zTemp;
  35273. nByte = osGetFullPathNameW((LPCWSTR)zConverted, 0, 0, 0);
  35274. if( nByte==0 ){
  35275. sqlite3_free(zConverted);
  35276. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35277. "winFullPathname1", zRelative);
  35278. }
  35279. nByte += 3;
  35280. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  35281. if( zTemp==0 ){
  35282. sqlite3_free(zConverted);
  35283. return SQLITE_IOERR_NOMEM;
  35284. }
  35285. nByte = osGetFullPathNameW((LPCWSTR)zConverted, nByte, zTemp, 0);
  35286. if( nByte==0 ){
  35287. sqlite3_free(zConverted);
  35288. sqlite3_free(zTemp);
  35289. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35290. "winFullPathname2", zRelative);
  35291. }
  35292. sqlite3_free(zConverted);
  35293. zOut = winUnicodeToUtf8(zTemp);
  35294. sqlite3_free(zTemp);
  35295. }
  35296. #ifdef SQLITE_WIN32_HAS_ANSI
  35297. else{
  35298. char *zTemp;
  35299. nByte = osGetFullPathNameA((char*)zConverted, 0, 0, 0);
  35300. if( nByte==0 ){
  35301. sqlite3_free(zConverted);
  35302. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35303. "winFullPathname3", zRelative);
  35304. }
  35305. nByte += 3;
  35306. zTemp = sqlite3MallocZero( nByte*sizeof(zTemp[0]) );
  35307. if( zTemp==0 ){
  35308. sqlite3_free(zConverted);
  35309. return SQLITE_IOERR_NOMEM;
  35310. }
  35311. nByte = osGetFullPathNameA((char*)zConverted, nByte, zTemp, 0);
  35312. if( nByte==0 ){
  35313. sqlite3_free(zConverted);
  35314. sqlite3_free(zTemp);
  35315. return winLogError(SQLITE_CANTOPEN_FULLPATH, osGetLastError(),
  35316. "winFullPathname4", zRelative);
  35317. }
  35318. sqlite3_free(zConverted);
  35319. zOut = sqlite3_win32_mbcs_to_utf8(zTemp);
  35320. sqlite3_free(zTemp);
  35321. }
  35322. #endif
  35323. if( zOut ){
  35324. sqlite3_snprintf(MIN(nFull, pVfs->mxPathname), zFull, "%s", zOut);
  35325. sqlite3_free(zOut);
  35326. return SQLITE_OK;
  35327. }else{
  35328. return SQLITE_IOERR_NOMEM;
  35329. }
  35330. #endif
  35331. }
  35332. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  35333. /*
  35334. ** Interfaces for opening a shared library, finding entry points
  35335. ** within the shared library, and closing the shared library.
  35336. */
  35337. static void *winDlOpen(sqlite3_vfs *pVfs, const char *zFilename){
  35338. HANDLE h;
  35339. #if defined(__CYGWIN__)
  35340. int nFull = pVfs->mxPathname+1;
  35341. char *zFull = sqlite3MallocZero( nFull );
  35342. void *zConverted = 0;
  35343. if( zFull==0 ){
  35344. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  35345. return 0;
  35346. }
  35347. if( winFullPathname(pVfs, zFilename, nFull, zFull)!=SQLITE_OK ){
  35348. sqlite3_free(zFull);
  35349. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  35350. return 0;
  35351. }
  35352. zConverted = winConvertFromUtf8Filename(zFull);
  35353. sqlite3_free(zFull);
  35354. #else
  35355. void *zConverted = winConvertFromUtf8Filename(zFilename);
  35356. UNUSED_PARAMETER(pVfs);
  35357. #endif
  35358. if( zConverted==0 ){
  35359. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)0));
  35360. return 0;
  35361. }
  35362. if( osIsNT() ){
  35363. #if SQLITE_OS_WINRT
  35364. h = osLoadPackagedLibrary((LPCWSTR)zConverted, 0);
  35365. #else
  35366. h = osLoadLibraryW((LPCWSTR)zConverted);
  35367. #endif
  35368. }
  35369. #ifdef SQLITE_WIN32_HAS_ANSI
  35370. else{
  35371. h = osLoadLibraryA((char*)zConverted);
  35372. }
  35373. #endif
  35374. OSTRACE(("DLOPEN name=%s, handle=%p\n", zFilename, (void*)h));
  35375. sqlite3_free(zConverted);
  35376. return (void*)h;
  35377. }
  35378. static void winDlError(sqlite3_vfs *pVfs, int nBuf, char *zBufOut){
  35379. UNUSED_PARAMETER(pVfs);
  35380. winGetLastErrorMsg(osGetLastError(), nBuf, zBufOut);
  35381. }
  35382. static void (*winDlSym(sqlite3_vfs *pVfs,void *pH,const char *zSym))(void){
  35383. FARPROC proc;
  35384. UNUSED_PARAMETER(pVfs);
  35385. proc = osGetProcAddressA((HANDLE)pH, zSym);
  35386. OSTRACE(("DLSYM handle=%p, symbol=%s, address=%p\n",
  35387. (void*)pH, zSym, (void*)proc));
  35388. return (void(*)(void))proc;
  35389. }
  35390. static void winDlClose(sqlite3_vfs *pVfs, void *pHandle){
  35391. UNUSED_PARAMETER(pVfs);
  35392. osFreeLibrary((HANDLE)pHandle);
  35393. OSTRACE(("DLCLOSE handle=%p\n", (void*)pHandle));
  35394. }
  35395. #else /* if SQLITE_OMIT_LOAD_EXTENSION is defined: */
  35396. #define winDlOpen 0
  35397. #define winDlError 0
  35398. #define winDlSym 0
  35399. #define winDlClose 0
  35400. #endif
  35401. /*
  35402. ** Write up to nBuf bytes of randomness into zBuf.
  35403. */
  35404. static int winRandomness(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  35405. int n = 0;
  35406. UNUSED_PARAMETER(pVfs);
  35407. #if defined(SQLITE_TEST)
  35408. n = nBuf;
  35409. memset(zBuf, 0, nBuf);
  35410. #else
  35411. if( sizeof(SYSTEMTIME)<=nBuf-n ){
  35412. SYSTEMTIME x;
  35413. osGetSystemTime(&x);
  35414. memcpy(&zBuf[n], &x, sizeof(x));
  35415. n += sizeof(x);
  35416. }
  35417. if( sizeof(DWORD)<=nBuf-n ){
  35418. DWORD pid = osGetCurrentProcessId();
  35419. memcpy(&zBuf[n], &pid, sizeof(pid));
  35420. n += sizeof(pid);
  35421. }
  35422. #if SQLITE_OS_WINRT
  35423. if( sizeof(ULONGLONG)<=nBuf-n ){
  35424. ULONGLONG cnt = osGetTickCount64();
  35425. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  35426. n += sizeof(cnt);
  35427. }
  35428. #else
  35429. if( sizeof(DWORD)<=nBuf-n ){
  35430. DWORD cnt = osGetTickCount();
  35431. memcpy(&zBuf[n], &cnt, sizeof(cnt));
  35432. n += sizeof(cnt);
  35433. }
  35434. #endif
  35435. if( sizeof(LARGE_INTEGER)<=nBuf-n ){
  35436. LARGE_INTEGER i;
  35437. osQueryPerformanceCounter(&i);
  35438. memcpy(&zBuf[n], &i, sizeof(i));
  35439. n += sizeof(i);
  35440. }
  35441. #endif
  35442. return n;
  35443. }
  35444. /*
  35445. ** Sleep for a little while. Return the amount of time slept.
  35446. */
  35447. static int winSleep(sqlite3_vfs *pVfs, int microsec){
  35448. sqlite3_win32_sleep((microsec+999)/1000);
  35449. UNUSED_PARAMETER(pVfs);
  35450. return ((microsec+999)/1000)*1000;
  35451. }
  35452. /*
  35453. ** The following variable, if set to a non-zero value, is interpreted as
  35454. ** the number of seconds since 1970 and is used to set the result of
  35455. ** sqlite3OsCurrentTime() during testing.
  35456. */
  35457. #ifdef SQLITE_TEST
  35458. SQLITE_API int sqlite3_current_time = 0; /* Fake system time in seconds since 1970. */
  35459. #endif
  35460. /*
  35461. ** Find the current time (in Universal Coordinated Time). Write into *piNow
  35462. ** the current time and date as a Julian Day number times 86_400_000. In
  35463. ** other words, write into *piNow the number of milliseconds since the Julian
  35464. ** epoch of noon in Greenwich on November 24, 4714 B.C according to the
  35465. ** proleptic Gregorian calendar.
  35466. **
  35467. ** On success, return SQLITE_OK. Return SQLITE_ERROR if the time and date
  35468. ** cannot be found.
  35469. */
  35470. static int winCurrentTimeInt64(sqlite3_vfs *pVfs, sqlite3_int64 *piNow){
  35471. /* FILETIME structure is a 64-bit value representing the number of
  35472. 100-nanosecond intervals since January 1, 1601 (= JD 2305813.5).
  35473. */
  35474. FILETIME ft;
  35475. static const sqlite3_int64 winFiletimeEpoch = 23058135*(sqlite3_int64)8640000;
  35476. #ifdef SQLITE_TEST
  35477. static const sqlite3_int64 unixEpoch = 24405875*(sqlite3_int64)8640000;
  35478. #endif
  35479. /* 2^32 - to avoid use of LL and warnings in gcc */
  35480. static const sqlite3_int64 max32BitValue =
  35481. (sqlite3_int64)2000000000 + (sqlite3_int64)2000000000 +
  35482. (sqlite3_int64)294967296;
  35483. #if SQLITE_OS_WINCE
  35484. SYSTEMTIME time;
  35485. osGetSystemTime(&time);
  35486. /* if SystemTimeToFileTime() fails, it returns zero. */
  35487. if (!osSystemTimeToFileTime(&time,&ft)){
  35488. return SQLITE_ERROR;
  35489. }
  35490. #else
  35491. osGetSystemTimeAsFileTime( &ft );
  35492. #endif
  35493. *piNow = winFiletimeEpoch +
  35494. ((((sqlite3_int64)ft.dwHighDateTime)*max32BitValue) +
  35495. (sqlite3_int64)ft.dwLowDateTime)/(sqlite3_int64)10000;
  35496. #ifdef SQLITE_TEST
  35497. if( sqlite3_current_time ){
  35498. *piNow = 1000*(sqlite3_int64)sqlite3_current_time + unixEpoch;
  35499. }
  35500. #endif
  35501. UNUSED_PARAMETER(pVfs);
  35502. return SQLITE_OK;
  35503. }
  35504. /*
  35505. ** Find the current time (in Universal Coordinated Time). Write the
  35506. ** current time and date as a Julian Day number into *prNow and
  35507. ** return 0. Return 1 if the time and date cannot be found.
  35508. */
  35509. static int winCurrentTime(sqlite3_vfs *pVfs, double *prNow){
  35510. int rc;
  35511. sqlite3_int64 i;
  35512. rc = winCurrentTimeInt64(pVfs, &i);
  35513. if( !rc ){
  35514. *prNow = i/86400000.0;
  35515. }
  35516. return rc;
  35517. }
  35518. /*
  35519. ** The idea is that this function works like a combination of
  35520. ** GetLastError() and FormatMessage() on Windows (or errno and
  35521. ** strerror_r() on Unix). After an error is returned by an OS
  35522. ** function, SQLite calls this function with zBuf pointing to
  35523. ** a buffer of nBuf bytes. The OS layer should populate the
  35524. ** buffer with a nul-terminated UTF-8 encoded error message
  35525. ** describing the last IO error to have occurred within the calling
  35526. ** thread.
  35527. **
  35528. ** If the error message is too large for the supplied buffer,
  35529. ** it should be truncated. The return value of xGetLastError
  35530. ** is zero if the error message fits in the buffer, or non-zero
  35531. ** otherwise (if the message was truncated). If non-zero is returned,
  35532. ** then it is not necessary to include the nul-terminator character
  35533. ** in the output buffer.
  35534. **
  35535. ** Not supplying an error message will have no adverse effect
  35536. ** on SQLite. It is fine to have an implementation that never
  35537. ** returns an error message:
  35538. **
  35539. ** int xGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  35540. ** assert(zBuf[0]=='\0');
  35541. ** return 0;
  35542. ** }
  35543. **
  35544. ** However if an error message is supplied, it will be incorporated
  35545. ** by sqlite into the error message available to the user using
  35546. ** sqlite3_errmsg(), possibly making IO errors easier to debug.
  35547. */
  35548. static int winGetLastError(sqlite3_vfs *pVfs, int nBuf, char *zBuf){
  35549. UNUSED_PARAMETER(pVfs);
  35550. return winGetLastErrorMsg(osGetLastError(), nBuf, zBuf);
  35551. }
  35552. /*
  35553. ** Initialize and deinitialize the operating system interface.
  35554. */
  35555. SQLITE_API int sqlite3_os_init(void){
  35556. static sqlite3_vfs winVfs = {
  35557. 3, /* iVersion */
  35558. sizeof(winFile), /* szOsFile */
  35559. SQLITE_WIN32_MAX_PATH_BYTES, /* mxPathname */
  35560. 0, /* pNext */
  35561. "win32", /* zName */
  35562. 0, /* pAppData */
  35563. winOpen, /* xOpen */
  35564. winDelete, /* xDelete */
  35565. winAccess, /* xAccess */
  35566. winFullPathname, /* xFullPathname */
  35567. winDlOpen, /* xDlOpen */
  35568. winDlError, /* xDlError */
  35569. winDlSym, /* xDlSym */
  35570. winDlClose, /* xDlClose */
  35571. winRandomness, /* xRandomness */
  35572. winSleep, /* xSleep */
  35573. winCurrentTime, /* xCurrentTime */
  35574. winGetLastError, /* xGetLastError */
  35575. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  35576. winSetSystemCall, /* xSetSystemCall */
  35577. winGetSystemCall, /* xGetSystemCall */
  35578. winNextSystemCall, /* xNextSystemCall */
  35579. };
  35580. #if defined(SQLITE_WIN32_HAS_WIDE)
  35581. static sqlite3_vfs winLongPathVfs = {
  35582. 3, /* iVersion */
  35583. sizeof(winFile), /* szOsFile */
  35584. SQLITE_WINNT_MAX_PATH_BYTES, /* mxPathname */
  35585. 0, /* pNext */
  35586. "win32-longpath", /* zName */
  35587. 0, /* pAppData */
  35588. winOpen, /* xOpen */
  35589. winDelete, /* xDelete */
  35590. winAccess, /* xAccess */
  35591. winFullPathname, /* xFullPathname */
  35592. winDlOpen, /* xDlOpen */
  35593. winDlError, /* xDlError */
  35594. winDlSym, /* xDlSym */
  35595. winDlClose, /* xDlClose */
  35596. winRandomness, /* xRandomness */
  35597. winSleep, /* xSleep */
  35598. winCurrentTime, /* xCurrentTime */
  35599. winGetLastError, /* xGetLastError */
  35600. winCurrentTimeInt64, /* xCurrentTimeInt64 */
  35601. winSetSystemCall, /* xSetSystemCall */
  35602. winGetSystemCall, /* xGetSystemCall */
  35603. winNextSystemCall, /* xNextSystemCall */
  35604. };
  35605. #endif
  35606. /* Double-check that the aSyscall[] array has been constructed
  35607. ** correctly. See ticket [bb3a86e890c8e96ab] */
  35608. assert( ArraySize(aSyscall)==77 );
  35609. /* get memory map allocation granularity */
  35610. memset(&winSysInfo, 0, sizeof(SYSTEM_INFO));
  35611. #if SQLITE_OS_WINRT
  35612. osGetNativeSystemInfo(&winSysInfo);
  35613. #else
  35614. osGetSystemInfo(&winSysInfo);
  35615. #endif
  35616. assert( winSysInfo.dwAllocationGranularity>0 );
  35617. assert( winSysInfo.dwPageSize>0 );
  35618. sqlite3_vfs_register(&winVfs, 1);
  35619. #if defined(SQLITE_WIN32_HAS_WIDE)
  35620. sqlite3_vfs_register(&winLongPathVfs, 0);
  35621. #endif
  35622. return SQLITE_OK;
  35623. }
  35624. SQLITE_API int sqlite3_os_end(void){
  35625. #if SQLITE_OS_WINRT
  35626. if( sleepObj!=NULL ){
  35627. osCloseHandle(sleepObj);
  35628. sleepObj = NULL;
  35629. }
  35630. #endif
  35631. return SQLITE_OK;
  35632. }
  35633. #endif /* SQLITE_OS_WIN */
  35634. /************** End of os_win.c **********************************************/
  35635. /************** Begin file bitvec.c ******************************************/
  35636. /*
  35637. ** 2008 February 16
  35638. **
  35639. ** The author disclaims copyright to this source code. In place of
  35640. ** a legal notice, here is a blessing:
  35641. **
  35642. ** May you do good and not evil.
  35643. ** May you find forgiveness for yourself and forgive others.
  35644. ** May you share freely, never taking more than you give.
  35645. **
  35646. *************************************************************************
  35647. ** This file implements an object that represents a fixed-length
  35648. ** bitmap. Bits are numbered starting with 1.
  35649. **
  35650. ** A bitmap is used to record which pages of a database file have been
  35651. ** journalled during a transaction, or which pages have the "dont-write"
  35652. ** property. Usually only a few pages are meet either condition.
  35653. ** So the bitmap is usually sparse and has low cardinality.
  35654. ** But sometimes (for example when during a DROP of a large table) most
  35655. ** or all of the pages in a database can get journalled. In those cases,
  35656. ** the bitmap becomes dense with high cardinality. The algorithm needs
  35657. ** to handle both cases well.
  35658. **
  35659. ** The size of the bitmap is fixed when the object is created.
  35660. **
  35661. ** All bits are clear when the bitmap is created. Individual bits
  35662. ** may be set or cleared one at a time.
  35663. **
  35664. ** Test operations are about 100 times more common that set operations.
  35665. ** Clear operations are exceedingly rare. There are usually between
  35666. ** 5 and 500 set operations per Bitvec object, though the number of sets can
  35667. ** sometimes grow into tens of thousands or larger. The size of the
  35668. ** Bitvec object is the number of pages in the database file at the
  35669. ** start of a transaction, and is thus usually less than a few thousand,
  35670. ** but can be as large as 2 billion for a really big database.
  35671. */
  35672. /* Size of the Bitvec structure in bytes. */
  35673. #define BITVEC_SZ 512
  35674. /* Round the union size down to the nearest pointer boundary, since that's how
  35675. ** it will be aligned within the Bitvec struct. */
  35676. #define BITVEC_USIZE (((BITVEC_SZ-(3*sizeof(u32)))/sizeof(Bitvec*))*sizeof(Bitvec*))
  35677. /* Type of the array "element" for the bitmap representation.
  35678. ** Should be a power of 2, and ideally, evenly divide into BITVEC_USIZE.
  35679. ** Setting this to the "natural word" size of your CPU may improve
  35680. ** performance. */
  35681. #define BITVEC_TELEM u8
  35682. /* Size, in bits, of the bitmap element. */
  35683. #define BITVEC_SZELEM 8
  35684. /* Number of elements in a bitmap array. */
  35685. #define BITVEC_NELEM (BITVEC_USIZE/sizeof(BITVEC_TELEM))
  35686. /* Number of bits in the bitmap array. */
  35687. #define BITVEC_NBIT (BITVEC_NELEM*BITVEC_SZELEM)
  35688. /* Number of u32 values in hash table. */
  35689. #define BITVEC_NINT (BITVEC_USIZE/sizeof(u32))
  35690. /* Maximum number of entries in hash table before
  35691. ** sub-dividing and re-hashing. */
  35692. #define BITVEC_MXHASH (BITVEC_NINT/2)
  35693. /* Hashing function for the aHash representation.
  35694. ** Empirical testing showed that the *37 multiplier
  35695. ** (an arbitrary prime)in the hash function provided
  35696. ** no fewer collisions than the no-op *1. */
  35697. #define BITVEC_HASH(X) (((X)*1)%BITVEC_NINT)
  35698. #define BITVEC_NPTR (BITVEC_USIZE/sizeof(Bitvec *))
  35699. /*
  35700. ** A bitmap is an instance of the following structure.
  35701. **
  35702. ** This bitmap records the existence of zero or more bits
  35703. ** with values between 1 and iSize, inclusive.
  35704. **
  35705. ** There are three possible representations of the bitmap.
  35706. ** If iSize<=BITVEC_NBIT, then Bitvec.u.aBitmap[] is a straight
  35707. ** bitmap. The least significant bit is bit 1.
  35708. **
  35709. ** If iSize>BITVEC_NBIT and iDivisor==0 then Bitvec.u.aHash[] is
  35710. ** a hash table that will hold up to BITVEC_MXHASH distinct values.
  35711. **
  35712. ** Otherwise, the value i is redirected into one of BITVEC_NPTR
  35713. ** sub-bitmaps pointed to by Bitvec.u.apSub[]. Each subbitmap
  35714. ** handles up to iDivisor separate values of i. apSub[0] holds
  35715. ** values between 1 and iDivisor. apSub[1] holds values between
  35716. ** iDivisor+1 and 2*iDivisor. apSub[N] holds values between
  35717. ** N*iDivisor+1 and (N+1)*iDivisor. Each subbitmap is normalized
  35718. ** to hold deal with values between 1 and iDivisor.
  35719. */
  35720. struct Bitvec {
  35721. u32 iSize; /* Maximum bit index. Max iSize is 4,294,967,296. */
  35722. u32 nSet; /* Number of bits that are set - only valid for aHash
  35723. ** element. Max is BITVEC_NINT. For BITVEC_SZ of 512,
  35724. ** this would be 125. */
  35725. u32 iDivisor; /* Number of bits handled by each apSub[] entry. */
  35726. /* Should >=0 for apSub element. */
  35727. /* Max iDivisor is max(u32) / BITVEC_NPTR + 1. */
  35728. /* For a BITVEC_SZ of 512, this would be 34,359,739. */
  35729. union {
  35730. BITVEC_TELEM aBitmap[BITVEC_NELEM]; /* Bitmap representation */
  35731. u32 aHash[BITVEC_NINT]; /* Hash table representation */
  35732. Bitvec *apSub[BITVEC_NPTR]; /* Recursive representation */
  35733. } u;
  35734. };
  35735. /*
  35736. ** Create a new bitmap object able to handle bits between 0 and iSize,
  35737. ** inclusive. Return a pointer to the new object. Return NULL if
  35738. ** malloc fails.
  35739. */
  35740. SQLITE_PRIVATE Bitvec *sqlite3BitvecCreate(u32 iSize){
  35741. Bitvec *p;
  35742. assert( sizeof(*p)==BITVEC_SZ );
  35743. p = sqlite3MallocZero( sizeof(*p) );
  35744. if( p ){
  35745. p->iSize = iSize;
  35746. }
  35747. return p;
  35748. }
  35749. /*
  35750. ** Check to see if the i-th bit is set. Return true or false.
  35751. ** If p is NULL (if the bitmap has not been created) or if
  35752. ** i is out of range, then return false.
  35753. */
  35754. SQLITE_PRIVATE int sqlite3BitvecTest(Bitvec *p, u32 i){
  35755. if( p==0 ) return 0;
  35756. if( i>p->iSize || i==0 ) return 0;
  35757. i--;
  35758. while( p->iDivisor ){
  35759. u32 bin = i/p->iDivisor;
  35760. i = i%p->iDivisor;
  35761. p = p->u.apSub[bin];
  35762. if (!p) {
  35763. return 0;
  35764. }
  35765. }
  35766. if( p->iSize<=BITVEC_NBIT ){
  35767. return (p->u.aBitmap[i/BITVEC_SZELEM] & (1<<(i&(BITVEC_SZELEM-1))))!=0;
  35768. } else{
  35769. u32 h = BITVEC_HASH(i++);
  35770. while( p->u.aHash[h] ){
  35771. if( p->u.aHash[h]==i ) return 1;
  35772. h = (h+1) % BITVEC_NINT;
  35773. }
  35774. return 0;
  35775. }
  35776. }
  35777. /*
  35778. ** Set the i-th bit. Return 0 on success and an error code if
  35779. ** anything goes wrong.
  35780. **
  35781. ** This routine might cause sub-bitmaps to be allocated. Failing
  35782. ** to get the memory needed to hold the sub-bitmap is the only
  35783. ** that can go wrong with an insert, assuming p and i are valid.
  35784. **
  35785. ** The calling function must ensure that p is a valid Bitvec object
  35786. ** and that the value for "i" is within range of the Bitvec object.
  35787. ** Otherwise the behavior is undefined.
  35788. */
  35789. SQLITE_PRIVATE int sqlite3BitvecSet(Bitvec *p, u32 i){
  35790. u32 h;
  35791. if( p==0 ) return SQLITE_OK;
  35792. assert( i>0 );
  35793. assert( i<=p->iSize );
  35794. i--;
  35795. while((p->iSize > BITVEC_NBIT) && p->iDivisor) {
  35796. u32 bin = i/p->iDivisor;
  35797. i = i%p->iDivisor;
  35798. if( p->u.apSub[bin]==0 ){
  35799. p->u.apSub[bin] = sqlite3BitvecCreate( p->iDivisor );
  35800. if( p->u.apSub[bin]==0 ) return SQLITE_NOMEM;
  35801. }
  35802. p = p->u.apSub[bin];
  35803. }
  35804. if( p->iSize<=BITVEC_NBIT ){
  35805. p->u.aBitmap[i/BITVEC_SZELEM] |= 1 << (i&(BITVEC_SZELEM-1));
  35806. return SQLITE_OK;
  35807. }
  35808. h = BITVEC_HASH(i++);
  35809. /* if there wasn't a hash collision, and this doesn't */
  35810. /* completely fill the hash, then just add it without */
  35811. /* worring about sub-dividing and re-hashing. */
  35812. if( !p->u.aHash[h] ){
  35813. if (p->nSet<(BITVEC_NINT-1)) {
  35814. goto bitvec_set_end;
  35815. } else {
  35816. goto bitvec_set_rehash;
  35817. }
  35818. }
  35819. /* there was a collision, check to see if it's already */
  35820. /* in hash, if not, try to find a spot for it */
  35821. do {
  35822. if( p->u.aHash[h]==i ) return SQLITE_OK;
  35823. h++;
  35824. if( h>=BITVEC_NINT ) h = 0;
  35825. } while( p->u.aHash[h] );
  35826. /* we didn't find it in the hash. h points to the first */
  35827. /* available free spot. check to see if this is going to */
  35828. /* make our hash too "full". */
  35829. bitvec_set_rehash:
  35830. if( p->nSet>=BITVEC_MXHASH ){
  35831. unsigned int j;
  35832. int rc;
  35833. u32 *aiValues = sqlite3StackAllocRaw(0, sizeof(p->u.aHash));
  35834. if( aiValues==0 ){
  35835. return SQLITE_NOMEM;
  35836. }else{
  35837. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  35838. memset(p->u.apSub, 0, sizeof(p->u.apSub));
  35839. p->iDivisor = (p->iSize + BITVEC_NPTR - 1)/BITVEC_NPTR;
  35840. rc = sqlite3BitvecSet(p, i);
  35841. for(j=0; j<BITVEC_NINT; j++){
  35842. if( aiValues[j] ) rc |= sqlite3BitvecSet(p, aiValues[j]);
  35843. }
  35844. sqlite3StackFree(0, aiValues);
  35845. return rc;
  35846. }
  35847. }
  35848. bitvec_set_end:
  35849. p->nSet++;
  35850. p->u.aHash[h] = i;
  35851. return SQLITE_OK;
  35852. }
  35853. /*
  35854. ** Clear the i-th bit.
  35855. **
  35856. ** pBuf must be a pointer to at least BITVEC_SZ bytes of temporary storage
  35857. ** that BitvecClear can use to rebuilt its hash table.
  35858. */
  35859. SQLITE_PRIVATE void sqlite3BitvecClear(Bitvec *p, u32 i, void *pBuf){
  35860. if( p==0 ) return;
  35861. assert( i>0 );
  35862. i--;
  35863. while( p->iDivisor ){
  35864. u32 bin = i/p->iDivisor;
  35865. i = i%p->iDivisor;
  35866. p = p->u.apSub[bin];
  35867. if (!p) {
  35868. return;
  35869. }
  35870. }
  35871. if( p->iSize<=BITVEC_NBIT ){
  35872. p->u.aBitmap[i/BITVEC_SZELEM] &= ~(1 << (i&(BITVEC_SZELEM-1)));
  35873. }else{
  35874. unsigned int j;
  35875. u32 *aiValues = pBuf;
  35876. memcpy(aiValues, p->u.aHash, sizeof(p->u.aHash));
  35877. memset(p->u.aHash, 0, sizeof(p->u.aHash));
  35878. p->nSet = 0;
  35879. for(j=0; j<BITVEC_NINT; j++){
  35880. if( aiValues[j] && aiValues[j]!=(i+1) ){
  35881. u32 h = BITVEC_HASH(aiValues[j]-1);
  35882. p->nSet++;
  35883. while( p->u.aHash[h] ){
  35884. h++;
  35885. if( h>=BITVEC_NINT ) h = 0;
  35886. }
  35887. p->u.aHash[h] = aiValues[j];
  35888. }
  35889. }
  35890. }
  35891. }
  35892. /*
  35893. ** Destroy a bitmap object. Reclaim all memory used.
  35894. */
  35895. SQLITE_PRIVATE void sqlite3BitvecDestroy(Bitvec *p){
  35896. if( p==0 ) return;
  35897. if( p->iDivisor ){
  35898. unsigned int i;
  35899. for(i=0; i<BITVEC_NPTR; i++){
  35900. sqlite3BitvecDestroy(p->u.apSub[i]);
  35901. }
  35902. }
  35903. sqlite3_free(p);
  35904. }
  35905. /*
  35906. ** Return the value of the iSize parameter specified when Bitvec *p
  35907. ** was created.
  35908. */
  35909. SQLITE_PRIVATE u32 sqlite3BitvecSize(Bitvec *p){
  35910. return p->iSize;
  35911. }
  35912. #ifndef SQLITE_OMIT_BUILTIN_TEST
  35913. /*
  35914. ** Let V[] be an array of unsigned characters sufficient to hold
  35915. ** up to N bits. Let I be an integer between 0 and N. 0<=I<N.
  35916. ** Then the following macros can be used to set, clear, or test
  35917. ** individual bits within V.
  35918. */
  35919. #define SETBIT(V,I) V[I>>3] |= (1<<(I&7))
  35920. #define CLEARBIT(V,I) V[I>>3] &= ~(1<<(I&7))
  35921. #define TESTBIT(V,I) (V[I>>3]&(1<<(I&7)))!=0
  35922. /*
  35923. ** This routine runs an extensive test of the Bitvec code.
  35924. **
  35925. ** The input is an array of integers that acts as a program
  35926. ** to test the Bitvec. The integers are opcodes followed
  35927. ** by 0, 1, or 3 operands, depending on the opcode. Another
  35928. ** opcode follows immediately after the last operand.
  35929. **
  35930. ** There are 6 opcodes numbered from 0 through 5. 0 is the
  35931. ** "halt" opcode and causes the test to end.
  35932. **
  35933. ** 0 Halt and return the number of errors
  35934. ** 1 N S X Set N bits beginning with S and incrementing by X
  35935. ** 2 N S X Clear N bits beginning with S and incrementing by X
  35936. ** 3 N Set N randomly chosen bits
  35937. ** 4 N Clear N randomly chosen bits
  35938. ** 5 N S X Set N bits from S increment X in array only, not in bitvec
  35939. **
  35940. ** The opcodes 1 through 4 perform set and clear operations are performed
  35941. ** on both a Bitvec object and on a linear array of bits obtained from malloc.
  35942. ** Opcode 5 works on the linear array only, not on the Bitvec.
  35943. ** Opcode 5 is used to deliberately induce a fault in order to
  35944. ** confirm that error detection works.
  35945. **
  35946. ** At the conclusion of the test the linear array is compared
  35947. ** against the Bitvec object. If there are any differences,
  35948. ** an error is returned. If they are the same, zero is returned.
  35949. **
  35950. ** If a memory allocation error occurs, return -1.
  35951. */
  35952. SQLITE_PRIVATE int sqlite3BitvecBuiltinTest(int sz, int *aOp){
  35953. Bitvec *pBitvec = 0;
  35954. unsigned char *pV = 0;
  35955. int rc = -1;
  35956. int i, nx, pc, op;
  35957. void *pTmpSpace;
  35958. /* Allocate the Bitvec to be tested and a linear array of
  35959. ** bits to act as the reference */
  35960. pBitvec = sqlite3BitvecCreate( sz );
  35961. pV = sqlite3MallocZero( (sz+7)/8 + 1 );
  35962. pTmpSpace = sqlite3_malloc(BITVEC_SZ);
  35963. if( pBitvec==0 || pV==0 || pTmpSpace==0 ) goto bitvec_end;
  35964. /* NULL pBitvec tests */
  35965. sqlite3BitvecSet(0, 1);
  35966. sqlite3BitvecClear(0, 1, pTmpSpace);
  35967. /* Run the program */
  35968. pc = 0;
  35969. while( (op = aOp[pc])!=0 ){
  35970. switch( op ){
  35971. case 1:
  35972. case 2:
  35973. case 5: {
  35974. nx = 4;
  35975. i = aOp[pc+2] - 1;
  35976. aOp[pc+2] += aOp[pc+3];
  35977. break;
  35978. }
  35979. case 3:
  35980. case 4:
  35981. default: {
  35982. nx = 2;
  35983. sqlite3_randomness(sizeof(i), &i);
  35984. break;
  35985. }
  35986. }
  35987. if( (--aOp[pc+1]) > 0 ) nx = 0;
  35988. pc += nx;
  35989. i = (i & 0x7fffffff)%sz;
  35990. if( (op & 1)!=0 ){
  35991. SETBIT(pV, (i+1));
  35992. if( op!=5 ){
  35993. if( sqlite3BitvecSet(pBitvec, i+1) ) goto bitvec_end;
  35994. }
  35995. }else{
  35996. CLEARBIT(pV, (i+1));
  35997. sqlite3BitvecClear(pBitvec, i+1, pTmpSpace);
  35998. }
  35999. }
  36000. /* Test to make sure the linear array exactly matches the
  36001. ** Bitvec object. Start with the assumption that they do
  36002. ** match (rc==0). Change rc to non-zero if a discrepancy
  36003. ** is found.
  36004. */
  36005. rc = sqlite3BitvecTest(0,0) + sqlite3BitvecTest(pBitvec, sz+1)
  36006. + sqlite3BitvecTest(pBitvec, 0)
  36007. + (sqlite3BitvecSize(pBitvec) - sz);
  36008. for(i=1; i<=sz; i++){
  36009. if( (TESTBIT(pV,i))!=sqlite3BitvecTest(pBitvec,i) ){
  36010. rc = i;
  36011. break;
  36012. }
  36013. }
  36014. /* Free allocated structure */
  36015. bitvec_end:
  36016. sqlite3_free(pTmpSpace);
  36017. sqlite3_free(pV);
  36018. sqlite3BitvecDestroy(pBitvec);
  36019. return rc;
  36020. }
  36021. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  36022. /************** End of bitvec.c **********************************************/
  36023. /************** Begin file pcache.c ******************************************/
  36024. /*
  36025. ** 2008 August 05
  36026. **
  36027. ** The author disclaims copyright to this source code. In place of
  36028. ** a legal notice, here is a blessing:
  36029. **
  36030. ** May you do good and not evil.
  36031. ** May you find forgiveness for yourself and forgive others.
  36032. ** May you share freely, never taking more than you give.
  36033. **
  36034. *************************************************************************
  36035. ** This file implements that page cache.
  36036. */
  36037. /*
  36038. ** A complete page cache is an instance of this structure.
  36039. */
  36040. struct PCache {
  36041. PgHdr *pDirty, *pDirtyTail; /* List of dirty pages in LRU order */
  36042. PgHdr *pSynced; /* Last synced page in dirty page list */
  36043. int nRef; /* Number of referenced pages */
  36044. int szCache; /* Configured cache size */
  36045. int szPage; /* Size of every page in this cache */
  36046. int szExtra; /* Size of extra space for each page */
  36047. u8 bPurgeable; /* True if pages are on backing store */
  36048. u8 eCreate; /* eCreate value for for xFetch() */
  36049. int (*xStress)(void*,PgHdr*); /* Call to try make a page clean */
  36050. void *pStress; /* Argument to xStress */
  36051. sqlite3_pcache *pCache; /* Pluggable cache module */
  36052. PgHdr *pPage1; /* Reference to page 1 */
  36053. };
  36054. /*
  36055. ** Some of the assert() macros in this code are too expensive to run
  36056. ** even during normal debugging. Use them only rarely on long-running
  36057. ** tests. Enable the expensive asserts using the
  36058. ** -DSQLITE_ENABLE_EXPENSIVE_ASSERT=1 compile-time option.
  36059. */
  36060. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  36061. # define expensive_assert(X) assert(X)
  36062. #else
  36063. # define expensive_assert(X)
  36064. #endif
  36065. /********************************** Linked List Management ********************/
  36066. /* Allowed values for second argument to pcacheManageDirtyList() */
  36067. #define PCACHE_DIRTYLIST_REMOVE 1 /* Remove pPage from dirty list */
  36068. #define PCACHE_DIRTYLIST_ADD 2 /* Add pPage to the dirty list */
  36069. #define PCACHE_DIRTYLIST_FRONT 3 /* Move pPage to the front of the list */
  36070. /*
  36071. ** Manage pPage's participation on the dirty list. Bits of the addRemove
  36072. ** argument determines what operation to do. The 0x01 bit means first
  36073. ** remove pPage from the dirty list. The 0x02 means add pPage back to
  36074. ** the dirty list. Doing both moves pPage to the front of the dirty list.
  36075. */
  36076. static void pcacheManageDirtyList(PgHdr *pPage, u8 addRemove){
  36077. PCache *p = pPage->pCache;
  36078. if( addRemove & PCACHE_DIRTYLIST_REMOVE ){
  36079. assert( pPage->pDirtyNext || pPage==p->pDirtyTail );
  36080. assert( pPage->pDirtyPrev || pPage==p->pDirty );
  36081. /* Update the PCache1.pSynced variable if necessary. */
  36082. if( p->pSynced==pPage ){
  36083. PgHdr *pSynced = pPage->pDirtyPrev;
  36084. while( pSynced && (pSynced->flags&PGHDR_NEED_SYNC) ){
  36085. pSynced = pSynced->pDirtyPrev;
  36086. }
  36087. p->pSynced = pSynced;
  36088. }
  36089. if( pPage->pDirtyNext ){
  36090. pPage->pDirtyNext->pDirtyPrev = pPage->pDirtyPrev;
  36091. }else{
  36092. assert( pPage==p->pDirtyTail );
  36093. p->pDirtyTail = pPage->pDirtyPrev;
  36094. }
  36095. if( pPage->pDirtyPrev ){
  36096. pPage->pDirtyPrev->pDirtyNext = pPage->pDirtyNext;
  36097. }else{
  36098. assert( pPage==p->pDirty );
  36099. p->pDirty = pPage->pDirtyNext;
  36100. if( p->pDirty==0 && p->bPurgeable ){
  36101. assert( p->eCreate==1 );
  36102. p->eCreate = 2;
  36103. }
  36104. }
  36105. pPage->pDirtyNext = 0;
  36106. pPage->pDirtyPrev = 0;
  36107. }
  36108. if( addRemove & PCACHE_DIRTYLIST_ADD ){
  36109. assert( pPage->pDirtyNext==0 && pPage->pDirtyPrev==0 && p->pDirty!=pPage );
  36110. pPage->pDirtyNext = p->pDirty;
  36111. if( pPage->pDirtyNext ){
  36112. assert( pPage->pDirtyNext->pDirtyPrev==0 );
  36113. pPage->pDirtyNext->pDirtyPrev = pPage;
  36114. }else{
  36115. p->pDirtyTail = pPage;
  36116. if( p->bPurgeable ){
  36117. assert( p->eCreate==2 );
  36118. p->eCreate = 1;
  36119. }
  36120. }
  36121. p->pDirty = pPage;
  36122. if( !p->pSynced && 0==(pPage->flags&PGHDR_NEED_SYNC) ){
  36123. p->pSynced = pPage;
  36124. }
  36125. }
  36126. }
  36127. /*
  36128. ** Wrapper around the pluggable caches xUnpin method. If the cache is
  36129. ** being used for an in-memory database, this function is a no-op.
  36130. */
  36131. static void pcacheUnpin(PgHdr *p){
  36132. if( p->pCache->bPurgeable ){
  36133. if( p->pgno==1 ){
  36134. p->pCache->pPage1 = 0;
  36135. }
  36136. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 0);
  36137. }
  36138. }
  36139. /*
  36140. ** Compute the number of pages of cache requested.
  36141. */
  36142. static int numberOfCachePages(PCache *p){
  36143. if( p->szCache>=0 ){
  36144. return p->szCache;
  36145. }else{
  36146. return (int)((-1024*(i64)p->szCache)/(p->szPage+p->szExtra));
  36147. }
  36148. }
  36149. /*************************************************** General Interfaces ******
  36150. **
  36151. ** Initialize and shutdown the page cache subsystem. Neither of these
  36152. ** functions are threadsafe.
  36153. */
  36154. SQLITE_PRIVATE int sqlite3PcacheInitialize(void){
  36155. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  36156. /* IMPLEMENTATION-OF: R-26801-64137 If the xInit() method is NULL, then the
  36157. ** built-in default page cache is used instead of the application defined
  36158. ** page cache. */
  36159. sqlite3PCacheSetDefault();
  36160. }
  36161. return sqlite3GlobalConfig.pcache2.xInit(sqlite3GlobalConfig.pcache2.pArg);
  36162. }
  36163. SQLITE_PRIVATE void sqlite3PcacheShutdown(void){
  36164. if( sqlite3GlobalConfig.pcache2.xShutdown ){
  36165. /* IMPLEMENTATION-OF: R-26000-56589 The xShutdown() method may be NULL. */
  36166. sqlite3GlobalConfig.pcache2.xShutdown(sqlite3GlobalConfig.pcache2.pArg);
  36167. }
  36168. }
  36169. /*
  36170. ** Return the size in bytes of a PCache object.
  36171. */
  36172. SQLITE_PRIVATE int sqlite3PcacheSize(void){ return sizeof(PCache); }
  36173. /*
  36174. ** Create a new PCache object. Storage space to hold the object
  36175. ** has already been allocated and is passed in as the p pointer.
  36176. ** The caller discovers how much space needs to be allocated by
  36177. ** calling sqlite3PcacheSize().
  36178. */
  36179. SQLITE_PRIVATE int sqlite3PcacheOpen(
  36180. int szPage, /* Size of every page */
  36181. int szExtra, /* Extra space associated with each page */
  36182. int bPurgeable, /* True if pages are on backing store */
  36183. int (*xStress)(void*,PgHdr*),/* Call to try to make pages clean */
  36184. void *pStress, /* Argument to xStress */
  36185. PCache *p /* Preallocated space for the PCache */
  36186. ){
  36187. memset(p, 0, sizeof(PCache));
  36188. p->szPage = 1;
  36189. p->szExtra = szExtra;
  36190. p->bPurgeable = bPurgeable;
  36191. p->eCreate = 2;
  36192. p->xStress = xStress;
  36193. p->pStress = pStress;
  36194. p->szCache = 100;
  36195. return sqlite3PcacheSetPageSize(p, szPage);
  36196. }
  36197. /*
  36198. ** Change the page size for PCache object. The caller must ensure that there
  36199. ** are no outstanding page references when this function is called.
  36200. */
  36201. SQLITE_PRIVATE int sqlite3PcacheSetPageSize(PCache *pCache, int szPage){
  36202. assert( pCache->nRef==0 && pCache->pDirty==0 );
  36203. if( pCache->szPage ){
  36204. sqlite3_pcache *pNew;
  36205. pNew = sqlite3GlobalConfig.pcache2.xCreate(
  36206. szPage, pCache->szExtra + sizeof(PgHdr), pCache->bPurgeable
  36207. );
  36208. if( pNew==0 ) return SQLITE_NOMEM;
  36209. sqlite3GlobalConfig.pcache2.xCachesize(pNew, numberOfCachePages(pCache));
  36210. if( pCache->pCache ){
  36211. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  36212. }
  36213. pCache->pCache = pNew;
  36214. pCache->pPage1 = 0;
  36215. pCache->szPage = szPage;
  36216. }
  36217. return SQLITE_OK;
  36218. }
  36219. /*
  36220. ** Try to obtain a page from the cache.
  36221. **
  36222. ** This routine returns a pointer to an sqlite3_pcache_page object if
  36223. ** such an object is already in cache, or if a new one is created.
  36224. ** This routine returns a NULL pointer if the object was not in cache
  36225. ** and could not be created.
  36226. **
  36227. ** The createFlags should be 0 to check for existing pages and should
  36228. ** be 3 (not 1, but 3) to try to create a new page.
  36229. **
  36230. ** If the createFlag is 0, then NULL is always returned if the page
  36231. ** is not already in the cache. If createFlag is 1, then a new page
  36232. ** is created only if that can be done without spilling dirty pages
  36233. ** and without exceeding the cache size limit.
  36234. **
  36235. ** The caller needs to invoke sqlite3PcacheFetchFinish() to properly
  36236. ** initialize the sqlite3_pcache_page object and convert it into a
  36237. ** PgHdr object. The sqlite3PcacheFetch() and sqlite3PcacheFetchFinish()
  36238. ** routines are split this way for performance reasons. When separated
  36239. ** they can both (usually) operate without having to push values to
  36240. ** the stack on entry and pop them back off on exit, which saves a
  36241. ** lot of pushing and popping.
  36242. */
  36243. SQLITE_PRIVATE sqlite3_pcache_page *sqlite3PcacheFetch(
  36244. PCache *pCache, /* Obtain the page from this cache */
  36245. Pgno pgno, /* Page number to obtain */
  36246. int createFlag /* If true, create page if it does not exist already */
  36247. ){
  36248. int eCreate;
  36249. assert( pCache!=0 );
  36250. assert( pCache->pCache!=0 );
  36251. assert( createFlag==3 || createFlag==0 );
  36252. assert( pgno>0 );
  36253. /* eCreate defines what to do if the page does not exist.
  36254. ** 0 Do not allocate a new page. (createFlag==0)
  36255. ** 1 Allocate a new page if doing so is inexpensive.
  36256. ** (createFlag==1 AND bPurgeable AND pDirty)
  36257. ** 2 Allocate a new page even it doing so is difficult.
  36258. ** (createFlag==1 AND !(bPurgeable AND pDirty)
  36259. */
  36260. eCreate = createFlag & pCache->eCreate;
  36261. assert( eCreate==0 || eCreate==1 || eCreate==2 );
  36262. assert( createFlag==0 || pCache->eCreate==eCreate );
  36263. assert( createFlag==0 || eCreate==1+(!pCache->bPurgeable||!pCache->pDirty) );
  36264. return sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, eCreate);
  36265. }
  36266. /*
  36267. ** If the sqlite3PcacheFetch() routine is unable to allocate a new
  36268. ** page because new clean pages are available for reuse and the cache
  36269. ** size limit has been reached, then this routine can be invoked to
  36270. ** try harder to allocate a page. This routine might invoke the stress
  36271. ** callback to spill dirty pages to the journal. It will then try to
  36272. ** allocate the new page and will only fail to allocate a new page on
  36273. ** an OOM error.
  36274. **
  36275. ** This routine should be invoked only after sqlite3PcacheFetch() fails.
  36276. */
  36277. SQLITE_PRIVATE int sqlite3PcacheFetchStress(
  36278. PCache *pCache, /* Obtain the page from this cache */
  36279. Pgno pgno, /* Page number to obtain */
  36280. sqlite3_pcache_page **ppPage /* Write result here */
  36281. ){
  36282. PgHdr *pPg;
  36283. if( pCache->eCreate==2 ) return 0;
  36284. /* Find a dirty page to write-out and recycle. First try to find a
  36285. ** page that does not require a journal-sync (one with PGHDR_NEED_SYNC
  36286. ** cleared), but if that is not possible settle for any other
  36287. ** unreferenced dirty page.
  36288. */
  36289. for(pPg=pCache->pSynced;
  36290. pPg && (pPg->nRef || (pPg->flags&PGHDR_NEED_SYNC));
  36291. pPg=pPg->pDirtyPrev
  36292. );
  36293. pCache->pSynced = pPg;
  36294. if( !pPg ){
  36295. for(pPg=pCache->pDirtyTail; pPg && pPg->nRef; pPg=pPg->pDirtyPrev);
  36296. }
  36297. if( pPg ){
  36298. int rc;
  36299. #ifdef SQLITE_LOG_CACHE_SPILL
  36300. sqlite3_log(SQLITE_FULL,
  36301. "spill page %d making room for %d - cache used: %d/%d",
  36302. pPg->pgno, pgno,
  36303. sqlite3GlobalConfig.pcache.xPagecount(pCache->pCache),
  36304. numberOfCachePages(pCache));
  36305. #endif
  36306. rc = pCache->xStress(pCache->pStress, pPg);
  36307. if( rc!=SQLITE_OK && rc!=SQLITE_BUSY ){
  36308. return rc;
  36309. }
  36310. }
  36311. *ppPage = sqlite3GlobalConfig.pcache2.xFetch(pCache->pCache, pgno, 2);
  36312. return *ppPage==0 ? SQLITE_NOMEM : SQLITE_OK;
  36313. }
  36314. /*
  36315. ** This is a helper routine for sqlite3PcacheFetchFinish()
  36316. **
  36317. ** In the uncommon case where the page being fetched has not been
  36318. ** initialized, this routine is invoked to do the initialization.
  36319. ** This routine is broken out into a separate function since it
  36320. ** requires extra stack manipulation that can be avoided in the common
  36321. ** case.
  36322. */
  36323. static SQLITE_NOINLINE PgHdr *pcacheFetchFinishWithInit(
  36324. PCache *pCache, /* Obtain the page from this cache */
  36325. Pgno pgno, /* Page number obtained */
  36326. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  36327. ){
  36328. PgHdr *pPgHdr;
  36329. assert( pPage!=0 );
  36330. pPgHdr = (PgHdr*)pPage->pExtra;
  36331. assert( pPgHdr->pPage==0 );
  36332. memset(pPgHdr, 0, sizeof(PgHdr));
  36333. pPgHdr->pPage = pPage;
  36334. pPgHdr->pData = pPage->pBuf;
  36335. pPgHdr->pExtra = (void *)&pPgHdr[1];
  36336. memset(pPgHdr->pExtra, 0, pCache->szExtra);
  36337. pPgHdr->pCache = pCache;
  36338. pPgHdr->pgno = pgno;
  36339. return sqlite3PcacheFetchFinish(pCache,pgno,pPage);
  36340. }
  36341. /*
  36342. ** This routine converts the sqlite3_pcache_page object returned by
  36343. ** sqlite3PcacheFetch() into an initialized PgHdr object. This routine
  36344. ** must be called after sqlite3PcacheFetch() in order to get a usable
  36345. ** result.
  36346. */
  36347. SQLITE_PRIVATE PgHdr *sqlite3PcacheFetchFinish(
  36348. PCache *pCache, /* Obtain the page from this cache */
  36349. Pgno pgno, /* Page number obtained */
  36350. sqlite3_pcache_page *pPage /* Page obtained by prior PcacheFetch() call */
  36351. ){
  36352. PgHdr *pPgHdr;
  36353. if( pPage==0 ) return 0;
  36354. pPgHdr = (PgHdr *)pPage->pExtra;
  36355. if( !pPgHdr->pPage ){
  36356. return pcacheFetchFinishWithInit(pCache, pgno, pPage);
  36357. }
  36358. if( 0==pPgHdr->nRef ){
  36359. pCache->nRef++;
  36360. }
  36361. pPgHdr->nRef++;
  36362. if( pgno==1 ){
  36363. pCache->pPage1 = pPgHdr;
  36364. }
  36365. return pPgHdr;
  36366. }
  36367. /*
  36368. ** Decrement the reference count on a page. If the page is clean and the
  36369. ** reference count drops to 0, then it is made eligible for recycling.
  36370. */
  36371. SQLITE_PRIVATE void SQLITE_NOINLINE sqlite3PcacheRelease(PgHdr *p){
  36372. assert( p->nRef>0 );
  36373. p->nRef--;
  36374. if( p->nRef==0 ){
  36375. p->pCache->nRef--;
  36376. if( (p->flags&PGHDR_DIRTY)==0 ){
  36377. pcacheUnpin(p);
  36378. }else if( p->pDirtyPrev!=0 ){
  36379. /* Move the page to the head of the dirty list. */
  36380. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  36381. }
  36382. }
  36383. }
  36384. /*
  36385. ** Increase the reference count of a supplied page by 1.
  36386. */
  36387. SQLITE_PRIVATE void sqlite3PcacheRef(PgHdr *p){
  36388. assert(p->nRef>0);
  36389. p->nRef++;
  36390. }
  36391. /*
  36392. ** Drop a page from the cache. There must be exactly one reference to the
  36393. ** page. This function deletes that reference, so after it returns the
  36394. ** page pointed to by p is invalid.
  36395. */
  36396. SQLITE_PRIVATE void sqlite3PcacheDrop(PgHdr *p){
  36397. assert( p->nRef==1 );
  36398. if( p->flags&PGHDR_DIRTY ){
  36399. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  36400. }
  36401. p->pCache->nRef--;
  36402. if( p->pgno==1 ){
  36403. p->pCache->pPage1 = 0;
  36404. }
  36405. sqlite3GlobalConfig.pcache2.xUnpin(p->pCache->pCache, p->pPage, 1);
  36406. }
  36407. /*
  36408. ** Make sure the page is marked as dirty. If it isn't dirty already,
  36409. ** make it so.
  36410. */
  36411. SQLITE_PRIVATE void sqlite3PcacheMakeDirty(PgHdr *p){
  36412. p->flags &= ~PGHDR_DONT_WRITE;
  36413. assert( p->nRef>0 );
  36414. if( 0==(p->flags & PGHDR_DIRTY) ){
  36415. p->flags |= PGHDR_DIRTY;
  36416. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_ADD);
  36417. }
  36418. }
  36419. /*
  36420. ** Make sure the page is marked as clean. If it isn't clean already,
  36421. ** make it so.
  36422. */
  36423. SQLITE_PRIVATE void sqlite3PcacheMakeClean(PgHdr *p){
  36424. if( (p->flags & PGHDR_DIRTY) ){
  36425. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_REMOVE);
  36426. p->flags &= ~(PGHDR_DIRTY|PGHDR_NEED_SYNC);
  36427. if( p->nRef==0 ){
  36428. pcacheUnpin(p);
  36429. }
  36430. }
  36431. }
  36432. /*
  36433. ** Make every page in the cache clean.
  36434. */
  36435. SQLITE_PRIVATE void sqlite3PcacheCleanAll(PCache *pCache){
  36436. PgHdr *p;
  36437. while( (p = pCache->pDirty)!=0 ){
  36438. sqlite3PcacheMakeClean(p);
  36439. }
  36440. }
  36441. /*
  36442. ** Clear the PGHDR_NEED_SYNC flag from all dirty pages.
  36443. */
  36444. SQLITE_PRIVATE void sqlite3PcacheClearSyncFlags(PCache *pCache){
  36445. PgHdr *p;
  36446. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  36447. p->flags &= ~PGHDR_NEED_SYNC;
  36448. }
  36449. pCache->pSynced = pCache->pDirtyTail;
  36450. }
  36451. /*
  36452. ** Change the page number of page p to newPgno.
  36453. */
  36454. SQLITE_PRIVATE void sqlite3PcacheMove(PgHdr *p, Pgno newPgno){
  36455. PCache *pCache = p->pCache;
  36456. assert( p->nRef>0 );
  36457. assert( newPgno>0 );
  36458. sqlite3GlobalConfig.pcache2.xRekey(pCache->pCache, p->pPage, p->pgno,newPgno);
  36459. p->pgno = newPgno;
  36460. if( (p->flags&PGHDR_DIRTY) && (p->flags&PGHDR_NEED_SYNC) ){
  36461. pcacheManageDirtyList(p, PCACHE_DIRTYLIST_FRONT);
  36462. }
  36463. }
  36464. /*
  36465. ** Drop every cache entry whose page number is greater than "pgno". The
  36466. ** caller must ensure that there are no outstanding references to any pages
  36467. ** other than page 1 with a page number greater than pgno.
  36468. **
  36469. ** If there is a reference to page 1 and the pgno parameter passed to this
  36470. ** function is 0, then the data area associated with page 1 is zeroed, but
  36471. ** the page object is not dropped.
  36472. */
  36473. SQLITE_PRIVATE void sqlite3PcacheTruncate(PCache *pCache, Pgno pgno){
  36474. if( pCache->pCache ){
  36475. PgHdr *p;
  36476. PgHdr *pNext;
  36477. for(p=pCache->pDirty; p; p=pNext){
  36478. pNext = p->pDirtyNext;
  36479. /* This routine never gets call with a positive pgno except right
  36480. ** after sqlite3PcacheCleanAll(). So if there are dirty pages,
  36481. ** it must be that pgno==0.
  36482. */
  36483. assert( p->pgno>0 );
  36484. if( ALWAYS(p->pgno>pgno) ){
  36485. assert( p->flags&PGHDR_DIRTY );
  36486. sqlite3PcacheMakeClean(p);
  36487. }
  36488. }
  36489. if( pgno==0 && pCache->pPage1 ){
  36490. memset(pCache->pPage1->pData, 0, pCache->szPage);
  36491. pgno = 1;
  36492. }
  36493. sqlite3GlobalConfig.pcache2.xTruncate(pCache->pCache, pgno+1);
  36494. }
  36495. }
  36496. /*
  36497. ** Close a cache.
  36498. */
  36499. SQLITE_PRIVATE void sqlite3PcacheClose(PCache *pCache){
  36500. assert( pCache->pCache!=0 );
  36501. sqlite3GlobalConfig.pcache2.xDestroy(pCache->pCache);
  36502. }
  36503. /*
  36504. ** Discard the contents of the cache.
  36505. */
  36506. SQLITE_PRIVATE void sqlite3PcacheClear(PCache *pCache){
  36507. sqlite3PcacheTruncate(pCache, 0);
  36508. }
  36509. /*
  36510. ** Merge two lists of pages connected by pDirty and in pgno order.
  36511. ** Do not both fixing the pDirtyPrev pointers.
  36512. */
  36513. static PgHdr *pcacheMergeDirtyList(PgHdr *pA, PgHdr *pB){
  36514. PgHdr result, *pTail;
  36515. pTail = &result;
  36516. while( pA && pB ){
  36517. if( pA->pgno<pB->pgno ){
  36518. pTail->pDirty = pA;
  36519. pTail = pA;
  36520. pA = pA->pDirty;
  36521. }else{
  36522. pTail->pDirty = pB;
  36523. pTail = pB;
  36524. pB = pB->pDirty;
  36525. }
  36526. }
  36527. if( pA ){
  36528. pTail->pDirty = pA;
  36529. }else if( pB ){
  36530. pTail->pDirty = pB;
  36531. }else{
  36532. pTail->pDirty = 0;
  36533. }
  36534. return result.pDirty;
  36535. }
  36536. /*
  36537. ** Sort the list of pages in accending order by pgno. Pages are
  36538. ** connected by pDirty pointers. The pDirtyPrev pointers are
  36539. ** corrupted by this sort.
  36540. **
  36541. ** Since there cannot be more than 2^31 distinct pages in a database,
  36542. ** there cannot be more than 31 buckets required by the merge sorter.
  36543. ** One extra bucket is added to catch overflow in case something
  36544. ** ever changes to make the previous sentence incorrect.
  36545. */
  36546. #define N_SORT_BUCKET 32
  36547. static PgHdr *pcacheSortDirtyList(PgHdr *pIn){
  36548. PgHdr *a[N_SORT_BUCKET], *p;
  36549. int i;
  36550. memset(a, 0, sizeof(a));
  36551. while( pIn ){
  36552. p = pIn;
  36553. pIn = p->pDirty;
  36554. p->pDirty = 0;
  36555. for(i=0; ALWAYS(i<N_SORT_BUCKET-1); i++){
  36556. if( a[i]==0 ){
  36557. a[i] = p;
  36558. break;
  36559. }else{
  36560. p = pcacheMergeDirtyList(a[i], p);
  36561. a[i] = 0;
  36562. }
  36563. }
  36564. if( NEVER(i==N_SORT_BUCKET-1) ){
  36565. /* To get here, there need to be 2^(N_SORT_BUCKET) elements in
  36566. ** the input list. But that is impossible.
  36567. */
  36568. a[i] = pcacheMergeDirtyList(a[i], p);
  36569. }
  36570. }
  36571. p = a[0];
  36572. for(i=1; i<N_SORT_BUCKET; i++){
  36573. p = pcacheMergeDirtyList(p, a[i]);
  36574. }
  36575. return p;
  36576. }
  36577. /*
  36578. ** Return a list of all dirty pages in the cache, sorted by page number.
  36579. */
  36580. SQLITE_PRIVATE PgHdr *sqlite3PcacheDirtyList(PCache *pCache){
  36581. PgHdr *p;
  36582. for(p=pCache->pDirty; p; p=p->pDirtyNext){
  36583. p->pDirty = p->pDirtyNext;
  36584. }
  36585. return pcacheSortDirtyList(pCache->pDirty);
  36586. }
  36587. /*
  36588. ** Return the total number of referenced pages held by the cache.
  36589. */
  36590. SQLITE_PRIVATE int sqlite3PcacheRefCount(PCache *pCache){
  36591. return pCache->nRef;
  36592. }
  36593. /*
  36594. ** Return the number of references to the page supplied as an argument.
  36595. */
  36596. SQLITE_PRIVATE int sqlite3PcachePageRefcount(PgHdr *p){
  36597. return p->nRef;
  36598. }
  36599. /*
  36600. ** Return the total number of pages in the cache.
  36601. */
  36602. SQLITE_PRIVATE int sqlite3PcachePagecount(PCache *pCache){
  36603. assert( pCache->pCache!=0 );
  36604. return sqlite3GlobalConfig.pcache2.xPagecount(pCache->pCache);
  36605. }
  36606. #ifdef SQLITE_TEST
  36607. /*
  36608. ** Get the suggested cache-size value.
  36609. */
  36610. SQLITE_PRIVATE int sqlite3PcacheGetCachesize(PCache *pCache){
  36611. return numberOfCachePages(pCache);
  36612. }
  36613. #endif
  36614. /*
  36615. ** Set the suggested cache-size value.
  36616. */
  36617. SQLITE_PRIVATE void sqlite3PcacheSetCachesize(PCache *pCache, int mxPage){
  36618. assert( pCache->pCache!=0 );
  36619. pCache->szCache = mxPage;
  36620. sqlite3GlobalConfig.pcache2.xCachesize(pCache->pCache,
  36621. numberOfCachePages(pCache));
  36622. }
  36623. /*
  36624. ** Free up as much memory as possible from the page cache.
  36625. */
  36626. SQLITE_PRIVATE void sqlite3PcacheShrink(PCache *pCache){
  36627. assert( pCache->pCache!=0 );
  36628. sqlite3GlobalConfig.pcache2.xShrink(pCache->pCache);
  36629. }
  36630. #if defined(SQLITE_CHECK_PAGES) || defined(SQLITE_DEBUG)
  36631. /*
  36632. ** For all dirty pages currently in the cache, invoke the specified
  36633. ** callback. This is only used if the SQLITE_CHECK_PAGES macro is
  36634. ** defined.
  36635. */
  36636. SQLITE_PRIVATE void sqlite3PcacheIterateDirty(PCache *pCache, void (*xIter)(PgHdr *)){
  36637. PgHdr *pDirty;
  36638. for(pDirty=pCache->pDirty; pDirty; pDirty=pDirty->pDirtyNext){
  36639. xIter(pDirty);
  36640. }
  36641. }
  36642. #endif
  36643. /************** End of pcache.c **********************************************/
  36644. /************** Begin file pcache1.c *****************************************/
  36645. /*
  36646. ** 2008 November 05
  36647. **
  36648. ** The author disclaims copyright to this source code. In place of
  36649. ** a legal notice, here is a blessing:
  36650. **
  36651. ** May you do good and not evil.
  36652. ** May you find forgiveness for yourself and forgive others.
  36653. ** May you share freely, never taking more than you give.
  36654. **
  36655. *************************************************************************
  36656. **
  36657. ** This file implements the default page cache implementation (the
  36658. ** sqlite3_pcache interface). It also contains part of the implementation
  36659. ** of the SQLITE_CONFIG_PAGECACHE and sqlite3_release_memory() features.
  36660. ** If the default page cache implementation is overridden, then neither of
  36661. ** these two features are available.
  36662. */
  36663. typedef struct PCache1 PCache1;
  36664. typedef struct PgHdr1 PgHdr1;
  36665. typedef struct PgFreeslot PgFreeslot;
  36666. typedef struct PGroup PGroup;
  36667. /* Each page cache (or PCache) belongs to a PGroup. A PGroup is a set
  36668. ** of one or more PCaches that are able to recycle each other's unpinned
  36669. ** pages when they are under memory pressure. A PGroup is an instance of
  36670. ** the following object.
  36671. **
  36672. ** This page cache implementation works in one of two modes:
  36673. **
  36674. ** (1) Every PCache is the sole member of its own PGroup. There is
  36675. ** one PGroup per PCache.
  36676. **
  36677. ** (2) There is a single global PGroup that all PCaches are a member
  36678. ** of.
  36679. **
  36680. ** Mode 1 uses more memory (since PCache instances are not able to rob
  36681. ** unused pages from other PCaches) but it also operates without a mutex,
  36682. ** and is therefore often faster. Mode 2 requires a mutex in order to be
  36683. ** threadsafe, but recycles pages more efficiently.
  36684. **
  36685. ** For mode (1), PGroup.mutex is NULL. For mode (2) there is only a single
  36686. ** PGroup which is the pcache1.grp global variable and its mutex is
  36687. ** SQLITE_MUTEX_STATIC_LRU.
  36688. */
  36689. struct PGroup {
  36690. sqlite3_mutex *mutex; /* MUTEX_STATIC_LRU or NULL */
  36691. unsigned int nMaxPage; /* Sum of nMax for purgeable caches */
  36692. unsigned int nMinPage; /* Sum of nMin for purgeable caches */
  36693. unsigned int mxPinned; /* nMaxpage + 10 - nMinPage */
  36694. unsigned int nCurrentPage; /* Number of purgeable pages allocated */
  36695. PgHdr1 *pLruHead, *pLruTail; /* LRU list of unpinned pages */
  36696. };
  36697. /* Each page cache is an instance of the following object. Every
  36698. ** open database file (including each in-memory database and each
  36699. ** temporary or transient database) has a single page cache which
  36700. ** is an instance of this object.
  36701. **
  36702. ** Pointers to structures of this type are cast and returned as
  36703. ** opaque sqlite3_pcache* handles.
  36704. */
  36705. struct PCache1 {
  36706. /* Cache configuration parameters. Page size (szPage) and the purgeable
  36707. ** flag (bPurgeable) are set when the cache is created. nMax may be
  36708. ** modified at any time by a call to the pcache1Cachesize() method.
  36709. ** The PGroup mutex must be held when accessing nMax.
  36710. */
  36711. PGroup *pGroup; /* PGroup this cache belongs to */
  36712. int szPage; /* Size of allocated pages in bytes */
  36713. int szExtra; /* Size of extra space in bytes */
  36714. int bPurgeable; /* True if cache is purgeable */
  36715. unsigned int nMin; /* Minimum number of pages reserved */
  36716. unsigned int nMax; /* Configured "cache_size" value */
  36717. unsigned int n90pct; /* nMax*9/10 */
  36718. unsigned int iMaxKey; /* Largest key seen since xTruncate() */
  36719. /* Hash table of all pages. The following variables may only be accessed
  36720. ** when the accessor is holding the PGroup mutex.
  36721. */
  36722. unsigned int nRecyclable; /* Number of pages in the LRU list */
  36723. unsigned int nPage; /* Total number of pages in apHash */
  36724. unsigned int nHash; /* Number of slots in apHash[] */
  36725. PgHdr1 **apHash; /* Hash table for fast lookup by key */
  36726. };
  36727. /*
  36728. ** Each cache entry is represented by an instance of the following
  36729. ** structure. Unless SQLITE_PCACHE_SEPARATE_HEADER is defined, a buffer of
  36730. ** PgHdr1.pCache->szPage bytes is allocated directly before this structure
  36731. ** in memory.
  36732. */
  36733. struct PgHdr1 {
  36734. sqlite3_pcache_page page;
  36735. unsigned int iKey; /* Key value (page number) */
  36736. u8 isPinned; /* Page in use, not on the LRU list */
  36737. PgHdr1 *pNext; /* Next in hash table chain */
  36738. PCache1 *pCache; /* Cache that currently owns this page */
  36739. PgHdr1 *pLruNext; /* Next in LRU list of unpinned pages */
  36740. PgHdr1 *pLruPrev; /* Previous in LRU list of unpinned pages */
  36741. };
  36742. /*
  36743. ** Free slots in the allocator used to divide up the buffer provided using
  36744. ** the SQLITE_CONFIG_PAGECACHE mechanism.
  36745. */
  36746. struct PgFreeslot {
  36747. PgFreeslot *pNext; /* Next free slot */
  36748. };
  36749. /*
  36750. ** Global data used by this cache.
  36751. */
  36752. static SQLITE_WSD struct PCacheGlobal {
  36753. PGroup grp; /* The global PGroup for mode (2) */
  36754. /* Variables related to SQLITE_CONFIG_PAGECACHE settings. The
  36755. ** szSlot, nSlot, pStart, pEnd, nReserve, and isInit values are all
  36756. ** fixed at sqlite3_initialize() time and do not require mutex protection.
  36757. ** The nFreeSlot and pFree values do require mutex protection.
  36758. */
  36759. int isInit; /* True if initialized */
  36760. int szSlot; /* Size of each free slot */
  36761. int nSlot; /* The number of pcache slots */
  36762. int nReserve; /* Try to keep nFreeSlot above this */
  36763. void *pStart, *pEnd; /* Bounds of pagecache malloc range */
  36764. /* Above requires no mutex. Use mutex below for variable that follow. */
  36765. sqlite3_mutex *mutex; /* Mutex for accessing the following: */
  36766. PgFreeslot *pFree; /* Free page blocks */
  36767. int nFreeSlot; /* Number of unused pcache slots */
  36768. /* The following value requires a mutex to change. We skip the mutex on
  36769. ** reading because (1) most platforms read a 32-bit integer atomically and
  36770. ** (2) even if an incorrect value is read, no great harm is done since this
  36771. ** is really just an optimization. */
  36772. int bUnderPressure; /* True if low on PAGECACHE memory */
  36773. } pcache1_g;
  36774. /*
  36775. ** All code in this file should access the global structure above via the
  36776. ** alias "pcache1". This ensures that the WSD emulation is used when
  36777. ** compiling for systems that do not support real WSD.
  36778. */
  36779. #define pcache1 (GLOBAL(struct PCacheGlobal, pcache1_g))
  36780. /*
  36781. ** Macros to enter and leave the PCache LRU mutex.
  36782. */
  36783. #define pcache1EnterMutex(X) sqlite3_mutex_enter((X)->mutex)
  36784. #define pcache1LeaveMutex(X) sqlite3_mutex_leave((X)->mutex)
  36785. /******************************************************************************/
  36786. /******** Page Allocation/SQLITE_CONFIG_PCACHE Related Functions **************/
  36787. /*
  36788. ** This function is called during initialization if a static buffer is
  36789. ** supplied to use for the page-cache by passing the SQLITE_CONFIG_PAGECACHE
  36790. ** verb to sqlite3_config(). Parameter pBuf points to an allocation large
  36791. ** enough to contain 'n' buffers of 'sz' bytes each.
  36792. **
  36793. ** This routine is called from sqlite3_initialize() and so it is guaranteed
  36794. ** to be serialized already. There is no need for further mutexing.
  36795. */
  36796. SQLITE_PRIVATE void sqlite3PCacheBufferSetup(void *pBuf, int sz, int n){
  36797. if( pcache1.isInit ){
  36798. PgFreeslot *p;
  36799. sz = ROUNDDOWN8(sz);
  36800. pcache1.szSlot = sz;
  36801. pcache1.nSlot = pcache1.nFreeSlot = n;
  36802. pcache1.nReserve = n>90 ? 10 : (n/10 + 1);
  36803. pcache1.pStart = pBuf;
  36804. pcache1.pFree = 0;
  36805. pcache1.bUnderPressure = 0;
  36806. while( n-- ){
  36807. p = (PgFreeslot*)pBuf;
  36808. p->pNext = pcache1.pFree;
  36809. pcache1.pFree = p;
  36810. pBuf = (void*)&((char*)pBuf)[sz];
  36811. }
  36812. pcache1.pEnd = pBuf;
  36813. }
  36814. }
  36815. /*
  36816. ** Malloc function used within this file to allocate space from the buffer
  36817. ** configured using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no
  36818. ** such buffer exists or there is no space left in it, this function falls
  36819. ** back to sqlite3Malloc().
  36820. **
  36821. ** Multiple threads can run this routine at the same time. Global variables
  36822. ** in pcache1 need to be protected via mutex.
  36823. */
  36824. static void *pcache1Alloc(int nByte){
  36825. void *p = 0;
  36826. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  36827. sqlite3StatusSet(SQLITE_STATUS_PAGECACHE_SIZE, nByte);
  36828. if( nByte<=pcache1.szSlot ){
  36829. sqlite3_mutex_enter(pcache1.mutex);
  36830. p = (PgHdr1 *)pcache1.pFree;
  36831. if( p ){
  36832. pcache1.pFree = pcache1.pFree->pNext;
  36833. pcache1.nFreeSlot--;
  36834. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  36835. assert( pcache1.nFreeSlot>=0 );
  36836. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, 1);
  36837. }
  36838. sqlite3_mutex_leave(pcache1.mutex);
  36839. }
  36840. if( p==0 ){
  36841. /* Memory is not available in the SQLITE_CONFIG_PAGECACHE pool. Get
  36842. ** it from sqlite3Malloc instead.
  36843. */
  36844. p = sqlite3Malloc(nByte);
  36845. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  36846. if( p ){
  36847. int sz = sqlite3MallocSize(p);
  36848. sqlite3_mutex_enter(pcache1.mutex);
  36849. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, sz);
  36850. sqlite3_mutex_leave(pcache1.mutex);
  36851. }
  36852. #endif
  36853. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  36854. }
  36855. return p;
  36856. }
  36857. /*
  36858. ** Free an allocated buffer obtained from pcache1Alloc().
  36859. */
  36860. static int pcache1Free(void *p){
  36861. int nFreed = 0;
  36862. if( p==0 ) return 0;
  36863. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  36864. PgFreeslot *pSlot;
  36865. sqlite3_mutex_enter(pcache1.mutex);
  36866. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_USED, -1);
  36867. pSlot = (PgFreeslot*)p;
  36868. pSlot->pNext = pcache1.pFree;
  36869. pcache1.pFree = pSlot;
  36870. pcache1.nFreeSlot++;
  36871. pcache1.bUnderPressure = pcache1.nFreeSlot<pcache1.nReserve;
  36872. assert( pcache1.nFreeSlot<=pcache1.nSlot );
  36873. sqlite3_mutex_leave(pcache1.mutex);
  36874. }else{
  36875. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  36876. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  36877. nFreed = sqlite3MallocSize(p);
  36878. #ifndef SQLITE_DISABLE_PAGECACHE_OVERFLOW_STATS
  36879. sqlite3_mutex_enter(pcache1.mutex);
  36880. sqlite3StatusAdd(SQLITE_STATUS_PAGECACHE_OVERFLOW, -nFreed);
  36881. sqlite3_mutex_leave(pcache1.mutex);
  36882. #endif
  36883. sqlite3_free(p);
  36884. }
  36885. return nFreed;
  36886. }
  36887. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  36888. /*
  36889. ** Return the size of a pcache allocation
  36890. */
  36891. static int pcache1MemSize(void *p){
  36892. if( p>=pcache1.pStart && p<pcache1.pEnd ){
  36893. return pcache1.szSlot;
  36894. }else{
  36895. int iSize;
  36896. assert( sqlite3MemdebugHasType(p, MEMTYPE_PCACHE) );
  36897. sqlite3MemdebugSetType(p, MEMTYPE_HEAP);
  36898. iSize = sqlite3MallocSize(p);
  36899. sqlite3MemdebugSetType(p, MEMTYPE_PCACHE);
  36900. return iSize;
  36901. }
  36902. }
  36903. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  36904. /*
  36905. ** Allocate a new page object initially associated with cache pCache.
  36906. */
  36907. static PgHdr1 *pcache1AllocPage(PCache1 *pCache){
  36908. PgHdr1 *p = 0;
  36909. void *pPg;
  36910. /* The group mutex must be released before pcache1Alloc() is called. This
  36911. ** is because it may call sqlite3_release_memory(), which assumes that
  36912. ** this mutex is not held. */
  36913. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  36914. pcache1LeaveMutex(pCache->pGroup);
  36915. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  36916. pPg = pcache1Alloc(pCache->szPage);
  36917. p = sqlite3Malloc(sizeof(PgHdr1) + pCache->szExtra);
  36918. if( !pPg || !p ){
  36919. pcache1Free(pPg);
  36920. sqlite3_free(p);
  36921. pPg = 0;
  36922. }
  36923. #else
  36924. pPg = pcache1Alloc(sizeof(PgHdr1) + pCache->szPage + pCache->szExtra);
  36925. p = (PgHdr1 *)&((u8 *)pPg)[pCache->szPage];
  36926. #endif
  36927. pcache1EnterMutex(pCache->pGroup);
  36928. if( pPg ){
  36929. p->page.pBuf = pPg;
  36930. p->page.pExtra = &p[1];
  36931. if( pCache->bPurgeable ){
  36932. pCache->pGroup->nCurrentPage++;
  36933. }
  36934. return p;
  36935. }
  36936. return 0;
  36937. }
  36938. /*
  36939. ** Free a page object allocated by pcache1AllocPage().
  36940. **
  36941. ** The pointer is allowed to be NULL, which is prudent. But it turns out
  36942. ** that the current implementation happens to never call this routine
  36943. ** with a NULL pointer, so we mark the NULL test with ALWAYS().
  36944. */
  36945. static void pcache1FreePage(PgHdr1 *p){
  36946. if( ALWAYS(p) ){
  36947. PCache1 *pCache = p->pCache;
  36948. assert( sqlite3_mutex_held(p->pCache->pGroup->mutex) );
  36949. pcache1Free(p->page.pBuf);
  36950. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  36951. sqlite3_free(p);
  36952. #endif
  36953. if( pCache->bPurgeable ){
  36954. pCache->pGroup->nCurrentPage--;
  36955. }
  36956. }
  36957. }
  36958. /*
  36959. ** Malloc function used by SQLite to obtain space from the buffer configured
  36960. ** using sqlite3_config(SQLITE_CONFIG_PAGECACHE) option. If no such buffer
  36961. ** exists, this function falls back to sqlite3Malloc().
  36962. */
  36963. SQLITE_PRIVATE void *sqlite3PageMalloc(int sz){
  36964. return pcache1Alloc(sz);
  36965. }
  36966. /*
  36967. ** Free an allocated buffer obtained from sqlite3PageMalloc().
  36968. */
  36969. SQLITE_PRIVATE void sqlite3PageFree(void *p){
  36970. pcache1Free(p);
  36971. }
  36972. /*
  36973. ** Return true if it desirable to avoid allocating a new page cache
  36974. ** entry.
  36975. **
  36976. ** If memory was allocated specifically to the page cache using
  36977. ** SQLITE_CONFIG_PAGECACHE but that memory has all been used, then
  36978. ** it is desirable to avoid allocating a new page cache entry because
  36979. ** presumably SQLITE_CONFIG_PAGECACHE was suppose to be sufficient
  36980. ** for all page cache needs and we should not need to spill the
  36981. ** allocation onto the heap.
  36982. **
  36983. ** Or, the heap is used for all page cache memory but the heap is
  36984. ** under memory pressure, then again it is desirable to avoid
  36985. ** allocating a new page cache entry in order to avoid stressing
  36986. ** the heap even further.
  36987. */
  36988. static int pcache1UnderMemoryPressure(PCache1 *pCache){
  36989. if( pcache1.nSlot && (pCache->szPage+pCache->szExtra)<=pcache1.szSlot ){
  36990. return pcache1.bUnderPressure;
  36991. }else{
  36992. return sqlite3HeapNearlyFull();
  36993. }
  36994. }
  36995. /******************************************************************************/
  36996. /******** General Implementation Functions ************************************/
  36997. /*
  36998. ** This function is used to resize the hash table used by the cache passed
  36999. ** as the first argument.
  37000. **
  37001. ** The PCache mutex must be held when this function is called.
  37002. */
  37003. static void pcache1ResizeHash(PCache1 *p){
  37004. PgHdr1 **apNew;
  37005. unsigned int nNew;
  37006. unsigned int i;
  37007. assert( sqlite3_mutex_held(p->pGroup->mutex) );
  37008. nNew = p->nHash*2;
  37009. if( nNew<256 ){
  37010. nNew = 256;
  37011. }
  37012. pcache1LeaveMutex(p->pGroup);
  37013. if( p->nHash ){ sqlite3BeginBenignMalloc(); }
  37014. apNew = (PgHdr1 **)sqlite3MallocZero(sizeof(PgHdr1 *)*nNew);
  37015. if( p->nHash ){ sqlite3EndBenignMalloc(); }
  37016. pcache1EnterMutex(p->pGroup);
  37017. if( apNew ){
  37018. for(i=0; i<p->nHash; i++){
  37019. PgHdr1 *pPage;
  37020. PgHdr1 *pNext = p->apHash[i];
  37021. while( (pPage = pNext)!=0 ){
  37022. unsigned int h = pPage->iKey % nNew;
  37023. pNext = pPage->pNext;
  37024. pPage->pNext = apNew[h];
  37025. apNew[h] = pPage;
  37026. }
  37027. }
  37028. sqlite3_free(p->apHash);
  37029. p->apHash = apNew;
  37030. p->nHash = nNew;
  37031. }
  37032. }
  37033. /*
  37034. ** This function is used internally to remove the page pPage from the
  37035. ** PGroup LRU list, if is part of it. If pPage is not part of the PGroup
  37036. ** LRU list, then this function is a no-op.
  37037. **
  37038. ** The PGroup mutex must be held when this function is called.
  37039. */
  37040. static void pcache1PinPage(PgHdr1 *pPage){
  37041. PCache1 *pCache;
  37042. PGroup *pGroup;
  37043. assert( pPage!=0 );
  37044. assert( pPage->isPinned==0 );
  37045. pCache = pPage->pCache;
  37046. pGroup = pCache->pGroup;
  37047. assert( pPage->pLruNext || pPage==pGroup->pLruTail );
  37048. assert( pPage->pLruPrev || pPage==pGroup->pLruHead );
  37049. assert( sqlite3_mutex_held(pGroup->mutex) );
  37050. if( pPage->pLruPrev ){
  37051. pPage->pLruPrev->pLruNext = pPage->pLruNext;
  37052. }else{
  37053. pGroup->pLruHead = pPage->pLruNext;
  37054. }
  37055. if( pPage->pLruNext ){
  37056. pPage->pLruNext->pLruPrev = pPage->pLruPrev;
  37057. }else{
  37058. pGroup->pLruTail = pPage->pLruPrev;
  37059. }
  37060. pPage->pLruNext = 0;
  37061. pPage->pLruPrev = 0;
  37062. pPage->isPinned = 1;
  37063. pCache->nRecyclable--;
  37064. }
  37065. /*
  37066. ** Remove the page supplied as an argument from the hash table
  37067. ** (PCache1.apHash structure) that it is currently stored in.
  37068. **
  37069. ** The PGroup mutex must be held when this function is called.
  37070. */
  37071. static void pcache1RemoveFromHash(PgHdr1 *pPage){
  37072. unsigned int h;
  37073. PCache1 *pCache = pPage->pCache;
  37074. PgHdr1 **pp;
  37075. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37076. h = pPage->iKey % pCache->nHash;
  37077. for(pp=&pCache->apHash[h]; (*pp)!=pPage; pp=&(*pp)->pNext);
  37078. *pp = (*pp)->pNext;
  37079. pCache->nPage--;
  37080. }
  37081. /*
  37082. ** If there are currently more than nMaxPage pages allocated, try
  37083. ** to recycle pages to reduce the number allocated to nMaxPage.
  37084. */
  37085. static void pcache1EnforceMaxPage(PGroup *pGroup){
  37086. assert( sqlite3_mutex_held(pGroup->mutex) );
  37087. while( pGroup->nCurrentPage>pGroup->nMaxPage && pGroup->pLruTail ){
  37088. PgHdr1 *p = pGroup->pLruTail;
  37089. assert( p->pCache->pGroup==pGroup );
  37090. assert( p->isPinned==0 );
  37091. pcache1PinPage(p);
  37092. pcache1RemoveFromHash(p);
  37093. pcache1FreePage(p);
  37094. }
  37095. }
  37096. /*
  37097. ** Discard all pages from cache pCache with a page number (key value)
  37098. ** greater than or equal to iLimit. Any pinned pages that meet this
  37099. ** criteria are unpinned before they are discarded.
  37100. **
  37101. ** The PCache mutex must be held when this function is called.
  37102. */
  37103. static void pcache1TruncateUnsafe(
  37104. PCache1 *pCache, /* The cache to truncate */
  37105. unsigned int iLimit /* Drop pages with this pgno or larger */
  37106. ){
  37107. TESTONLY( unsigned int nPage = 0; ) /* To assert pCache->nPage is correct */
  37108. unsigned int h;
  37109. assert( sqlite3_mutex_held(pCache->pGroup->mutex) );
  37110. for(h=0; h<pCache->nHash; h++){
  37111. PgHdr1 **pp = &pCache->apHash[h];
  37112. PgHdr1 *pPage;
  37113. while( (pPage = *pp)!=0 ){
  37114. if( pPage->iKey>=iLimit ){
  37115. pCache->nPage--;
  37116. *pp = pPage->pNext;
  37117. if( !pPage->isPinned ) pcache1PinPage(pPage);
  37118. pcache1FreePage(pPage);
  37119. }else{
  37120. pp = &pPage->pNext;
  37121. TESTONLY( nPage++; )
  37122. }
  37123. }
  37124. }
  37125. assert( pCache->nPage==nPage );
  37126. }
  37127. /******************************************************************************/
  37128. /******** sqlite3_pcache Methods **********************************************/
  37129. /*
  37130. ** Implementation of the sqlite3_pcache.xInit method.
  37131. */
  37132. static int pcache1Init(void *NotUsed){
  37133. UNUSED_PARAMETER(NotUsed);
  37134. assert( pcache1.isInit==0 );
  37135. memset(&pcache1, 0, sizeof(pcache1));
  37136. if( sqlite3GlobalConfig.bCoreMutex ){
  37137. pcache1.grp.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_LRU);
  37138. pcache1.mutex = sqlite3_mutex_alloc(SQLITE_MUTEX_STATIC_PMEM);
  37139. }
  37140. pcache1.grp.mxPinned = 10;
  37141. pcache1.isInit = 1;
  37142. return SQLITE_OK;
  37143. }
  37144. /*
  37145. ** Implementation of the sqlite3_pcache.xShutdown method.
  37146. ** Note that the static mutex allocated in xInit does
  37147. ** not need to be freed.
  37148. */
  37149. static void pcache1Shutdown(void *NotUsed){
  37150. UNUSED_PARAMETER(NotUsed);
  37151. assert( pcache1.isInit!=0 );
  37152. memset(&pcache1, 0, sizeof(pcache1));
  37153. }
  37154. /* forward declaration */
  37155. static void pcache1Destroy(sqlite3_pcache *p);
  37156. /*
  37157. ** Implementation of the sqlite3_pcache.xCreate method.
  37158. **
  37159. ** Allocate a new cache.
  37160. */
  37161. static sqlite3_pcache *pcache1Create(int szPage, int szExtra, int bPurgeable){
  37162. PCache1 *pCache; /* The newly created page cache */
  37163. PGroup *pGroup; /* The group the new page cache will belong to */
  37164. int sz; /* Bytes of memory required to allocate the new cache */
  37165. /*
  37166. ** The separateCache variable is true if each PCache has its own private
  37167. ** PGroup. In other words, separateCache is true for mode (1) where no
  37168. ** mutexing is required.
  37169. **
  37170. ** * Always use a unified cache (mode-2) if ENABLE_MEMORY_MANAGEMENT
  37171. **
  37172. ** * Always use a unified cache in single-threaded applications
  37173. **
  37174. ** * Otherwise (if multi-threaded and ENABLE_MEMORY_MANAGEMENT is off)
  37175. ** use separate caches (mode-1)
  37176. */
  37177. #if defined(SQLITE_ENABLE_MEMORY_MANAGEMENT) || SQLITE_THREADSAFE==0
  37178. const int separateCache = 0;
  37179. #else
  37180. int separateCache = sqlite3GlobalConfig.bCoreMutex>0;
  37181. #endif
  37182. assert( (szPage & (szPage-1))==0 && szPage>=512 && szPage<=65536 );
  37183. assert( szExtra < 300 );
  37184. sz = sizeof(PCache1) + sizeof(PGroup)*separateCache;
  37185. pCache = (PCache1 *)sqlite3MallocZero(sz);
  37186. if( pCache ){
  37187. if( separateCache ){
  37188. pGroup = (PGroup*)&pCache[1];
  37189. pGroup->mxPinned = 10;
  37190. }else{
  37191. pGroup = &pcache1.grp;
  37192. }
  37193. pCache->pGroup = pGroup;
  37194. pCache->szPage = szPage;
  37195. pCache->szExtra = szExtra;
  37196. pCache->bPurgeable = (bPurgeable ? 1 : 0);
  37197. pcache1EnterMutex(pGroup);
  37198. pcache1ResizeHash(pCache);
  37199. if( bPurgeable ){
  37200. pCache->nMin = 10;
  37201. pGroup->nMinPage += pCache->nMin;
  37202. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  37203. }
  37204. pcache1LeaveMutex(pGroup);
  37205. if( pCache->nHash==0 ){
  37206. pcache1Destroy((sqlite3_pcache*)pCache);
  37207. pCache = 0;
  37208. }
  37209. }
  37210. return (sqlite3_pcache *)pCache;
  37211. }
  37212. /*
  37213. ** Implementation of the sqlite3_pcache.xCachesize method.
  37214. **
  37215. ** Configure the cache_size limit for a cache.
  37216. */
  37217. static void pcache1Cachesize(sqlite3_pcache *p, int nMax){
  37218. PCache1 *pCache = (PCache1 *)p;
  37219. if( pCache->bPurgeable ){
  37220. PGroup *pGroup = pCache->pGroup;
  37221. pcache1EnterMutex(pGroup);
  37222. pGroup->nMaxPage += (nMax - pCache->nMax);
  37223. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  37224. pCache->nMax = nMax;
  37225. pCache->n90pct = pCache->nMax*9/10;
  37226. pcache1EnforceMaxPage(pGroup);
  37227. pcache1LeaveMutex(pGroup);
  37228. }
  37229. }
  37230. /*
  37231. ** Implementation of the sqlite3_pcache.xShrink method.
  37232. **
  37233. ** Free up as much memory as possible.
  37234. */
  37235. static void pcache1Shrink(sqlite3_pcache *p){
  37236. PCache1 *pCache = (PCache1*)p;
  37237. if( pCache->bPurgeable ){
  37238. PGroup *pGroup = pCache->pGroup;
  37239. int savedMaxPage;
  37240. pcache1EnterMutex(pGroup);
  37241. savedMaxPage = pGroup->nMaxPage;
  37242. pGroup->nMaxPage = 0;
  37243. pcache1EnforceMaxPage(pGroup);
  37244. pGroup->nMaxPage = savedMaxPage;
  37245. pcache1LeaveMutex(pGroup);
  37246. }
  37247. }
  37248. /*
  37249. ** Implementation of the sqlite3_pcache.xPagecount method.
  37250. */
  37251. static int pcache1Pagecount(sqlite3_pcache *p){
  37252. int n;
  37253. PCache1 *pCache = (PCache1*)p;
  37254. pcache1EnterMutex(pCache->pGroup);
  37255. n = pCache->nPage;
  37256. pcache1LeaveMutex(pCache->pGroup);
  37257. return n;
  37258. }
  37259. /*
  37260. ** Implement steps 3, 4, and 5 of the pcache1Fetch() algorithm described
  37261. ** in the header of the pcache1Fetch() procedure.
  37262. **
  37263. ** This steps are broken out into a separate procedure because they are
  37264. ** usually not needed, and by avoiding the stack initialization required
  37265. ** for these steps, the main pcache1Fetch() procedure can run faster.
  37266. */
  37267. static SQLITE_NOINLINE PgHdr1 *pcache1FetchStage2(
  37268. PCache1 *pCache,
  37269. unsigned int iKey,
  37270. int createFlag
  37271. ){
  37272. unsigned int nPinned;
  37273. PGroup *pGroup = pCache->pGroup;
  37274. PgHdr1 *pPage = 0;
  37275. /* Step 3: Abort if createFlag is 1 but the cache is nearly full */
  37276. assert( pCache->nPage >= pCache->nRecyclable );
  37277. nPinned = pCache->nPage - pCache->nRecyclable;
  37278. assert( pGroup->mxPinned == pGroup->nMaxPage + 10 - pGroup->nMinPage );
  37279. assert( pCache->n90pct == pCache->nMax*9/10 );
  37280. if( createFlag==1 && (
  37281. nPinned>=pGroup->mxPinned
  37282. || nPinned>=pCache->n90pct
  37283. || (pcache1UnderMemoryPressure(pCache) && pCache->nRecyclable<nPinned)
  37284. )){
  37285. return 0;
  37286. }
  37287. if( pCache->nPage>=pCache->nHash ) pcache1ResizeHash(pCache);
  37288. assert( pCache->nHash>0 && pCache->apHash );
  37289. /* Step 4. Try to recycle a page. */
  37290. if( pCache->bPurgeable && pGroup->pLruTail && (
  37291. (pCache->nPage+1>=pCache->nMax)
  37292. || pGroup->nCurrentPage>=pGroup->nMaxPage
  37293. || pcache1UnderMemoryPressure(pCache)
  37294. )){
  37295. PCache1 *pOther;
  37296. pPage = pGroup->pLruTail;
  37297. assert( pPage->isPinned==0 );
  37298. pcache1RemoveFromHash(pPage);
  37299. pcache1PinPage(pPage);
  37300. pOther = pPage->pCache;
  37301. /* We want to verify that szPage and szExtra are the same for pOther
  37302. ** and pCache. Assert that we can verify this by comparing sums. */
  37303. assert( (pCache->szPage & (pCache->szPage-1))==0 && pCache->szPage>=512 );
  37304. assert( pCache->szExtra<512 );
  37305. assert( (pOther->szPage & (pOther->szPage-1))==0 && pOther->szPage>=512 );
  37306. assert( pOther->szExtra<512 );
  37307. if( pOther->szPage+pOther->szExtra != pCache->szPage+pCache->szExtra ){
  37308. pcache1FreePage(pPage);
  37309. pPage = 0;
  37310. }else{
  37311. pGroup->nCurrentPage -= (pOther->bPurgeable - pCache->bPurgeable);
  37312. }
  37313. }
  37314. /* Step 5. If a usable page buffer has still not been found,
  37315. ** attempt to allocate a new one.
  37316. */
  37317. if( !pPage ){
  37318. if( createFlag==1 ) sqlite3BeginBenignMalloc();
  37319. pPage = pcache1AllocPage(pCache);
  37320. if( createFlag==1 ) sqlite3EndBenignMalloc();
  37321. }
  37322. if( pPage ){
  37323. unsigned int h = iKey % pCache->nHash;
  37324. pCache->nPage++;
  37325. pPage->iKey = iKey;
  37326. pPage->pNext = pCache->apHash[h];
  37327. pPage->pCache = pCache;
  37328. pPage->pLruPrev = 0;
  37329. pPage->pLruNext = 0;
  37330. pPage->isPinned = 1;
  37331. *(void **)pPage->page.pExtra = 0;
  37332. pCache->apHash[h] = pPage;
  37333. if( iKey>pCache->iMaxKey ){
  37334. pCache->iMaxKey = iKey;
  37335. }
  37336. }
  37337. return pPage;
  37338. }
  37339. /*
  37340. ** Implementation of the sqlite3_pcache.xFetch method.
  37341. **
  37342. ** Fetch a page by key value.
  37343. **
  37344. ** Whether or not a new page may be allocated by this function depends on
  37345. ** the value of the createFlag argument. 0 means do not allocate a new
  37346. ** page. 1 means allocate a new page if space is easily available. 2
  37347. ** means to try really hard to allocate a new page.
  37348. **
  37349. ** For a non-purgeable cache (a cache used as the storage for an in-memory
  37350. ** database) there is really no difference between createFlag 1 and 2. So
  37351. ** the calling function (pcache.c) will never have a createFlag of 1 on
  37352. ** a non-purgeable cache.
  37353. **
  37354. ** There are three different approaches to obtaining space for a page,
  37355. ** depending on the value of parameter createFlag (which may be 0, 1 or 2).
  37356. **
  37357. ** 1. Regardless of the value of createFlag, the cache is searched for a
  37358. ** copy of the requested page. If one is found, it is returned.
  37359. **
  37360. ** 2. If createFlag==0 and the page is not already in the cache, NULL is
  37361. ** returned.
  37362. **
  37363. ** 3. If createFlag is 1, and the page is not already in the cache, then
  37364. ** return NULL (do not allocate a new page) if any of the following
  37365. ** conditions are true:
  37366. **
  37367. ** (a) the number of pages pinned by the cache is greater than
  37368. ** PCache1.nMax, or
  37369. **
  37370. ** (b) the number of pages pinned by the cache is greater than
  37371. ** the sum of nMax for all purgeable caches, less the sum of
  37372. ** nMin for all other purgeable caches, or
  37373. **
  37374. ** 4. If none of the first three conditions apply and the cache is marked
  37375. ** as purgeable, and if one of the following is true:
  37376. **
  37377. ** (a) The number of pages allocated for the cache is already
  37378. ** PCache1.nMax, or
  37379. **
  37380. ** (b) The number of pages allocated for all purgeable caches is
  37381. ** already equal to or greater than the sum of nMax for all
  37382. ** purgeable caches,
  37383. **
  37384. ** (c) The system is under memory pressure and wants to avoid
  37385. ** unnecessary pages cache entry allocations
  37386. **
  37387. ** then attempt to recycle a page from the LRU list. If it is the right
  37388. ** size, return the recycled buffer. Otherwise, free the buffer and
  37389. ** proceed to step 5.
  37390. **
  37391. ** 5. Otherwise, allocate and return a new page buffer.
  37392. */
  37393. static sqlite3_pcache_page *pcache1Fetch(
  37394. sqlite3_pcache *p,
  37395. unsigned int iKey,
  37396. int createFlag
  37397. ){
  37398. PCache1 *pCache = (PCache1 *)p;
  37399. PgHdr1 *pPage = 0;
  37400. assert( offsetof(PgHdr1,page)==0 );
  37401. assert( pCache->bPurgeable || createFlag!=1 );
  37402. assert( pCache->bPurgeable || pCache->nMin==0 );
  37403. assert( pCache->bPurgeable==0 || pCache->nMin==10 );
  37404. assert( pCache->nMin==0 || pCache->bPurgeable );
  37405. assert( pCache->nHash>0 );
  37406. pcache1EnterMutex(pCache->pGroup);
  37407. /* Step 1: Search the hash table for an existing entry. */
  37408. pPage = pCache->apHash[iKey % pCache->nHash];
  37409. while( pPage && pPage->iKey!=iKey ){ pPage = pPage->pNext; }
  37410. /* Step 2: Abort if no existing page is found and createFlag is 0 */
  37411. if( pPage ){
  37412. if( !pPage->isPinned ) pcache1PinPage(pPage);
  37413. }else if( createFlag ){
  37414. /* Steps 3, 4, and 5 implemented by this subroutine */
  37415. pPage = pcache1FetchStage2(pCache, iKey, createFlag);
  37416. }
  37417. assert( pPage==0 || pCache->iMaxKey>=iKey );
  37418. pcache1LeaveMutex(pCache->pGroup);
  37419. return (sqlite3_pcache_page*)pPage;
  37420. }
  37421. /*
  37422. ** Implementation of the sqlite3_pcache.xUnpin method.
  37423. **
  37424. ** Mark a page as unpinned (eligible for asynchronous recycling).
  37425. */
  37426. static void pcache1Unpin(
  37427. sqlite3_pcache *p,
  37428. sqlite3_pcache_page *pPg,
  37429. int reuseUnlikely
  37430. ){
  37431. PCache1 *pCache = (PCache1 *)p;
  37432. PgHdr1 *pPage = (PgHdr1 *)pPg;
  37433. PGroup *pGroup = pCache->pGroup;
  37434. assert( pPage->pCache==pCache );
  37435. pcache1EnterMutex(pGroup);
  37436. /* It is an error to call this function if the page is already
  37437. ** part of the PGroup LRU list.
  37438. */
  37439. assert( pPage->pLruPrev==0 && pPage->pLruNext==0 );
  37440. assert( pGroup->pLruHead!=pPage && pGroup->pLruTail!=pPage );
  37441. assert( pPage->isPinned==1 );
  37442. if( reuseUnlikely || pGroup->nCurrentPage>pGroup->nMaxPage ){
  37443. pcache1RemoveFromHash(pPage);
  37444. pcache1FreePage(pPage);
  37445. }else{
  37446. /* Add the page to the PGroup LRU list. */
  37447. if( pGroup->pLruHead ){
  37448. pGroup->pLruHead->pLruPrev = pPage;
  37449. pPage->pLruNext = pGroup->pLruHead;
  37450. pGroup->pLruHead = pPage;
  37451. }else{
  37452. pGroup->pLruTail = pPage;
  37453. pGroup->pLruHead = pPage;
  37454. }
  37455. pCache->nRecyclable++;
  37456. pPage->isPinned = 0;
  37457. }
  37458. pcache1LeaveMutex(pCache->pGroup);
  37459. }
  37460. /*
  37461. ** Implementation of the sqlite3_pcache.xRekey method.
  37462. */
  37463. static void pcache1Rekey(
  37464. sqlite3_pcache *p,
  37465. sqlite3_pcache_page *pPg,
  37466. unsigned int iOld,
  37467. unsigned int iNew
  37468. ){
  37469. PCache1 *pCache = (PCache1 *)p;
  37470. PgHdr1 *pPage = (PgHdr1 *)pPg;
  37471. PgHdr1 **pp;
  37472. unsigned int h;
  37473. assert( pPage->iKey==iOld );
  37474. assert( pPage->pCache==pCache );
  37475. pcache1EnterMutex(pCache->pGroup);
  37476. h = iOld%pCache->nHash;
  37477. pp = &pCache->apHash[h];
  37478. while( (*pp)!=pPage ){
  37479. pp = &(*pp)->pNext;
  37480. }
  37481. *pp = pPage->pNext;
  37482. h = iNew%pCache->nHash;
  37483. pPage->iKey = iNew;
  37484. pPage->pNext = pCache->apHash[h];
  37485. pCache->apHash[h] = pPage;
  37486. if( iNew>pCache->iMaxKey ){
  37487. pCache->iMaxKey = iNew;
  37488. }
  37489. pcache1LeaveMutex(pCache->pGroup);
  37490. }
  37491. /*
  37492. ** Implementation of the sqlite3_pcache.xTruncate method.
  37493. **
  37494. ** Discard all unpinned pages in the cache with a page number equal to
  37495. ** or greater than parameter iLimit. Any pinned pages with a page number
  37496. ** equal to or greater than iLimit are implicitly unpinned.
  37497. */
  37498. static void pcache1Truncate(sqlite3_pcache *p, unsigned int iLimit){
  37499. PCache1 *pCache = (PCache1 *)p;
  37500. pcache1EnterMutex(pCache->pGroup);
  37501. if( iLimit<=pCache->iMaxKey ){
  37502. pcache1TruncateUnsafe(pCache, iLimit);
  37503. pCache->iMaxKey = iLimit-1;
  37504. }
  37505. pcache1LeaveMutex(pCache->pGroup);
  37506. }
  37507. /*
  37508. ** Implementation of the sqlite3_pcache.xDestroy method.
  37509. **
  37510. ** Destroy a cache allocated using pcache1Create().
  37511. */
  37512. static void pcache1Destroy(sqlite3_pcache *p){
  37513. PCache1 *pCache = (PCache1 *)p;
  37514. PGroup *pGroup = pCache->pGroup;
  37515. assert( pCache->bPurgeable || (pCache->nMax==0 && pCache->nMin==0) );
  37516. pcache1EnterMutex(pGroup);
  37517. pcache1TruncateUnsafe(pCache, 0);
  37518. assert( pGroup->nMaxPage >= pCache->nMax );
  37519. pGroup->nMaxPage -= pCache->nMax;
  37520. assert( pGroup->nMinPage >= pCache->nMin );
  37521. pGroup->nMinPage -= pCache->nMin;
  37522. pGroup->mxPinned = pGroup->nMaxPage + 10 - pGroup->nMinPage;
  37523. pcache1EnforceMaxPage(pGroup);
  37524. pcache1LeaveMutex(pGroup);
  37525. sqlite3_free(pCache->apHash);
  37526. sqlite3_free(pCache);
  37527. }
  37528. /*
  37529. ** This function is called during initialization (sqlite3_initialize()) to
  37530. ** install the default pluggable cache module, assuming the user has not
  37531. ** already provided an alternative.
  37532. */
  37533. SQLITE_PRIVATE void sqlite3PCacheSetDefault(void){
  37534. static const sqlite3_pcache_methods2 defaultMethods = {
  37535. 1, /* iVersion */
  37536. 0, /* pArg */
  37537. pcache1Init, /* xInit */
  37538. pcache1Shutdown, /* xShutdown */
  37539. pcache1Create, /* xCreate */
  37540. pcache1Cachesize, /* xCachesize */
  37541. pcache1Pagecount, /* xPagecount */
  37542. pcache1Fetch, /* xFetch */
  37543. pcache1Unpin, /* xUnpin */
  37544. pcache1Rekey, /* xRekey */
  37545. pcache1Truncate, /* xTruncate */
  37546. pcache1Destroy, /* xDestroy */
  37547. pcache1Shrink /* xShrink */
  37548. };
  37549. sqlite3_config(SQLITE_CONFIG_PCACHE2, &defaultMethods);
  37550. }
  37551. #ifdef SQLITE_ENABLE_MEMORY_MANAGEMENT
  37552. /*
  37553. ** This function is called to free superfluous dynamically allocated memory
  37554. ** held by the pager system. Memory in use by any SQLite pager allocated
  37555. ** by the current thread may be sqlite3_free()ed.
  37556. **
  37557. ** nReq is the number of bytes of memory required. Once this much has
  37558. ** been released, the function returns. The return value is the total number
  37559. ** of bytes of memory released.
  37560. */
  37561. SQLITE_PRIVATE int sqlite3PcacheReleaseMemory(int nReq){
  37562. int nFree = 0;
  37563. assert( sqlite3_mutex_notheld(pcache1.grp.mutex) );
  37564. assert( sqlite3_mutex_notheld(pcache1.mutex) );
  37565. if( pcache1.pStart==0 ){
  37566. PgHdr1 *p;
  37567. pcache1EnterMutex(&pcache1.grp);
  37568. while( (nReq<0 || nFree<nReq) && ((p=pcache1.grp.pLruTail)!=0) ){
  37569. nFree += pcache1MemSize(p->page.pBuf);
  37570. #ifdef SQLITE_PCACHE_SEPARATE_HEADER
  37571. nFree += sqlite3MemSize(p);
  37572. #endif
  37573. assert( p->isPinned==0 );
  37574. pcache1PinPage(p);
  37575. pcache1RemoveFromHash(p);
  37576. pcache1FreePage(p);
  37577. }
  37578. pcache1LeaveMutex(&pcache1.grp);
  37579. }
  37580. return nFree;
  37581. }
  37582. #endif /* SQLITE_ENABLE_MEMORY_MANAGEMENT */
  37583. #ifdef SQLITE_TEST
  37584. /*
  37585. ** This function is used by test procedures to inspect the internal state
  37586. ** of the global cache.
  37587. */
  37588. SQLITE_PRIVATE void sqlite3PcacheStats(
  37589. int *pnCurrent, /* OUT: Total number of pages cached */
  37590. int *pnMax, /* OUT: Global maximum cache size */
  37591. int *pnMin, /* OUT: Sum of PCache1.nMin for purgeable caches */
  37592. int *pnRecyclable /* OUT: Total number of pages available for recycling */
  37593. ){
  37594. PgHdr1 *p;
  37595. int nRecyclable = 0;
  37596. for(p=pcache1.grp.pLruHead; p; p=p->pLruNext){
  37597. assert( p->isPinned==0 );
  37598. nRecyclable++;
  37599. }
  37600. *pnCurrent = pcache1.grp.nCurrentPage;
  37601. *pnMax = (int)pcache1.grp.nMaxPage;
  37602. *pnMin = (int)pcache1.grp.nMinPage;
  37603. *pnRecyclable = nRecyclable;
  37604. }
  37605. #endif
  37606. /************** End of pcache1.c *********************************************/
  37607. /************** Begin file rowset.c ******************************************/
  37608. /*
  37609. ** 2008 December 3
  37610. **
  37611. ** The author disclaims copyright to this source code. In place of
  37612. ** a legal notice, here is a blessing:
  37613. **
  37614. ** May you do good and not evil.
  37615. ** May you find forgiveness for yourself and forgive others.
  37616. ** May you share freely, never taking more than you give.
  37617. **
  37618. *************************************************************************
  37619. **
  37620. ** This module implements an object we call a "RowSet".
  37621. **
  37622. ** The RowSet object is a collection of rowids. Rowids
  37623. ** are inserted into the RowSet in an arbitrary order. Inserts
  37624. ** can be intermixed with tests to see if a given rowid has been
  37625. ** previously inserted into the RowSet.
  37626. **
  37627. ** After all inserts are finished, it is possible to extract the
  37628. ** elements of the RowSet in sorted order. Once this extraction
  37629. ** process has started, no new elements may be inserted.
  37630. **
  37631. ** Hence, the primitive operations for a RowSet are:
  37632. **
  37633. ** CREATE
  37634. ** INSERT
  37635. ** TEST
  37636. ** SMALLEST
  37637. ** DESTROY
  37638. **
  37639. ** The CREATE and DESTROY primitives are the constructor and destructor,
  37640. ** obviously. The INSERT primitive adds a new element to the RowSet.
  37641. ** TEST checks to see if an element is already in the RowSet. SMALLEST
  37642. ** extracts the least value from the RowSet.
  37643. **
  37644. ** The INSERT primitive might allocate additional memory. Memory is
  37645. ** allocated in chunks so most INSERTs do no allocation. There is an
  37646. ** upper bound on the size of allocated memory. No memory is freed
  37647. ** until DESTROY.
  37648. **
  37649. ** The TEST primitive includes a "batch" number. The TEST primitive
  37650. ** will only see elements that were inserted before the last change
  37651. ** in the batch number. In other words, if an INSERT occurs between
  37652. ** two TESTs where the TESTs have the same batch nubmer, then the
  37653. ** value added by the INSERT will not be visible to the second TEST.
  37654. ** The initial batch number is zero, so if the very first TEST contains
  37655. ** a non-zero batch number, it will see all prior INSERTs.
  37656. **
  37657. ** No INSERTs may occurs after a SMALLEST. An assertion will fail if
  37658. ** that is attempted.
  37659. **
  37660. ** The cost of an INSERT is roughly constant. (Sometimes new memory
  37661. ** has to be allocated on an INSERT.) The cost of a TEST with a new
  37662. ** batch number is O(NlogN) where N is the number of elements in the RowSet.
  37663. ** The cost of a TEST using the same batch number is O(logN). The cost
  37664. ** of the first SMALLEST is O(NlogN). Second and subsequent SMALLEST
  37665. ** primitives are constant time. The cost of DESTROY is O(N).
  37666. **
  37667. ** There is an added cost of O(N) when switching between TEST and
  37668. ** SMALLEST primitives.
  37669. */
  37670. /*
  37671. ** Target size for allocation chunks.
  37672. */
  37673. #define ROWSET_ALLOCATION_SIZE 1024
  37674. /*
  37675. ** The number of rowset entries per allocation chunk.
  37676. */
  37677. #define ROWSET_ENTRY_PER_CHUNK \
  37678. ((ROWSET_ALLOCATION_SIZE-8)/sizeof(struct RowSetEntry))
  37679. /*
  37680. ** Each entry in a RowSet is an instance of the following object.
  37681. **
  37682. ** This same object is reused to store a linked list of trees of RowSetEntry
  37683. ** objects. In that alternative use, pRight points to the next entry
  37684. ** in the list, pLeft points to the tree, and v is unused. The
  37685. ** RowSet.pForest value points to the head of this forest list.
  37686. */
  37687. struct RowSetEntry {
  37688. i64 v; /* ROWID value for this entry */
  37689. struct RowSetEntry *pRight; /* Right subtree (larger entries) or list */
  37690. struct RowSetEntry *pLeft; /* Left subtree (smaller entries) */
  37691. };
  37692. /*
  37693. ** RowSetEntry objects are allocated in large chunks (instances of the
  37694. ** following structure) to reduce memory allocation overhead. The
  37695. ** chunks are kept on a linked list so that they can be deallocated
  37696. ** when the RowSet is destroyed.
  37697. */
  37698. struct RowSetChunk {
  37699. struct RowSetChunk *pNextChunk; /* Next chunk on list of them all */
  37700. struct RowSetEntry aEntry[ROWSET_ENTRY_PER_CHUNK]; /* Allocated entries */
  37701. };
  37702. /*
  37703. ** A RowSet in an instance of the following structure.
  37704. **
  37705. ** A typedef of this structure if found in sqliteInt.h.
  37706. */
  37707. struct RowSet {
  37708. struct RowSetChunk *pChunk; /* List of all chunk allocations */
  37709. sqlite3 *db; /* The database connection */
  37710. struct RowSetEntry *pEntry; /* List of entries using pRight */
  37711. struct RowSetEntry *pLast; /* Last entry on the pEntry list */
  37712. struct RowSetEntry *pFresh; /* Source of new entry objects */
  37713. struct RowSetEntry *pForest; /* List of binary trees of entries */
  37714. u16 nFresh; /* Number of objects on pFresh */
  37715. u16 rsFlags; /* Various flags */
  37716. int iBatch; /* Current insert batch */
  37717. };
  37718. /*
  37719. ** Allowed values for RowSet.rsFlags
  37720. */
  37721. #define ROWSET_SORTED 0x01 /* True if RowSet.pEntry is sorted */
  37722. #define ROWSET_NEXT 0x02 /* True if sqlite3RowSetNext() has been called */
  37723. /*
  37724. ** Turn bulk memory into a RowSet object. N bytes of memory
  37725. ** are available at pSpace. The db pointer is used as a memory context
  37726. ** for any subsequent allocations that need to occur.
  37727. ** Return a pointer to the new RowSet object.
  37728. **
  37729. ** It must be the case that N is sufficient to make a Rowset. If not
  37730. ** an assertion fault occurs.
  37731. **
  37732. ** If N is larger than the minimum, use the surplus as an initial
  37733. ** allocation of entries available to be filled.
  37734. */
  37735. SQLITE_PRIVATE RowSet *sqlite3RowSetInit(sqlite3 *db, void *pSpace, unsigned int N){
  37736. RowSet *p;
  37737. assert( N >= ROUND8(sizeof(*p)) );
  37738. p = pSpace;
  37739. p->pChunk = 0;
  37740. p->db = db;
  37741. p->pEntry = 0;
  37742. p->pLast = 0;
  37743. p->pForest = 0;
  37744. p->pFresh = (struct RowSetEntry*)(ROUND8(sizeof(*p)) + (char*)p);
  37745. p->nFresh = (u16)((N - ROUND8(sizeof(*p)))/sizeof(struct RowSetEntry));
  37746. p->rsFlags = ROWSET_SORTED;
  37747. p->iBatch = 0;
  37748. return p;
  37749. }
  37750. /*
  37751. ** Deallocate all chunks from a RowSet. This frees all memory that
  37752. ** the RowSet has allocated over its lifetime. This routine is
  37753. ** the destructor for the RowSet.
  37754. */
  37755. SQLITE_PRIVATE void sqlite3RowSetClear(RowSet *p){
  37756. struct RowSetChunk *pChunk, *pNextChunk;
  37757. for(pChunk=p->pChunk; pChunk; pChunk = pNextChunk){
  37758. pNextChunk = pChunk->pNextChunk;
  37759. sqlite3DbFree(p->db, pChunk);
  37760. }
  37761. p->pChunk = 0;
  37762. p->nFresh = 0;
  37763. p->pEntry = 0;
  37764. p->pLast = 0;
  37765. p->pForest = 0;
  37766. p->rsFlags = ROWSET_SORTED;
  37767. }
  37768. /*
  37769. ** Allocate a new RowSetEntry object that is associated with the
  37770. ** given RowSet. Return a pointer to the new and completely uninitialized
  37771. ** objected.
  37772. **
  37773. ** In an OOM situation, the RowSet.db->mallocFailed flag is set and this
  37774. ** routine returns NULL.
  37775. */
  37776. static struct RowSetEntry *rowSetEntryAlloc(RowSet *p){
  37777. assert( p!=0 );
  37778. if( p->nFresh==0 ){
  37779. struct RowSetChunk *pNew;
  37780. pNew = sqlite3DbMallocRaw(p->db, sizeof(*pNew));
  37781. if( pNew==0 ){
  37782. return 0;
  37783. }
  37784. pNew->pNextChunk = p->pChunk;
  37785. p->pChunk = pNew;
  37786. p->pFresh = pNew->aEntry;
  37787. p->nFresh = ROWSET_ENTRY_PER_CHUNK;
  37788. }
  37789. p->nFresh--;
  37790. return p->pFresh++;
  37791. }
  37792. /*
  37793. ** Insert a new value into a RowSet.
  37794. **
  37795. ** The mallocFailed flag of the database connection is set if a
  37796. ** memory allocation fails.
  37797. */
  37798. SQLITE_PRIVATE void sqlite3RowSetInsert(RowSet *p, i64 rowid){
  37799. struct RowSetEntry *pEntry; /* The new entry */
  37800. struct RowSetEntry *pLast; /* The last prior entry */
  37801. /* This routine is never called after sqlite3RowSetNext() */
  37802. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  37803. pEntry = rowSetEntryAlloc(p);
  37804. if( pEntry==0 ) return;
  37805. pEntry->v = rowid;
  37806. pEntry->pRight = 0;
  37807. pLast = p->pLast;
  37808. if( pLast ){
  37809. if( (p->rsFlags & ROWSET_SORTED)!=0 && rowid<=pLast->v ){
  37810. p->rsFlags &= ~ROWSET_SORTED;
  37811. }
  37812. pLast->pRight = pEntry;
  37813. }else{
  37814. p->pEntry = pEntry;
  37815. }
  37816. p->pLast = pEntry;
  37817. }
  37818. /*
  37819. ** Merge two lists of RowSetEntry objects. Remove duplicates.
  37820. **
  37821. ** The input lists are connected via pRight pointers and are
  37822. ** assumed to each already be in sorted order.
  37823. */
  37824. static struct RowSetEntry *rowSetEntryMerge(
  37825. struct RowSetEntry *pA, /* First sorted list to be merged */
  37826. struct RowSetEntry *pB /* Second sorted list to be merged */
  37827. ){
  37828. struct RowSetEntry head;
  37829. struct RowSetEntry *pTail;
  37830. pTail = &head;
  37831. while( pA && pB ){
  37832. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  37833. assert( pB->pRight==0 || pB->v<=pB->pRight->v );
  37834. if( pA->v<pB->v ){
  37835. pTail->pRight = pA;
  37836. pA = pA->pRight;
  37837. pTail = pTail->pRight;
  37838. }else if( pB->v<pA->v ){
  37839. pTail->pRight = pB;
  37840. pB = pB->pRight;
  37841. pTail = pTail->pRight;
  37842. }else{
  37843. pA = pA->pRight;
  37844. }
  37845. }
  37846. if( pA ){
  37847. assert( pA->pRight==0 || pA->v<=pA->pRight->v );
  37848. pTail->pRight = pA;
  37849. }else{
  37850. assert( pB==0 || pB->pRight==0 || pB->v<=pB->pRight->v );
  37851. pTail->pRight = pB;
  37852. }
  37853. return head.pRight;
  37854. }
  37855. /*
  37856. ** Sort all elements on the list of RowSetEntry objects into order of
  37857. ** increasing v.
  37858. */
  37859. static struct RowSetEntry *rowSetEntrySort(struct RowSetEntry *pIn){
  37860. unsigned int i;
  37861. struct RowSetEntry *pNext, *aBucket[40];
  37862. memset(aBucket, 0, sizeof(aBucket));
  37863. while( pIn ){
  37864. pNext = pIn->pRight;
  37865. pIn->pRight = 0;
  37866. for(i=0; aBucket[i]; i++){
  37867. pIn = rowSetEntryMerge(aBucket[i], pIn);
  37868. aBucket[i] = 0;
  37869. }
  37870. aBucket[i] = pIn;
  37871. pIn = pNext;
  37872. }
  37873. pIn = 0;
  37874. for(i=0; i<sizeof(aBucket)/sizeof(aBucket[0]); i++){
  37875. pIn = rowSetEntryMerge(pIn, aBucket[i]);
  37876. }
  37877. return pIn;
  37878. }
  37879. /*
  37880. ** The input, pIn, is a binary tree (or subtree) of RowSetEntry objects.
  37881. ** Convert this tree into a linked list connected by the pRight pointers
  37882. ** and return pointers to the first and last elements of the new list.
  37883. */
  37884. static void rowSetTreeToList(
  37885. struct RowSetEntry *pIn, /* Root of the input tree */
  37886. struct RowSetEntry **ppFirst, /* Write head of the output list here */
  37887. struct RowSetEntry **ppLast /* Write tail of the output list here */
  37888. ){
  37889. assert( pIn!=0 );
  37890. if( pIn->pLeft ){
  37891. struct RowSetEntry *p;
  37892. rowSetTreeToList(pIn->pLeft, ppFirst, &p);
  37893. p->pRight = pIn;
  37894. }else{
  37895. *ppFirst = pIn;
  37896. }
  37897. if( pIn->pRight ){
  37898. rowSetTreeToList(pIn->pRight, &pIn->pRight, ppLast);
  37899. }else{
  37900. *ppLast = pIn;
  37901. }
  37902. assert( (*ppLast)->pRight==0 );
  37903. }
  37904. /*
  37905. ** Convert a sorted list of elements (connected by pRight) into a binary
  37906. ** tree with depth of iDepth. A depth of 1 means the tree contains a single
  37907. ** node taken from the head of *ppList. A depth of 2 means a tree with
  37908. ** three nodes. And so forth.
  37909. **
  37910. ** Use as many entries from the input list as required and update the
  37911. ** *ppList to point to the unused elements of the list. If the input
  37912. ** list contains too few elements, then construct an incomplete tree
  37913. ** and leave *ppList set to NULL.
  37914. **
  37915. ** Return a pointer to the root of the constructed binary tree.
  37916. */
  37917. static struct RowSetEntry *rowSetNDeepTree(
  37918. struct RowSetEntry **ppList,
  37919. int iDepth
  37920. ){
  37921. struct RowSetEntry *p; /* Root of the new tree */
  37922. struct RowSetEntry *pLeft; /* Left subtree */
  37923. if( *ppList==0 ){
  37924. return 0;
  37925. }
  37926. if( iDepth==1 ){
  37927. p = *ppList;
  37928. *ppList = p->pRight;
  37929. p->pLeft = p->pRight = 0;
  37930. return p;
  37931. }
  37932. pLeft = rowSetNDeepTree(ppList, iDepth-1);
  37933. p = *ppList;
  37934. if( p==0 ){
  37935. return pLeft;
  37936. }
  37937. p->pLeft = pLeft;
  37938. *ppList = p->pRight;
  37939. p->pRight = rowSetNDeepTree(ppList, iDepth-1);
  37940. return p;
  37941. }
  37942. /*
  37943. ** Convert a sorted list of elements into a binary tree. Make the tree
  37944. ** as deep as it needs to be in order to contain the entire list.
  37945. */
  37946. static struct RowSetEntry *rowSetListToTree(struct RowSetEntry *pList){
  37947. int iDepth; /* Depth of the tree so far */
  37948. struct RowSetEntry *p; /* Current tree root */
  37949. struct RowSetEntry *pLeft; /* Left subtree */
  37950. assert( pList!=0 );
  37951. p = pList;
  37952. pList = p->pRight;
  37953. p->pLeft = p->pRight = 0;
  37954. for(iDepth=1; pList; iDepth++){
  37955. pLeft = p;
  37956. p = pList;
  37957. pList = p->pRight;
  37958. p->pLeft = pLeft;
  37959. p->pRight = rowSetNDeepTree(&pList, iDepth);
  37960. }
  37961. return p;
  37962. }
  37963. /*
  37964. ** Take all the entries on p->pEntry and on the trees in p->pForest and
  37965. ** sort them all together into one big ordered list on p->pEntry.
  37966. **
  37967. ** This routine should only be called once in the life of a RowSet.
  37968. */
  37969. static void rowSetToList(RowSet *p){
  37970. /* This routine is called only once */
  37971. assert( p!=0 && (p->rsFlags & ROWSET_NEXT)==0 );
  37972. if( (p->rsFlags & ROWSET_SORTED)==0 ){
  37973. p->pEntry = rowSetEntrySort(p->pEntry);
  37974. }
  37975. /* While this module could theoretically support it, sqlite3RowSetNext()
  37976. ** is never called after sqlite3RowSetText() for the same RowSet. So
  37977. ** there is never a forest to deal with. Should this change, simply
  37978. ** remove the assert() and the #if 0. */
  37979. assert( p->pForest==0 );
  37980. #if 0
  37981. while( p->pForest ){
  37982. struct RowSetEntry *pTree = p->pForest->pLeft;
  37983. if( pTree ){
  37984. struct RowSetEntry *pHead, *pTail;
  37985. rowSetTreeToList(pTree, &pHead, &pTail);
  37986. p->pEntry = rowSetEntryMerge(p->pEntry, pHead);
  37987. }
  37988. p->pForest = p->pForest->pRight;
  37989. }
  37990. #endif
  37991. p->rsFlags |= ROWSET_NEXT; /* Verify this routine is never called again */
  37992. }
  37993. /*
  37994. ** Extract the smallest element from the RowSet.
  37995. ** Write the element into *pRowid. Return 1 on success. Return
  37996. ** 0 if the RowSet is already empty.
  37997. **
  37998. ** After this routine has been called, the sqlite3RowSetInsert()
  37999. ** routine may not be called again.
  38000. */
  38001. SQLITE_PRIVATE int sqlite3RowSetNext(RowSet *p, i64 *pRowid){
  38002. assert( p!=0 );
  38003. /* Merge the forest into a single sorted list on first call */
  38004. if( (p->rsFlags & ROWSET_NEXT)==0 ) rowSetToList(p);
  38005. /* Return the next entry on the list */
  38006. if( p->pEntry ){
  38007. *pRowid = p->pEntry->v;
  38008. p->pEntry = p->pEntry->pRight;
  38009. if( p->pEntry==0 ){
  38010. sqlite3RowSetClear(p);
  38011. }
  38012. return 1;
  38013. }else{
  38014. return 0;
  38015. }
  38016. }
  38017. /*
  38018. ** Check to see if element iRowid was inserted into the rowset as
  38019. ** part of any insert batch prior to iBatch. Return 1 or 0.
  38020. **
  38021. ** If this is the first test of a new batch and if there exist entries
  38022. ** on pRowSet->pEntry, then sort those entries into the forest at
  38023. ** pRowSet->pForest so that they can be tested.
  38024. */
  38025. SQLITE_PRIVATE int sqlite3RowSetTest(RowSet *pRowSet, int iBatch, sqlite3_int64 iRowid){
  38026. struct RowSetEntry *p, *pTree;
  38027. /* This routine is never called after sqlite3RowSetNext() */
  38028. assert( pRowSet!=0 && (pRowSet->rsFlags & ROWSET_NEXT)==0 );
  38029. /* Sort entries into the forest on the first test of a new batch
  38030. */
  38031. if( iBatch!=pRowSet->iBatch ){
  38032. p = pRowSet->pEntry;
  38033. if( p ){
  38034. struct RowSetEntry **ppPrevTree = &pRowSet->pForest;
  38035. if( (pRowSet->rsFlags & ROWSET_SORTED)==0 ){
  38036. p = rowSetEntrySort(p);
  38037. }
  38038. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  38039. ppPrevTree = &pTree->pRight;
  38040. if( pTree->pLeft==0 ){
  38041. pTree->pLeft = rowSetListToTree(p);
  38042. break;
  38043. }else{
  38044. struct RowSetEntry *pAux, *pTail;
  38045. rowSetTreeToList(pTree->pLeft, &pAux, &pTail);
  38046. pTree->pLeft = 0;
  38047. p = rowSetEntryMerge(pAux, p);
  38048. }
  38049. }
  38050. if( pTree==0 ){
  38051. *ppPrevTree = pTree = rowSetEntryAlloc(pRowSet);
  38052. if( pTree ){
  38053. pTree->v = 0;
  38054. pTree->pRight = 0;
  38055. pTree->pLeft = rowSetListToTree(p);
  38056. }
  38057. }
  38058. pRowSet->pEntry = 0;
  38059. pRowSet->pLast = 0;
  38060. pRowSet->rsFlags |= ROWSET_SORTED;
  38061. }
  38062. pRowSet->iBatch = iBatch;
  38063. }
  38064. /* Test to see if the iRowid value appears anywhere in the forest.
  38065. ** Return 1 if it does and 0 if not.
  38066. */
  38067. for(pTree = pRowSet->pForest; pTree; pTree=pTree->pRight){
  38068. p = pTree->pLeft;
  38069. while( p ){
  38070. if( p->v<iRowid ){
  38071. p = p->pRight;
  38072. }else if( p->v>iRowid ){
  38073. p = p->pLeft;
  38074. }else{
  38075. return 1;
  38076. }
  38077. }
  38078. }
  38079. return 0;
  38080. }
  38081. /************** End of rowset.c **********************************************/
  38082. /************** Begin file pager.c *******************************************/
  38083. /*
  38084. ** 2001 September 15
  38085. **
  38086. ** The author disclaims copyright to this source code. In place of
  38087. ** a legal notice, here is a blessing:
  38088. **
  38089. ** May you do good and not evil.
  38090. ** May you find forgiveness for yourself and forgive others.
  38091. ** May you share freely, never taking more than you give.
  38092. **
  38093. *************************************************************************
  38094. ** This is the implementation of the page cache subsystem or "pager".
  38095. **
  38096. ** The pager is used to access a database disk file. It implements
  38097. ** atomic commit and rollback through the use of a journal file that
  38098. ** is separate from the database file. The pager also implements file
  38099. ** locking to prevent two processes from writing the same database
  38100. ** file simultaneously, or one process from reading the database while
  38101. ** another is writing.
  38102. */
  38103. #ifndef SQLITE_OMIT_DISKIO
  38104. /************** Include wal.h in the middle of pager.c ***********************/
  38105. /************** Begin file wal.h *********************************************/
  38106. /*
  38107. ** 2010 February 1
  38108. **
  38109. ** The author disclaims copyright to this source code. In place of
  38110. ** a legal notice, here is a blessing:
  38111. **
  38112. ** May you do good and not evil.
  38113. ** May you find forgiveness for yourself and forgive others.
  38114. ** May you share freely, never taking more than you give.
  38115. **
  38116. *************************************************************************
  38117. ** This header file defines the interface to the write-ahead logging
  38118. ** system. Refer to the comments below and the header comment attached to
  38119. ** the implementation of each function in log.c for further details.
  38120. */
  38121. #ifndef _WAL_H_
  38122. #define _WAL_H_
  38123. /* Additional values that can be added to the sync_flags argument of
  38124. ** sqlite3WalFrames():
  38125. */
  38126. #define WAL_SYNC_TRANSACTIONS 0x20 /* Sync at the end of each transaction */
  38127. #define SQLITE_SYNC_MASK 0x13 /* Mask off the SQLITE_SYNC_* values */
  38128. #ifdef SQLITE_OMIT_WAL
  38129. # define sqlite3WalOpen(x,y,z) 0
  38130. # define sqlite3WalLimit(x,y)
  38131. # define sqlite3WalClose(w,x,y,z) 0
  38132. # define sqlite3WalBeginReadTransaction(y,z) 0
  38133. # define sqlite3WalEndReadTransaction(z)
  38134. # define sqlite3WalDbsize(y) 0
  38135. # define sqlite3WalBeginWriteTransaction(y) 0
  38136. # define sqlite3WalEndWriteTransaction(x) 0
  38137. # define sqlite3WalUndo(x,y,z) 0
  38138. # define sqlite3WalSavepoint(y,z)
  38139. # define sqlite3WalSavepointUndo(y,z) 0
  38140. # define sqlite3WalFrames(u,v,w,x,y,z) 0
  38141. # define sqlite3WalCheckpoint(r,s,t,u,v,w,x,y,z) 0
  38142. # define sqlite3WalCallback(z) 0
  38143. # define sqlite3WalExclusiveMode(y,z) 0
  38144. # define sqlite3WalHeapMemory(z) 0
  38145. # define sqlite3WalFramesize(z) 0
  38146. # define sqlite3WalFindFrame(x,y,z) 0
  38147. #else
  38148. #define WAL_SAVEPOINT_NDATA 4
  38149. /* Connection to a write-ahead log (WAL) file.
  38150. ** There is one object of this type for each pager.
  38151. */
  38152. typedef struct Wal Wal;
  38153. /* Open and close a connection to a write-ahead log. */
  38154. SQLITE_PRIVATE int sqlite3WalOpen(sqlite3_vfs*, sqlite3_file*, const char *, int, i64, Wal**);
  38155. SQLITE_PRIVATE int sqlite3WalClose(Wal *pWal, int sync_flags, int, u8 *);
  38156. /* Set the limiting size of a WAL file. */
  38157. SQLITE_PRIVATE void sqlite3WalLimit(Wal*, i64);
  38158. /* Used by readers to open (lock) and close (unlock) a snapshot. A
  38159. ** snapshot is like a read-transaction. It is the state of the database
  38160. ** at an instant in time. sqlite3WalOpenSnapshot gets a read lock and
  38161. ** preserves the current state even if the other threads or processes
  38162. ** write to or checkpoint the WAL. sqlite3WalCloseSnapshot() closes the
  38163. ** transaction and releases the lock.
  38164. */
  38165. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *);
  38166. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal);
  38167. /* Read a page from the write-ahead log, if it is present. */
  38168. SQLITE_PRIVATE int sqlite3WalFindFrame(Wal *, Pgno, u32 *);
  38169. SQLITE_PRIVATE int sqlite3WalReadFrame(Wal *, u32, int, u8 *);
  38170. /* If the WAL is not empty, return the size of the database. */
  38171. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal);
  38172. /* Obtain or release the WRITER lock. */
  38173. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal);
  38174. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal);
  38175. /* Undo any frames written (but not committed) to the log */
  38176. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx);
  38177. /* Return an integer that records the current (uncommitted) write
  38178. ** position in the WAL */
  38179. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData);
  38180. /* Move the write position of the WAL back to iFrame. Called in
  38181. ** response to a ROLLBACK TO command. */
  38182. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData);
  38183. /* Write a frame or frames to the log. */
  38184. SQLITE_PRIVATE int sqlite3WalFrames(Wal *pWal, int, PgHdr *, Pgno, int, int);
  38185. /* Copy pages from the log to the database file */
  38186. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  38187. Wal *pWal, /* Write-ahead log connection */
  38188. int eMode, /* One of PASSIVE, FULL and RESTART */
  38189. int (*xBusy)(void*), /* Function to call when busy */
  38190. void *pBusyArg, /* Context argument for xBusyHandler */
  38191. int sync_flags, /* Flags to sync db file with (or 0) */
  38192. int nBuf, /* Size of buffer nBuf */
  38193. u8 *zBuf, /* Temporary buffer to use */
  38194. int *pnLog, /* OUT: Number of frames in WAL */
  38195. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  38196. );
  38197. /* Return the value to pass to a sqlite3_wal_hook callback, the
  38198. ** number of frames in the WAL at the point of the last commit since
  38199. ** sqlite3WalCallback() was called. If no commits have occurred since
  38200. ** the last call, then return 0.
  38201. */
  38202. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal);
  38203. /* Tell the wal layer that an EXCLUSIVE lock has been obtained (or released)
  38204. ** by the pager layer on the database file.
  38205. */
  38206. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op);
  38207. /* Return true if the argument is non-NULL and the WAL module is using
  38208. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  38209. ** WAL module is using shared-memory, return false.
  38210. */
  38211. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal);
  38212. #ifdef SQLITE_ENABLE_ZIPVFS
  38213. /* If the WAL file is not empty, return the number of bytes of content
  38214. ** stored in each frame (i.e. the db page-size when the WAL was created).
  38215. */
  38216. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal);
  38217. #endif
  38218. #endif /* ifndef SQLITE_OMIT_WAL */
  38219. #endif /* _WAL_H_ */
  38220. /************** End of wal.h *************************************************/
  38221. /************** Continuing where we left off in pager.c **********************/
  38222. /******************* NOTES ON THE DESIGN OF THE PAGER ************************
  38223. **
  38224. ** This comment block describes invariants that hold when using a rollback
  38225. ** journal. These invariants do not apply for journal_mode=WAL,
  38226. ** journal_mode=MEMORY, or journal_mode=OFF.
  38227. **
  38228. ** Within this comment block, a page is deemed to have been synced
  38229. ** automatically as soon as it is written when PRAGMA synchronous=OFF.
  38230. ** Otherwise, the page is not synced until the xSync method of the VFS
  38231. ** is called successfully on the file containing the page.
  38232. **
  38233. ** Definition: A page of the database file is said to be "overwriteable" if
  38234. ** one or more of the following are true about the page:
  38235. **
  38236. ** (a) The original content of the page as it was at the beginning of
  38237. ** the transaction has been written into the rollback journal and
  38238. ** synced.
  38239. **
  38240. ** (b) The page was a freelist leaf page at the start of the transaction.
  38241. **
  38242. ** (c) The page number is greater than the largest page that existed in
  38243. ** the database file at the start of the transaction.
  38244. **
  38245. ** (1) A page of the database file is never overwritten unless one of the
  38246. ** following are true:
  38247. **
  38248. ** (a) The page and all other pages on the same sector are overwriteable.
  38249. **
  38250. ** (b) The atomic page write optimization is enabled, and the entire
  38251. ** transaction other than the update of the transaction sequence
  38252. ** number consists of a single page change.
  38253. **
  38254. ** (2) The content of a page written into the rollback journal exactly matches
  38255. ** both the content in the database when the rollback journal was written
  38256. ** and the content in the database at the beginning of the current
  38257. ** transaction.
  38258. **
  38259. ** (3) Writes to the database file are an integer multiple of the page size
  38260. ** in length and are aligned on a page boundary.
  38261. **
  38262. ** (4) Reads from the database file are either aligned on a page boundary and
  38263. ** an integer multiple of the page size in length or are taken from the
  38264. ** first 100 bytes of the database file.
  38265. **
  38266. ** (5) All writes to the database file are synced prior to the rollback journal
  38267. ** being deleted, truncated, or zeroed.
  38268. **
  38269. ** (6) If a master journal file is used, then all writes to the database file
  38270. ** are synced prior to the master journal being deleted.
  38271. **
  38272. ** Definition: Two databases (or the same database at two points it time)
  38273. ** are said to be "logically equivalent" if they give the same answer to
  38274. ** all queries. Note in particular the content of freelist leaf
  38275. ** pages can be changed arbitrarily without affecting the logical equivalence
  38276. ** of the database.
  38277. **
  38278. ** (7) At any time, if any subset, including the empty set and the total set,
  38279. ** of the unsynced changes to a rollback journal are removed and the
  38280. ** journal is rolled back, the resulting database file will be logically
  38281. ** equivalent to the database file at the beginning of the transaction.
  38282. **
  38283. ** (8) When a transaction is rolled back, the xTruncate method of the VFS
  38284. ** is called to restore the database file to the same size it was at
  38285. ** the beginning of the transaction. (In some VFSes, the xTruncate
  38286. ** method is a no-op, but that does not change the fact the SQLite will
  38287. ** invoke it.)
  38288. **
  38289. ** (9) Whenever the database file is modified, at least one bit in the range
  38290. ** of bytes from 24 through 39 inclusive will be changed prior to releasing
  38291. ** the EXCLUSIVE lock, thus signaling other connections on the same
  38292. ** database to flush their caches.
  38293. **
  38294. ** (10) The pattern of bits in bytes 24 through 39 shall not repeat in less
  38295. ** than one billion transactions.
  38296. **
  38297. ** (11) A database file is well-formed at the beginning and at the conclusion
  38298. ** of every transaction.
  38299. **
  38300. ** (12) An EXCLUSIVE lock is held on the database file when writing to
  38301. ** the database file.
  38302. **
  38303. ** (13) A SHARED lock is held on the database file while reading any
  38304. ** content out of the database file.
  38305. **
  38306. ******************************************************************************/
  38307. /*
  38308. ** Macros for troubleshooting. Normally turned off
  38309. */
  38310. #if 0
  38311. int sqlite3PagerTrace=1; /* True to enable tracing */
  38312. #define sqlite3DebugPrintf printf
  38313. #define PAGERTRACE(X) if( sqlite3PagerTrace ){ sqlite3DebugPrintf X; }
  38314. #else
  38315. #define PAGERTRACE(X)
  38316. #endif
  38317. /*
  38318. ** The following two macros are used within the PAGERTRACE() macros above
  38319. ** to print out file-descriptors.
  38320. **
  38321. ** PAGERID() takes a pointer to a Pager struct as its argument. The
  38322. ** associated file-descriptor is returned. FILEHANDLEID() takes an sqlite3_file
  38323. ** struct as its argument.
  38324. */
  38325. #define PAGERID(p) ((int)(p->fd))
  38326. #define FILEHANDLEID(fd) ((int)fd)
  38327. /*
  38328. ** The Pager.eState variable stores the current 'state' of a pager. A
  38329. ** pager may be in any one of the seven states shown in the following
  38330. ** state diagram.
  38331. **
  38332. ** OPEN <------+------+
  38333. ** | | |
  38334. ** V | |
  38335. ** +---------> READER-------+ |
  38336. ** | | |
  38337. ** | V |
  38338. ** |<-------WRITER_LOCKED------> ERROR
  38339. ** | | ^
  38340. ** | V |
  38341. ** |<------WRITER_CACHEMOD-------->|
  38342. ** | | |
  38343. ** | V |
  38344. ** |<-------WRITER_DBMOD---------->|
  38345. ** | | |
  38346. ** | V |
  38347. ** +<------WRITER_FINISHED-------->+
  38348. **
  38349. **
  38350. ** List of state transitions and the C [function] that performs each:
  38351. **
  38352. ** OPEN -> READER [sqlite3PagerSharedLock]
  38353. ** READER -> OPEN [pager_unlock]
  38354. **
  38355. ** READER -> WRITER_LOCKED [sqlite3PagerBegin]
  38356. ** WRITER_LOCKED -> WRITER_CACHEMOD [pager_open_journal]
  38357. ** WRITER_CACHEMOD -> WRITER_DBMOD [syncJournal]
  38358. ** WRITER_DBMOD -> WRITER_FINISHED [sqlite3PagerCommitPhaseOne]
  38359. ** WRITER_*** -> READER [pager_end_transaction]
  38360. **
  38361. ** WRITER_*** -> ERROR [pager_error]
  38362. ** ERROR -> OPEN [pager_unlock]
  38363. **
  38364. **
  38365. ** OPEN:
  38366. **
  38367. ** The pager starts up in this state. Nothing is guaranteed in this
  38368. ** state - the file may or may not be locked and the database size is
  38369. ** unknown. The database may not be read or written.
  38370. **
  38371. ** * No read or write transaction is active.
  38372. ** * Any lock, or no lock at all, may be held on the database file.
  38373. ** * The dbSize, dbOrigSize and dbFileSize variables may not be trusted.
  38374. **
  38375. ** READER:
  38376. **
  38377. ** In this state all the requirements for reading the database in
  38378. ** rollback (non-WAL) mode are met. Unless the pager is (or recently
  38379. ** was) in exclusive-locking mode, a user-level read transaction is
  38380. ** open. The database size is known in this state.
  38381. **
  38382. ** A connection running with locking_mode=normal enters this state when
  38383. ** it opens a read-transaction on the database and returns to state
  38384. ** OPEN after the read-transaction is completed. However a connection
  38385. ** running in locking_mode=exclusive (including temp databases) remains in
  38386. ** this state even after the read-transaction is closed. The only way
  38387. ** a locking_mode=exclusive connection can transition from READER to OPEN
  38388. ** is via the ERROR state (see below).
  38389. **
  38390. ** * A read transaction may be active (but a write-transaction cannot).
  38391. ** * A SHARED or greater lock is held on the database file.
  38392. ** * The dbSize variable may be trusted (even if a user-level read
  38393. ** transaction is not active). The dbOrigSize and dbFileSize variables
  38394. ** may not be trusted at this point.
  38395. ** * If the database is a WAL database, then the WAL connection is open.
  38396. ** * Even if a read-transaction is not open, it is guaranteed that
  38397. ** there is no hot-journal in the file-system.
  38398. **
  38399. ** WRITER_LOCKED:
  38400. **
  38401. ** The pager moves to this state from READER when a write-transaction
  38402. ** is first opened on the database. In WRITER_LOCKED state, all locks
  38403. ** required to start a write-transaction are held, but no actual
  38404. ** modifications to the cache or database have taken place.
  38405. **
  38406. ** In rollback mode, a RESERVED or (if the transaction was opened with
  38407. ** BEGIN EXCLUSIVE) EXCLUSIVE lock is obtained on the database file when
  38408. ** moving to this state, but the journal file is not written to or opened
  38409. ** to in this state. If the transaction is committed or rolled back while
  38410. ** in WRITER_LOCKED state, all that is required is to unlock the database
  38411. ** file.
  38412. **
  38413. ** IN WAL mode, WalBeginWriteTransaction() is called to lock the log file.
  38414. ** If the connection is running with locking_mode=exclusive, an attempt
  38415. ** is made to obtain an EXCLUSIVE lock on the database file.
  38416. **
  38417. ** * A write transaction is active.
  38418. ** * If the connection is open in rollback-mode, a RESERVED or greater
  38419. ** lock is held on the database file.
  38420. ** * If the connection is open in WAL-mode, a WAL write transaction
  38421. ** is open (i.e. sqlite3WalBeginWriteTransaction() has been successfully
  38422. ** called).
  38423. ** * The dbSize, dbOrigSize and dbFileSize variables are all valid.
  38424. ** * The contents of the pager cache have not been modified.
  38425. ** * The journal file may or may not be open.
  38426. ** * Nothing (not even the first header) has been written to the journal.
  38427. **
  38428. ** WRITER_CACHEMOD:
  38429. **
  38430. ** A pager moves from WRITER_LOCKED state to this state when a page is
  38431. ** first modified by the upper layer. In rollback mode the journal file
  38432. ** is opened (if it is not already open) and a header written to the
  38433. ** start of it. The database file on disk has not been modified.
  38434. **
  38435. ** * A write transaction is active.
  38436. ** * A RESERVED or greater lock is held on the database file.
  38437. ** * The journal file is open and the first header has been written
  38438. ** to it, but the header has not been synced to disk.
  38439. ** * The contents of the page cache have been modified.
  38440. **
  38441. ** WRITER_DBMOD:
  38442. **
  38443. ** The pager transitions from WRITER_CACHEMOD into WRITER_DBMOD state
  38444. ** when it modifies the contents of the database file. WAL connections
  38445. ** never enter this state (since they do not modify the database file,
  38446. ** just the log file).
  38447. **
  38448. ** * A write transaction is active.
  38449. ** * An EXCLUSIVE or greater lock is held on the database file.
  38450. ** * The journal file is open and the first header has been written
  38451. ** and synced to disk.
  38452. ** * The contents of the page cache have been modified (and possibly
  38453. ** written to disk).
  38454. **
  38455. ** WRITER_FINISHED:
  38456. **
  38457. ** It is not possible for a WAL connection to enter this state.
  38458. **
  38459. ** A rollback-mode pager changes to WRITER_FINISHED state from WRITER_DBMOD
  38460. ** state after the entire transaction has been successfully written into the
  38461. ** database file. In this state the transaction may be committed simply
  38462. ** by finalizing the journal file. Once in WRITER_FINISHED state, it is
  38463. ** not possible to modify the database further. At this point, the upper
  38464. ** layer must either commit or rollback the transaction.
  38465. **
  38466. ** * A write transaction is active.
  38467. ** * An EXCLUSIVE or greater lock is held on the database file.
  38468. ** * All writing and syncing of journal and database data has finished.
  38469. ** If no error occurred, all that remains is to finalize the journal to
  38470. ** commit the transaction. If an error did occur, the caller will need
  38471. ** to rollback the transaction.
  38472. **
  38473. ** ERROR:
  38474. **
  38475. ** The ERROR state is entered when an IO or disk-full error (including
  38476. ** SQLITE_IOERR_NOMEM) occurs at a point in the code that makes it
  38477. ** difficult to be sure that the in-memory pager state (cache contents,
  38478. ** db size etc.) are consistent with the contents of the file-system.
  38479. **
  38480. ** Temporary pager files may enter the ERROR state, but in-memory pagers
  38481. ** cannot.
  38482. **
  38483. ** For example, if an IO error occurs while performing a rollback,
  38484. ** the contents of the page-cache may be left in an inconsistent state.
  38485. ** At this point it would be dangerous to change back to READER state
  38486. ** (as usually happens after a rollback). Any subsequent readers might
  38487. ** report database corruption (due to the inconsistent cache), and if
  38488. ** they upgrade to writers, they may inadvertently corrupt the database
  38489. ** file. To avoid this hazard, the pager switches into the ERROR state
  38490. ** instead of READER following such an error.
  38491. **
  38492. ** Once it has entered the ERROR state, any attempt to use the pager
  38493. ** to read or write data returns an error. Eventually, once all
  38494. ** outstanding transactions have been abandoned, the pager is able to
  38495. ** transition back to OPEN state, discarding the contents of the
  38496. ** page-cache and any other in-memory state at the same time. Everything
  38497. ** is reloaded from disk (and, if necessary, hot-journal rollback peformed)
  38498. ** when a read-transaction is next opened on the pager (transitioning
  38499. ** the pager into READER state). At that point the system has recovered
  38500. ** from the error.
  38501. **
  38502. ** Specifically, the pager jumps into the ERROR state if:
  38503. **
  38504. ** 1. An error occurs while attempting a rollback. This happens in
  38505. ** function sqlite3PagerRollback().
  38506. **
  38507. ** 2. An error occurs while attempting to finalize a journal file
  38508. ** following a commit in function sqlite3PagerCommitPhaseTwo().
  38509. **
  38510. ** 3. An error occurs while attempting to write to the journal or
  38511. ** database file in function pagerStress() in order to free up
  38512. ** memory.
  38513. **
  38514. ** In other cases, the error is returned to the b-tree layer. The b-tree
  38515. ** layer then attempts a rollback operation. If the error condition
  38516. ** persists, the pager enters the ERROR state via condition (1) above.
  38517. **
  38518. ** Condition (3) is necessary because it can be triggered by a read-only
  38519. ** statement executed within a transaction. In this case, if the error
  38520. ** code were simply returned to the user, the b-tree layer would not
  38521. ** automatically attempt a rollback, as it assumes that an error in a
  38522. ** read-only statement cannot leave the pager in an internally inconsistent
  38523. ** state.
  38524. **
  38525. ** * The Pager.errCode variable is set to something other than SQLITE_OK.
  38526. ** * There are one or more outstanding references to pages (after the
  38527. ** last reference is dropped the pager should move back to OPEN state).
  38528. ** * The pager is not an in-memory pager.
  38529. **
  38530. **
  38531. ** Notes:
  38532. **
  38533. ** * A pager is never in WRITER_DBMOD or WRITER_FINISHED state if the
  38534. ** connection is open in WAL mode. A WAL connection is always in one
  38535. ** of the first four states.
  38536. **
  38537. ** * Normally, a connection open in exclusive mode is never in PAGER_OPEN
  38538. ** state. There are two exceptions: immediately after exclusive-mode has
  38539. ** been turned on (and before any read or write transactions are
  38540. ** executed), and when the pager is leaving the "error state".
  38541. **
  38542. ** * See also: assert_pager_state().
  38543. */
  38544. #define PAGER_OPEN 0
  38545. #define PAGER_READER 1
  38546. #define PAGER_WRITER_LOCKED 2
  38547. #define PAGER_WRITER_CACHEMOD 3
  38548. #define PAGER_WRITER_DBMOD 4
  38549. #define PAGER_WRITER_FINISHED 5
  38550. #define PAGER_ERROR 6
  38551. /*
  38552. ** The Pager.eLock variable is almost always set to one of the
  38553. ** following locking-states, according to the lock currently held on
  38554. ** the database file: NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  38555. ** This variable is kept up to date as locks are taken and released by
  38556. ** the pagerLockDb() and pagerUnlockDb() wrappers.
  38557. **
  38558. ** If the VFS xLock() or xUnlock() returns an error other than SQLITE_BUSY
  38559. ** (i.e. one of the SQLITE_IOERR subtypes), it is not clear whether or not
  38560. ** the operation was successful. In these circumstances pagerLockDb() and
  38561. ** pagerUnlockDb() take a conservative approach - eLock is always updated
  38562. ** when unlocking the file, and only updated when locking the file if the
  38563. ** VFS call is successful. This way, the Pager.eLock variable may be set
  38564. ** to a less exclusive (lower) value than the lock that is actually held
  38565. ** at the system level, but it is never set to a more exclusive value.
  38566. **
  38567. ** This is usually safe. If an xUnlock fails or appears to fail, there may
  38568. ** be a few redundant xLock() calls or a lock may be held for longer than
  38569. ** required, but nothing really goes wrong.
  38570. **
  38571. ** The exception is when the database file is unlocked as the pager moves
  38572. ** from ERROR to OPEN state. At this point there may be a hot-journal file
  38573. ** in the file-system that needs to be rolled back (as part of an OPEN->SHARED
  38574. ** transition, by the same pager or any other). If the call to xUnlock()
  38575. ** fails at this point and the pager is left holding an EXCLUSIVE lock, this
  38576. ** can confuse the call to xCheckReservedLock() call made later as part
  38577. ** of hot-journal detection.
  38578. **
  38579. ** xCheckReservedLock() is defined as returning true "if there is a RESERVED
  38580. ** lock held by this process or any others". So xCheckReservedLock may
  38581. ** return true because the caller itself is holding an EXCLUSIVE lock (but
  38582. ** doesn't know it because of a previous error in xUnlock). If this happens
  38583. ** a hot-journal may be mistaken for a journal being created by an active
  38584. ** transaction in another process, causing SQLite to read from the database
  38585. ** without rolling it back.
  38586. **
  38587. ** To work around this, if a call to xUnlock() fails when unlocking the
  38588. ** database in the ERROR state, Pager.eLock is set to UNKNOWN_LOCK. It
  38589. ** is only changed back to a real locking state after a successful call
  38590. ** to xLock(EXCLUSIVE). Also, the code to do the OPEN->SHARED state transition
  38591. ** omits the check for a hot-journal if Pager.eLock is set to UNKNOWN_LOCK
  38592. ** lock. Instead, it assumes a hot-journal exists and obtains an EXCLUSIVE
  38593. ** lock on the database file before attempting to roll it back. See function
  38594. ** PagerSharedLock() for more detail.
  38595. **
  38596. ** Pager.eLock may only be set to UNKNOWN_LOCK when the pager is in
  38597. ** PAGER_OPEN state.
  38598. */
  38599. #define UNKNOWN_LOCK (EXCLUSIVE_LOCK+1)
  38600. /*
  38601. ** A macro used for invoking the codec if there is one
  38602. */
  38603. #ifdef SQLITE_HAS_CODEC
  38604. # define CODEC1(P,D,N,X,E) \
  38605. if( P->xCodec && P->xCodec(P->pCodec,D,N,X)==0 ){ E; }
  38606. # define CODEC2(P,D,N,X,E,O) \
  38607. if( P->xCodec==0 ){ O=(char*)D; }else \
  38608. if( (O=(char*)(P->xCodec(P->pCodec,D,N,X)))==0 ){ E; }
  38609. #else
  38610. # define CODEC1(P,D,N,X,E) /* NO-OP */
  38611. # define CODEC2(P,D,N,X,E,O) O=(char*)D
  38612. #endif
  38613. /*
  38614. ** The maximum allowed sector size. 64KiB. If the xSectorsize() method
  38615. ** returns a value larger than this, then MAX_SECTOR_SIZE is used instead.
  38616. ** This could conceivably cause corruption following a power failure on
  38617. ** such a system. This is currently an undocumented limit.
  38618. */
  38619. #define MAX_SECTOR_SIZE 0x10000
  38620. /*
  38621. ** An instance of the following structure is allocated for each active
  38622. ** savepoint and statement transaction in the system. All such structures
  38623. ** are stored in the Pager.aSavepoint[] array, which is allocated and
  38624. ** resized using sqlite3Realloc().
  38625. **
  38626. ** When a savepoint is created, the PagerSavepoint.iHdrOffset field is
  38627. ** set to 0. If a journal-header is written into the main journal while
  38628. ** the savepoint is active, then iHdrOffset is set to the byte offset
  38629. ** immediately following the last journal record written into the main
  38630. ** journal before the journal-header. This is required during savepoint
  38631. ** rollback (see pagerPlaybackSavepoint()).
  38632. */
  38633. typedef struct PagerSavepoint PagerSavepoint;
  38634. struct PagerSavepoint {
  38635. i64 iOffset; /* Starting offset in main journal */
  38636. i64 iHdrOffset; /* See above */
  38637. Bitvec *pInSavepoint; /* Set of pages in this savepoint */
  38638. Pgno nOrig; /* Original number of pages in file */
  38639. Pgno iSubRec; /* Index of first record in sub-journal */
  38640. #ifndef SQLITE_OMIT_WAL
  38641. u32 aWalData[WAL_SAVEPOINT_NDATA]; /* WAL savepoint context */
  38642. #endif
  38643. };
  38644. /*
  38645. ** Bits of the Pager.doNotSpill flag. See further description below.
  38646. */
  38647. #define SPILLFLAG_OFF 0x01 /* Never spill cache. Set via pragma */
  38648. #define SPILLFLAG_ROLLBACK 0x02 /* Current rolling back, so do not spill */
  38649. #define SPILLFLAG_NOSYNC 0x04 /* Spill is ok, but do not sync */
  38650. /*
  38651. ** An open page cache is an instance of struct Pager. A description of
  38652. ** some of the more important member variables follows:
  38653. **
  38654. ** eState
  38655. **
  38656. ** The current 'state' of the pager object. See the comment and state
  38657. ** diagram above for a description of the pager state.
  38658. **
  38659. ** eLock
  38660. **
  38661. ** For a real on-disk database, the current lock held on the database file -
  38662. ** NO_LOCK, SHARED_LOCK, RESERVED_LOCK or EXCLUSIVE_LOCK.
  38663. **
  38664. ** For a temporary or in-memory database (neither of which require any
  38665. ** locks), this variable is always set to EXCLUSIVE_LOCK. Since such
  38666. ** databases always have Pager.exclusiveMode==1, this tricks the pager
  38667. ** logic into thinking that it already has all the locks it will ever
  38668. ** need (and no reason to release them).
  38669. **
  38670. ** In some (obscure) circumstances, this variable may also be set to
  38671. ** UNKNOWN_LOCK. See the comment above the #define of UNKNOWN_LOCK for
  38672. ** details.
  38673. **
  38674. ** changeCountDone
  38675. **
  38676. ** This boolean variable is used to make sure that the change-counter
  38677. ** (the 4-byte header field at byte offset 24 of the database file) is
  38678. ** not updated more often than necessary.
  38679. **
  38680. ** It is set to true when the change-counter field is updated, which
  38681. ** can only happen if an exclusive lock is held on the database file.
  38682. ** It is cleared (set to false) whenever an exclusive lock is
  38683. ** relinquished on the database file. Each time a transaction is committed,
  38684. ** The changeCountDone flag is inspected. If it is true, the work of
  38685. ** updating the change-counter is omitted for the current transaction.
  38686. **
  38687. ** This mechanism means that when running in exclusive mode, a connection
  38688. ** need only update the change-counter once, for the first transaction
  38689. ** committed.
  38690. **
  38691. ** setMaster
  38692. **
  38693. ** When PagerCommitPhaseOne() is called to commit a transaction, it may
  38694. ** (or may not) specify a master-journal name to be written into the
  38695. ** journal file before it is synced to disk.
  38696. **
  38697. ** Whether or not a journal file contains a master-journal pointer affects
  38698. ** the way in which the journal file is finalized after the transaction is
  38699. ** committed or rolled back when running in "journal_mode=PERSIST" mode.
  38700. ** If a journal file does not contain a master-journal pointer, it is
  38701. ** finalized by overwriting the first journal header with zeroes. If
  38702. ** it does contain a master-journal pointer the journal file is finalized
  38703. ** by truncating it to zero bytes, just as if the connection were
  38704. ** running in "journal_mode=truncate" mode.
  38705. **
  38706. ** Journal files that contain master journal pointers cannot be finalized
  38707. ** simply by overwriting the first journal-header with zeroes, as the
  38708. ** master journal pointer could interfere with hot-journal rollback of any
  38709. ** subsequently interrupted transaction that reuses the journal file.
  38710. **
  38711. ** The flag is cleared as soon as the journal file is finalized (either
  38712. ** by PagerCommitPhaseTwo or PagerRollback). If an IO error prevents the
  38713. ** journal file from being successfully finalized, the setMaster flag
  38714. ** is cleared anyway (and the pager will move to ERROR state).
  38715. **
  38716. ** doNotSpill
  38717. **
  38718. ** This variables control the behavior of cache-spills (calls made by
  38719. ** the pcache module to the pagerStress() routine to write cached data
  38720. ** to the file-system in order to free up memory).
  38721. **
  38722. ** When bits SPILLFLAG_OFF or SPILLFLAG_ROLLBACK of doNotSpill are set,
  38723. ** writing to the database from pagerStress() is disabled altogether.
  38724. ** The SPILLFLAG_ROLLBACK case is done in a very obscure case that
  38725. ** comes up during savepoint rollback that requires the pcache module
  38726. ** to allocate a new page to prevent the journal file from being written
  38727. ** while it is being traversed by code in pager_playback(). The SPILLFLAG_OFF
  38728. ** case is a user preference.
  38729. **
  38730. ** If the SPILLFLAG_NOSYNC bit is set, writing to the database from pagerStress()
  38731. ** is permitted, but syncing the journal file is not. This flag is set
  38732. ** by sqlite3PagerWrite() when the file-system sector-size is larger than
  38733. ** the database page-size in order to prevent a journal sync from happening
  38734. ** in between the journalling of two pages on the same sector.
  38735. **
  38736. ** subjInMemory
  38737. **
  38738. ** This is a boolean variable. If true, then any required sub-journal
  38739. ** is opened as an in-memory journal file. If false, then in-memory
  38740. ** sub-journals are only used for in-memory pager files.
  38741. **
  38742. ** This variable is updated by the upper layer each time a new
  38743. ** write-transaction is opened.
  38744. **
  38745. ** dbSize, dbOrigSize, dbFileSize
  38746. **
  38747. ** Variable dbSize is set to the number of pages in the database file.
  38748. ** It is valid in PAGER_READER and higher states (all states except for
  38749. ** OPEN and ERROR).
  38750. **
  38751. ** dbSize is set based on the size of the database file, which may be
  38752. ** larger than the size of the database (the value stored at offset
  38753. ** 28 of the database header by the btree). If the size of the file
  38754. ** is not an integer multiple of the page-size, the value stored in
  38755. ** dbSize is rounded down (i.e. a 5KB file with 2K page-size has dbSize==2).
  38756. ** Except, any file that is greater than 0 bytes in size is considered
  38757. ** to have at least one page. (i.e. a 1KB file with 2K page-size leads
  38758. ** to dbSize==1).
  38759. **
  38760. ** During a write-transaction, if pages with page-numbers greater than
  38761. ** dbSize are modified in the cache, dbSize is updated accordingly.
  38762. ** Similarly, if the database is truncated using PagerTruncateImage(),
  38763. ** dbSize is updated.
  38764. **
  38765. ** Variables dbOrigSize and dbFileSize are valid in states
  38766. ** PAGER_WRITER_LOCKED and higher. dbOrigSize is a copy of the dbSize
  38767. ** variable at the start of the transaction. It is used during rollback,
  38768. ** and to determine whether or not pages need to be journalled before
  38769. ** being modified.
  38770. **
  38771. ** Throughout a write-transaction, dbFileSize contains the size of
  38772. ** the file on disk in pages. It is set to a copy of dbSize when the
  38773. ** write-transaction is first opened, and updated when VFS calls are made
  38774. ** to write or truncate the database file on disk.
  38775. **
  38776. ** The only reason the dbFileSize variable is required is to suppress
  38777. ** unnecessary calls to xTruncate() after committing a transaction. If,
  38778. ** when a transaction is committed, the dbFileSize variable indicates
  38779. ** that the database file is larger than the database image (Pager.dbSize),
  38780. ** pager_truncate() is called. The pager_truncate() call uses xFilesize()
  38781. ** to measure the database file on disk, and then truncates it if required.
  38782. ** dbFileSize is not used when rolling back a transaction. In this case
  38783. ** pager_truncate() is called unconditionally (which means there may be
  38784. ** a call to xFilesize() that is not strictly required). In either case,
  38785. ** pager_truncate() may cause the file to become smaller or larger.
  38786. **
  38787. ** dbHintSize
  38788. **
  38789. ** The dbHintSize variable is used to limit the number of calls made to
  38790. ** the VFS xFileControl(FCNTL_SIZE_HINT) method.
  38791. **
  38792. ** dbHintSize is set to a copy of the dbSize variable when a
  38793. ** write-transaction is opened (at the same time as dbFileSize and
  38794. ** dbOrigSize). If the xFileControl(FCNTL_SIZE_HINT) method is called,
  38795. ** dbHintSize is increased to the number of pages that correspond to the
  38796. ** size-hint passed to the method call. See pager_write_pagelist() for
  38797. ** details.
  38798. **
  38799. ** errCode
  38800. **
  38801. ** The Pager.errCode variable is only ever used in PAGER_ERROR state. It
  38802. ** is set to zero in all other states. In PAGER_ERROR state, Pager.errCode
  38803. ** is always set to SQLITE_FULL, SQLITE_IOERR or one of the SQLITE_IOERR_XXX
  38804. ** sub-codes.
  38805. */
  38806. struct Pager {
  38807. sqlite3_vfs *pVfs; /* OS functions to use for IO */
  38808. u8 exclusiveMode; /* Boolean. True if locking_mode==EXCLUSIVE */
  38809. u8 journalMode; /* One of the PAGER_JOURNALMODE_* values */
  38810. u8 useJournal; /* Use a rollback journal on this file */
  38811. u8 noSync; /* Do not sync the journal if true */
  38812. u8 fullSync; /* Do extra syncs of the journal for robustness */
  38813. u8 ckptSyncFlags; /* SYNC_NORMAL or SYNC_FULL for checkpoint */
  38814. u8 walSyncFlags; /* SYNC_NORMAL or SYNC_FULL for wal writes */
  38815. u8 syncFlags; /* SYNC_NORMAL or SYNC_FULL otherwise */
  38816. u8 tempFile; /* zFilename is a temporary or immutable file */
  38817. u8 noLock; /* Do not lock (except in WAL mode) */
  38818. u8 readOnly; /* True for a read-only database */
  38819. u8 memDb; /* True to inhibit all file I/O */
  38820. /**************************************************************************
  38821. ** The following block contains those class members that change during
  38822. ** routine operation. Class members not in this block are either fixed
  38823. ** when the pager is first created or else only change when there is a
  38824. ** significant mode change (such as changing the page_size, locking_mode,
  38825. ** or the journal_mode). From another view, these class members describe
  38826. ** the "state" of the pager, while other class members describe the
  38827. ** "configuration" of the pager.
  38828. */
  38829. u8 eState; /* Pager state (OPEN, READER, WRITER_LOCKED..) */
  38830. u8 eLock; /* Current lock held on database file */
  38831. u8 changeCountDone; /* Set after incrementing the change-counter */
  38832. u8 setMaster; /* True if a m-j name has been written to jrnl */
  38833. u8 doNotSpill; /* Do not spill the cache when non-zero */
  38834. u8 subjInMemory; /* True to use in-memory sub-journals */
  38835. Pgno dbSize; /* Number of pages in the database */
  38836. Pgno dbOrigSize; /* dbSize before the current transaction */
  38837. Pgno dbFileSize; /* Number of pages in the database file */
  38838. Pgno dbHintSize; /* Value passed to FCNTL_SIZE_HINT call */
  38839. int errCode; /* One of several kinds of errors */
  38840. int nRec; /* Pages journalled since last j-header written */
  38841. u32 cksumInit; /* Quasi-random value added to every checksum */
  38842. u32 nSubRec; /* Number of records written to sub-journal */
  38843. Bitvec *pInJournal; /* One bit for each page in the database file */
  38844. sqlite3_file *fd; /* File descriptor for database */
  38845. sqlite3_file *jfd; /* File descriptor for main journal */
  38846. sqlite3_file *sjfd; /* File descriptor for sub-journal */
  38847. i64 journalOff; /* Current write offset in the journal file */
  38848. i64 journalHdr; /* Byte offset to previous journal header */
  38849. sqlite3_backup *pBackup; /* Pointer to list of ongoing backup processes */
  38850. PagerSavepoint *aSavepoint; /* Array of active savepoints */
  38851. int nSavepoint; /* Number of elements in aSavepoint[] */
  38852. char dbFileVers[16]; /* Changes whenever database file changes */
  38853. u8 bUseFetch; /* True to use xFetch() */
  38854. int nMmapOut; /* Number of mmap pages currently outstanding */
  38855. sqlite3_int64 szMmap; /* Desired maximum mmap size */
  38856. PgHdr *pMmapFreelist; /* List of free mmap page headers (pDirty) */
  38857. /*
  38858. ** End of the routinely-changing class members
  38859. ***************************************************************************/
  38860. u16 nExtra; /* Add this many bytes to each in-memory page */
  38861. i16 nReserve; /* Number of unused bytes at end of each page */
  38862. u32 vfsFlags; /* Flags for sqlite3_vfs.xOpen() */
  38863. u32 sectorSize; /* Assumed sector size during rollback */
  38864. int pageSize; /* Number of bytes in a page */
  38865. Pgno mxPgno; /* Maximum allowed size of the database */
  38866. i64 journalSizeLimit; /* Size limit for persistent journal files */
  38867. char *zFilename; /* Name of the database file */
  38868. char *zJournal; /* Name of the journal file */
  38869. int (*xBusyHandler)(void*); /* Function to call when busy */
  38870. void *pBusyHandlerArg; /* Context argument for xBusyHandler */
  38871. int aStat[3]; /* Total cache hits, misses and writes */
  38872. #ifdef SQLITE_TEST
  38873. int nRead; /* Database pages read */
  38874. #endif
  38875. void (*xReiniter)(DbPage*); /* Call this routine when reloading pages */
  38876. #ifdef SQLITE_HAS_CODEC
  38877. void *(*xCodec)(void*,void*,Pgno,int); /* Routine for en/decoding data */
  38878. void (*xCodecSizeChng)(void*,int,int); /* Notify of page size changes */
  38879. void (*xCodecFree)(void*); /* Destructor for the codec */
  38880. void *pCodec; /* First argument to xCodec... methods */
  38881. #endif
  38882. char *pTmpSpace; /* Pager.pageSize bytes of space for tmp use */
  38883. PCache *pPCache; /* Pointer to page cache object */
  38884. #ifndef SQLITE_OMIT_WAL
  38885. Wal *pWal; /* Write-ahead log used by "journal_mode=wal" */
  38886. char *zWal; /* File name for write-ahead log */
  38887. #endif
  38888. };
  38889. /*
  38890. ** Indexes for use with Pager.aStat[]. The Pager.aStat[] array contains
  38891. ** the values accessed by passing SQLITE_DBSTATUS_CACHE_HIT, CACHE_MISS
  38892. ** or CACHE_WRITE to sqlite3_db_status().
  38893. */
  38894. #define PAGER_STAT_HIT 0
  38895. #define PAGER_STAT_MISS 1
  38896. #define PAGER_STAT_WRITE 2
  38897. /*
  38898. ** The following global variables hold counters used for
  38899. ** testing purposes only. These variables do not exist in
  38900. ** a non-testing build. These variables are not thread-safe.
  38901. */
  38902. #ifdef SQLITE_TEST
  38903. SQLITE_API int sqlite3_pager_readdb_count = 0; /* Number of full pages read from DB */
  38904. SQLITE_API int sqlite3_pager_writedb_count = 0; /* Number of full pages written to DB */
  38905. SQLITE_API int sqlite3_pager_writej_count = 0; /* Number of pages written to journal */
  38906. # define PAGER_INCR(v) v++
  38907. #else
  38908. # define PAGER_INCR(v)
  38909. #endif
  38910. /*
  38911. ** Journal files begin with the following magic string. The data
  38912. ** was obtained from /dev/random. It is used only as a sanity check.
  38913. **
  38914. ** Since version 2.8.0, the journal format contains additional sanity
  38915. ** checking information. If the power fails while the journal is being
  38916. ** written, semi-random garbage data might appear in the journal
  38917. ** file after power is restored. If an attempt is then made
  38918. ** to roll the journal back, the database could be corrupted. The additional
  38919. ** sanity checking data is an attempt to discover the garbage in the
  38920. ** journal and ignore it.
  38921. **
  38922. ** The sanity checking information for the new journal format consists
  38923. ** of a 32-bit checksum on each page of data. The checksum covers both
  38924. ** the page number and the pPager->pageSize bytes of data for the page.
  38925. ** This cksum is initialized to a 32-bit random value that appears in the
  38926. ** journal file right after the header. The random initializer is important,
  38927. ** because garbage data that appears at the end of a journal is likely
  38928. ** data that was once in other files that have now been deleted. If the
  38929. ** garbage data came from an obsolete journal file, the checksums might
  38930. ** be correct. But by initializing the checksum to random value which
  38931. ** is different for every journal, we minimize that risk.
  38932. */
  38933. static const unsigned char aJournalMagic[] = {
  38934. 0xd9, 0xd5, 0x05, 0xf9, 0x20, 0xa1, 0x63, 0xd7,
  38935. };
  38936. /*
  38937. ** The size of the of each page record in the journal is given by
  38938. ** the following macro.
  38939. */
  38940. #define JOURNAL_PG_SZ(pPager) ((pPager->pageSize) + 8)
  38941. /*
  38942. ** The journal header size for this pager. This is usually the same
  38943. ** size as a single disk sector. See also setSectorSize().
  38944. */
  38945. #define JOURNAL_HDR_SZ(pPager) (pPager->sectorSize)
  38946. /*
  38947. ** The macro MEMDB is true if we are dealing with an in-memory database.
  38948. ** We do this as a macro so that if the SQLITE_OMIT_MEMORYDB macro is set,
  38949. ** the value of MEMDB will be a constant and the compiler will optimize
  38950. ** out code that would never execute.
  38951. */
  38952. #ifdef SQLITE_OMIT_MEMORYDB
  38953. # define MEMDB 0
  38954. #else
  38955. # define MEMDB pPager->memDb
  38956. #endif
  38957. /*
  38958. ** The macro USEFETCH is true if we are allowed to use the xFetch and xUnfetch
  38959. ** interfaces to access the database using memory-mapped I/O.
  38960. */
  38961. #if SQLITE_MAX_MMAP_SIZE>0
  38962. # define USEFETCH(x) ((x)->bUseFetch)
  38963. #else
  38964. # define USEFETCH(x) 0
  38965. #endif
  38966. /*
  38967. ** The maximum legal page number is (2^31 - 1).
  38968. */
  38969. #define PAGER_MAX_PGNO 2147483647
  38970. /*
  38971. ** The argument to this macro is a file descriptor (type sqlite3_file*).
  38972. ** Return 0 if it is not open, or non-zero (but not 1) if it is.
  38973. **
  38974. ** This is so that expressions can be written as:
  38975. **
  38976. ** if( isOpen(pPager->jfd) ){ ...
  38977. **
  38978. ** instead of
  38979. **
  38980. ** if( pPager->jfd->pMethods ){ ...
  38981. */
  38982. #define isOpen(pFd) ((pFd)->pMethods)
  38983. /*
  38984. ** Return true if this pager uses a write-ahead log instead of the usual
  38985. ** rollback journal. Otherwise false.
  38986. */
  38987. #ifndef SQLITE_OMIT_WAL
  38988. static int pagerUseWal(Pager *pPager){
  38989. return (pPager->pWal!=0);
  38990. }
  38991. #else
  38992. # define pagerUseWal(x) 0
  38993. # define pagerRollbackWal(x) 0
  38994. # define pagerWalFrames(v,w,x,y) 0
  38995. # define pagerOpenWalIfPresent(z) SQLITE_OK
  38996. # define pagerBeginReadTransaction(z) SQLITE_OK
  38997. #endif
  38998. #ifndef NDEBUG
  38999. /*
  39000. ** Usage:
  39001. **
  39002. ** assert( assert_pager_state(pPager) );
  39003. **
  39004. ** This function runs many asserts to try to find inconsistencies in
  39005. ** the internal state of the Pager object.
  39006. */
  39007. static int assert_pager_state(Pager *p){
  39008. Pager *pPager = p;
  39009. /* State must be valid. */
  39010. assert( p->eState==PAGER_OPEN
  39011. || p->eState==PAGER_READER
  39012. || p->eState==PAGER_WRITER_LOCKED
  39013. || p->eState==PAGER_WRITER_CACHEMOD
  39014. || p->eState==PAGER_WRITER_DBMOD
  39015. || p->eState==PAGER_WRITER_FINISHED
  39016. || p->eState==PAGER_ERROR
  39017. );
  39018. /* Regardless of the current state, a temp-file connection always behaves
  39019. ** as if it has an exclusive lock on the database file. It never updates
  39020. ** the change-counter field, so the changeCountDone flag is always set.
  39021. */
  39022. assert( p->tempFile==0 || p->eLock==EXCLUSIVE_LOCK );
  39023. assert( p->tempFile==0 || pPager->changeCountDone );
  39024. /* If the useJournal flag is clear, the journal-mode must be "OFF".
  39025. ** And if the journal-mode is "OFF", the journal file must not be open.
  39026. */
  39027. assert( p->journalMode==PAGER_JOURNALMODE_OFF || p->useJournal );
  39028. assert( p->journalMode!=PAGER_JOURNALMODE_OFF || !isOpen(p->jfd) );
  39029. /* Check that MEMDB implies noSync. And an in-memory journal. Since
  39030. ** this means an in-memory pager performs no IO at all, it cannot encounter
  39031. ** either SQLITE_IOERR or SQLITE_FULL during rollback or while finalizing
  39032. ** a journal file. (although the in-memory journal implementation may
  39033. ** return SQLITE_IOERR_NOMEM while the journal file is being written). It
  39034. ** is therefore not possible for an in-memory pager to enter the ERROR
  39035. ** state.
  39036. */
  39037. if( MEMDB ){
  39038. assert( p->noSync );
  39039. assert( p->journalMode==PAGER_JOURNALMODE_OFF
  39040. || p->journalMode==PAGER_JOURNALMODE_MEMORY
  39041. );
  39042. assert( p->eState!=PAGER_ERROR && p->eState!=PAGER_OPEN );
  39043. assert( pagerUseWal(p)==0 );
  39044. }
  39045. /* If changeCountDone is set, a RESERVED lock or greater must be held
  39046. ** on the file.
  39047. */
  39048. assert( pPager->changeCountDone==0 || pPager->eLock>=RESERVED_LOCK );
  39049. assert( p->eLock!=PENDING_LOCK );
  39050. switch( p->eState ){
  39051. case PAGER_OPEN:
  39052. assert( !MEMDB );
  39053. assert( pPager->errCode==SQLITE_OK );
  39054. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 || pPager->tempFile );
  39055. break;
  39056. case PAGER_READER:
  39057. assert( pPager->errCode==SQLITE_OK );
  39058. assert( p->eLock!=UNKNOWN_LOCK );
  39059. assert( p->eLock>=SHARED_LOCK );
  39060. break;
  39061. case PAGER_WRITER_LOCKED:
  39062. assert( p->eLock!=UNKNOWN_LOCK );
  39063. assert( pPager->errCode==SQLITE_OK );
  39064. if( !pagerUseWal(pPager) ){
  39065. assert( p->eLock>=RESERVED_LOCK );
  39066. }
  39067. assert( pPager->dbSize==pPager->dbOrigSize );
  39068. assert( pPager->dbOrigSize==pPager->dbFileSize );
  39069. assert( pPager->dbOrigSize==pPager->dbHintSize );
  39070. assert( pPager->setMaster==0 );
  39071. break;
  39072. case PAGER_WRITER_CACHEMOD:
  39073. assert( p->eLock!=UNKNOWN_LOCK );
  39074. assert( pPager->errCode==SQLITE_OK );
  39075. if( !pagerUseWal(pPager) ){
  39076. /* It is possible that if journal_mode=wal here that neither the
  39077. ** journal file nor the WAL file are open. This happens during
  39078. ** a rollback transaction that switches from journal_mode=off
  39079. ** to journal_mode=wal.
  39080. */
  39081. assert( p->eLock>=RESERVED_LOCK );
  39082. assert( isOpen(p->jfd)
  39083. || p->journalMode==PAGER_JOURNALMODE_OFF
  39084. || p->journalMode==PAGER_JOURNALMODE_WAL
  39085. );
  39086. }
  39087. assert( pPager->dbOrigSize==pPager->dbFileSize );
  39088. assert( pPager->dbOrigSize==pPager->dbHintSize );
  39089. break;
  39090. case PAGER_WRITER_DBMOD:
  39091. assert( p->eLock==EXCLUSIVE_LOCK );
  39092. assert( pPager->errCode==SQLITE_OK );
  39093. assert( !pagerUseWal(pPager) );
  39094. assert( p->eLock>=EXCLUSIVE_LOCK );
  39095. assert( isOpen(p->jfd)
  39096. || p->journalMode==PAGER_JOURNALMODE_OFF
  39097. || p->journalMode==PAGER_JOURNALMODE_WAL
  39098. );
  39099. assert( pPager->dbOrigSize<=pPager->dbHintSize );
  39100. break;
  39101. case PAGER_WRITER_FINISHED:
  39102. assert( p->eLock==EXCLUSIVE_LOCK );
  39103. assert( pPager->errCode==SQLITE_OK );
  39104. assert( !pagerUseWal(pPager) );
  39105. assert( isOpen(p->jfd)
  39106. || p->journalMode==PAGER_JOURNALMODE_OFF
  39107. || p->journalMode==PAGER_JOURNALMODE_WAL
  39108. );
  39109. break;
  39110. case PAGER_ERROR:
  39111. /* There must be at least one outstanding reference to the pager if
  39112. ** in ERROR state. Otherwise the pager should have already dropped
  39113. ** back to OPEN state.
  39114. */
  39115. assert( pPager->errCode!=SQLITE_OK );
  39116. assert( sqlite3PcacheRefCount(pPager->pPCache)>0 );
  39117. break;
  39118. }
  39119. return 1;
  39120. }
  39121. #endif /* ifndef NDEBUG */
  39122. #ifdef SQLITE_DEBUG
  39123. /*
  39124. ** Return a pointer to a human readable string in a static buffer
  39125. ** containing the state of the Pager object passed as an argument. This
  39126. ** is intended to be used within debuggers. For example, as an alternative
  39127. ** to "print *pPager" in gdb:
  39128. **
  39129. ** (gdb) printf "%s", print_pager_state(pPager)
  39130. */
  39131. static char *print_pager_state(Pager *p){
  39132. static char zRet[1024];
  39133. sqlite3_snprintf(1024, zRet,
  39134. "Filename: %s\n"
  39135. "State: %s errCode=%d\n"
  39136. "Lock: %s\n"
  39137. "Locking mode: locking_mode=%s\n"
  39138. "Journal mode: journal_mode=%s\n"
  39139. "Backing store: tempFile=%d memDb=%d useJournal=%d\n"
  39140. "Journal: journalOff=%lld journalHdr=%lld\n"
  39141. "Size: dbsize=%d dbOrigSize=%d dbFileSize=%d\n"
  39142. , p->zFilename
  39143. , p->eState==PAGER_OPEN ? "OPEN" :
  39144. p->eState==PAGER_READER ? "READER" :
  39145. p->eState==PAGER_WRITER_LOCKED ? "WRITER_LOCKED" :
  39146. p->eState==PAGER_WRITER_CACHEMOD ? "WRITER_CACHEMOD" :
  39147. p->eState==PAGER_WRITER_DBMOD ? "WRITER_DBMOD" :
  39148. p->eState==PAGER_WRITER_FINISHED ? "WRITER_FINISHED" :
  39149. p->eState==PAGER_ERROR ? "ERROR" : "?error?"
  39150. , (int)p->errCode
  39151. , p->eLock==NO_LOCK ? "NO_LOCK" :
  39152. p->eLock==RESERVED_LOCK ? "RESERVED" :
  39153. p->eLock==EXCLUSIVE_LOCK ? "EXCLUSIVE" :
  39154. p->eLock==SHARED_LOCK ? "SHARED" :
  39155. p->eLock==UNKNOWN_LOCK ? "UNKNOWN" : "?error?"
  39156. , p->exclusiveMode ? "exclusive" : "normal"
  39157. , p->journalMode==PAGER_JOURNALMODE_MEMORY ? "memory" :
  39158. p->journalMode==PAGER_JOURNALMODE_OFF ? "off" :
  39159. p->journalMode==PAGER_JOURNALMODE_DELETE ? "delete" :
  39160. p->journalMode==PAGER_JOURNALMODE_PERSIST ? "persist" :
  39161. p->journalMode==PAGER_JOURNALMODE_TRUNCATE ? "truncate" :
  39162. p->journalMode==PAGER_JOURNALMODE_WAL ? "wal" : "?error?"
  39163. , (int)p->tempFile, (int)p->memDb, (int)p->useJournal
  39164. , p->journalOff, p->journalHdr
  39165. , (int)p->dbSize, (int)p->dbOrigSize, (int)p->dbFileSize
  39166. );
  39167. return zRet;
  39168. }
  39169. #endif
  39170. /*
  39171. ** Return true if it is necessary to write page *pPg into the sub-journal.
  39172. ** A page needs to be written into the sub-journal if there exists one
  39173. ** or more open savepoints for which:
  39174. **
  39175. ** * The page-number is less than or equal to PagerSavepoint.nOrig, and
  39176. ** * The bit corresponding to the page-number is not set in
  39177. ** PagerSavepoint.pInSavepoint.
  39178. */
  39179. static int subjRequiresPage(PgHdr *pPg){
  39180. Pager *pPager = pPg->pPager;
  39181. PagerSavepoint *p;
  39182. Pgno pgno = pPg->pgno;
  39183. int i;
  39184. for(i=0; i<pPager->nSavepoint; i++){
  39185. p = &pPager->aSavepoint[i];
  39186. if( p->nOrig>=pgno && 0==sqlite3BitvecTest(p->pInSavepoint, pgno) ){
  39187. return 1;
  39188. }
  39189. }
  39190. return 0;
  39191. }
  39192. /*
  39193. ** Return true if the page is already in the journal file.
  39194. */
  39195. static int pageInJournal(Pager *pPager, PgHdr *pPg){
  39196. return sqlite3BitvecTest(pPager->pInJournal, pPg->pgno);
  39197. }
  39198. /*
  39199. ** Read a 32-bit integer from the given file descriptor. Store the integer
  39200. ** that is read in *pRes. Return SQLITE_OK if everything worked, or an
  39201. ** error code is something goes wrong.
  39202. **
  39203. ** All values are stored on disk as big-endian.
  39204. */
  39205. static int read32bits(sqlite3_file *fd, i64 offset, u32 *pRes){
  39206. unsigned char ac[4];
  39207. int rc = sqlite3OsRead(fd, ac, sizeof(ac), offset);
  39208. if( rc==SQLITE_OK ){
  39209. *pRes = sqlite3Get4byte(ac);
  39210. }
  39211. return rc;
  39212. }
  39213. /*
  39214. ** Write a 32-bit integer into a string buffer in big-endian byte order.
  39215. */
  39216. #define put32bits(A,B) sqlite3Put4byte((u8*)A,B)
  39217. /*
  39218. ** Write a 32-bit integer into the given file descriptor. Return SQLITE_OK
  39219. ** on success or an error code is something goes wrong.
  39220. */
  39221. static int write32bits(sqlite3_file *fd, i64 offset, u32 val){
  39222. char ac[4];
  39223. put32bits(ac, val);
  39224. return sqlite3OsWrite(fd, ac, 4, offset);
  39225. }
  39226. /*
  39227. ** Unlock the database file to level eLock, which must be either NO_LOCK
  39228. ** or SHARED_LOCK. Regardless of whether or not the call to xUnlock()
  39229. ** succeeds, set the Pager.eLock variable to match the (attempted) new lock.
  39230. **
  39231. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  39232. ** called, do not modify it. See the comment above the #define of
  39233. ** UNKNOWN_LOCK for an explanation of this.
  39234. */
  39235. static int pagerUnlockDb(Pager *pPager, int eLock){
  39236. int rc = SQLITE_OK;
  39237. assert( !pPager->exclusiveMode || pPager->eLock==eLock );
  39238. assert( eLock==NO_LOCK || eLock==SHARED_LOCK );
  39239. assert( eLock!=NO_LOCK || pagerUseWal(pPager)==0 );
  39240. if( isOpen(pPager->fd) ){
  39241. assert( pPager->eLock>=eLock );
  39242. rc = pPager->noLock ? SQLITE_OK : sqlite3OsUnlock(pPager->fd, eLock);
  39243. if( pPager->eLock!=UNKNOWN_LOCK ){
  39244. pPager->eLock = (u8)eLock;
  39245. }
  39246. IOTRACE(("UNLOCK %p %d\n", pPager, eLock))
  39247. }
  39248. return rc;
  39249. }
  39250. /*
  39251. ** Lock the database file to level eLock, which must be either SHARED_LOCK,
  39252. ** RESERVED_LOCK or EXCLUSIVE_LOCK. If the caller is successful, set the
  39253. ** Pager.eLock variable to the new locking state.
  39254. **
  39255. ** Except, if Pager.eLock is set to UNKNOWN_LOCK when this function is
  39256. ** called, do not modify it unless the new locking state is EXCLUSIVE_LOCK.
  39257. ** See the comment above the #define of UNKNOWN_LOCK for an explanation
  39258. ** of this.
  39259. */
  39260. static int pagerLockDb(Pager *pPager, int eLock){
  39261. int rc = SQLITE_OK;
  39262. assert( eLock==SHARED_LOCK || eLock==RESERVED_LOCK || eLock==EXCLUSIVE_LOCK );
  39263. if( pPager->eLock<eLock || pPager->eLock==UNKNOWN_LOCK ){
  39264. rc = pPager->noLock ? SQLITE_OK : sqlite3OsLock(pPager->fd, eLock);
  39265. if( rc==SQLITE_OK && (pPager->eLock!=UNKNOWN_LOCK||eLock==EXCLUSIVE_LOCK) ){
  39266. pPager->eLock = (u8)eLock;
  39267. IOTRACE(("LOCK %p %d\n", pPager, eLock))
  39268. }
  39269. }
  39270. return rc;
  39271. }
  39272. /*
  39273. ** This function determines whether or not the atomic-write optimization
  39274. ** can be used with this pager. The optimization can be used if:
  39275. **
  39276. ** (a) the value returned by OsDeviceCharacteristics() indicates that
  39277. ** a database page may be written atomically, and
  39278. ** (b) the value returned by OsSectorSize() is less than or equal
  39279. ** to the page size.
  39280. **
  39281. ** The optimization is also always enabled for temporary files. It is
  39282. ** an error to call this function if pPager is opened on an in-memory
  39283. ** database.
  39284. **
  39285. ** If the optimization cannot be used, 0 is returned. If it can be used,
  39286. ** then the value returned is the size of the journal file when it
  39287. ** contains rollback data for exactly one page.
  39288. */
  39289. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  39290. static int jrnlBufferSize(Pager *pPager){
  39291. assert( !MEMDB );
  39292. if( !pPager->tempFile ){
  39293. int dc; /* Device characteristics */
  39294. int nSector; /* Sector size */
  39295. int szPage; /* Page size */
  39296. assert( isOpen(pPager->fd) );
  39297. dc = sqlite3OsDeviceCharacteristics(pPager->fd);
  39298. nSector = pPager->sectorSize;
  39299. szPage = pPager->pageSize;
  39300. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  39301. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  39302. if( 0==(dc&(SQLITE_IOCAP_ATOMIC|(szPage>>8)) || nSector>szPage) ){
  39303. return 0;
  39304. }
  39305. }
  39306. return JOURNAL_HDR_SZ(pPager) + JOURNAL_PG_SZ(pPager);
  39307. }
  39308. #endif
  39309. /*
  39310. ** If SQLITE_CHECK_PAGES is defined then we do some sanity checking
  39311. ** on the cache using a hash function. This is used for testing
  39312. ** and debugging only.
  39313. */
  39314. #ifdef SQLITE_CHECK_PAGES
  39315. /*
  39316. ** Return a 32-bit hash of the page data for pPage.
  39317. */
  39318. static u32 pager_datahash(int nByte, unsigned char *pData){
  39319. u32 hash = 0;
  39320. int i;
  39321. for(i=0; i<nByte; i++){
  39322. hash = (hash*1039) + pData[i];
  39323. }
  39324. return hash;
  39325. }
  39326. static u32 pager_pagehash(PgHdr *pPage){
  39327. return pager_datahash(pPage->pPager->pageSize, (unsigned char *)pPage->pData);
  39328. }
  39329. static void pager_set_pagehash(PgHdr *pPage){
  39330. pPage->pageHash = pager_pagehash(pPage);
  39331. }
  39332. /*
  39333. ** The CHECK_PAGE macro takes a PgHdr* as an argument. If SQLITE_CHECK_PAGES
  39334. ** is defined, and NDEBUG is not defined, an assert() statement checks
  39335. ** that the page is either dirty or still matches the calculated page-hash.
  39336. */
  39337. #define CHECK_PAGE(x) checkPage(x)
  39338. static void checkPage(PgHdr *pPg){
  39339. Pager *pPager = pPg->pPager;
  39340. assert( pPager->eState!=PAGER_ERROR );
  39341. assert( (pPg->flags&PGHDR_DIRTY) || pPg->pageHash==pager_pagehash(pPg) );
  39342. }
  39343. #else
  39344. #define pager_datahash(X,Y) 0
  39345. #define pager_pagehash(X) 0
  39346. #define pager_set_pagehash(X)
  39347. #define CHECK_PAGE(x)
  39348. #endif /* SQLITE_CHECK_PAGES */
  39349. /*
  39350. ** When this is called the journal file for pager pPager must be open.
  39351. ** This function attempts to read a master journal file name from the
  39352. ** end of the file and, if successful, copies it into memory supplied
  39353. ** by the caller. See comments above writeMasterJournal() for the format
  39354. ** used to store a master journal file name at the end of a journal file.
  39355. **
  39356. ** zMaster must point to a buffer of at least nMaster bytes allocated by
  39357. ** the caller. This should be sqlite3_vfs.mxPathname+1 (to ensure there is
  39358. ** enough space to write the master journal name). If the master journal
  39359. ** name in the journal is longer than nMaster bytes (including a
  39360. ** nul-terminator), then this is handled as if no master journal name
  39361. ** were present in the journal.
  39362. **
  39363. ** If a master journal file name is present at the end of the journal
  39364. ** file, then it is copied into the buffer pointed to by zMaster. A
  39365. ** nul-terminator byte is appended to the buffer following the master
  39366. ** journal file name.
  39367. **
  39368. ** If it is determined that no master journal file name is present
  39369. ** zMaster[0] is set to 0 and SQLITE_OK returned.
  39370. **
  39371. ** If an error occurs while reading from the journal file, an SQLite
  39372. ** error code is returned.
  39373. */
  39374. static int readMasterJournal(sqlite3_file *pJrnl, char *zMaster, u32 nMaster){
  39375. int rc; /* Return code */
  39376. u32 len; /* Length in bytes of master journal name */
  39377. i64 szJ; /* Total size in bytes of journal file pJrnl */
  39378. u32 cksum; /* MJ checksum value read from journal */
  39379. u32 u; /* Unsigned loop counter */
  39380. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  39381. zMaster[0] = '\0';
  39382. if( SQLITE_OK!=(rc = sqlite3OsFileSize(pJrnl, &szJ))
  39383. || szJ<16
  39384. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-16, &len))
  39385. || len>=nMaster
  39386. || len==0
  39387. || SQLITE_OK!=(rc = read32bits(pJrnl, szJ-12, &cksum))
  39388. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, aMagic, 8, szJ-8))
  39389. || memcmp(aMagic, aJournalMagic, 8)
  39390. || SQLITE_OK!=(rc = sqlite3OsRead(pJrnl, zMaster, len, szJ-16-len))
  39391. ){
  39392. return rc;
  39393. }
  39394. /* See if the checksum matches the master journal name */
  39395. for(u=0; u<len; u++){
  39396. cksum -= zMaster[u];
  39397. }
  39398. if( cksum ){
  39399. /* If the checksum doesn't add up, then one or more of the disk sectors
  39400. ** containing the master journal filename is corrupted. This means
  39401. ** definitely roll back, so just return SQLITE_OK and report a (nul)
  39402. ** master-journal filename.
  39403. */
  39404. len = 0;
  39405. }
  39406. zMaster[len] = '\0';
  39407. return SQLITE_OK;
  39408. }
  39409. /*
  39410. ** Return the offset of the sector boundary at or immediately
  39411. ** following the value in pPager->journalOff, assuming a sector
  39412. ** size of pPager->sectorSize bytes.
  39413. **
  39414. ** i.e for a sector size of 512:
  39415. **
  39416. ** Pager.journalOff Return value
  39417. ** ---------------------------------------
  39418. ** 0 0
  39419. ** 512 512
  39420. ** 100 512
  39421. ** 2000 2048
  39422. **
  39423. */
  39424. static i64 journalHdrOffset(Pager *pPager){
  39425. i64 offset = 0;
  39426. i64 c = pPager->journalOff;
  39427. if( c ){
  39428. offset = ((c-1)/JOURNAL_HDR_SZ(pPager) + 1) * JOURNAL_HDR_SZ(pPager);
  39429. }
  39430. assert( offset%JOURNAL_HDR_SZ(pPager)==0 );
  39431. assert( offset>=c );
  39432. assert( (offset-c)<JOURNAL_HDR_SZ(pPager) );
  39433. return offset;
  39434. }
  39435. /*
  39436. ** The journal file must be open when this function is called.
  39437. **
  39438. ** This function is a no-op if the journal file has not been written to
  39439. ** within the current transaction (i.e. if Pager.journalOff==0).
  39440. **
  39441. ** If doTruncate is non-zero or the Pager.journalSizeLimit variable is
  39442. ** set to 0, then truncate the journal file to zero bytes in size. Otherwise,
  39443. ** zero the 28-byte header at the start of the journal file. In either case,
  39444. ** if the pager is not in no-sync mode, sync the journal file immediately
  39445. ** after writing or truncating it.
  39446. **
  39447. ** If Pager.journalSizeLimit is set to a positive, non-zero value, and
  39448. ** following the truncation or zeroing described above the size of the
  39449. ** journal file in bytes is larger than this value, then truncate the
  39450. ** journal file to Pager.journalSizeLimit bytes. The journal file does
  39451. ** not need to be synced following this operation.
  39452. **
  39453. ** If an IO error occurs, abandon processing and return the IO error code.
  39454. ** Otherwise, return SQLITE_OK.
  39455. */
  39456. static int zeroJournalHdr(Pager *pPager, int doTruncate){
  39457. int rc = SQLITE_OK; /* Return code */
  39458. assert( isOpen(pPager->jfd) );
  39459. if( pPager->journalOff ){
  39460. const i64 iLimit = pPager->journalSizeLimit; /* Local cache of jsl */
  39461. IOTRACE(("JZEROHDR %p\n", pPager))
  39462. if( doTruncate || iLimit==0 ){
  39463. rc = sqlite3OsTruncate(pPager->jfd, 0);
  39464. }else{
  39465. static const char zeroHdr[28] = {0};
  39466. rc = sqlite3OsWrite(pPager->jfd, zeroHdr, sizeof(zeroHdr), 0);
  39467. }
  39468. if( rc==SQLITE_OK && !pPager->noSync ){
  39469. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_DATAONLY|pPager->syncFlags);
  39470. }
  39471. /* At this point the transaction is committed but the write lock
  39472. ** is still held on the file. If there is a size limit configured for
  39473. ** the persistent journal and the journal file currently consumes more
  39474. ** space than that limit allows for, truncate it now. There is no need
  39475. ** to sync the file following this operation.
  39476. */
  39477. if( rc==SQLITE_OK && iLimit>0 ){
  39478. i64 sz;
  39479. rc = sqlite3OsFileSize(pPager->jfd, &sz);
  39480. if( rc==SQLITE_OK && sz>iLimit ){
  39481. rc = sqlite3OsTruncate(pPager->jfd, iLimit);
  39482. }
  39483. }
  39484. }
  39485. return rc;
  39486. }
  39487. /*
  39488. ** The journal file must be open when this routine is called. A journal
  39489. ** header (JOURNAL_HDR_SZ bytes) is written into the journal file at the
  39490. ** current location.
  39491. **
  39492. ** The format for the journal header is as follows:
  39493. ** - 8 bytes: Magic identifying journal format.
  39494. ** - 4 bytes: Number of records in journal, or -1 no-sync mode is on.
  39495. ** - 4 bytes: Random number used for page hash.
  39496. ** - 4 bytes: Initial database page count.
  39497. ** - 4 bytes: Sector size used by the process that wrote this journal.
  39498. ** - 4 bytes: Database page size.
  39499. **
  39500. ** Followed by (JOURNAL_HDR_SZ - 28) bytes of unused space.
  39501. */
  39502. static int writeJournalHdr(Pager *pPager){
  39503. int rc = SQLITE_OK; /* Return code */
  39504. char *zHeader = pPager->pTmpSpace; /* Temporary space used to build header */
  39505. u32 nHeader = (u32)pPager->pageSize;/* Size of buffer pointed to by zHeader */
  39506. u32 nWrite; /* Bytes of header sector written */
  39507. int ii; /* Loop counter */
  39508. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  39509. if( nHeader>JOURNAL_HDR_SZ(pPager) ){
  39510. nHeader = JOURNAL_HDR_SZ(pPager);
  39511. }
  39512. /* If there are active savepoints and any of them were created
  39513. ** since the most recent journal header was written, update the
  39514. ** PagerSavepoint.iHdrOffset fields now.
  39515. */
  39516. for(ii=0; ii<pPager->nSavepoint; ii++){
  39517. if( pPager->aSavepoint[ii].iHdrOffset==0 ){
  39518. pPager->aSavepoint[ii].iHdrOffset = pPager->journalOff;
  39519. }
  39520. }
  39521. pPager->journalHdr = pPager->journalOff = journalHdrOffset(pPager);
  39522. /*
  39523. ** Write the nRec Field - the number of page records that follow this
  39524. ** journal header. Normally, zero is written to this value at this time.
  39525. ** After the records are added to the journal (and the journal synced,
  39526. ** if in full-sync mode), the zero is overwritten with the true number
  39527. ** of records (see syncJournal()).
  39528. **
  39529. ** A faster alternative is to write 0xFFFFFFFF to the nRec field. When
  39530. ** reading the journal this value tells SQLite to assume that the
  39531. ** rest of the journal file contains valid page records. This assumption
  39532. ** is dangerous, as if a failure occurred whilst writing to the journal
  39533. ** file it may contain some garbage data. There are two scenarios
  39534. ** where this risk can be ignored:
  39535. **
  39536. ** * When the pager is in no-sync mode. Corruption can follow a
  39537. ** power failure in this case anyway.
  39538. **
  39539. ** * When the SQLITE_IOCAP_SAFE_APPEND flag is set. This guarantees
  39540. ** that garbage data is never appended to the journal file.
  39541. */
  39542. assert( isOpen(pPager->fd) || pPager->noSync );
  39543. if( pPager->noSync || (pPager->journalMode==PAGER_JOURNALMODE_MEMORY)
  39544. || (sqlite3OsDeviceCharacteristics(pPager->fd)&SQLITE_IOCAP_SAFE_APPEND)
  39545. ){
  39546. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  39547. put32bits(&zHeader[sizeof(aJournalMagic)], 0xffffffff);
  39548. }else{
  39549. memset(zHeader, 0, sizeof(aJournalMagic)+4);
  39550. }
  39551. /* The random check-hash initializer */
  39552. sqlite3_randomness(sizeof(pPager->cksumInit), &pPager->cksumInit);
  39553. put32bits(&zHeader[sizeof(aJournalMagic)+4], pPager->cksumInit);
  39554. /* The initial database size */
  39555. put32bits(&zHeader[sizeof(aJournalMagic)+8], pPager->dbOrigSize);
  39556. /* The assumed sector size for this process */
  39557. put32bits(&zHeader[sizeof(aJournalMagic)+12], pPager->sectorSize);
  39558. /* The page size */
  39559. put32bits(&zHeader[sizeof(aJournalMagic)+16], pPager->pageSize);
  39560. /* Initializing the tail of the buffer is not necessary. Everything
  39561. ** works find if the following memset() is omitted. But initializing
  39562. ** the memory prevents valgrind from complaining, so we are willing to
  39563. ** take the performance hit.
  39564. */
  39565. memset(&zHeader[sizeof(aJournalMagic)+20], 0,
  39566. nHeader-(sizeof(aJournalMagic)+20));
  39567. /* In theory, it is only necessary to write the 28 bytes that the
  39568. ** journal header consumes to the journal file here. Then increment the
  39569. ** Pager.journalOff variable by JOURNAL_HDR_SZ so that the next
  39570. ** record is written to the following sector (leaving a gap in the file
  39571. ** that will be implicitly filled in by the OS).
  39572. **
  39573. ** However it has been discovered that on some systems this pattern can
  39574. ** be significantly slower than contiguously writing data to the file,
  39575. ** even if that means explicitly writing data to the block of
  39576. ** (JOURNAL_HDR_SZ - 28) bytes that will not be used. So that is what
  39577. ** is done.
  39578. **
  39579. ** The loop is required here in case the sector-size is larger than the
  39580. ** database page size. Since the zHeader buffer is only Pager.pageSize
  39581. ** bytes in size, more than one call to sqlite3OsWrite() may be required
  39582. ** to populate the entire journal header sector.
  39583. */
  39584. for(nWrite=0; rc==SQLITE_OK&&nWrite<JOURNAL_HDR_SZ(pPager); nWrite+=nHeader){
  39585. IOTRACE(("JHDR %p %lld %d\n", pPager, pPager->journalHdr, nHeader))
  39586. rc = sqlite3OsWrite(pPager->jfd, zHeader, nHeader, pPager->journalOff);
  39587. assert( pPager->journalHdr <= pPager->journalOff );
  39588. pPager->journalOff += nHeader;
  39589. }
  39590. return rc;
  39591. }
  39592. /*
  39593. ** The journal file must be open when this is called. A journal header file
  39594. ** (JOURNAL_HDR_SZ bytes) is read from the current location in the journal
  39595. ** file. The current location in the journal file is given by
  39596. ** pPager->journalOff. See comments above function writeJournalHdr() for
  39597. ** a description of the journal header format.
  39598. **
  39599. ** If the header is read successfully, *pNRec is set to the number of
  39600. ** page records following this header and *pDbSize is set to the size of the
  39601. ** database before the transaction began, in pages. Also, pPager->cksumInit
  39602. ** is set to the value read from the journal header. SQLITE_OK is returned
  39603. ** in this case.
  39604. **
  39605. ** If the journal header file appears to be corrupted, SQLITE_DONE is
  39606. ** returned and *pNRec and *PDbSize are undefined. If JOURNAL_HDR_SZ bytes
  39607. ** cannot be read from the journal file an error code is returned.
  39608. */
  39609. static int readJournalHdr(
  39610. Pager *pPager, /* Pager object */
  39611. int isHot,
  39612. i64 journalSize, /* Size of the open journal file in bytes */
  39613. u32 *pNRec, /* OUT: Value read from the nRec field */
  39614. u32 *pDbSize /* OUT: Value of original database size field */
  39615. ){
  39616. int rc; /* Return code */
  39617. unsigned char aMagic[8]; /* A buffer to hold the magic header */
  39618. i64 iHdrOff; /* Offset of journal header being read */
  39619. assert( isOpen(pPager->jfd) ); /* Journal file must be open. */
  39620. /* Advance Pager.journalOff to the start of the next sector. If the
  39621. ** journal file is too small for there to be a header stored at this
  39622. ** point, return SQLITE_DONE.
  39623. */
  39624. pPager->journalOff = journalHdrOffset(pPager);
  39625. if( pPager->journalOff+JOURNAL_HDR_SZ(pPager) > journalSize ){
  39626. return SQLITE_DONE;
  39627. }
  39628. iHdrOff = pPager->journalOff;
  39629. /* Read in the first 8 bytes of the journal header. If they do not match
  39630. ** the magic string found at the start of each journal header, return
  39631. ** SQLITE_DONE. If an IO error occurs, return an error code. Otherwise,
  39632. ** proceed.
  39633. */
  39634. if( isHot || iHdrOff!=pPager->journalHdr ){
  39635. rc = sqlite3OsRead(pPager->jfd, aMagic, sizeof(aMagic), iHdrOff);
  39636. if( rc ){
  39637. return rc;
  39638. }
  39639. if( memcmp(aMagic, aJournalMagic, sizeof(aMagic))!=0 ){
  39640. return SQLITE_DONE;
  39641. }
  39642. }
  39643. /* Read the first three 32-bit fields of the journal header: The nRec
  39644. ** field, the checksum-initializer and the database size at the start
  39645. ** of the transaction. Return an error code if anything goes wrong.
  39646. */
  39647. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+8, pNRec))
  39648. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+12, &pPager->cksumInit))
  39649. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+16, pDbSize))
  39650. ){
  39651. return rc;
  39652. }
  39653. if( pPager->journalOff==0 ){
  39654. u32 iPageSize; /* Page-size field of journal header */
  39655. u32 iSectorSize; /* Sector-size field of journal header */
  39656. /* Read the page-size and sector-size journal header fields. */
  39657. if( SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+20, &iSectorSize))
  39658. || SQLITE_OK!=(rc = read32bits(pPager->jfd, iHdrOff+24, &iPageSize))
  39659. ){
  39660. return rc;
  39661. }
  39662. /* Versions of SQLite prior to 3.5.8 set the page-size field of the
  39663. ** journal header to zero. In this case, assume that the Pager.pageSize
  39664. ** variable is already set to the correct page size.
  39665. */
  39666. if( iPageSize==0 ){
  39667. iPageSize = pPager->pageSize;
  39668. }
  39669. /* Check that the values read from the page-size and sector-size fields
  39670. ** are within range. To be 'in range', both values need to be a power
  39671. ** of two greater than or equal to 512 or 32, and not greater than their
  39672. ** respective compile time maximum limits.
  39673. */
  39674. if( iPageSize<512 || iSectorSize<32
  39675. || iPageSize>SQLITE_MAX_PAGE_SIZE || iSectorSize>MAX_SECTOR_SIZE
  39676. || ((iPageSize-1)&iPageSize)!=0 || ((iSectorSize-1)&iSectorSize)!=0
  39677. ){
  39678. /* If the either the page-size or sector-size in the journal-header is
  39679. ** invalid, then the process that wrote the journal-header must have
  39680. ** crashed before the header was synced. In this case stop reading
  39681. ** the journal file here.
  39682. */
  39683. return SQLITE_DONE;
  39684. }
  39685. /* Update the page-size to match the value read from the journal.
  39686. ** Use a testcase() macro to make sure that malloc failure within
  39687. ** PagerSetPagesize() is tested.
  39688. */
  39689. rc = sqlite3PagerSetPagesize(pPager, &iPageSize, -1);
  39690. testcase( rc!=SQLITE_OK );
  39691. /* Update the assumed sector-size to match the value used by
  39692. ** the process that created this journal. If this journal was
  39693. ** created by a process other than this one, then this routine
  39694. ** is being called from within pager_playback(). The local value
  39695. ** of Pager.sectorSize is restored at the end of that routine.
  39696. */
  39697. pPager->sectorSize = iSectorSize;
  39698. }
  39699. pPager->journalOff += JOURNAL_HDR_SZ(pPager);
  39700. return rc;
  39701. }
  39702. /*
  39703. ** Write the supplied master journal name into the journal file for pager
  39704. ** pPager at the current location. The master journal name must be the last
  39705. ** thing written to a journal file. If the pager is in full-sync mode, the
  39706. ** journal file descriptor is advanced to the next sector boundary before
  39707. ** anything is written. The format is:
  39708. **
  39709. ** + 4 bytes: PAGER_MJ_PGNO.
  39710. ** + N bytes: Master journal filename in utf-8.
  39711. ** + 4 bytes: N (length of master journal name in bytes, no nul-terminator).
  39712. ** + 4 bytes: Master journal name checksum.
  39713. ** + 8 bytes: aJournalMagic[].
  39714. **
  39715. ** The master journal page checksum is the sum of the bytes in the master
  39716. ** journal name, where each byte is interpreted as a signed 8-bit integer.
  39717. **
  39718. ** If zMaster is a NULL pointer (occurs for a single database transaction),
  39719. ** this call is a no-op.
  39720. */
  39721. static int writeMasterJournal(Pager *pPager, const char *zMaster){
  39722. int rc; /* Return code */
  39723. int nMaster; /* Length of string zMaster */
  39724. i64 iHdrOff; /* Offset of header in journal file */
  39725. i64 jrnlSize; /* Size of journal file on disk */
  39726. u32 cksum = 0; /* Checksum of string zMaster */
  39727. assert( pPager->setMaster==0 );
  39728. assert( !pagerUseWal(pPager) );
  39729. if( !zMaster
  39730. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  39731. || !isOpen(pPager->jfd)
  39732. ){
  39733. return SQLITE_OK;
  39734. }
  39735. pPager->setMaster = 1;
  39736. assert( pPager->journalHdr <= pPager->journalOff );
  39737. /* Calculate the length in bytes and the checksum of zMaster */
  39738. for(nMaster=0; zMaster[nMaster]; nMaster++){
  39739. cksum += zMaster[nMaster];
  39740. }
  39741. /* If in full-sync mode, advance to the next disk sector before writing
  39742. ** the master journal name. This is in case the previous page written to
  39743. ** the journal has already been synced.
  39744. */
  39745. if( pPager->fullSync ){
  39746. pPager->journalOff = journalHdrOffset(pPager);
  39747. }
  39748. iHdrOff = pPager->journalOff;
  39749. /* Write the master journal data to the end of the journal file. If
  39750. ** an error occurs, return the error code to the caller.
  39751. */
  39752. if( (0 != (rc = write32bits(pPager->jfd, iHdrOff, PAGER_MJ_PGNO(pPager))))
  39753. || (0 != (rc = sqlite3OsWrite(pPager->jfd, zMaster, nMaster, iHdrOff+4)))
  39754. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster, nMaster)))
  39755. || (0 != (rc = write32bits(pPager->jfd, iHdrOff+4+nMaster+4, cksum)))
  39756. || (0 != (rc = sqlite3OsWrite(pPager->jfd, aJournalMagic, 8, iHdrOff+4+nMaster+8)))
  39757. ){
  39758. return rc;
  39759. }
  39760. pPager->journalOff += (nMaster+20);
  39761. /* If the pager is in peristent-journal mode, then the physical
  39762. ** journal-file may extend past the end of the master-journal name
  39763. ** and 8 bytes of magic data just written to the file. This is
  39764. ** dangerous because the code to rollback a hot-journal file
  39765. ** will not be able to find the master-journal name to determine
  39766. ** whether or not the journal is hot.
  39767. **
  39768. ** Easiest thing to do in this scenario is to truncate the journal
  39769. ** file to the required size.
  39770. */
  39771. if( SQLITE_OK==(rc = sqlite3OsFileSize(pPager->jfd, &jrnlSize))
  39772. && jrnlSize>pPager->journalOff
  39773. ){
  39774. rc = sqlite3OsTruncate(pPager->jfd, pPager->journalOff);
  39775. }
  39776. return rc;
  39777. }
  39778. /*
  39779. ** Discard the entire contents of the in-memory page-cache.
  39780. */
  39781. static void pager_reset(Pager *pPager){
  39782. sqlite3BackupRestart(pPager->pBackup);
  39783. sqlite3PcacheClear(pPager->pPCache);
  39784. }
  39785. /*
  39786. ** Free all structures in the Pager.aSavepoint[] array and set both
  39787. ** Pager.aSavepoint and Pager.nSavepoint to zero. Close the sub-journal
  39788. ** if it is open and the pager is not in exclusive mode.
  39789. */
  39790. static void releaseAllSavepoints(Pager *pPager){
  39791. int ii; /* Iterator for looping through Pager.aSavepoint */
  39792. for(ii=0; ii<pPager->nSavepoint; ii++){
  39793. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  39794. }
  39795. if( !pPager->exclusiveMode || sqlite3IsMemJournal(pPager->sjfd) ){
  39796. sqlite3OsClose(pPager->sjfd);
  39797. }
  39798. sqlite3_free(pPager->aSavepoint);
  39799. pPager->aSavepoint = 0;
  39800. pPager->nSavepoint = 0;
  39801. pPager->nSubRec = 0;
  39802. }
  39803. /*
  39804. ** Set the bit number pgno in the PagerSavepoint.pInSavepoint
  39805. ** bitvecs of all open savepoints. Return SQLITE_OK if successful
  39806. ** or SQLITE_NOMEM if a malloc failure occurs.
  39807. */
  39808. static int addToSavepointBitvecs(Pager *pPager, Pgno pgno){
  39809. int ii; /* Loop counter */
  39810. int rc = SQLITE_OK; /* Result code */
  39811. for(ii=0; ii<pPager->nSavepoint; ii++){
  39812. PagerSavepoint *p = &pPager->aSavepoint[ii];
  39813. if( pgno<=p->nOrig ){
  39814. rc |= sqlite3BitvecSet(p->pInSavepoint, pgno);
  39815. testcase( rc==SQLITE_NOMEM );
  39816. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  39817. }
  39818. }
  39819. return rc;
  39820. }
  39821. /*
  39822. ** This function is a no-op if the pager is in exclusive mode and not
  39823. ** in the ERROR state. Otherwise, it switches the pager to PAGER_OPEN
  39824. ** state.
  39825. **
  39826. ** If the pager is not in exclusive-access mode, the database file is
  39827. ** completely unlocked. If the file is unlocked and the file-system does
  39828. ** not exhibit the UNDELETABLE_WHEN_OPEN property, the journal file is
  39829. ** closed (if it is open).
  39830. **
  39831. ** If the pager is in ERROR state when this function is called, the
  39832. ** contents of the pager cache are discarded before switching back to
  39833. ** the OPEN state. Regardless of whether the pager is in exclusive-mode
  39834. ** or not, any journal file left in the file-system will be treated
  39835. ** as a hot-journal and rolled back the next time a read-transaction
  39836. ** is opened (by this or by any other connection).
  39837. */
  39838. static void pager_unlock(Pager *pPager){
  39839. assert( pPager->eState==PAGER_READER
  39840. || pPager->eState==PAGER_OPEN
  39841. || pPager->eState==PAGER_ERROR
  39842. );
  39843. sqlite3BitvecDestroy(pPager->pInJournal);
  39844. pPager->pInJournal = 0;
  39845. releaseAllSavepoints(pPager);
  39846. if( pagerUseWal(pPager) ){
  39847. assert( !isOpen(pPager->jfd) );
  39848. sqlite3WalEndReadTransaction(pPager->pWal);
  39849. pPager->eState = PAGER_OPEN;
  39850. }else if( !pPager->exclusiveMode ){
  39851. int rc; /* Error code returned by pagerUnlockDb() */
  39852. int iDc = isOpen(pPager->fd)?sqlite3OsDeviceCharacteristics(pPager->fd):0;
  39853. /* If the operating system support deletion of open files, then
  39854. ** close the journal file when dropping the database lock. Otherwise
  39855. ** another connection with journal_mode=delete might delete the file
  39856. ** out from under us.
  39857. */
  39858. assert( (PAGER_JOURNALMODE_MEMORY & 5)!=1 );
  39859. assert( (PAGER_JOURNALMODE_OFF & 5)!=1 );
  39860. assert( (PAGER_JOURNALMODE_WAL & 5)!=1 );
  39861. assert( (PAGER_JOURNALMODE_DELETE & 5)!=1 );
  39862. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  39863. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  39864. if( 0==(iDc & SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN)
  39865. || 1!=(pPager->journalMode & 5)
  39866. ){
  39867. sqlite3OsClose(pPager->jfd);
  39868. }
  39869. /* If the pager is in the ERROR state and the call to unlock the database
  39870. ** file fails, set the current lock to UNKNOWN_LOCK. See the comment
  39871. ** above the #define for UNKNOWN_LOCK for an explanation of why this
  39872. ** is necessary.
  39873. */
  39874. rc = pagerUnlockDb(pPager, NO_LOCK);
  39875. if( rc!=SQLITE_OK && pPager->eState==PAGER_ERROR ){
  39876. pPager->eLock = UNKNOWN_LOCK;
  39877. }
  39878. /* The pager state may be changed from PAGER_ERROR to PAGER_OPEN here
  39879. ** without clearing the error code. This is intentional - the error
  39880. ** code is cleared and the cache reset in the block below.
  39881. */
  39882. assert( pPager->errCode || pPager->eState!=PAGER_ERROR );
  39883. pPager->changeCountDone = 0;
  39884. pPager->eState = PAGER_OPEN;
  39885. }
  39886. /* If Pager.errCode is set, the contents of the pager cache cannot be
  39887. ** trusted. Now that there are no outstanding references to the pager,
  39888. ** it can safely move back to PAGER_OPEN state. This happens in both
  39889. ** normal and exclusive-locking mode.
  39890. */
  39891. if( pPager->errCode ){
  39892. assert( !MEMDB );
  39893. pager_reset(pPager);
  39894. pPager->changeCountDone = pPager->tempFile;
  39895. pPager->eState = PAGER_OPEN;
  39896. pPager->errCode = SQLITE_OK;
  39897. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  39898. }
  39899. pPager->journalOff = 0;
  39900. pPager->journalHdr = 0;
  39901. pPager->setMaster = 0;
  39902. }
  39903. /*
  39904. ** This function is called whenever an IOERR or FULL error that requires
  39905. ** the pager to transition into the ERROR state may ahve occurred.
  39906. ** The first argument is a pointer to the pager structure, the second
  39907. ** the error-code about to be returned by a pager API function. The
  39908. ** value returned is a copy of the second argument to this function.
  39909. **
  39910. ** If the second argument is SQLITE_FULL, SQLITE_IOERR or one of the
  39911. ** IOERR sub-codes, the pager enters the ERROR state and the error code
  39912. ** is stored in Pager.errCode. While the pager remains in the ERROR state,
  39913. ** all major API calls on the Pager will immediately return Pager.errCode.
  39914. **
  39915. ** The ERROR state indicates that the contents of the pager-cache
  39916. ** cannot be trusted. This state can be cleared by completely discarding
  39917. ** the contents of the pager-cache. If a transaction was active when
  39918. ** the persistent error occurred, then the rollback journal may need
  39919. ** to be replayed to restore the contents of the database file (as if
  39920. ** it were a hot-journal).
  39921. */
  39922. static int pager_error(Pager *pPager, int rc){
  39923. int rc2 = rc & 0xff;
  39924. assert( rc==SQLITE_OK || !MEMDB );
  39925. assert(
  39926. pPager->errCode==SQLITE_FULL ||
  39927. pPager->errCode==SQLITE_OK ||
  39928. (pPager->errCode & 0xff)==SQLITE_IOERR
  39929. );
  39930. if( rc2==SQLITE_FULL || rc2==SQLITE_IOERR ){
  39931. pPager->errCode = rc;
  39932. pPager->eState = PAGER_ERROR;
  39933. }
  39934. return rc;
  39935. }
  39936. static int pager_truncate(Pager *pPager, Pgno nPage);
  39937. /*
  39938. ** This routine ends a transaction. A transaction is usually ended by
  39939. ** either a COMMIT or a ROLLBACK operation. This routine may be called
  39940. ** after rollback of a hot-journal, or if an error occurs while opening
  39941. ** the journal file or writing the very first journal-header of a
  39942. ** database transaction.
  39943. **
  39944. ** This routine is never called in PAGER_ERROR state. If it is called
  39945. ** in PAGER_NONE or PAGER_SHARED state and the lock held is less
  39946. ** exclusive than a RESERVED lock, it is a no-op.
  39947. **
  39948. ** Otherwise, any active savepoints are released.
  39949. **
  39950. ** If the journal file is open, then it is "finalized". Once a journal
  39951. ** file has been finalized it is not possible to use it to roll back a
  39952. ** transaction. Nor will it be considered to be a hot-journal by this
  39953. ** or any other database connection. Exactly how a journal is finalized
  39954. ** depends on whether or not the pager is running in exclusive mode and
  39955. ** the current journal-mode (Pager.journalMode value), as follows:
  39956. **
  39957. ** journalMode==MEMORY
  39958. ** Journal file descriptor is simply closed. This destroys an
  39959. ** in-memory journal.
  39960. **
  39961. ** journalMode==TRUNCATE
  39962. ** Journal file is truncated to zero bytes in size.
  39963. **
  39964. ** journalMode==PERSIST
  39965. ** The first 28 bytes of the journal file are zeroed. This invalidates
  39966. ** the first journal header in the file, and hence the entire journal
  39967. ** file. An invalid journal file cannot be rolled back.
  39968. **
  39969. ** journalMode==DELETE
  39970. ** The journal file is closed and deleted using sqlite3OsDelete().
  39971. **
  39972. ** If the pager is running in exclusive mode, this method of finalizing
  39973. ** the journal file is never used. Instead, if the journalMode is
  39974. ** DELETE and the pager is in exclusive mode, the method described under
  39975. ** journalMode==PERSIST is used instead.
  39976. **
  39977. ** After the journal is finalized, the pager moves to PAGER_READER state.
  39978. ** If running in non-exclusive rollback mode, the lock on the file is
  39979. ** downgraded to a SHARED_LOCK.
  39980. **
  39981. ** SQLITE_OK is returned if no error occurs. If an error occurs during
  39982. ** any of the IO operations to finalize the journal file or unlock the
  39983. ** database then the IO error code is returned to the user. If the
  39984. ** operation to finalize the journal file fails, then the code still
  39985. ** tries to unlock the database file if not in exclusive mode. If the
  39986. ** unlock operation fails as well, then the first error code related
  39987. ** to the first error encountered (the journal finalization one) is
  39988. ** returned.
  39989. */
  39990. static int pager_end_transaction(Pager *pPager, int hasMaster, int bCommit){
  39991. int rc = SQLITE_OK; /* Error code from journal finalization operation */
  39992. int rc2 = SQLITE_OK; /* Error code from db file unlock operation */
  39993. /* Do nothing if the pager does not have an open write transaction
  39994. ** or at least a RESERVED lock. This function may be called when there
  39995. ** is no write-transaction active but a RESERVED or greater lock is
  39996. ** held under two circumstances:
  39997. **
  39998. ** 1. After a successful hot-journal rollback, it is called with
  39999. ** eState==PAGER_NONE and eLock==EXCLUSIVE_LOCK.
  40000. **
  40001. ** 2. If a connection with locking_mode=exclusive holding an EXCLUSIVE
  40002. ** lock switches back to locking_mode=normal and then executes a
  40003. ** read-transaction, this function is called with eState==PAGER_READER
  40004. ** and eLock==EXCLUSIVE_LOCK when the read-transaction is closed.
  40005. */
  40006. assert( assert_pager_state(pPager) );
  40007. assert( pPager->eState!=PAGER_ERROR );
  40008. if( pPager->eState<PAGER_WRITER_LOCKED && pPager->eLock<RESERVED_LOCK ){
  40009. return SQLITE_OK;
  40010. }
  40011. releaseAllSavepoints(pPager);
  40012. assert( isOpen(pPager->jfd) || pPager->pInJournal==0 );
  40013. if( isOpen(pPager->jfd) ){
  40014. assert( !pagerUseWal(pPager) );
  40015. /* Finalize the journal file. */
  40016. if( sqlite3IsMemJournal(pPager->jfd) ){
  40017. assert( pPager->journalMode==PAGER_JOURNALMODE_MEMORY );
  40018. sqlite3OsClose(pPager->jfd);
  40019. }else if( pPager->journalMode==PAGER_JOURNALMODE_TRUNCATE ){
  40020. if( pPager->journalOff==0 ){
  40021. rc = SQLITE_OK;
  40022. }else{
  40023. rc = sqlite3OsTruncate(pPager->jfd, 0);
  40024. if( rc==SQLITE_OK && pPager->fullSync ){
  40025. /* Make sure the new file size is written into the inode right away.
  40026. ** Otherwise the journal might resurrect following a power loss and
  40027. ** cause the last transaction to roll back. See
  40028. ** https://bugzilla.mozilla.org/show_bug.cgi?id=1072773
  40029. */
  40030. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  40031. }
  40032. }
  40033. pPager->journalOff = 0;
  40034. }else if( pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  40035. || (pPager->exclusiveMode && pPager->journalMode!=PAGER_JOURNALMODE_WAL)
  40036. ){
  40037. rc = zeroJournalHdr(pPager, hasMaster);
  40038. pPager->journalOff = 0;
  40039. }else{
  40040. /* This branch may be executed with Pager.journalMode==MEMORY if
  40041. ** a hot-journal was just rolled back. In this case the journal
  40042. ** file should be closed and deleted. If this connection writes to
  40043. ** the database file, it will do so using an in-memory journal.
  40044. */
  40045. int bDelete = (!pPager->tempFile && sqlite3JournalExists(pPager->jfd));
  40046. assert( pPager->journalMode==PAGER_JOURNALMODE_DELETE
  40047. || pPager->journalMode==PAGER_JOURNALMODE_MEMORY
  40048. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  40049. );
  40050. sqlite3OsClose(pPager->jfd);
  40051. if( bDelete ){
  40052. rc = sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  40053. }
  40054. }
  40055. }
  40056. #ifdef SQLITE_CHECK_PAGES
  40057. sqlite3PcacheIterateDirty(pPager->pPCache, pager_set_pagehash);
  40058. if( pPager->dbSize==0 && sqlite3PcacheRefCount(pPager->pPCache)>0 ){
  40059. PgHdr *p = sqlite3PagerLookup(pPager, 1);
  40060. if( p ){
  40061. p->pageHash = 0;
  40062. sqlite3PagerUnrefNotNull(p);
  40063. }
  40064. }
  40065. #endif
  40066. sqlite3BitvecDestroy(pPager->pInJournal);
  40067. pPager->pInJournal = 0;
  40068. pPager->nRec = 0;
  40069. sqlite3PcacheCleanAll(pPager->pPCache);
  40070. sqlite3PcacheTruncate(pPager->pPCache, pPager->dbSize);
  40071. if( pagerUseWal(pPager) ){
  40072. /* Drop the WAL write-lock, if any. Also, if the connection was in
  40073. ** locking_mode=exclusive mode but is no longer, drop the EXCLUSIVE
  40074. ** lock held on the database file.
  40075. */
  40076. rc2 = sqlite3WalEndWriteTransaction(pPager->pWal);
  40077. assert( rc2==SQLITE_OK );
  40078. }else if( rc==SQLITE_OK && bCommit && pPager->dbFileSize>pPager->dbSize ){
  40079. /* This branch is taken when committing a transaction in rollback-journal
  40080. ** mode if the database file on disk is larger than the database image.
  40081. ** At this point the journal has been finalized and the transaction
  40082. ** successfully committed, but the EXCLUSIVE lock is still held on the
  40083. ** file. So it is safe to truncate the database file to its minimum
  40084. ** required size. */
  40085. assert( pPager->eLock==EXCLUSIVE_LOCK );
  40086. rc = pager_truncate(pPager, pPager->dbSize);
  40087. }
  40088. if( rc==SQLITE_OK && bCommit && isOpen(pPager->fd) ){
  40089. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_COMMIT_PHASETWO, 0);
  40090. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  40091. }
  40092. if( !pPager->exclusiveMode
  40093. && (!pagerUseWal(pPager) || sqlite3WalExclusiveMode(pPager->pWal, 0))
  40094. ){
  40095. rc2 = pagerUnlockDb(pPager, SHARED_LOCK);
  40096. pPager->changeCountDone = 0;
  40097. }
  40098. pPager->eState = PAGER_READER;
  40099. pPager->setMaster = 0;
  40100. return (rc==SQLITE_OK?rc2:rc);
  40101. }
  40102. /*
  40103. ** Execute a rollback if a transaction is active and unlock the
  40104. ** database file.
  40105. **
  40106. ** If the pager has already entered the ERROR state, do not attempt
  40107. ** the rollback at this time. Instead, pager_unlock() is called. The
  40108. ** call to pager_unlock() will discard all in-memory pages, unlock
  40109. ** the database file and move the pager back to OPEN state. If this
  40110. ** means that there is a hot-journal left in the file-system, the next
  40111. ** connection to obtain a shared lock on the pager (which may be this one)
  40112. ** will roll it back.
  40113. **
  40114. ** If the pager has not already entered the ERROR state, but an IO or
  40115. ** malloc error occurs during a rollback, then this will itself cause
  40116. ** the pager to enter the ERROR state. Which will be cleared by the
  40117. ** call to pager_unlock(), as described above.
  40118. */
  40119. static void pagerUnlockAndRollback(Pager *pPager){
  40120. if( pPager->eState!=PAGER_ERROR && pPager->eState!=PAGER_OPEN ){
  40121. assert( assert_pager_state(pPager) );
  40122. if( pPager->eState>=PAGER_WRITER_LOCKED ){
  40123. sqlite3BeginBenignMalloc();
  40124. sqlite3PagerRollback(pPager);
  40125. sqlite3EndBenignMalloc();
  40126. }else if( !pPager->exclusiveMode ){
  40127. assert( pPager->eState==PAGER_READER );
  40128. pager_end_transaction(pPager, 0, 0);
  40129. }
  40130. }
  40131. pager_unlock(pPager);
  40132. }
  40133. /*
  40134. ** Parameter aData must point to a buffer of pPager->pageSize bytes
  40135. ** of data. Compute and return a checksum based ont the contents of the
  40136. ** page of data and the current value of pPager->cksumInit.
  40137. **
  40138. ** This is not a real checksum. It is really just the sum of the
  40139. ** random initial value (pPager->cksumInit) and every 200th byte
  40140. ** of the page data, starting with byte offset (pPager->pageSize%200).
  40141. ** Each byte is interpreted as an 8-bit unsigned integer.
  40142. **
  40143. ** Changing the formula used to compute this checksum results in an
  40144. ** incompatible journal file format.
  40145. **
  40146. ** If journal corruption occurs due to a power failure, the most likely
  40147. ** scenario is that one end or the other of the record will be changed.
  40148. ** It is much less likely that the two ends of the journal record will be
  40149. ** correct and the middle be corrupt. Thus, this "checksum" scheme,
  40150. ** though fast and simple, catches the mostly likely kind of corruption.
  40151. */
  40152. static u32 pager_cksum(Pager *pPager, const u8 *aData){
  40153. u32 cksum = pPager->cksumInit; /* Checksum value to return */
  40154. int i = pPager->pageSize-200; /* Loop counter */
  40155. while( i>0 ){
  40156. cksum += aData[i];
  40157. i -= 200;
  40158. }
  40159. return cksum;
  40160. }
  40161. /*
  40162. ** Report the current page size and number of reserved bytes back
  40163. ** to the codec.
  40164. */
  40165. #ifdef SQLITE_HAS_CODEC
  40166. static void pagerReportSize(Pager *pPager){
  40167. if( pPager->xCodecSizeChng ){
  40168. pPager->xCodecSizeChng(pPager->pCodec, pPager->pageSize,
  40169. (int)pPager->nReserve);
  40170. }
  40171. }
  40172. #else
  40173. # define pagerReportSize(X) /* No-op if we do not support a codec */
  40174. #endif
  40175. /*
  40176. ** Read a single page from either the journal file (if isMainJrnl==1) or
  40177. ** from the sub-journal (if isMainJrnl==0) and playback that page.
  40178. ** The page begins at offset *pOffset into the file. The *pOffset
  40179. ** value is increased to the start of the next page in the journal.
  40180. **
  40181. ** The main rollback journal uses checksums - the statement journal does
  40182. ** not.
  40183. **
  40184. ** If the page number of the page record read from the (sub-)journal file
  40185. ** is greater than the current value of Pager.dbSize, then playback is
  40186. ** skipped and SQLITE_OK is returned.
  40187. **
  40188. ** If pDone is not NULL, then it is a record of pages that have already
  40189. ** been played back. If the page at *pOffset has already been played back
  40190. ** (if the corresponding pDone bit is set) then skip the playback.
  40191. ** Make sure the pDone bit corresponding to the *pOffset page is set
  40192. ** prior to returning.
  40193. **
  40194. ** If the page record is successfully read from the (sub-)journal file
  40195. ** and played back, then SQLITE_OK is returned. If an IO error occurs
  40196. ** while reading the record from the (sub-)journal file or while writing
  40197. ** to the database file, then the IO error code is returned. If data
  40198. ** is successfully read from the (sub-)journal file but appears to be
  40199. ** corrupted, SQLITE_DONE is returned. Data is considered corrupted in
  40200. ** two circumstances:
  40201. **
  40202. ** * If the record page-number is illegal (0 or PAGER_MJ_PGNO), or
  40203. ** * If the record is being rolled back from the main journal file
  40204. ** and the checksum field does not match the record content.
  40205. **
  40206. ** Neither of these two scenarios are possible during a savepoint rollback.
  40207. **
  40208. ** If this is a savepoint rollback, then memory may have to be dynamically
  40209. ** allocated by this function. If this is the case and an allocation fails,
  40210. ** SQLITE_NOMEM is returned.
  40211. */
  40212. static int pager_playback_one_page(
  40213. Pager *pPager, /* The pager being played back */
  40214. i64 *pOffset, /* Offset of record to playback */
  40215. Bitvec *pDone, /* Bitvec of pages already played back */
  40216. int isMainJrnl, /* 1 -> main journal. 0 -> sub-journal. */
  40217. int isSavepnt /* True for a savepoint rollback */
  40218. ){
  40219. int rc;
  40220. PgHdr *pPg; /* An existing page in the cache */
  40221. Pgno pgno; /* The page number of a page in journal */
  40222. u32 cksum; /* Checksum used for sanity checking */
  40223. char *aData; /* Temporary storage for the page */
  40224. sqlite3_file *jfd; /* The file descriptor for the journal file */
  40225. int isSynced; /* True if journal page is synced */
  40226. assert( (isMainJrnl&~1)==0 ); /* isMainJrnl is 0 or 1 */
  40227. assert( (isSavepnt&~1)==0 ); /* isSavepnt is 0 or 1 */
  40228. assert( isMainJrnl || pDone ); /* pDone always used on sub-journals */
  40229. assert( isSavepnt || pDone==0 ); /* pDone never used on non-savepoint */
  40230. aData = pPager->pTmpSpace;
  40231. assert( aData ); /* Temp storage must have already been allocated */
  40232. assert( pagerUseWal(pPager)==0 || (!isMainJrnl && isSavepnt) );
  40233. /* Either the state is greater than PAGER_WRITER_CACHEMOD (a transaction
  40234. ** or savepoint rollback done at the request of the caller) or this is
  40235. ** a hot-journal rollback. If it is a hot-journal rollback, the pager
  40236. ** is in state OPEN and holds an EXCLUSIVE lock. Hot-journal rollback
  40237. ** only reads from the main journal, not the sub-journal.
  40238. */
  40239. assert( pPager->eState>=PAGER_WRITER_CACHEMOD
  40240. || (pPager->eState==PAGER_OPEN && pPager->eLock==EXCLUSIVE_LOCK)
  40241. );
  40242. assert( pPager->eState>=PAGER_WRITER_CACHEMOD || isMainJrnl );
  40243. /* Read the page number and page data from the journal or sub-journal
  40244. ** file. Return an error code to the caller if an IO error occurs.
  40245. */
  40246. jfd = isMainJrnl ? pPager->jfd : pPager->sjfd;
  40247. rc = read32bits(jfd, *pOffset, &pgno);
  40248. if( rc!=SQLITE_OK ) return rc;
  40249. rc = sqlite3OsRead(jfd, (u8*)aData, pPager->pageSize, (*pOffset)+4);
  40250. if( rc!=SQLITE_OK ) return rc;
  40251. *pOffset += pPager->pageSize + 4 + isMainJrnl*4;
  40252. /* Sanity checking on the page. This is more important that I originally
  40253. ** thought. If a power failure occurs while the journal is being written,
  40254. ** it could cause invalid data to be written into the journal. We need to
  40255. ** detect this invalid data (with high probability) and ignore it.
  40256. */
  40257. if( pgno==0 || pgno==PAGER_MJ_PGNO(pPager) ){
  40258. assert( !isSavepnt );
  40259. return SQLITE_DONE;
  40260. }
  40261. if( pgno>(Pgno)pPager->dbSize || sqlite3BitvecTest(pDone, pgno) ){
  40262. return SQLITE_OK;
  40263. }
  40264. if( isMainJrnl ){
  40265. rc = read32bits(jfd, (*pOffset)-4, &cksum);
  40266. if( rc ) return rc;
  40267. if( !isSavepnt && pager_cksum(pPager, (u8*)aData)!=cksum ){
  40268. return SQLITE_DONE;
  40269. }
  40270. }
  40271. /* If this page has already been played by before during the current
  40272. ** rollback, then don't bother to play it back again.
  40273. */
  40274. if( pDone && (rc = sqlite3BitvecSet(pDone, pgno))!=SQLITE_OK ){
  40275. return rc;
  40276. }
  40277. /* When playing back page 1, restore the nReserve setting
  40278. */
  40279. if( pgno==1 && pPager->nReserve!=((u8*)aData)[20] ){
  40280. pPager->nReserve = ((u8*)aData)[20];
  40281. pagerReportSize(pPager);
  40282. }
  40283. /* If the pager is in CACHEMOD state, then there must be a copy of this
  40284. ** page in the pager cache. In this case just update the pager cache,
  40285. ** not the database file. The page is left marked dirty in this case.
  40286. **
  40287. ** An exception to the above rule: If the database is in no-sync mode
  40288. ** and a page is moved during an incremental vacuum then the page may
  40289. ** not be in the pager cache. Later: if a malloc() or IO error occurs
  40290. ** during a Movepage() call, then the page may not be in the cache
  40291. ** either. So the condition described in the above paragraph is not
  40292. ** assert()able.
  40293. **
  40294. ** If in WRITER_DBMOD, WRITER_FINISHED or OPEN state, then we update the
  40295. ** pager cache if it exists and the main file. The page is then marked
  40296. ** not dirty. Since this code is only executed in PAGER_OPEN state for
  40297. ** a hot-journal rollback, it is guaranteed that the page-cache is empty
  40298. ** if the pager is in OPEN state.
  40299. **
  40300. ** Ticket #1171: The statement journal might contain page content that is
  40301. ** different from the page content at the start of the transaction.
  40302. ** This occurs when a page is changed prior to the start of a statement
  40303. ** then changed again within the statement. When rolling back such a
  40304. ** statement we must not write to the original database unless we know
  40305. ** for certain that original page contents are synced into the main rollback
  40306. ** journal. Otherwise, a power loss might leave modified data in the
  40307. ** database file without an entry in the rollback journal that can
  40308. ** restore the database to its original form. Two conditions must be
  40309. ** met before writing to the database files. (1) the database must be
  40310. ** locked. (2) we know that the original page content is fully synced
  40311. ** in the main journal either because the page is not in cache or else
  40312. ** the page is marked as needSync==0.
  40313. **
  40314. ** 2008-04-14: When attempting to vacuum a corrupt database file, it
  40315. ** is possible to fail a statement on a database that does not yet exist.
  40316. ** Do not attempt to write if database file has never been opened.
  40317. */
  40318. if( pagerUseWal(pPager) ){
  40319. pPg = 0;
  40320. }else{
  40321. pPg = sqlite3PagerLookup(pPager, pgno);
  40322. }
  40323. assert( pPg || !MEMDB );
  40324. assert( pPager->eState!=PAGER_OPEN || pPg==0 );
  40325. PAGERTRACE(("PLAYBACK %d page %d hash(%08x) %s\n",
  40326. PAGERID(pPager), pgno, pager_datahash(pPager->pageSize, (u8*)aData),
  40327. (isMainJrnl?"main-journal":"sub-journal")
  40328. ));
  40329. if( isMainJrnl ){
  40330. isSynced = pPager->noSync || (*pOffset <= pPager->journalHdr);
  40331. }else{
  40332. isSynced = (pPg==0 || 0==(pPg->flags & PGHDR_NEED_SYNC));
  40333. }
  40334. if( isOpen(pPager->fd)
  40335. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  40336. && isSynced
  40337. ){
  40338. i64 ofst = (pgno-1)*(i64)pPager->pageSize;
  40339. testcase( !isSavepnt && pPg!=0 && (pPg->flags&PGHDR_NEED_SYNC)!=0 );
  40340. assert( !pagerUseWal(pPager) );
  40341. rc = sqlite3OsWrite(pPager->fd, (u8 *)aData, pPager->pageSize, ofst);
  40342. if( pgno>pPager->dbFileSize ){
  40343. pPager->dbFileSize = pgno;
  40344. }
  40345. if( pPager->pBackup ){
  40346. CODEC1(pPager, aData, pgno, 3, rc=SQLITE_NOMEM);
  40347. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)aData);
  40348. CODEC2(pPager, aData, pgno, 7, rc=SQLITE_NOMEM, aData);
  40349. }
  40350. }else if( !isMainJrnl && pPg==0 ){
  40351. /* If this is a rollback of a savepoint and data was not written to
  40352. ** the database and the page is not in-memory, there is a potential
  40353. ** problem. When the page is next fetched by the b-tree layer, it
  40354. ** will be read from the database file, which may or may not be
  40355. ** current.
  40356. **
  40357. ** There are a couple of different ways this can happen. All are quite
  40358. ** obscure. When running in synchronous mode, this can only happen
  40359. ** if the page is on the free-list at the start of the transaction, then
  40360. ** populated, then moved using sqlite3PagerMovepage().
  40361. **
  40362. ** The solution is to add an in-memory page to the cache containing
  40363. ** the data just read from the sub-journal. Mark the page as dirty
  40364. ** and if the pager requires a journal-sync, then mark the page as
  40365. ** requiring a journal-sync before it is written.
  40366. */
  40367. assert( isSavepnt );
  40368. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)==0 );
  40369. pPager->doNotSpill |= SPILLFLAG_ROLLBACK;
  40370. rc = sqlite3PagerAcquire(pPager, pgno, &pPg, 1);
  40371. assert( (pPager->doNotSpill & SPILLFLAG_ROLLBACK)!=0 );
  40372. pPager->doNotSpill &= ~SPILLFLAG_ROLLBACK;
  40373. if( rc!=SQLITE_OK ) return rc;
  40374. pPg->flags &= ~PGHDR_NEED_READ;
  40375. sqlite3PcacheMakeDirty(pPg);
  40376. }
  40377. if( pPg ){
  40378. /* No page should ever be explicitly rolled back that is in use, except
  40379. ** for page 1 which is held in use in order to keep the lock on the
  40380. ** database active. However such a page may be rolled back as a result
  40381. ** of an internal error resulting in an automatic call to
  40382. ** sqlite3PagerRollback().
  40383. */
  40384. void *pData;
  40385. pData = pPg->pData;
  40386. memcpy(pData, (u8*)aData, pPager->pageSize);
  40387. pPager->xReiniter(pPg);
  40388. if( isMainJrnl && (!isSavepnt || *pOffset<=pPager->journalHdr) ){
  40389. /* If the contents of this page were just restored from the main
  40390. ** journal file, then its content must be as they were when the
  40391. ** transaction was first opened. In this case we can mark the page
  40392. ** as clean, since there will be no need to write it out to the
  40393. ** database.
  40394. **
  40395. ** There is one exception to this rule. If the page is being rolled
  40396. ** back as part of a savepoint (or statement) rollback from an
  40397. ** unsynced portion of the main journal file, then it is not safe
  40398. ** to mark the page as clean. This is because marking the page as
  40399. ** clean will clear the PGHDR_NEED_SYNC flag. Since the page is
  40400. ** already in the journal file (recorded in Pager.pInJournal) and
  40401. ** the PGHDR_NEED_SYNC flag is cleared, if the page is written to
  40402. ** again within this transaction, it will be marked as dirty but
  40403. ** the PGHDR_NEED_SYNC flag will not be set. It could then potentially
  40404. ** be written out into the database file before its journal file
  40405. ** segment is synced. If a crash occurs during or following this,
  40406. ** database corruption may ensue.
  40407. */
  40408. assert( !pagerUseWal(pPager) );
  40409. sqlite3PcacheMakeClean(pPg);
  40410. }
  40411. pager_set_pagehash(pPg);
  40412. /* If this was page 1, then restore the value of Pager.dbFileVers.
  40413. ** Do this before any decoding. */
  40414. if( pgno==1 ){
  40415. memcpy(&pPager->dbFileVers, &((u8*)pData)[24],sizeof(pPager->dbFileVers));
  40416. }
  40417. /* Decode the page just read from disk */
  40418. CODEC1(pPager, pData, pPg->pgno, 3, rc=SQLITE_NOMEM);
  40419. sqlite3PcacheRelease(pPg);
  40420. }
  40421. return rc;
  40422. }
  40423. /*
  40424. ** Parameter zMaster is the name of a master journal file. A single journal
  40425. ** file that referred to the master journal file has just been rolled back.
  40426. ** This routine checks if it is possible to delete the master journal file,
  40427. ** and does so if it is.
  40428. **
  40429. ** Argument zMaster may point to Pager.pTmpSpace. So that buffer is not
  40430. ** available for use within this function.
  40431. **
  40432. ** When a master journal file is created, it is populated with the names
  40433. ** of all of its child journals, one after another, formatted as utf-8
  40434. ** encoded text. The end of each child journal file is marked with a
  40435. ** nul-terminator byte (0x00). i.e. the entire contents of a master journal
  40436. ** file for a transaction involving two databases might be:
  40437. **
  40438. ** "/home/bill/a.db-journal\x00/home/bill/b.db-journal\x00"
  40439. **
  40440. ** A master journal file may only be deleted once all of its child
  40441. ** journals have been rolled back.
  40442. **
  40443. ** This function reads the contents of the master-journal file into
  40444. ** memory and loops through each of the child journal names. For
  40445. ** each child journal, it checks if:
  40446. **
  40447. ** * if the child journal exists, and if so
  40448. ** * if the child journal contains a reference to master journal
  40449. ** file zMaster
  40450. **
  40451. ** If a child journal can be found that matches both of the criteria
  40452. ** above, this function returns without doing anything. Otherwise, if
  40453. ** no such child journal can be found, file zMaster is deleted from
  40454. ** the file-system using sqlite3OsDelete().
  40455. **
  40456. ** If an IO error within this function, an error code is returned. This
  40457. ** function allocates memory by calling sqlite3Malloc(). If an allocation
  40458. ** fails, SQLITE_NOMEM is returned. Otherwise, if no IO or malloc errors
  40459. ** occur, SQLITE_OK is returned.
  40460. **
  40461. ** TODO: This function allocates a single block of memory to load
  40462. ** the entire contents of the master journal file. This could be
  40463. ** a couple of kilobytes or so - potentially larger than the page
  40464. ** size.
  40465. */
  40466. static int pager_delmaster(Pager *pPager, const char *zMaster){
  40467. sqlite3_vfs *pVfs = pPager->pVfs;
  40468. int rc; /* Return code */
  40469. sqlite3_file *pMaster; /* Malloc'd master-journal file descriptor */
  40470. sqlite3_file *pJournal; /* Malloc'd child-journal file descriptor */
  40471. char *zMasterJournal = 0; /* Contents of master journal file */
  40472. i64 nMasterJournal; /* Size of master journal file */
  40473. char *zJournal; /* Pointer to one journal within MJ file */
  40474. char *zMasterPtr; /* Space to hold MJ filename from a journal file */
  40475. int nMasterPtr; /* Amount of space allocated to zMasterPtr[] */
  40476. /* Allocate space for both the pJournal and pMaster file descriptors.
  40477. ** If successful, open the master journal file for reading.
  40478. */
  40479. pMaster = (sqlite3_file *)sqlite3MallocZero(pVfs->szOsFile * 2);
  40480. pJournal = (sqlite3_file *)(((u8 *)pMaster) + pVfs->szOsFile);
  40481. if( !pMaster ){
  40482. rc = SQLITE_NOMEM;
  40483. }else{
  40484. const int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MASTER_JOURNAL);
  40485. rc = sqlite3OsOpen(pVfs, zMaster, pMaster, flags, 0);
  40486. }
  40487. if( rc!=SQLITE_OK ) goto delmaster_out;
  40488. /* Load the entire master journal file into space obtained from
  40489. ** sqlite3_malloc() and pointed to by zMasterJournal. Also obtain
  40490. ** sufficient space (in zMasterPtr) to hold the names of master
  40491. ** journal files extracted from regular rollback-journals.
  40492. */
  40493. rc = sqlite3OsFileSize(pMaster, &nMasterJournal);
  40494. if( rc!=SQLITE_OK ) goto delmaster_out;
  40495. nMasterPtr = pVfs->mxPathname+1;
  40496. zMasterJournal = sqlite3Malloc(nMasterJournal + nMasterPtr + 1);
  40497. if( !zMasterJournal ){
  40498. rc = SQLITE_NOMEM;
  40499. goto delmaster_out;
  40500. }
  40501. zMasterPtr = &zMasterJournal[nMasterJournal+1];
  40502. rc = sqlite3OsRead(pMaster, zMasterJournal, (int)nMasterJournal, 0);
  40503. if( rc!=SQLITE_OK ) goto delmaster_out;
  40504. zMasterJournal[nMasterJournal] = 0;
  40505. zJournal = zMasterJournal;
  40506. while( (zJournal-zMasterJournal)<nMasterJournal ){
  40507. int exists;
  40508. rc = sqlite3OsAccess(pVfs, zJournal, SQLITE_ACCESS_EXISTS, &exists);
  40509. if( rc!=SQLITE_OK ){
  40510. goto delmaster_out;
  40511. }
  40512. if( exists ){
  40513. /* One of the journals pointed to by the master journal exists.
  40514. ** Open it and check if it points at the master journal. If
  40515. ** so, return without deleting the master journal file.
  40516. */
  40517. int c;
  40518. int flags = (SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL);
  40519. rc = sqlite3OsOpen(pVfs, zJournal, pJournal, flags, 0);
  40520. if( rc!=SQLITE_OK ){
  40521. goto delmaster_out;
  40522. }
  40523. rc = readMasterJournal(pJournal, zMasterPtr, nMasterPtr);
  40524. sqlite3OsClose(pJournal);
  40525. if( rc!=SQLITE_OK ){
  40526. goto delmaster_out;
  40527. }
  40528. c = zMasterPtr[0]!=0 && strcmp(zMasterPtr, zMaster)==0;
  40529. if( c ){
  40530. /* We have a match. Do not delete the master journal file. */
  40531. goto delmaster_out;
  40532. }
  40533. }
  40534. zJournal += (sqlite3Strlen30(zJournal)+1);
  40535. }
  40536. sqlite3OsClose(pMaster);
  40537. rc = sqlite3OsDelete(pVfs, zMaster, 0);
  40538. delmaster_out:
  40539. sqlite3_free(zMasterJournal);
  40540. if( pMaster ){
  40541. sqlite3OsClose(pMaster);
  40542. assert( !isOpen(pJournal) );
  40543. sqlite3_free(pMaster);
  40544. }
  40545. return rc;
  40546. }
  40547. /*
  40548. ** This function is used to change the actual size of the database
  40549. ** file in the file-system. This only happens when committing a transaction,
  40550. ** or rolling back a transaction (including rolling back a hot-journal).
  40551. **
  40552. ** If the main database file is not open, or the pager is not in either
  40553. ** DBMOD or OPEN state, this function is a no-op. Otherwise, the size
  40554. ** of the file is changed to nPage pages (nPage*pPager->pageSize bytes).
  40555. ** If the file on disk is currently larger than nPage pages, then use the VFS
  40556. ** xTruncate() method to truncate it.
  40557. **
  40558. ** Or, it might be the case that the file on disk is smaller than
  40559. ** nPage pages. Some operating system implementations can get confused if
  40560. ** you try to truncate a file to some size that is larger than it
  40561. ** currently is, so detect this case and write a single zero byte to
  40562. ** the end of the new file instead.
  40563. **
  40564. ** If successful, return SQLITE_OK. If an IO error occurs while modifying
  40565. ** the database file, return the error code to the caller.
  40566. */
  40567. static int pager_truncate(Pager *pPager, Pgno nPage){
  40568. int rc = SQLITE_OK;
  40569. assert( pPager->eState!=PAGER_ERROR );
  40570. assert( pPager->eState!=PAGER_READER );
  40571. if( isOpen(pPager->fd)
  40572. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  40573. ){
  40574. i64 currentSize, newSize;
  40575. int szPage = pPager->pageSize;
  40576. assert( pPager->eLock==EXCLUSIVE_LOCK );
  40577. /* TODO: Is it safe to use Pager.dbFileSize here? */
  40578. rc = sqlite3OsFileSize(pPager->fd, &currentSize);
  40579. newSize = szPage*(i64)nPage;
  40580. if( rc==SQLITE_OK && currentSize!=newSize ){
  40581. if( currentSize>newSize ){
  40582. rc = sqlite3OsTruncate(pPager->fd, newSize);
  40583. }else if( (currentSize+szPage)<=newSize ){
  40584. char *pTmp = pPager->pTmpSpace;
  40585. memset(pTmp, 0, szPage);
  40586. testcase( (newSize-szPage) == currentSize );
  40587. testcase( (newSize-szPage) > currentSize );
  40588. rc = sqlite3OsWrite(pPager->fd, pTmp, szPage, newSize-szPage);
  40589. }
  40590. if( rc==SQLITE_OK ){
  40591. pPager->dbFileSize = nPage;
  40592. }
  40593. }
  40594. }
  40595. return rc;
  40596. }
  40597. /*
  40598. ** Return a sanitized version of the sector-size of OS file pFile. The
  40599. ** return value is guaranteed to lie between 32 and MAX_SECTOR_SIZE.
  40600. */
  40601. SQLITE_PRIVATE int sqlite3SectorSize(sqlite3_file *pFile){
  40602. int iRet = sqlite3OsSectorSize(pFile);
  40603. if( iRet<32 ){
  40604. iRet = 512;
  40605. }else if( iRet>MAX_SECTOR_SIZE ){
  40606. assert( MAX_SECTOR_SIZE>=512 );
  40607. iRet = MAX_SECTOR_SIZE;
  40608. }
  40609. return iRet;
  40610. }
  40611. /*
  40612. ** Set the value of the Pager.sectorSize variable for the given
  40613. ** pager based on the value returned by the xSectorSize method
  40614. ** of the open database file. The sector size will be used
  40615. ** to determine the size and alignment of journal header and
  40616. ** master journal pointers within created journal files.
  40617. **
  40618. ** For temporary files the effective sector size is always 512 bytes.
  40619. **
  40620. ** Otherwise, for non-temporary files, the effective sector size is
  40621. ** the value returned by the xSectorSize() method rounded up to 32 if
  40622. ** it is less than 32, or rounded down to MAX_SECTOR_SIZE if it
  40623. ** is greater than MAX_SECTOR_SIZE.
  40624. **
  40625. ** If the file has the SQLITE_IOCAP_POWERSAFE_OVERWRITE property, then set
  40626. ** the effective sector size to its minimum value (512). The purpose of
  40627. ** pPager->sectorSize is to define the "blast radius" of bytes that
  40628. ** might change if a crash occurs while writing to a single byte in
  40629. ** that range. But with POWERSAFE_OVERWRITE, the blast radius is zero
  40630. ** (that is what POWERSAFE_OVERWRITE means), so we minimize the sector
  40631. ** size. For backwards compatibility of the rollback journal file format,
  40632. ** we cannot reduce the effective sector size below 512.
  40633. */
  40634. static void setSectorSize(Pager *pPager){
  40635. assert( isOpen(pPager->fd) || pPager->tempFile );
  40636. if( pPager->tempFile
  40637. || (sqlite3OsDeviceCharacteristics(pPager->fd) &
  40638. SQLITE_IOCAP_POWERSAFE_OVERWRITE)!=0
  40639. ){
  40640. /* Sector size doesn't matter for temporary files. Also, the file
  40641. ** may not have been opened yet, in which case the OsSectorSize()
  40642. ** call will segfault. */
  40643. pPager->sectorSize = 512;
  40644. }else{
  40645. pPager->sectorSize = sqlite3SectorSize(pPager->fd);
  40646. }
  40647. }
  40648. /*
  40649. ** Playback the journal and thus restore the database file to
  40650. ** the state it was in before we started making changes.
  40651. **
  40652. ** The journal file format is as follows:
  40653. **
  40654. ** (1) 8 byte prefix. A copy of aJournalMagic[].
  40655. ** (2) 4 byte big-endian integer which is the number of valid page records
  40656. ** in the journal. If this value is 0xffffffff, then compute the
  40657. ** number of page records from the journal size.
  40658. ** (3) 4 byte big-endian integer which is the initial value for the
  40659. ** sanity checksum.
  40660. ** (4) 4 byte integer which is the number of pages to truncate the
  40661. ** database to during a rollback.
  40662. ** (5) 4 byte big-endian integer which is the sector size. The header
  40663. ** is this many bytes in size.
  40664. ** (6) 4 byte big-endian integer which is the page size.
  40665. ** (7) zero padding out to the next sector size.
  40666. ** (8) Zero or more pages instances, each as follows:
  40667. ** + 4 byte page number.
  40668. ** + pPager->pageSize bytes of data.
  40669. ** + 4 byte checksum
  40670. **
  40671. ** When we speak of the journal header, we mean the first 7 items above.
  40672. ** Each entry in the journal is an instance of the 8th item.
  40673. **
  40674. ** Call the value from the second bullet "nRec". nRec is the number of
  40675. ** valid page entries in the journal. In most cases, you can compute the
  40676. ** value of nRec from the size of the journal file. But if a power
  40677. ** failure occurred while the journal was being written, it could be the
  40678. ** case that the size of the journal file had already been increased but
  40679. ** the extra entries had not yet made it safely to disk. In such a case,
  40680. ** the value of nRec computed from the file size would be too large. For
  40681. ** that reason, we always use the nRec value in the header.
  40682. **
  40683. ** If the nRec value is 0xffffffff it means that nRec should be computed
  40684. ** from the file size. This value is used when the user selects the
  40685. ** no-sync option for the journal. A power failure could lead to corruption
  40686. ** in this case. But for things like temporary table (which will be
  40687. ** deleted when the power is restored) we don't care.
  40688. **
  40689. ** If the file opened as the journal file is not a well-formed
  40690. ** journal file then all pages up to the first corrupted page are rolled
  40691. ** back (or no pages if the journal header is corrupted). The journal file
  40692. ** is then deleted and SQLITE_OK returned, just as if no corruption had
  40693. ** been encountered.
  40694. **
  40695. ** If an I/O or malloc() error occurs, the journal-file is not deleted
  40696. ** and an error code is returned.
  40697. **
  40698. ** The isHot parameter indicates that we are trying to rollback a journal
  40699. ** that might be a hot journal. Or, it could be that the journal is
  40700. ** preserved because of JOURNALMODE_PERSIST or JOURNALMODE_TRUNCATE.
  40701. ** If the journal really is hot, reset the pager cache prior rolling
  40702. ** back any content. If the journal is merely persistent, no reset is
  40703. ** needed.
  40704. */
  40705. static int pager_playback(Pager *pPager, int isHot){
  40706. sqlite3_vfs *pVfs = pPager->pVfs;
  40707. i64 szJ; /* Size of the journal file in bytes */
  40708. u32 nRec; /* Number of Records in the journal */
  40709. u32 u; /* Unsigned loop counter */
  40710. Pgno mxPg = 0; /* Size of the original file in pages */
  40711. int rc; /* Result code of a subroutine */
  40712. int res = 1; /* Value returned by sqlite3OsAccess() */
  40713. char *zMaster = 0; /* Name of master journal file if any */
  40714. int needPagerReset; /* True to reset page prior to first page rollback */
  40715. int nPlayback = 0; /* Total number of pages restored from journal */
  40716. /* Figure out how many records are in the journal. Abort early if
  40717. ** the journal is empty.
  40718. */
  40719. assert( isOpen(pPager->jfd) );
  40720. rc = sqlite3OsFileSize(pPager->jfd, &szJ);
  40721. if( rc!=SQLITE_OK ){
  40722. goto end_playback;
  40723. }
  40724. /* Read the master journal name from the journal, if it is present.
  40725. ** If a master journal file name is specified, but the file is not
  40726. ** present on disk, then the journal is not hot and does not need to be
  40727. ** played back.
  40728. **
  40729. ** TODO: Technically the following is an error because it assumes that
  40730. ** buffer Pager.pTmpSpace is (mxPathname+1) bytes or larger. i.e. that
  40731. ** (pPager->pageSize >= pPager->pVfs->mxPathname+1). Using os_unix.c,
  40732. ** mxPathname is 512, which is the same as the minimum allowable value
  40733. ** for pageSize.
  40734. */
  40735. zMaster = pPager->pTmpSpace;
  40736. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  40737. if( rc==SQLITE_OK && zMaster[0] ){
  40738. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  40739. }
  40740. zMaster = 0;
  40741. if( rc!=SQLITE_OK || !res ){
  40742. goto end_playback;
  40743. }
  40744. pPager->journalOff = 0;
  40745. needPagerReset = isHot;
  40746. /* This loop terminates either when a readJournalHdr() or
  40747. ** pager_playback_one_page() call returns SQLITE_DONE or an IO error
  40748. ** occurs.
  40749. */
  40750. while( 1 ){
  40751. /* Read the next journal header from the journal file. If there are
  40752. ** not enough bytes left in the journal file for a complete header, or
  40753. ** it is corrupted, then a process must have failed while writing it.
  40754. ** This indicates nothing more needs to be rolled back.
  40755. */
  40756. rc = readJournalHdr(pPager, isHot, szJ, &nRec, &mxPg);
  40757. if( rc!=SQLITE_OK ){
  40758. if( rc==SQLITE_DONE ){
  40759. rc = SQLITE_OK;
  40760. }
  40761. goto end_playback;
  40762. }
  40763. /* If nRec is 0xffffffff, then this journal was created by a process
  40764. ** working in no-sync mode. This means that the rest of the journal
  40765. ** file consists of pages, there are no more journal headers. Compute
  40766. ** the value of nRec based on this assumption.
  40767. */
  40768. if( nRec==0xffffffff ){
  40769. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) );
  40770. nRec = (int)((szJ - JOURNAL_HDR_SZ(pPager))/JOURNAL_PG_SZ(pPager));
  40771. }
  40772. /* If nRec is 0 and this rollback is of a transaction created by this
  40773. ** process and if this is the final header in the journal, then it means
  40774. ** that this part of the journal was being filled but has not yet been
  40775. ** synced to disk. Compute the number of pages based on the remaining
  40776. ** size of the file.
  40777. **
  40778. ** The third term of the test was added to fix ticket #2565.
  40779. ** When rolling back a hot journal, nRec==0 always means that the next
  40780. ** chunk of the journal contains zero pages to be rolled back. But
  40781. ** when doing a ROLLBACK and the nRec==0 chunk is the last chunk in
  40782. ** the journal, it means that the journal might contain additional
  40783. ** pages that need to be rolled back and that the number of pages
  40784. ** should be computed based on the journal file size.
  40785. */
  40786. if( nRec==0 && !isHot &&
  40787. pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff ){
  40788. nRec = (int)((szJ - pPager->journalOff) / JOURNAL_PG_SZ(pPager));
  40789. }
  40790. /* If this is the first header read from the journal, truncate the
  40791. ** database file back to its original size.
  40792. */
  40793. if( pPager->journalOff==JOURNAL_HDR_SZ(pPager) ){
  40794. rc = pager_truncate(pPager, mxPg);
  40795. if( rc!=SQLITE_OK ){
  40796. goto end_playback;
  40797. }
  40798. pPager->dbSize = mxPg;
  40799. }
  40800. /* Copy original pages out of the journal and back into the
  40801. ** database file and/or page cache.
  40802. */
  40803. for(u=0; u<nRec; u++){
  40804. if( needPagerReset ){
  40805. pager_reset(pPager);
  40806. needPagerReset = 0;
  40807. }
  40808. rc = pager_playback_one_page(pPager,&pPager->journalOff,0,1,0);
  40809. if( rc==SQLITE_OK ){
  40810. nPlayback++;
  40811. }else{
  40812. if( rc==SQLITE_DONE ){
  40813. pPager->journalOff = szJ;
  40814. break;
  40815. }else if( rc==SQLITE_IOERR_SHORT_READ ){
  40816. /* If the journal has been truncated, simply stop reading and
  40817. ** processing the journal. This might happen if the journal was
  40818. ** not completely written and synced prior to a crash. In that
  40819. ** case, the database should have never been written in the
  40820. ** first place so it is OK to simply abandon the rollback. */
  40821. rc = SQLITE_OK;
  40822. goto end_playback;
  40823. }else{
  40824. /* If we are unable to rollback, quit and return the error
  40825. ** code. This will cause the pager to enter the error state
  40826. ** so that no further harm will be done. Perhaps the next
  40827. ** process to come along will be able to rollback the database.
  40828. */
  40829. goto end_playback;
  40830. }
  40831. }
  40832. }
  40833. }
  40834. /*NOTREACHED*/
  40835. assert( 0 );
  40836. end_playback:
  40837. /* Following a rollback, the database file should be back in its original
  40838. ** state prior to the start of the transaction, so invoke the
  40839. ** SQLITE_FCNTL_DB_UNCHANGED file-control method to disable the
  40840. ** assertion that the transaction counter was modified.
  40841. */
  40842. #ifdef SQLITE_DEBUG
  40843. if( pPager->fd->pMethods ){
  40844. sqlite3OsFileControlHint(pPager->fd,SQLITE_FCNTL_DB_UNCHANGED,0);
  40845. }
  40846. #endif
  40847. /* If this playback is happening automatically as a result of an IO or
  40848. ** malloc error that occurred after the change-counter was updated but
  40849. ** before the transaction was committed, then the change-counter
  40850. ** modification may just have been reverted. If this happens in exclusive
  40851. ** mode, then subsequent transactions performed by the connection will not
  40852. ** update the change-counter at all. This may lead to cache inconsistency
  40853. ** problems for other processes at some point in the future. So, just
  40854. ** in case this has happened, clear the changeCountDone flag now.
  40855. */
  40856. pPager->changeCountDone = pPager->tempFile;
  40857. if( rc==SQLITE_OK ){
  40858. zMaster = pPager->pTmpSpace;
  40859. rc = readMasterJournal(pPager->jfd, zMaster, pPager->pVfs->mxPathname+1);
  40860. testcase( rc!=SQLITE_OK );
  40861. }
  40862. if( rc==SQLITE_OK
  40863. && (pPager->eState>=PAGER_WRITER_DBMOD || pPager->eState==PAGER_OPEN)
  40864. ){
  40865. rc = sqlite3PagerSync(pPager, 0);
  40866. }
  40867. if( rc==SQLITE_OK ){
  40868. rc = pager_end_transaction(pPager, zMaster[0]!='\0', 0);
  40869. testcase( rc!=SQLITE_OK );
  40870. }
  40871. if( rc==SQLITE_OK && zMaster[0] && res ){
  40872. /* If there was a master journal and this routine will return success,
  40873. ** see if it is possible to delete the master journal.
  40874. */
  40875. rc = pager_delmaster(pPager, zMaster);
  40876. testcase( rc!=SQLITE_OK );
  40877. }
  40878. if( isHot && nPlayback ){
  40879. sqlite3_log(SQLITE_NOTICE_RECOVER_ROLLBACK, "recovered %d pages from %s",
  40880. nPlayback, pPager->zJournal);
  40881. }
  40882. /* The Pager.sectorSize variable may have been updated while rolling
  40883. ** back a journal created by a process with a different sector size
  40884. ** value. Reset it to the correct value for this process.
  40885. */
  40886. setSectorSize(pPager);
  40887. return rc;
  40888. }
  40889. /*
  40890. ** Read the content for page pPg out of the database file and into
  40891. ** pPg->pData. A shared lock or greater must be held on the database
  40892. ** file before this function is called.
  40893. **
  40894. ** If page 1 is read, then the value of Pager.dbFileVers[] is set to
  40895. ** the value read from the database file.
  40896. **
  40897. ** If an IO error occurs, then the IO error is returned to the caller.
  40898. ** Otherwise, SQLITE_OK is returned.
  40899. */
  40900. static int readDbPage(PgHdr *pPg, u32 iFrame){
  40901. Pager *pPager = pPg->pPager; /* Pager object associated with page pPg */
  40902. Pgno pgno = pPg->pgno; /* Page number to read */
  40903. int rc = SQLITE_OK; /* Return code */
  40904. int pgsz = pPager->pageSize; /* Number of bytes to read */
  40905. assert( pPager->eState>=PAGER_READER && !MEMDB );
  40906. assert( isOpen(pPager->fd) );
  40907. #ifndef SQLITE_OMIT_WAL
  40908. if( iFrame ){
  40909. /* Try to pull the page from the write-ahead log. */
  40910. rc = sqlite3WalReadFrame(pPager->pWal, iFrame, pgsz, pPg->pData);
  40911. }else
  40912. #endif
  40913. {
  40914. i64 iOffset = (pgno-1)*(i64)pPager->pageSize;
  40915. rc = sqlite3OsRead(pPager->fd, pPg->pData, pgsz, iOffset);
  40916. if( rc==SQLITE_IOERR_SHORT_READ ){
  40917. rc = SQLITE_OK;
  40918. }
  40919. }
  40920. if( pgno==1 ){
  40921. if( rc ){
  40922. /* If the read is unsuccessful, set the dbFileVers[] to something
  40923. ** that will never be a valid file version. dbFileVers[] is a copy
  40924. ** of bytes 24..39 of the database. Bytes 28..31 should always be
  40925. ** zero or the size of the database in page. Bytes 32..35 and 35..39
  40926. ** should be page numbers which are never 0xffffffff. So filling
  40927. ** pPager->dbFileVers[] with all 0xff bytes should suffice.
  40928. **
  40929. ** For an encrypted database, the situation is more complex: bytes
  40930. ** 24..39 of the database are white noise. But the probability of
  40931. ** white noising equaling 16 bytes of 0xff is vanishingly small so
  40932. ** we should still be ok.
  40933. */
  40934. memset(pPager->dbFileVers, 0xff, sizeof(pPager->dbFileVers));
  40935. }else{
  40936. u8 *dbFileVers = &((u8*)pPg->pData)[24];
  40937. memcpy(&pPager->dbFileVers, dbFileVers, sizeof(pPager->dbFileVers));
  40938. }
  40939. }
  40940. CODEC1(pPager, pPg->pData, pgno, 3, rc = SQLITE_NOMEM);
  40941. PAGER_INCR(sqlite3_pager_readdb_count);
  40942. PAGER_INCR(pPager->nRead);
  40943. IOTRACE(("PGIN %p %d\n", pPager, pgno));
  40944. PAGERTRACE(("FETCH %d page %d hash(%08x)\n",
  40945. PAGERID(pPager), pgno, pager_pagehash(pPg)));
  40946. return rc;
  40947. }
  40948. /*
  40949. ** Update the value of the change-counter at offsets 24 and 92 in
  40950. ** the header and the sqlite version number at offset 96.
  40951. **
  40952. ** This is an unconditional update. See also the pager_incr_changecounter()
  40953. ** routine which only updates the change-counter if the update is actually
  40954. ** needed, as determined by the pPager->changeCountDone state variable.
  40955. */
  40956. static void pager_write_changecounter(PgHdr *pPg){
  40957. u32 change_counter;
  40958. /* Increment the value just read and write it back to byte 24. */
  40959. change_counter = sqlite3Get4byte((u8*)pPg->pPager->dbFileVers)+1;
  40960. put32bits(((char*)pPg->pData)+24, change_counter);
  40961. /* Also store the SQLite version number in bytes 96..99 and in
  40962. ** bytes 92..95 store the change counter for which the version number
  40963. ** is valid. */
  40964. put32bits(((char*)pPg->pData)+92, change_counter);
  40965. put32bits(((char*)pPg->pData)+96, SQLITE_VERSION_NUMBER);
  40966. }
  40967. #ifndef SQLITE_OMIT_WAL
  40968. /*
  40969. ** This function is invoked once for each page that has already been
  40970. ** written into the log file when a WAL transaction is rolled back.
  40971. ** Parameter iPg is the page number of said page. The pCtx argument
  40972. ** is actually a pointer to the Pager structure.
  40973. **
  40974. ** If page iPg is present in the cache, and has no outstanding references,
  40975. ** it is discarded. Otherwise, if there are one or more outstanding
  40976. ** references, the page content is reloaded from the database. If the
  40977. ** attempt to reload content from the database is required and fails,
  40978. ** return an SQLite error code. Otherwise, SQLITE_OK.
  40979. */
  40980. static int pagerUndoCallback(void *pCtx, Pgno iPg){
  40981. int rc = SQLITE_OK;
  40982. Pager *pPager = (Pager *)pCtx;
  40983. PgHdr *pPg;
  40984. assert( pagerUseWal(pPager) );
  40985. pPg = sqlite3PagerLookup(pPager, iPg);
  40986. if( pPg ){
  40987. if( sqlite3PcachePageRefcount(pPg)==1 ){
  40988. sqlite3PcacheDrop(pPg);
  40989. }else{
  40990. u32 iFrame = 0;
  40991. rc = sqlite3WalFindFrame(pPager->pWal, pPg->pgno, &iFrame);
  40992. if( rc==SQLITE_OK ){
  40993. rc = readDbPage(pPg, iFrame);
  40994. }
  40995. if( rc==SQLITE_OK ){
  40996. pPager->xReiniter(pPg);
  40997. }
  40998. sqlite3PagerUnrefNotNull(pPg);
  40999. }
  41000. }
  41001. /* Normally, if a transaction is rolled back, any backup processes are
  41002. ** updated as data is copied out of the rollback journal and into the
  41003. ** database. This is not generally possible with a WAL database, as
  41004. ** rollback involves simply truncating the log file. Therefore, if one
  41005. ** or more frames have already been written to the log (and therefore
  41006. ** also copied into the backup databases) as part of this transaction,
  41007. ** the backups must be restarted.
  41008. */
  41009. sqlite3BackupRestart(pPager->pBackup);
  41010. return rc;
  41011. }
  41012. /*
  41013. ** This function is called to rollback a transaction on a WAL database.
  41014. */
  41015. static int pagerRollbackWal(Pager *pPager){
  41016. int rc; /* Return Code */
  41017. PgHdr *pList; /* List of dirty pages to revert */
  41018. /* For all pages in the cache that are currently dirty or have already
  41019. ** been written (but not committed) to the log file, do one of the
  41020. ** following:
  41021. **
  41022. ** + Discard the cached page (if refcount==0), or
  41023. ** + Reload page content from the database (if refcount>0).
  41024. */
  41025. pPager->dbSize = pPager->dbOrigSize;
  41026. rc = sqlite3WalUndo(pPager->pWal, pagerUndoCallback, (void *)pPager);
  41027. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41028. while( pList && rc==SQLITE_OK ){
  41029. PgHdr *pNext = pList->pDirty;
  41030. rc = pagerUndoCallback((void *)pPager, pList->pgno);
  41031. pList = pNext;
  41032. }
  41033. return rc;
  41034. }
  41035. /*
  41036. ** This function is a wrapper around sqlite3WalFrames(). As well as logging
  41037. ** the contents of the list of pages headed by pList (connected by pDirty),
  41038. ** this function notifies any active backup processes that the pages have
  41039. ** changed.
  41040. **
  41041. ** The list of pages passed into this routine is always sorted by page number.
  41042. ** Hence, if page 1 appears anywhere on the list, it will be the first page.
  41043. */
  41044. static int pagerWalFrames(
  41045. Pager *pPager, /* Pager object */
  41046. PgHdr *pList, /* List of frames to log */
  41047. Pgno nTruncate, /* Database size after this commit */
  41048. int isCommit /* True if this is a commit */
  41049. ){
  41050. int rc; /* Return code */
  41051. int nList; /* Number of pages in pList */
  41052. #if defined(SQLITE_DEBUG) || defined(SQLITE_CHECK_PAGES)
  41053. PgHdr *p; /* For looping over pages */
  41054. #endif
  41055. assert( pPager->pWal );
  41056. assert( pList );
  41057. #ifdef SQLITE_DEBUG
  41058. /* Verify that the page list is in accending order */
  41059. for(p=pList; p && p->pDirty; p=p->pDirty){
  41060. assert( p->pgno < p->pDirty->pgno );
  41061. }
  41062. #endif
  41063. assert( pList->pDirty==0 || isCommit );
  41064. if( isCommit ){
  41065. /* If a WAL transaction is being committed, there is no point in writing
  41066. ** any pages with page numbers greater than nTruncate into the WAL file.
  41067. ** They will never be read by any client. So remove them from the pDirty
  41068. ** list here. */
  41069. PgHdr *p;
  41070. PgHdr **ppNext = &pList;
  41071. nList = 0;
  41072. for(p=pList; (*ppNext = p)!=0; p=p->pDirty){
  41073. if( p->pgno<=nTruncate ){
  41074. ppNext = &p->pDirty;
  41075. nList++;
  41076. }
  41077. }
  41078. assert( pList );
  41079. }else{
  41080. nList = 1;
  41081. }
  41082. pPager->aStat[PAGER_STAT_WRITE] += nList;
  41083. if( pList->pgno==1 ) pager_write_changecounter(pList);
  41084. rc = sqlite3WalFrames(pPager->pWal,
  41085. pPager->pageSize, pList, nTruncate, isCommit, pPager->walSyncFlags
  41086. );
  41087. if( rc==SQLITE_OK && pPager->pBackup ){
  41088. PgHdr *p;
  41089. for(p=pList; p; p=p->pDirty){
  41090. sqlite3BackupUpdate(pPager->pBackup, p->pgno, (u8 *)p->pData);
  41091. }
  41092. }
  41093. #ifdef SQLITE_CHECK_PAGES
  41094. pList = sqlite3PcacheDirtyList(pPager->pPCache);
  41095. for(p=pList; p; p=p->pDirty){
  41096. pager_set_pagehash(p);
  41097. }
  41098. #endif
  41099. return rc;
  41100. }
  41101. /*
  41102. ** Begin a read transaction on the WAL.
  41103. **
  41104. ** This routine used to be called "pagerOpenSnapshot()" because it essentially
  41105. ** makes a snapshot of the database at the current point in time and preserves
  41106. ** that snapshot for use by the reader in spite of concurrently changes by
  41107. ** other writers or checkpointers.
  41108. */
  41109. static int pagerBeginReadTransaction(Pager *pPager){
  41110. int rc; /* Return code */
  41111. int changed = 0; /* True if cache must be reset */
  41112. assert( pagerUseWal(pPager) );
  41113. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  41114. /* sqlite3WalEndReadTransaction() was not called for the previous
  41115. ** transaction in locking_mode=EXCLUSIVE. So call it now. If we
  41116. ** are in locking_mode=NORMAL and EndRead() was previously called,
  41117. ** the duplicate call is harmless.
  41118. */
  41119. sqlite3WalEndReadTransaction(pPager->pWal);
  41120. rc = sqlite3WalBeginReadTransaction(pPager->pWal, &changed);
  41121. if( rc!=SQLITE_OK || changed ){
  41122. pager_reset(pPager);
  41123. if( USEFETCH(pPager) ) sqlite3OsUnfetch(pPager->fd, 0, 0);
  41124. }
  41125. return rc;
  41126. }
  41127. #endif
  41128. /*
  41129. ** This function is called as part of the transition from PAGER_OPEN
  41130. ** to PAGER_READER state to determine the size of the database file
  41131. ** in pages (assuming the page size currently stored in Pager.pageSize).
  41132. **
  41133. ** If no error occurs, SQLITE_OK is returned and the size of the database
  41134. ** in pages is stored in *pnPage. Otherwise, an error code (perhaps
  41135. ** SQLITE_IOERR_FSTAT) is returned and *pnPage is left unmodified.
  41136. */
  41137. static int pagerPagecount(Pager *pPager, Pgno *pnPage){
  41138. Pgno nPage; /* Value to return via *pnPage */
  41139. /* Query the WAL sub-system for the database size. The WalDbsize()
  41140. ** function returns zero if the WAL is not open (i.e. Pager.pWal==0), or
  41141. ** if the database size is not available. The database size is not
  41142. ** available from the WAL sub-system if the log file is empty or
  41143. ** contains no valid committed transactions.
  41144. */
  41145. assert( pPager->eState==PAGER_OPEN );
  41146. assert( pPager->eLock>=SHARED_LOCK );
  41147. nPage = sqlite3WalDbsize(pPager->pWal);
  41148. /* If the database size was not available from the WAL sub-system,
  41149. ** determine it based on the size of the database file. If the size
  41150. ** of the database file is not an integer multiple of the page-size,
  41151. ** round down to the nearest page. Except, any file larger than 0
  41152. ** bytes in size is considered to contain at least one page.
  41153. */
  41154. if( nPage==0 ){
  41155. i64 n = 0; /* Size of db file in bytes */
  41156. assert( isOpen(pPager->fd) || pPager->tempFile );
  41157. if( isOpen(pPager->fd) ){
  41158. int rc = sqlite3OsFileSize(pPager->fd, &n);
  41159. if( rc!=SQLITE_OK ){
  41160. return rc;
  41161. }
  41162. }
  41163. nPage = (Pgno)((n+pPager->pageSize-1) / pPager->pageSize);
  41164. }
  41165. /* If the current number of pages in the file is greater than the
  41166. ** configured maximum pager number, increase the allowed limit so
  41167. ** that the file can be read.
  41168. */
  41169. if( nPage>pPager->mxPgno ){
  41170. pPager->mxPgno = (Pgno)nPage;
  41171. }
  41172. *pnPage = nPage;
  41173. return SQLITE_OK;
  41174. }
  41175. #ifndef SQLITE_OMIT_WAL
  41176. /*
  41177. ** Check if the *-wal file that corresponds to the database opened by pPager
  41178. ** exists if the database is not empy, or verify that the *-wal file does
  41179. ** not exist (by deleting it) if the database file is empty.
  41180. **
  41181. ** If the database is not empty and the *-wal file exists, open the pager
  41182. ** in WAL mode. If the database is empty or if no *-wal file exists and
  41183. ** if no error occurs, make sure Pager.journalMode is not set to
  41184. ** PAGER_JOURNALMODE_WAL.
  41185. **
  41186. ** Return SQLITE_OK or an error code.
  41187. **
  41188. ** The caller must hold a SHARED lock on the database file to call this
  41189. ** function. Because an EXCLUSIVE lock on the db file is required to delete
  41190. ** a WAL on a none-empty database, this ensures there is no race condition
  41191. ** between the xAccess() below and an xDelete() being executed by some
  41192. ** other connection.
  41193. */
  41194. static int pagerOpenWalIfPresent(Pager *pPager){
  41195. int rc = SQLITE_OK;
  41196. assert( pPager->eState==PAGER_OPEN );
  41197. assert( pPager->eLock>=SHARED_LOCK );
  41198. if( !pPager->tempFile ){
  41199. int isWal; /* True if WAL file exists */
  41200. Pgno nPage; /* Size of the database file */
  41201. rc = pagerPagecount(pPager, &nPage);
  41202. if( rc ) return rc;
  41203. if( nPage==0 ){
  41204. rc = sqlite3OsDelete(pPager->pVfs, pPager->zWal, 0);
  41205. if( rc==SQLITE_IOERR_DELETE_NOENT ) rc = SQLITE_OK;
  41206. isWal = 0;
  41207. }else{
  41208. rc = sqlite3OsAccess(
  41209. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &isWal
  41210. );
  41211. }
  41212. if( rc==SQLITE_OK ){
  41213. if( isWal ){
  41214. testcase( sqlite3PcachePagecount(pPager->pPCache)==0 );
  41215. rc = sqlite3PagerOpenWal(pPager, 0);
  41216. }else if( pPager->journalMode==PAGER_JOURNALMODE_WAL ){
  41217. pPager->journalMode = PAGER_JOURNALMODE_DELETE;
  41218. }
  41219. }
  41220. }
  41221. return rc;
  41222. }
  41223. #endif
  41224. /*
  41225. ** Playback savepoint pSavepoint. Or, if pSavepoint==NULL, then playback
  41226. ** the entire master journal file. The case pSavepoint==NULL occurs when
  41227. ** a ROLLBACK TO command is invoked on a SAVEPOINT that is a transaction
  41228. ** savepoint.
  41229. **
  41230. ** When pSavepoint is not NULL (meaning a non-transaction savepoint is
  41231. ** being rolled back), then the rollback consists of up to three stages,
  41232. ** performed in the order specified:
  41233. **
  41234. ** * Pages are played back from the main journal starting at byte
  41235. ** offset PagerSavepoint.iOffset and continuing to
  41236. ** PagerSavepoint.iHdrOffset, or to the end of the main journal
  41237. ** file if PagerSavepoint.iHdrOffset is zero.
  41238. **
  41239. ** * If PagerSavepoint.iHdrOffset is not zero, then pages are played
  41240. ** back starting from the journal header immediately following
  41241. ** PagerSavepoint.iHdrOffset to the end of the main journal file.
  41242. **
  41243. ** * Pages are then played back from the sub-journal file, starting
  41244. ** with the PagerSavepoint.iSubRec and continuing to the end of
  41245. ** the journal file.
  41246. **
  41247. ** Throughout the rollback process, each time a page is rolled back, the
  41248. ** corresponding bit is set in a bitvec structure (variable pDone in the
  41249. ** implementation below). This is used to ensure that a page is only
  41250. ** rolled back the first time it is encountered in either journal.
  41251. **
  41252. ** If pSavepoint is NULL, then pages are only played back from the main
  41253. ** journal file. There is no need for a bitvec in this case.
  41254. **
  41255. ** In either case, before playback commences the Pager.dbSize variable
  41256. ** is reset to the value that it held at the start of the savepoint
  41257. ** (or transaction). No page with a page-number greater than this value
  41258. ** is played back. If one is encountered it is simply skipped.
  41259. */
  41260. static int pagerPlaybackSavepoint(Pager *pPager, PagerSavepoint *pSavepoint){
  41261. i64 szJ; /* Effective size of the main journal */
  41262. i64 iHdrOff; /* End of first segment of main-journal records */
  41263. int rc = SQLITE_OK; /* Return code */
  41264. Bitvec *pDone = 0; /* Bitvec to ensure pages played back only once */
  41265. assert( pPager->eState!=PAGER_ERROR );
  41266. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  41267. /* Allocate a bitvec to use to store the set of pages rolled back */
  41268. if( pSavepoint ){
  41269. pDone = sqlite3BitvecCreate(pSavepoint->nOrig);
  41270. if( !pDone ){
  41271. return SQLITE_NOMEM;
  41272. }
  41273. }
  41274. /* Set the database size back to the value it was before the savepoint
  41275. ** being reverted was opened.
  41276. */
  41277. pPager->dbSize = pSavepoint ? pSavepoint->nOrig : pPager->dbOrigSize;
  41278. pPager->changeCountDone = pPager->tempFile;
  41279. if( !pSavepoint && pagerUseWal(pPager) ){
  41280. return pagerRollbackWal(pPager);
  41281. }
  41282. /* Use pPager->journalOff as the effective size of the main rollback
  41283. ** journal. The actual file might be larger than this in
  41284. ** PAGER_JOURNALMODE_TRUNCATE or PAGER_JOURNALMODE_PERSIST. But anything
  41285. ** past pPager->journalOff is off-limits to us.
  41286. */
  41287. szJ = pPager->journalOff;
  41288. assert( pagerUseWal(pPager)==0 || szJ==0 );
  41289. /* Begin by rolling back records from the main journal starting at
  41290. ** PagerSavepoint.iOffset and continuing to the next journal header.
  41291. ** There might be records in the main journal that have a page number
  41292. ** greater than the current database size (pPager->dbSize) but those
  41293. ** will be skipped automatically. Pages are added to pDone as they
  41294. ** are played back.
  41295. */
  41296. if( pSavepoint && !pagerUseWal(pPager) ){
  41297. iHdrOff = pSavepoint->iHdrOffset ? pSavepoint->iHdrOffset : szJ;
  41298. pPager->journalOff = pSavepoint->iOffset;
  41299. while( rc==SQLITE_OK && pPager->journalOff<iHdrOff ){
  41300. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  41301. }
  41302. assert( rc!=SQLITE_DONE );
  41303. }else{
  41304. pPager->journalOff = 0;
  41305. }
  41306. /* Continue rolling back records out of the main journal starting at
  41307. ** the first journal header seen and continuing until the effective end
  41308. ** of the main journal file. Continue to skip out-of-range pages and
  41309. ** continue adding pages rolled back to pDone.
  41310. */
  41311. while( rc==SQLITE_OK && pPager->journalOff<szJ ){
  41312. u32 ii; /* Loop counter */
  41313. u32 nJRec = 0; /* Number of Journal Records */
  41314. u32 dummy;
  41315. rc = readJournalHdr(pPager, 0, szJ, &nJRec, &dummy);
  41316. assert( rc!=SQLITE_DONE );
  41317. /*
  41318. ** The "pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff"
  41319. ** test is related to ticket #2565. See the discussion in the
  41320. ** pager_playback() function for additional information.
  41321. */
  41322. if( nJRec==0
  41323. && pPager->journalHdr+JOURNAL_HDR_SZ(pPager)==pPager->journalOff
  41324. ){
  41325. nJRec = (u32)((szJ - pPager->journalOff)/JOURNAL_PG_SZ(pPager));
  41326. }
  41327. for(ii=0; rc==SQLITE_OK && ii<nJRec && pPager->journalOff<szJ; ii++){
  41328. rc = pager_playback_one_page(pPager, &pPager->journalOff, pDone, 1, 1);
  41329. }
  41330. assert( rc!=SQLITE_DONE );
  41331. }
  41332. assert( rc!=SQLITE_OK || pPager->journalOff>=szJ );
  41333. /* Finally, rollback pages from the sub-journal. Page that were
  41334. ** previously rolled back out of the main journal (and are hence in pDone)
  41335. ** will be skipped. Out-of-range pages are also skipped.
  41336. */
  41337. if( pSavepoint ){
  41338. u32 ii; /* Loop counter */
  41339. i64 offset = (i64)pSavepoint->iSubRec*(4+pPager->pageSize);
  41340. if( pagerUseWal(pPager) ){
  41341. rc = sqlite3WalSavepointUndo(pPager->pWal, pSavepoint->aWalData);
  41342. }
  41343. for(ii=pSavepoint->iSubRec; rc==SQLITE_OK && ii<pPager->nSubRec; ii++){
  41344. assert( offset==(i64)ii*(4+pPager->pageSize) );
  41345. rc = pager_playback_one_page(pPager, &offset, pDone, 0, 1);
  41346. }
  41347. assert( rc!=SQLITE_DONE );
  41348. }
  41349. sqlite3BitvecDestroy(pDone);
  41350. if( rc==SQLITE_OK ){
  41351. pPager->journalOff = szJ;
  41352. }
  41353. return rc;
  41354. }
  41355. /*
  41356. ** Change the maximum number of in-memory pages that are allowed.
  41357. */
  41358. SQLITE_PRIVATE void sqlite3PagerSetCachesize(Pager *pPager, int mxPage){
  41359. sqlite3PcacheSetCachesize(pPager->pPCache, mxPage);
  41360. }
  41361. /*
  41362. ** Invoke SQLITE_FCNTL_MMAP_SIZE based on the current value of szMmap.
  41363. */
  41364. static void pagerFixMaplimit(Pager *pPager){
  41365. #if SQLITE_MAX_MMAP_SIZE>0
  41366. sqlite3_file *fd = pPager->fd;
  41367. if( isOpen(fd) && fd->pMethods->iVersion>=3 ){
  41368. sqlite3_int64 sz;
  41369. sz = pPager->szMmap;
  41370. pPager->bUseFetch = (sz>0);
  41371. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_MMAP_SIZE, &sz);
  41372. }
  41373. #endif
  41374. }
  41375. /*
  41376. ** Change the maximum size of any memory mapping made of the database file.
  41377. */
  41378. SQLITE_PRIVATE void sqlite3PagerSetMmapLimit(Pager *pPager, sqlite3_int64 szMmap){
  41379. pPager->szMmap = szMmap;
  41380. pagerFixMaplimit(pPager);
  41381. }
  41382. /*
  41383. ** Free as much memory as possible from the pager.
  41384. */
  41385. SQLITE_PRIVATE void sqlite3PagerShrink(Pager *pPager){
  41386. sqlite3PcacheShrink(pPager->pPCache);
  41387. }
  41388. /*
  41389. ** Adjust settings of the pager to those specified in the pgFlags parameter.
  41390. **
  41391. ** The "level" in pgFlags & PAGER_SYNCHRONOUS_MASK sets the robustness
  41392. ** of the database to damage due to OS crashes or power failures by
  41393. ** changing the number of syncs()s when writing the journals.
  41394. ** There are three levels:
  41395. **
  41396. ** OFF sqlite3OsSync() is never called. This is the default
  41397. ** for temporary and transient files.
  41398. **
  41399. ** NORMAL The journal is synced once before writes begin on the
  41400. ** database. This is normally adequate protection, but
  41401. ** it is theoretically possible, though very unlikely,
  41402. ** that an inopertune power failure could leave the journal
  41403. ** in a state which would cause damage to the database
  41404. ** when it is rolled back.
  41405. **
  41406. ** FULL The journal is synced twice before writes begin on the
  41407. ** database (with some additional information - the nRec field
  41408. ** of the journal header - being written in between the two
  41409. ** syncs). If we assume that writing a
  41410. ** single disk sector is atomic, then this mode provides
  41411. ** assurance that the journal will not be corrupted to the
  41412. ** point of causing damage to the database during rollback.
  41413. **
  41414. ** The above is for a rollback-journal mode. For WAL mode, OFF continues
  41415. ** to mean that no syncs ever occur. NORMAL means that the WAL is synced
  41416. ** prior to the start of checkpoint and that the database file is synced
  41417. ** at the conclusion of the checkpoint if the entire content of the WAL
  41418. ** was written back into the database. But no sync operations occur for
  41419. ** an ordinary commit in NORMAL mode with WAL. FULL means that the WAL
  41420. ** file is synced following each commit operation, in addition to the
  41421. ** syncs associated with NORMAL.
  41422. **
  41423. ** Do not confuse synchronous=FULL with SQLITE_SYNC_FULL. The
  41424. ** SQLITE_SYNC_FULL macro means to use the MacOSX-style full-fsync
  41425. ** using fcntl(F_FULLFSYNC). SQLITE_SYNC_NORMAL means to do an
  41426. ** ordinary fsync() call. There is no difference between SQLITE_SYNC_FULL
  41427. ** and SQLITE_SYNC_NORMAL on platforms other than MacOSX. But the
  41428. ** synchronous=FULL versus synchronous=NORMAL setting determines when
  41429. ** the xSync primitive is called and is relevant to all platforms.
  41430. **
  41431. ** Numeric values associated with these states are OFF==1, NORMAL=2,
  41432. ** and FULL=3.
  41433. */
  41434. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  41435. SQLITE_PRIVATE void sqlite3PagerSetFlags(
  41436. Pager *pPager, /* The pager to set safety level for */
  41437. unsigned pgFlags /* Various flags */
  41438. ){
  41439. unsigned level = pgFlags & PAGER_SYNCHRONOUS_MASK;
  41440. assert( level>=1 && level<=3 );
  41441. pPager->noSync = (level==1 || pPager->tempFile) ?1:0;
  41442. pPager->fullSync = (level==3 && !pPager->tempFile) ?1:0;
  41443. if( pPager->noSync ){
  41444. pPager->syncFlags = 0;
  41445. pPager->ckptSyncFlags = 0;
  41446. }else if( pgFlags & PAGER_FULLFSYNC ){
  41447. pPager->syncFlags = SQLITE_SYNC_FULL;
  41448. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  41449. }else if( pgFlags & PAGER_CKPT_FULLFSYNC ){
  41450. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  41451. pPager->ckptSyncFlags = SQLITE_SYNC_FULL;
  41452. }else{
  41453. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  41454. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  41455. }
  41456. pPager->walSyncFlags = pPager->syncFlags;
  41457. if( pPager->fullSync ){
  41458. pPager->walSyncFlags |= WAL_SYNC_TRANSACTIONS;
  41459. }
  41460. if( pgFlags & PAGER_CACHESPILL ){
  41461. pPager->doNotSpill &= ~SPILLFLAG_OFF;
  41462. }else{
  41463. pPager->doNotSpill |= SPILLFLAG_OFF;
  41464. }
  41465. }
  41466. #endif
  41467. /*
  41468. ** The following global variable is incremented whenever the library
  41469. ** attempts to open a temporary file. This information is used for
  41470. ** testing and analysis only.
  41471. */
  41472. #ifdef SQLITE_TEST
  41473. SQLITE_API int sqlite3_opentemp_count = 0;
  41474. #endif
  41475. /*
  41476. ** Open a temporary file.
  41477. **
  41478. ** Write the file descriptor into *pFile. Return SQLITE_OK on success
  41479. ** or some other error code if we fail. The OS will automatically
  41480. ** delete the temporary file when it is closed.
  41481. **
  41482. ** The flags passed to the VFS layer xOpen() call are those specified
  41483. ** by parameter vfsFlags ORed with the following:
  41484. **
  41485. ** SQLITE_OPEN_READWRITE
  41486. ** SQLITE_OPEN_CREATE
  41487. ** SQLITE_OPEN_EXCLUSIVE
  41488. ** SQLITE_OPEN_DELETEONCLOSE
  41489. */
  41490. static int pagerOpentemp(
  41491. Pager *pPager, /* The pager object */
  41492. sqlite3_file *pFile, /* Write the file descriptor here */
  41493. int vfsFlags /* Flags passed through to the VFS */
  41494. ){
  41495. int rc; /* Return code */
  41496. #ifdef SQLITE_TEST
  41497. sqlite3_opentemp_count++; /* Used for testing and analysis only */
  41498. #endif
  41499. vfsFlags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  41500. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE;
  41501. rc = sqlite3OsOpen(pPager->pVfs, 0, pFile, vfsFlags, 0);
  41502. assert( rc!=SQLITE_OK || isOpen(pFile) );
  41503. return rc;
  41504. }
  41505. /*
  41506. ** Set the busy handler function.
  41507. **
  41508. ** The pager invokes the busy-handler if sqlite3OsLock() returns
  41509. ** SQLITE_BUSY when trying to upgrade from no-lock to a SHARED lock,
  41510. ** or when trying to upgrade from a RESERVED lock to an EXCLUSIVE
  41511. ** lock. It does *not* invoke the busy handler when upgrading from
  41512. ** SHARED to RESERVED, or when upgrading from SHARED to EXCLUSIVE
  41513. ** (which occurs during hot-journal rollback). Summary:
  41514. **
  41515. ** Transition | Invokes xBusyHandler
  41516. ** --------------------------------------------------------
  41517. ** NO_LOCK -> SHARED_LOCK | Yes
  41518. ** SHARED_LOCK -> RESERVED_LOCK | No
  41519. ** SHARED_LOCK -> EXCLUSIVE_LOCK | No
  41520. ** RESERVED_LOCK -> EXCLUSIVE_LOCK | Yes
  41521. **
  41522. ** If the busy-handler callback returns non-zero, the lock is
  41523. ** retried. If it returns zero, then the SQLITE_BUSY error is
  41524. ** returned to the caller of the pager API function.
  41525. */
  41526. SQLITE_PRIVATE void sqlite3PagerSetBusyhandler(
  41527. Pager *pPager, /* Pager object */
  41528. int (*xBusyHandler)(void *), /* Pointer to busy-handler function */
  41529. void *pBusyHandlerArg /* Argument to pass to xBusyHandler */
  41530. ){
  41531. pPager->xBusyHandler = xBusyHandler;
  41532. pPager->pBusyHandlerArg = pBusyHandlerArg;
  41533. if( isOpen(pPager->fd) ){
  41534. void **ap = (void **)&pPager->xBusyHandler;
  41535. assert( ((int(*)(void *))(ap[0]))==xBusyHandler );
  41536. assert( ap[1]==pBusyHandlerArg );
  41537. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_BUSYHANDLER, (void *)ap);
  41538. }
  41539. }
  41540. /*
  41541. ** Change the page size used by the Pager object. The new page size
  41542. ** is passed in *pPageSize.
  41543. **
  41544. ** If the pager is in the error state when this function is called, it
  41545. ** is a no-op. The value returned is the error state error code (i.e.
  41546. ** one of SQLITE_IOERR, an SQLITE_IOERR_xxx sub-code or SQLITE_FULL).
  41547. **
  41548. ** Otherwise, if all of the following are true:
  41549. **
  41550. ** * the new page size (value of *pPageSize) is valid (a power
  41551. ** of two between 512 and SQLITE_MAX_PAGE_SIZE, inclusive), and
  41552. **
  41553. ** * there are no outstanding page references, and
  41554. **
  41555. ** * the database is either not an in-memory database or it is
  41556. ** an in-memory database that currently consists of zero pages.
  41557. **
  41558. ** then the pager object page size is set to *pPageSize.
  41559. **
  41560. ** If the page size is changed, then this function uses sqlite3PagerMalloc()
  41561. ** to obtain a new Pager.pTmpSpace buffer. If this allocation attempt
  41562. ** fails, SQLITE_NOMEM is returned and the page size remains unchanged.
  41563. ** In all other cases, SQLITE_OK is returned.
  41564. **
  41565. ** If the page size is not changed, either because one of the enumerated
  41566. ** conditions above is not true, the pager was in error state when this
  41567. ** function was called, or because the memory allocation attempt failed,
  41568. ** then *pPageSize is set to the old, retained page size before returning.
  41569. */
  41570. SQLITE_PRIVATE int sqlite3PagerSetPagesize(Pager *pPager, u32 *pPageSize, int nReserve){
  41571. int rc = SQLITE_OK;
  41572. /* It is not possible to do a full assert_pager_state() here, as this
  41573. ** function may be called from within PagerOpen(), before the state
  41574. ** of the Pager object is internally consistent.
  41575. **
  41576. ** At one point this function returned an error if the pager was in
  41577. ** PAGER_ERROR state. But since PAGER_ERROR state guarantees that
  41578. ** there is at least one outstanding page reference, this function
  41579. ** is a no-op for that case anyhow.
  41580. */
  41581. u32 pageSize = *pPageSize;
  41582. assert( pageSize==0 || (pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE) );
  41583. if( (pPager->memDb==0 || pPager->dbSize==0)
  41584. && sqlite3PcacheRefCount(pPager->pPCache)==0
  41585. && pageSize && pageSize!=(u32)pPager->pageSize
  41586. ){
  41587. char *pNew = NULL; /* New temp space */
  41588. i64 nByte = 0;
  41589. if( pPager->eState>PAGER_OPEN && isOpen(pPager->fd) ){
  41590. rc = sqlite3OsFileSize(pPager->fd, &nByte);
  41591. }
  41592. if( rc==SQLITE_OK ){
  41593. pNew = (char *)sqlite3PageMalloc(pageSize);
  41594. if( !pNew ) rc = SQLITE_NOMEM;
  41595. }
  41596. if( rc==SQLITE_OK ){
  41597. pager_reset(pPager);
  41598. rc = sqlite3PcacheSetPageSize(pPager->pPCache, pageSize);
  41599. }
  41600. if( rc==SQLITE_OK ){
  41601. sqlite3PageFree(pPager->pTmpSpace);
  41602. pPager->pTmpSpace = pNew;
  41603. pPager->dbSize = (Pgno)((nByte+pageSize-1)/pageSize);
  41604. pPager->pageSize = pageSize;
  41605. }else{
  41606. sqlite3PageFree(pNew);
  41607. }
  41608. }
  41609. *pPageSize = pPager->pageSize;
  41610. if( rc==SQLITE_OK ){
  41611. if( nReserve<0 ) nReserve = pPager->nReserve;
  41612. assert( nReserve>=0 && nReserve<1000 );
  41613. pPager->nReserve = (i16)nReserve;
  41614. pagerReportSize(pPager);
  41615. pagerFixMaplimit(pPager);
  41616. }
  41617. return rc;
  41618. }
  41619. /*
  41620. ** Return a pointer to the "temporary page" buffer held internally
  41621. ** by the pager. This is a buffer that is big enough to hold the
  41622. ** entire content of a database page. This buffer is used internally
  41623. ** during rollback and will be overwritten whenever a rollback
  41624. ** occurs. But other modules are free to use it too, as long as
  41625. ** no rollbacks are happening.
  41626. */
  41627. SQLITE_PRIVATE void *sqlite3PagerTempSpace(Pager *pPager){
  41628. return pPager->pTmpSpace;
  41629. }
  41630. /*
  41631. ** Attempt to set the maximum database page count if mxPage is positive.
  41632. ** Make no changes if mxPage is zero or negative. And never reduce the
  41633. ** maximum page count below the current size of the database.
  41634. **
  41635. ** Regardless of mxPage, return the current maximum page count.
  41636. */
  41637. SQLITE_PRIVATE int sqlite3PagerMaxPageCount(Pager *pPager, int mxPage){
  41638. if( mxPage>0 ){
  41639. pPager->mxPgno = mxPage;
  41640. }
  41641. assert( pPager->eState!=PAGER_OPEN ); /* Called only by OP_MaxPgcnt */
  41642. assert( pPager->mxPgno>=pPager->dbSize ); /* OP_MaxPgcnt enforces this */
  41643. return pPager->mxPgno;
  41644. }
  41645. /*
  41646. ** The following set of routines are used to disable the simulated
  41647. ** I/O error mechanism. These routines are used to avoid simulated
  41648. ** errors in places where we do not care about errors.
  41649. **
  41650. ** Unless -DSQLITE_TEST=1 is used, these routines are all no-ops
  41651. ** and generate no code.
  41652. */
  41653. #ifdef SQLITE_TEST
  41654. SQLITE_API extern int sqlite3_io_error_pending;
  41655. SQLITE_API extern int sqlite3_io_error_hit;
  41656. static int saved_cnt;
  41657. void disable_simulated_io_errors(void){
  41658. saved_cnt = sqlite3_io_error_pending;
  41659. sqlite3_io_error_pending = -1;
  41660. }
  41661. void enable_simulated_io_errors(void){
  41662. sqlite3_io_error_pending = saved_cnt;
  41663. }
  41664. #else
  41665. # define disable_simulated_io_errors()
  41666. # define enable_simulated_io_errors()
  41667. #endif
  41668. /*
  41669. ** Read the first N bytes from the beginning of the file into memory
  41670. ** that pDest points to.
  41671. **
  41672. ** If the pager was opened on a transient file (zFilename==""), or
  41673. ** opened on a file less than N bytes in size, the output buffer is
  41674. ** zeroed and SQLITE_OK returned. The rationale for this is that this
  41675. ** function is used to read database headers, and a new transient or
  41676. ** zero sized database has a header than consists entirely of zeroes.
  41677. **
  41678. ** If any IO error apart from SQLITE_IOERR_SHORT_READ is encountered,
  41679. ** the error code is returned to the caller and the contents of the
  41680. ** output buffer undefined.
  41681. */
  41682. SQLITE_PRIVATE int sqlite3PagerReadFileheader(Pager *pPager, int N, unsigned char *pDest){
  41683. int rc = SQLITE_OK;
  41684. memset(pDest, 0, N);
  41685. assert( isOpen(pPager->fd) || pPager->tempFile );
  41686. /* This routine is only called by btree immediately after creating
  41687. ** the Pager object. There has not been an opportunity to transition
  41688. ** to WAL mode yet.
  41689. */
  41690. assert( !pagerUseWal(pPager) );
  41691. if( isOpen(pPager->fd) ){
  41692. IOTRACE(("DBHDR %p 0 %d\n", pPager, N))
  41693. rc = sqlite3OsRead(pPager->fd, pDest, N, 0);
  41694. if( rc==SQLITE_IOERR_SHORT_READ ){
  41695. rc = SQLITE_OK;
  41696. }
  41697. }
  41698. return rc;
  41699. }
  41700. /*
  41701. ** This function may only be called when a read-transaction is open on
  41702. ** the pager. It returns the total number of pages in the database.
  41703. **
  41704. ** However, if the file is between 1 and <page-size> bytes in size, then
  41705. ** this is considered a 1 page file.
  41706. */
  41707. SQLITE_PRIVATE void sqlite3PagerPagecount(Pager *pPager, int *pnPage){
  41708. assert( pPager->eState>=PAGER_READER );
  41709. assert( pPager->eState!=PAGER_WRITER_FINISHED );
  41710. *pnPage = (int)pPager->dbSize;
  41711. }
  41712. /*
  41713. ** Try to obtain a lock of type locktype on the database file. If
  41714. ** a similar or greater lock is already held, this function is a no-op
  41715. ** (returning SQLITE_OK immediately).
  41716. **
  41717. ** Otherwise, attempt to obtain the lock using sqlite3OsLock(). Invoke
  41718. ** the busy callback if the lock is currently not available. Repeat
  41719. ** until the busy callback returns false or until the attempt to
  41720. ** obtain the lock succeeds.
  41721. **
  41722. ** Return SQLITE_OK on success and an error code if we cannot obtain
  41723. ** the lock. If the lock is obtained successfully, set the Pager.state
  41724. ** variable to locktype before returning.
  41725. */
  41726. static int pager_wait_on_lock(Pager *pPager, int locktype){
  41727. int rc; /* Return code */
  41728. /* Check that this is either a no-op (because the requested lock is
  41729. ** already held), or one of the transitions that the busy-handler
  41730. ** may be invoked during, according to the comment above
  41731. ** sqlite3PagerSetBusyhandler().
  41732. */
  41733. assert( (pPager->eLock>=locktype)
  41734. || (pPager->eLock==NO_LOCK && locktype==SHARED_LOCK)
  41735. || (pPager->eLock==RESERVED_LOCK && locktype==EXCLUSIVE_LOCK)
  41736. );
  41737. do {
  41738. rc = pagerLockDb(pPager, locktype);
  41739. }while( rc==SQLITE_BUSY && pPager->xBusyHandler(pPager->pBusyHandlerArg) );
  41740. return rc;
  41741. }
  41742. /*
  41743. ** Function assertTruncateConstraint(pPager) checks that one of the
  41744. ** following is true for all dirty pages currently in the page-cache:
  41745. **
  41746. ** a) The page number is less than or equal to the size of the
  41747. ** current database image, in pages, OR
  41748. **
  41749. ** b) if the page content were written at this time, it would not
  41750. ** be necessary to write the current content out to the sub-journal
  41751. ** (as determined by function subjRequiresPage()).
  41752. **
  41753. ** If the condition asserted by this function were not true, and the
  41754. ** dirty page were to be discarded from the cache via the pagerStress()
  41755. ** routine, pagerStress() would not write the current page content to
  41756. ** the database file. If a savepoint transaction were rolled back after
  41757. ** this happened, the correct behavior would be to restore the current
  41758. ** content of the page. However, since this content is not present in either
  41759. ** the database file or the portion of the rollback journal and
  41760. ** sub-journal rolled back the content could not be restored and the
  41761. ** database image would become corrupt. It is therefore fortunate that
  41762. ** this circumstance cannot arise.
  41763. */
  41764. #if defined(SQLITE_DEBUG)
  41765. static void assertTruncateConstraintCb(PgHdr *pPg){
  41766. assert( pPg->flags&PGHDR_DIRTY );
  41767. assert( !subjRequiresPage(pPg) || pPg->pgno<=pPg->pPager->dbSize );
  41768. }
  41769. static void assertTruncateConstraint(Pager *pPager){
  41770. sqlite3PcacheIterateDirty(pPager->pPCache, assertTruncateConstraintCb);
  41771. }
  41772. #else
  41773. # define assertTruncateConstraint(pPager)
  41774. #endif
  41775. /*
  41776. ** Truncate the in-memory database file image to nPage pages. This
  41777. ** function does not actually modify the database file on disk. It
  41778. ** just sets the internal state of the pager object so that the
  41779. ** truncation will be done when the current transaction is committed.
  41780. **
  41781. ** This function is only called right before committing a transaction.
  41782. ** Once this function has been called, the transaction must either be
  41783. ** rolled back or committed. It is not safe to call this function and
  41784. ** then continue writing to the database.
  41785. */
  41786. SQLITE_PRIVATE void sqlite3PagerTruncateImage(Pager *pPager, Pgno nPage){
  41787. assert( pPager->dbSize>=nPage );
  41788. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  41789. pPager->dbSize = nPage;
  41790. /* At one point the code here called assertTruncateConstraint() to
  41791. ** ensure that all pages being truncated away by this operation are,
  41792. ** if one or more savepoints are open, present in the savepoint
  41793. ** journal so that they can be restored if the savepoint is rolled
  41794. ** back. This is no longer necessary as this function is now only
  41795. ** called right before committing a transaction. So although the
  41796. ** Pager object may still have open savepoints (Pager.nSavepoint!=0),
  41797. ** they cannot be rolled back. So the assertTruncateConstraint() call
  41798. ** is no longer correct. */
  41799. }
  41800. /*
  41801. ** This function is called before attempting a hot-journal rollback. It
  41802. ** syncs the journal file to disk, then sets pPager->journalHdr to the
  41803. ** size of the journal file so that the pager_playback() routine knows
  41804. ** that the entire journal file has been synced.
  41805. **
  41806. ** Syncing a hot-journal to disk before attempting to roll it back ensures
  41807. ** that if a power-failure occurs during the rollback, the process that
  41808. ** attempts rollback following system recovery sees the same journal
  41809. ** content as this process.
  41810. **
  41811. ** If everything goes as planned, SQLITE_OK is returned. Otherwise,
  41812. ** an SQLite error code.
  41813. */
  41814. static int pagerSyncHotJournal(Pager *pPager){
  41815. int rc = SQLITE_OK;
  41816. if( !pPager->noSync ){
  41817. rc = sqlite3OsSync(pPager->jfd, SQLITE_SYNC_NORMAL);
  41818. }
  41819. if( rc==SQLITE_OK ){
  41820. rc = sqlite3OsFileSize(pPager->jfd, &pPager->journalHdr);
  41821. }
  41822. return rc;
  41823. }
  41824. /*
  41825. ** Obtain a reference to a memory mapped page object for page number pgno.
  41826. ** The new object will use the pointer pData, obtained from xFetch().
  41827. ** If successful, set *ppPage to point to the new page reference
  41828. ** and return SQLITE_OK. Otherwise, return an SQLite error code and set
  41829. ** *ppPage to zero.
  41830. **
  41831. ** Page references obtained by calling this function should be released
  41832. ** by calling pagerReleaseMapPage().
  41833. */
  41834. static int pagerAcquireMapPage(
  41835. Pager *pPager, /* Pager object */
  41836. Pgno pgno, /* Page number */
  41837. void *pData, /* xFetch()'d data for this page */
  41838. PgHdr **ppPage /* OUT: Acquired page object */
  41839. ){
  41840. PgHdr *p; /* Memory mapped page to return */
  41841. if( pPager->pMmapFreelist ){
  41842. *ppPage = p = pPager->pMmapFreelist;
  41843. pPager->pMmapFreelist = p->pDirty;
  41844. p->pDirty = 0;
  41845. memset(p->pExtra, 0, pPager->nExtra);
  41846. }else{
  41847. *ppPage = p = (PgHdr *)sqlite3MallocZero(sizeof(PgHdr) + pPager->nExtra);
  41848. if( p==0 ){
  41849. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1) * pPager->pageSize, pData);
  41850. return SQLITE_NOMEM;
  41851. }
  41852. p->pExtra = (void *)&p[1];
  41853. p->flags = PGHDR_MMAP;
  41854. p->nRef = 1;
  41855. p->pPager = pPager;
  41856. }
  41857. assert( p->pExtra==(void *)&p[1] );
  41858. assert( p->pPage==0 );
  41859. assert( p->flags==PGHDR_MMAP );
  41860. assert( p->pPager==pPager );
  41861. assert( p->nRef==1 );
  41862. p->pgno = pgno;
  41863. p->pData = pData;
  41864. pPager->nMmapOut++;
  41865. return SQLITE_OK;
  41866. }
  41867. /*
  41868. ** Release a reference to page pPg. pPg must have been returned by an
  41869. ** earlier call to pagerAcquireMapPage().
  41870. */
  41871. static void pagerReleaseMapPage(PgHdr *pPg){
  41872. Pager *pPager = pPg->pPager;
  41873. pPager->nMmapOut--;
  41874. pPg->pDirty = pPager->pMmapFreelist;
  41875. pPager->pMmapFreelist = pPg;
  41876. assert( pPager->fd->pMethods->iVersion>=3 );
  41877. sqlite3OsUnfetch(pPager->fd, (i64)(pPg->pgno-1)*pPager->pageSize, pPg->pData);
  41878. }
  41879. /*
  41880. ** Free all PgHdr objects stored in the Pager.pMmapFreelist list.
  41881. */
  41882. static void pagerFreeMapHdrs(Pager *pPager){
  41883. PgHdr *p;
  41884. PgHdr *pNext;
  41885. for(p=pPager->pMmapFreelist; p; p=pNext){
  41886. pNext = p->pDirty;
  41887. sqlite3_free(p);
  41888. }
  41889. }
  41890. /*
  41891. ** Shutdown the page cache. Free all memory and close all files.
  41892. **
  41893. ** If a transaction was in progress when this routine is called, that
  41894. ** transaction is rolled back. All outstanding pages are invalidated
  41895. ** and their memory is freed. Any attempt to use a page associated
  41896. ** with this page cache after this function returns will likely
  41897. ** result in a coredump.
  41898. **
  41899. ** This function always succeeds. If a transaction is active an attempt
  41900. ** is made to roll it back. If an error occurs during the rollback
  41901. ** a hot journal may be left in the filesystem but no error is returned
  41902. ** to the caller.
  41903. */
  41904. SQLITE_PRIVATE int sqlite3PagerClose(Pager *pPager){
  41905. u8 *pTmp = (u8 *)pPager->pTmpSpace;
  41906. assert( assert_pager_state(pPager) );
  41907. disable_simulated_io_errors();
  41908. sqlite3BeginBenignMalloc();
  41909. pagerFreeMapHdrs(pPager);
  41910. /* pPager->errCode = 0; */
  41911. pPager->exclusiveMode = 0;
  41912. #ifndef SQLITE_OMIT_WAL
  41913. sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags, pPager->pageSize, pTmp);
  41914. pPager->pWal = 0;
  41915. #endif
  41916. pager_reset(pPager);
  41917. if( MEMDB ){
  41918. pager_unlock(pPager);
  41919. }else{
  41920. /* If it is open, sync the journal file before calling UnlockAndRollback.
  41921. ** If this is not done, then an unsynced portion of the open journal
  41922. ** file may be played back into the database. If a power failure occurs
  41923. ** while this is happening, the database could become corrupt.
  41924. **
  41925. ** If an error occurs while trying to sync the journal, shift the pager
  41926. ** into the ERROR state. This causes UnlockAndRollback to unlock the
  41927. ** database and close the journal file without attempting to roll it
  41928. ** back or finalize it. The next database user will have to do hot-journal
  41929. ** rollback before accessing the database file.
  41930. */
  41931. if( isOpen(pPager->jfd) ){
  41932. pager_error(pPager, pagerSyncHotJournal(pPager));
  41933. }
  41934. pagerUnlockAndRollback(pPager);
  41935. }
  41936. sqlite3EndBenignMalloc();
  41937. enable_simulated_io_errors();
  41938. PAGERTRACE(("CLOSE %d\n", PAGERID(pPager)));
  41939. IOTRACE(("CLOSE %p\n", pPager))
  41940. sqlite3OsClose(pPager->jfd);
  41941. sqlite3OsClose(pPager->fd);
  41942. sqlite3PageFree(pTmp);
  41943. sqlite3PcacheClose(pPager->pPCache);
  41944. #ifdef SQLITE_HAS_CODEC
  41945. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  41946. #endif
  41947. assert( !pPager->aSavepoint && !pPager->pInJournal );
  41948. assert( !isOpen(pPager->jfd) && !isOpen(pPager->sjfd) );
  41949. sqlite3_free(pPager);
  41950. return SQLITE_OK;
  41951. }
  41952. #if !defined(NDEBUG) || defined(SQLITE_TEST)
  41953. /*
  41954. ** Return the page number for page pPg.
  41955. */
  41956. SQLITE_PRIVATE Pgno sqlite3PagerPagenumber(DbPage *pPg){
  41957. return pPg->pgno;
  41958. }
  41959. #endif
  41960. /*
  41961. ** Increment the reference count for page pPg.
  41962. */
  41963. SQLITE_PRIVATE void sqlite3PagerRef(DbPage *pPg){
  41964. sqlite3PcacheRef(pPg);
  41965. }
  41966. /*
  41967. ** Sync the journal. In other words, make sure all the pages that have
  41968. ** been written to the journal have actually reached the surface of the
  41969. ** disk and can be restored in the event of a hot-journal rollback.
  41970. **
  41971. ** If the Pager.noSync flag is set, then this function is a no-op.
  41972. ** Otherwise, the actions required depend on the journal-mode and the
  41973. ** device characteristics of the file-system, as follows:
  41974. **
  41975. ** * If the journal file is an in-memory journal file, no action need
  41976. ** be taken.
  41977. **
  41978. ** * Otherwise, if the device does not support the SAFE_APPEND property,
  41979. ** then the nRec field of the most recently written journal header
  41980. ** is updated to contain the number of journal records that have
  41981. ** been written following it. If the pager is operating in full-sync
  41982. ** mode, then the journal file is synced before this field is updated.
  41983. **
  41984. ** * If the device does not support the SEQUENTIAL property, then
  41985. ** journal file is synced.
  41986. **
  41987. ** Or, in pseudo-code:
  41988. **
  41989. ** if( NOT <in-memory journal> ){
  41990. ** if( NOT SAFE_APPEND ){
  41991. ** if( <full-sync mode> ) xSync(<journal file>);
  41992. ** <update nRec field>
  41993. ** }
  41994. ** if( NOT SEQUENTIAL ) xSync(<journal file>);
  41995. ** }
  41996. **
  41997. ** If successful, this routine clears the PGHDR_NEED_SYNC flag of every
  41998. ** page currently held in memory before returning SQLITE_OK. If an IO
  41999. ** error is encountered, then the IO error code is returned to the caller.
  42000. */
  42001. static int syncJournal(Pager *pPager, int newHdr){
  42002. int rc; /* Return code */
  42003. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  42004. || pPager->eState==PAGER_WRITER_DBMOD
  42005. );
  42006. assert( assert_pager_state(pPager) );
  42007. assert( !pagerUseWal(pPager) );
  42008. rc = sqlite3PagerExclusiveLock(pPager);
  42009. if( rc!=SQLITE_OK ) return rc;
  42010. if( !pPager->noSync ){
  42011. assert( !pPager->tempFile );
  42012. if( isOpen(pPager->jfd) && pPager->journalMode!=PAGER_JOURNALMODE_MEMORY ){
  42013. const int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  42014. assert( isOpen(pPager->jfd) );
  42015. if( 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  42016. /* This block deals with an obscure problem. If the last connection
  42017. ** that wrote to this database was operating in persistent-journal
  42018. ** mode, then the journal file may at this point actually be larger
  42019. ** than Pager.journalOff bytes. If the next thing in the journal
  42020. ** file happens to be a journal-header (written as part of the
  42021. ** previous connection's transaction), and a crash or power-failure
  42022. ** occurs after nRec is updated but before this connection writes
  42023. ** anything else to the journal file (or commits/rolls back its
  42024. ** transaction), then SQLite may become confused when doing the
  42025. ** hot-journal rollback following recovery. It may roll back all
  42026. ** of this connections data, then proceed to rolling back the old,
  42027. ** out-of-date data that follows it. Database corruption.
  42028. **
  42029. ** To work around this, if the journal file does appear to contain
  42030. ** a valid header following Pager.journalOff, then write a 0x00
  42031. ** byte to the start of it to prevent it from being recognized.
  42032. **
  42033. ** Variable iNextHdrOffset is set to the offset at which this
  42034. ** problematic header will occur, if it exists. aMagic is used
  42035. ** as a temporary buffer to inspect the first couple of bytes of
  42036. ** the potential journal header.
  42037. */
  42038. i64 iNextHdrOffset;
  42039. u8 aMagic[8];
  42040. u8 zHeader[sizeof(aJournalMagic)+4];
  42041. memcpy(zHeader, aJournalMagic, sizeof(aJournalMagic));
  42042. put32bits(&zHeader[sizeof(aJournalMagic)], pPager->nRec);
  42043. iNextHdrOffset = journalHdrOffset(pPager);
  42044. rc = sqlite3OsRead(pPager->jfd, aMagic, 8, iNextHdrOffset);
  42045. if( rc==SQLITE_OK && 0==memcmp(aMagic, aJournalMagic, 8) ){
  42046. static const u8 zerobyte = 0;
  42047. rc = sqlite3OsWrite(pPager->jfd, &zerobyte, 1, iNextHdrOffset);
  42048. }
  42049. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  42050. return rc;
  42051. }
  42052. /* Write the nRec value into the journal file header. If in
  42053. ** full-synchronous mode, sync the journal first. This ensures that
  42054. ** all data has really hit the disk before nRec is updated to mark
  42055. ** it as a candidate for rollback.
  42056. **
  42057. ** This is not required if the persistent media supports the
  42058. ** SAFE_APPEND property. Because in this case it is not possible
  42059. ** for garbage data to be appended to the file, the nRec field
  42060. ** is populated with 0xFFFFFFFF when the journal header is written
  42061. ** and never needs to be updated.
  42062. */
  42063. if( pPager->fullSync && 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  42064. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  42065. IOTRACE(("JSYNC %p\n", pPager))
  42066. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags);
  42067. if( rc!=SQLITE_OK ) return rc;
  42068. }
  42069. IOTRACE(("JHDR %p %lld\n", pPager, pPager->journalHdr));
  42070. rc = sqlite3OsWrite(
  42071. pPager->jfd, zHeader, sizeof(zHeader), pPager->journalHdr
  42072. );
  42073. if( rc!=SQLITE_OK ) return rc;
  42074. }
  42075. if( 0==(iDc&SQLITE_IOCAP_SEQUENTIAL) ){
  42076. PAGERTRACE(("SYNC journal of %d\n", PAGERID(pPager)));
  42077. IOTRACE(("JSYNC %p\n", pPager))
  42078. rc = sqlite3OsSync(pPager->jfd, pPager->syncFlags|
  42079. (pPager->syncFlags==SQLITE_SYNC_FULL?SQLITE_SYNC_DATAONLY:0)
  42080. );
  42081. if( rc!=SQLITE_OK ) return rc;
  42082. }
  42083. pPager->journalHdr = pPager->journalOff;
  42084. if( newHdr && 0==(iDc&SQLITE_IOCAP_SAFE_APPEND) ){
  42085. pPager->nRec = 0;
  42086. rc = writeJournalHdr(pPager);
  42087. if( rc!=SQLITE_OK ) return rc;
  42088. }
  42089. }else{
  42090. pPager->journalHdr = pPager->journalOff;
  42091. }
  42092. }
  42093. /* Unless the pager is in noSync mode, the journal file was just
  42094. ** successfully synced. Either way, clear the PGHDR_NEED_SYNC flag on
  42095. ** all pages.
  42096. */
  42097. sqlite3PcacheClearSyncFlags(pPager->pPCache);
  42098. pPager->eState = PAGER_WRITER_DBMOD;
  42099. assert( assert_pager_state(pPager) );
  42100. return SQLITE_OK;
  42101. }
  42102. /*
  42103. ** The argument is the first in a linked list of dirty pages connected
  42104. ** by the PgHdr.pDirty pointer. This function writes each one of the
  42105. ** in-memory pages in the list to the database file. The argument may
  42106. ** be NULL, representing an empty list. In this case this function is
  42107. ** a no-op.
  42108. **
  42109. ** The pager must hold at least a RESERVED lock when this function
  42110. ** is called. Before writing anything to the database file, this lock
  42111. ** is upgraded to an EXCLUSIVE lock. If the lock cannot be obtained,
  42112. ** SQLITE_BUSY is returned and no data is written to the database file.
  42113. **
  42114. ** If the pager is a temp-file pager and the actual file-system file
  42115. ** is not yet open, it is created and opened before any data is
  42116. ** written out.
  42117. **
  42118. ** Once the lock has been upgraded and, if necessary, the file opened,
  42119. ** the pages are written out to the database file in list order. Writing
  42120. ** a page is skipped if it meets either of the following criteria:
  42121. **
  42122. ** * The page number is greater than Pager.dbSize, or
  42123. ** * The PGHDR_DONT_WRITE flag is set on the page.
  42124. **
  42125. ** If writing out a page causes the database file to grow, Pager.dbFileSize
  42126. ** is updated accordingly. If page 1 is written out, then the value cached
  42127. ** in Pager.dbFileVers[] is updated to match the new value stored in
  42128. ** the database file.
  42129. **
  42130. ** If everything is successful, SQLITE_OK is returned. If an IO error
  42131. ** occurs, an IO error code is returned. Or, if the EXCLUSIVE lock cannot
  42132. ** be obtained, SQLITE_BUSY is returned.
  42133. */
  42134. static int pager_write_pagelist(Pager *pPager, PgHdr *pList){
  42135. int rc = SQLITE_OK; /* Return code */
  42136. /* This function is only called for rollback pagers in WRITER_DBMOD state. */
  42137. assert( !pagerUseWal(pPager) );
  42138. assert( pPager->eState==PAGER_WRITER_DBMOD );
  42139. assert( pPager->eLock==EXCLUSIVE_LOCK );
  42140. /* If the file is a temp-file has not yet been opened, open it now. It
  42141. ** is not possible for rc to be other than SQLITE_OK if this branch
  42142. ** is taken, as pager_wait_on_lock() is a no-op for temp-files.
  42143. */
  42144. if( !isOpen(pPager->fd) ){
  42145. assert( pPager->tempFile && rc==SQLITE_OK );
  42146. rc = pagerOpentemp(pPager, pPager->fd, pPager->vfsFlags);
  42147. }
  42148. /* Before the first write, give the VFS a hint of what the final
  42149. ** file size will be.
  42150. */
  42151. assert( rc!=SQLITE_OK || isOpen(pPager->fd) );
  42152. if( rc==SQLITE_OK
  42153. && pPager->dbHintSize<pPager->dbSize
  42154. && (pList->pDirty || pList->pgno>pPager->dbHintSize)
  42155. ){
  42156. sqlite3_int64 szFile = pPager->pageSize * (sqlite3_int64)pPager->dbSize;
  42157. sqlite3OsFileControlHint(pPager->fd, SQLITE_FCNTL_SIZE_HINT, &szFile);
  42158. pPager->dbHintSize = pPager->dbSize;
  42159. }
  42160. while( rc==SQLITE_OK && pList ){
  42161. Pgno pgno = pList->pgno;
  42162. /* If there are dirty pages in the page cache with page numbers greater
  42163. ** than Pager.dbSize, this means sqlite3PagerTruncateImage() was called to
  42164. ** make the file smaller (presumably by auto-vacuum code). Do not write
  42165. ** any such pages to the file.
  42166. **
  42167. ** Also, do not write out any page that has the PGHDR_DONT_WRITE flag
  42168. ** set (set by sqlite3PagerDontWrite()).
  42169. */
  42170. if( pgno<=pPager->dbSize && 0==(pList->flags&PGHDR_DONT_WRITE) ){
  42171. i64 offset = (pgno-1)*(i64)pPager->pageSize; /* Offset to write */
  42172. char *pData; /* Data to write */
  42173. assert( (pList->flags&PGHDR_NEED_SYNC)==0 );
  42174. if( pList->pgno==1 ) pager_write_changecounter(pList);
  42175. /* Encode the database */
  42176. CODEC2(pPager, pList->pData, pgno, 6, return SQLITE_NOMEM, pData);
  42177. /* Write out the page data. */
  42178. rc = sqlite3OsWrite(pPager->fd, pData, pPager->pageSize, offset);
  42179. /* If page 1 was just written, update Pager.dbFileVers to match
  42180. ** the value now stored in the database file. If writing this
  42181. ** page caused the database file to grow, update dbFileSize.
  42182. */
  42183. if( pgno==1 ){
  42184. memcpy(&pPager->dbFileVers, &pData[24], sizeof(pPager->dbFileVers));
  42185. }
  42186. if( pgno>pPager->dbFileSize ){
  42187. pPager->dbFileSize = pgno;
  42188. }
  42189. pPager->aStat[PAGER_STAT_WRITE]++;
  42190. /* Update any backup objects copying the contents of this pager. */
  42191. sqlite3BackupUpdate(pPager->pBackup, pgno, (u8*)pList->pData);
  42192. PAGERTRACE(("STORE %d page %d hash(%08x)\n",
  42193. PAGERID(pPager), pgno, pager_pagehash(pList)));
  42194. IOTRACE(("PGOUT %p %d\n", pPager, pgno));
  42195. PAGER_INCR(sqlite3_pager_writedb_count);
  42196. }else{
  42197. PAGERTRACE(("NOSTORE %d page %d\n", PAGERID(pPager), pgno));
  42198. }
  42199. pager_set_pagehash(pList);
  42200. pList = pList->pDirty;
  42201. }
  42202. return rc;
  42203. }
  42204. /*
  42205. ** Ensure that the sub-journal file is open. If it is already open, this
  42206. ** function is a no-op.
  42207. **
  42208. ** SQLITE_OK is returned if everything goes according to plan. An
  42209. ** SQLITE_IOERR_XXX error code is returned if a call to sqlite3OsOpen()
  42210. ** fails.
  42211. */
  42212. static int openSubJournal(Pager *pPager){
  42213. int rc = SQLITE_OK;
  42214. if( !isOpen(pPager->sjfd) ){
  42215. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY || pPager->subjInMemory ){
  42216. sqlite3MemJournalOpen(pPager->sjfd);
  42217. }else{
  42218. rc = pagerOpentemp(pPager, pPager->sjfd, SQLITE_OPEN_SUBJOURNAL);
  42219. }
  42220. }
  42221. return rc;
  42222. }
  42223. /*
  42224. ** Append a record of the current state of page pPg to the sub-journal.
  42225. ** It is the callers responsibility to use subjRequiresPage() to check
  42226. ** that it is really required before calling this function.
  42227. **
  42228. ** If successful, set the bit corresponding to pPg->pgno in the bitvecs
  42229. ** for all open savepoints before returning.
  42230. **
  42231. ** This function returns SQLITE_OK if everything is successful, an IO
  42232. ** error code if the attempt to write to the sub-journal fails, or
  42233. ** SQLITE_NOMEM if a malloc fails while setting a bit in a savepoint
  42234. ** bitvec.
  42235. */
  42236. static int subjournalPage(PgHdr *pPg){
  42237. int rc = SQLITE_OK;
  42238. Pager *pPager = pPg->pPager;
  42239. if( pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  42240. /* Open the sub-journal, if it has not already been opened */
  42241. assert( pPager->useJournal );
  42242. assert( isOpen(pPager->jfd) || pagerUseWal(pPager) );
  42243. assert( isOpen(pPager->sjfd) || pPager->nSubRec==0 );
  42244. assert( pagerUseWal(pPager)
  42245. || pageInJournal(pPager, pPg)
  42246. || pPg->pgno>pPager->dbOrigSize
  42247. );
  42248. rc = openSubJournal(pPager);
  42249. /* If the sub-journal was opened successfully (or was already open),
  42250. ** write the journal record into the file. */
  42251. if( rc==SQLITE_OK ){
  42252. void *pData = pPg->pData;
  42253. i64 offset = (i64)pPager->nSubRec*(4+pPager->pageSize);
  42254. char *pData2;
  42255. CODEC2(pPager, pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  42256. PAGERTRACE(("STMT-JOURNAL %d page %d\n", PAGERID(pPager), pPg->pgno));
  42257. rc = write32bits(pPager->sjfd, offset, pPg->pgno);
  42258. if( rc==SQLITE_OK ){
  42259. rc = sqlite3OsWrite(pPager->sjfd, pData2, pPager->pageSize, offset+4);
  42260. }
  42261. }
  42262. }
  42263. if( rc==SQLITE_OK ){
  42264. pPager->nSubRec++;
  42265. assert( pPager->nSavepoint>0 );
  42266. rc = addToSavepointBitvecs(pPager, pPg->pgno);
  42267. }
  42268. return rc;
  42269. }
  42270. /*
  42271. ** This function is called by the pcache layer when it has reached some
  42272. ** soft memory limit. The first argument is a pointer to a Pager object
  42273. ** (cast as a void*). The pager is always 'purgeable' (not an in-memory
  42274. ** database). The second argument is a reference to a page that is
  42275. ** currently dirty but has no outstanding references. The page
  42276. ** is always associated with the Pager object passed as the first
  42277. ** argument.
  42278. **
  42279. ** The job of this function is to make pPg clean by writing its contents
  42280. ** out to the database file, if possible. This may involve syncing the
  42281. ** journal file.
  42282. **
  42283. ** If successful, sqlite3PcacheMakeClean() is called on the page and
  42284. ** SQLITE_OK returned. If an IO error occurs while trying to make the
  42285. ** page clean, the IO error code is returned. If the page cannot be
  42286. ** made clean for some other reason, but no error occurs, then SQLITE_OK
  42287. ** is returned by sqlite3PcacheMakeClean() is not called.
  42288. */
  42289. static int pagerStress(void *p, PgHdr *pPg){
  42290. Pager *pPager = (Pager *)p;
  42291. int rc = SQLITE_OK;
  42292. assert( pPg->pPager==pPager );
  42293. assert( pPg->flags&PGHDR_DIRTY );
  42294. /* The doNotSpill NOSYNC bit is set during times when doing a sync of
  42295. ** journal (and adding a new header) is not allowed. This occurs
  42296. ** during calls to sqlite3PagerWrite() while trying to journal multiple
  42297. ** pages belonging to the same sector.
  42298. **
  42299. ** The doNotSpill ROLLBACK and OFF bits inhibits all cache spilling
  42300. ** regardless of whether or not a sync is required. This is set during
  42301. ** a rollback or by user request, respectively.
  42302. **
  42303. ** Spilling is also prohibited when in an error state since that could
  42304. ** lead to database corruption. In the current implementation it
  42305. ** is impossible for sqlite3PcacheFetch() to be called with createFlag==3
  42306. ** while in the error state, hence it is impossible for this routine to
  42307. ** be called in the error state. Nevertheless, we include a NEVER()
  42308. ** test for the error state as a safeguard against future changes.
  42309. */
  42310. if( NEVER(pPager->errCode) ) return SQLITE_OK;
  42311. testcase( pPager->doNotSpill & SPILLFLAG_ROLLBACK );
  42312. testcase( pPager->doNotSpill & SPILLFLAG_OFF );
  42313. testcase( pPager->doNotSpill & SPILLFLAG_NOSYNC );
  42314. if( pPager->doNotSpill
  42315. && ((pPager->doNotSpill & (SPILLFLAG_ROLLBACK|SPILLFLAG_OFF))!=0
  42316. || (pPg->flags & PGHDR_NEED_SYNC)!=0)
  42317. ){
  42318. return SQLITE_OK;
  42319. }
  42320. pPg->pDirty = 0;
  42321. if( pagerUseWal(pPager) ){
  42322. /* Write a single frame for this page to the log. */
  42323. if( subjRequiresPage(pPg) ){
  42324. rc = subjournalPage(pPg);
  42325. }
  42326. if( rc==SQLITE_OK ){
  42327. rc = pagerWalFrames(pPager, pPg, 0, 0);
  42328. }
  42329. }else{
  42330. /* Sync the journal file if required. */
  42331. if( pPg->flags&PGHDR_NEED_SYNC
  42332. || pPager->eState==PAGER_WRITER_CACHEMOD
  42333. ){
  42334. rc = syncJournal(pPager, 1);
  42335. }
  42336. /* If the page number of this page is larger than the current size of
  42337. ** the database image, it may need to be written to the sub-journal.
  42338. ** This is because the call to pager_write_pagelist() below will not
  42339. ** actually write data to the file in this case.
  42340. **
  42341. ** Consider the following sequence of events:
  42342. **
  42343. ** BEGIN;
  42344. ** <journal page X>
  42345. ** <modify page X>
  42346. ** SAVEPOINT sp;
  42347. ** <shrink database file to Y pages>
  42348. ** pagerStress(page X)
  42349. ** ROLLBACK TO sp;
  42350. **
  42351. ** If (X>Y), then when pagerStress is called page X will not be written
  42352. ** out to the database file, but will be dropped from the cache. Then,
  42353. ** following the "ROLLBACK TO sp" statement, reading page X will read
  42354. ** data from the database file. This will be the copy of page X as it
  42355. ** was when the transaction started, not as it was when "SAVEPOINT sp"
  42356. ** was executed.
  42357. **
  42358. ** The solution is to write the current data for page X into the
  42359. ** sub-journal file now (if it is not already there), so that it will
  42360. ** be restored to its current value when the "ROLLBACK TO sp" is
  42361. ** executed.
  42362. */
  42363. if( NEVER(
  42364. rc==SQLITE_OK && pPg->pgno>pPager->dbSize && subjRequiresPage(pPg)
  42365. ) ){
  42366. rc = subjournalPage(pPg);
  42367. }
  42368. /* Write the contents of the page out to the database file. */
  42369. if( rc==SQLITE_OK ){
  42370. assert( (pPg->flags&PGHDR_NEED_SYNC)==0 );
  42371. rc = pager_write_pagelist(pPager, pPg);
  42372. }
  42373. }
  42374. /* Mark the page as clean. */
  42375. if( rc==SQLITE_OK ){
  42376. PAGERTRACE(("STRESS %d page %d\n", PAGERID(pPager), pPg->pgno));
  42377. sqlite3PcacheMakeClean(pPg);
  42378. }
  42379. return pager_error(pPager, rc);
  42380. }
  42381. /*
  42382. ** Allocate and initialize a new Pager object and put a pointer to it
  42383. ** in *ppPager. The pager should eventually be freed by passing it
  42384. ** to sqlite3PagerClose().
  42385. **
  42386. ** The zFilename argument is the path to the database file to open.
  42387. ** If zFilename is NULL then a randomly-named temporary file is created
  42388. ** and used as the file to be cached. Temporary files are be deleted
  42389. ** automatically when they are closed. If zFilename is ":memory:" then
  42390. ** all information is held in cache. It is never written to disk.
  42391. ** This can be used to implement an in-memory database.
  42392. **
  42393. ** The nExtra parameter specifies the number of bytes of space allocated
  42394. ** along with each page reference. This space is available to the user
  42395. ** via the sqlite3PagerGetExtra() API.
  42396. **
  42397. ** The flags argument is used to specify properties that affect the
  42398. ** operation of the pager. It should be passed some bitwise combination
  42399. ** of the PAGER_* flags.
  42400. **
  42401. ** The vfsFlags parameter is a bitmask to pass to the flags parameter
  42402. ** of the xOpen() method of the supplied VFS when opening files.
  42403. **
  42404. ** If the pager object is allocated and the specified file opened
  42405. ** successfully, SQLITE_OK is returned and *ppPager set to point to
  42406. ** the new pager object. If an error occurs, *ppPager is set to NULL
  42407. ** and error code returned. This function may return SQLITE_NOMEM
  42408. ** (sqlite3Malloc() is used to allocate memory), SQLITE_CANTOPEN or
  42409. ** various SQLITE_IO_XXX errors.
  42410. */
  42411. SQLITE_PRIVATE int sqlite3PagerOpen(
  42412. sqlite3_vfs *pVfs, /* The virtual file system to use */
  42413. Pager **ppPager, /* OUT: Return the Pager structure here */
  42414. const char *zFilename, /* Name of the database file to open */
  42415. int nExtra, /* Extra bytes append to each in-memory page */
  42416. int flags, /* flags controlling this file */
  42417. int vfsFlags, /* flags passed through to sqlite3_vfs.xOpen() */
  42418. void (*xReinit)(DbPage*) /* Function to reinitialize pages */
  42419. ){
  42420. u8 *pPtr;
  42421. Pager *pPager = 0; /* Pager object to allocate and return */
  42422. int rc = SQLITE_OK; /* Return code */
  42423. int tempFile = 0; /* True for temp files (incl. in-memory files) */
  42424. int memDb = 0; /* True if this is an in-memory file */
  42425. int readOnly = 0; /* True if this is a read-only file */
  42426. int journalFileSize; /* Bytes to allocate for each journal fd */
  42427. char *zPathname = 0; /* Full path to database file */
  42428. int nPathname = 0; /* Number of bytes in zPathname */
  42429. int useJournal = (flags & PAGER_OMIT_JOURNAL)==0; /* False to omit journal */
  42430. int pcacheSize = sqlite3PcacheSize(); /* Bytes to allocate for PCache */
  42431. u32 szPageDflt = SQLITE_DEFAULT_PAGE_SIZE; /* Default page size */
  42432. const char *zUri = 0; /* URI args to copy */
  42433. int nUri = 0; /* Number of bytes of URI args at *zUri */
  42434. /* Figure out how much space is required for each journal file-handle
  42435. ** (there are two of them, the main journal and the sub-journal). This
  42436. ** is the maximum space required for an in-memory journal file handle
  42437. ** and a regular journal file-handle. Note that a "regular journal-handle"
  42438. ** may be a wrapper capable of caching the first portion of the journal
  42439. ** file in memory to implement the atomic-write optimization (see
  42440. ** source file journal.c).
  42441. */
  42442. if( sqlite3JournalSize(pVfs)>sqlite3MemJournalSize() ){
  42443. journalFileSize = ROUND8(sqlite3JournalSize(pVfs));
  42444. }else{
  42445. journalFileSize = ROUND8(sqlite3MemJournalSize());
  42446. }
  42447. /* Set the output variable to NULL in case an error occurs. */
  42448. *ppPager = 0;
  42449. #ifndef SQLITE_OMIT_MEMORYDB
  42450. if( flags & PAGER_MEMORY ){
  42451. memDb = 1;
  42452. if( zFilename && zFilename[0] ){
  42453. zPathname = sqlite3DbStrDup(0, zFilename);
  42454. if( zPathname==0 ) return SQLITE_NOMEM;
  42455. nPathname = sqlite3Strlen30(zPathname);
  42456. zFilename = 0;
  42457. }
  42458. }
  42459. #endif
  42460. /* Compute and store the full pathname in an allocated buffer pointed
  42461. ** to by zPathname, length nPathname. Or, if this is a temporary file,
  42462. ** leave both nPathname and zPathname set to 0.
  42463. */
  42464. if( zFilename && zFilename[0] ){
  42465. const char *z;
  42466. nPathname = pVfs->mxPathname+1;
  42467. zPathname = sqlite3DbMallocRaw(0, nPathname*2);
  42468. if( zPathname==0 ){
  42469. return SQLITE_NOMEM;
  42470. }
  42471. zPathname[0] = 0; /* Make sure initialized even if FullPathname() fails */
  42472. rc = sqlite3OsFullPathname(pVfs, zFilename, nPathname, zPathname);
  42473. nPathname = sqlite3Strlen30(zPathname);
  42474. z = zUri = &zFilename[sqlite3Strlen30(zFilename)+1];
  42475. while( *z ){
  42476. z += sqlite3Strlen30(z)+1;
  42477. z += sqlite3Strlen30(z)+1;
  42478. }
  42479. nUri = (int)(&z[1] - zUri);
  42480. assert( nUri>=0 );
  42481. if( rc==SQLITE_OK && nPathname+8>pVfs->mxPathname ){
  42482. /* This branch is taken when the journal path required by
  42483. ** the database being opened will be more than pVfs->mxPathname
  42484. ** bytes in length. This means the database cannot be opened,
  42485. ** as it will not be possible to open the journal file or even
  42486. ** check for a hot-journal before reading.
  42487. */
  42488. rc = SQLITE_CANTOPEN_BKPT;
  42489. }
  42490. if( rc!=SQLITE_OK ){
  42491. sqlite3DbFree(0, zPathname);
  42492. return rc;
  42493. }
  42494. }
  42495. /* Allocate memory for the Pager structure, PCache object, the
  42496. ** three file descriptors, the database file name and the journal
  42497. ** file name. The layout in memory is as follows:
  42498. **
  42499. ** Pager object (sizeof(Pager) bytes)
  42500. ** PCache object (sqlite3PcacheSize() bytes)
  42501. ** Database file handle (pVfs->szOsFile bytes)
  42502. ** Sub-journal file handle (journalFileSize bytes)
  42503. ** Main journal file handle (journalFileSize bytes)
  42504. ** Database file name (nPathname+1 bytes)
  42505. ** Journal file name (nPathname+8+1 bytes)
  42506. */
  42507. pPtr = (u8 *)sqlite3MallocZero(
  42508. ROUND8(sizeof(*pPager)) + /* Pager structure */
  42509. ROUND8(pcacheSize) + /* PCache object */
  42510. ROUND8(pVfs->szOsFile) + /* The main db file */
  42511. journalFileSize * 2 + /* The two journal files */
  42512. nPathname + 1 + nUri + /* zFilename */
  42513. nPathname + 8 + 2 /* zJournal */
  42514. #ifndef SQLITE_OMIT_WAL
  42515. + nPathname + 4 + 2 /* zWal */
  42516. #endif
  42517. );
  42518. assert( EIGHT_BYTE_ALIGNMENT(SQLITE_INT_TO_PTR(journalFileSize)) );
  42519. if( !pPtr ){
  42520. sqlite3DbFree(0, zPathname);
  42521. return SQLITE_NOMEM;
  42522. }
  42523. pPager = (Pager*)(pPtr);
  42524. pPager->pPCache = (PCache*)(pPtr += ROUND8(sizeof(*pPager)));
  42525. pPager->fd = (sqlite3_file*)(pPtr += ROUND8(pcacheSize));
  42526. pPager->sjfd = (sqlite3_file*)(pPtr += ROUND8(pVfs->szOsFile));
  42527. pPager->jfd = (sqlite3_file*)(pPtr += journalFileSize);
  42528. pPager->zFilename = (char*)(pPtr += journalFileSize);
  42529. assert( EIGHT_BYTE_ALIGNMENT(pPager->jfd) );
  42530. /* Fill in the Pager.zFilename and Pager.zJournal buffers, if required. */
  42531. if( zPathname ){
  42532. assert( nPathname>0 );
  42533. pPager->zJournal = (char*)(pPtr += nPathname + 1 + nUri);
  42534. memcpy(pPager->zFilename, zPathname, nPathname);
  42535. if( nUri ) memcpy(&pPager->zFilename[nPathname+1], zUri, nUri);
  42536. memcpy(pPager->zJournal, zPathname, nPathname);
  42537. memcpy(&pPager->zJournal[nPathname], "-journal\000", 8+2);
  42538. sqlite3FileSuffix3(pPager->zFilename, pPager->zJournal);
  42539. #ifndef SQLITE_OMIT_WAL
  42540. pPager->zWal = &pPager->zJournal[nPathname+8+1];
  42541. memcpy(pPager->zWal, zPathname, nPathname);
  42542. memcpy(&pPager->zWal[nPathname], "-wal\000", 4+1);
  42543. sqlite3FileSuffix3(pPager->zFilename, pPager->zWal);
  42544. #endif
  42545. sqlite3DbFree(0, zPathname);
  42546. }
  42547. pPager->pVfs = pVfs;
  42548. pPager->vfsFlags = vfsFlags;
  42549. /* Open the pager file.
  42550. */
  42551. if( zFilename && zFilename[0] ){
  42552. int fout = 0; /* VFS flags returned by xOpen() */
  42553. rc = sqlite3OsOpen(pVfs, pPager->zFilename, pPager->fd, vfsFlags, &fout);
  42554. assert( !memDb );
  42555. readOnly = (fout&SQLITE_OPEN_READONLY);
  42556. /* If the file was successfully opened for read/write access,
  42557. ** choose a default page size in case we have to create the
  42558. ** database file. The default page size is the maximum of:
  42559. **
  42560. ** + SQLITE_DEFAULT_PAGE_SIZE,
  42561. ** + The value returned by sqlite3OsSectorSize()
  42562. ** + The largest page size that can be written atomically.
  42563. */
  42564. if( rc==SQLITE_OK ){
  42565. int iDc = sqlite3OsDeviceCharacteristics(pPager->fd);
  42566. if( !readOnly ){
  42567. setSectorSize(pPager);
  42568. assert(SQLITE_DEFAULT_PAGE_SIZE<=SQLITE_MAX_DEFAULT_PAGE_SIZE);
  42569. if( szPageDflt<pPager->sectorSize ){
  42570. if( pPager->sectorSize>SQLITE_MAX_DEFAULT_PAGE_SIZE ){
  42571. szPageDflt = SQLITE_MAX_DEFAULT_PAGE_SIZE;
  42572. }else{
  42573. szPageDflt = (u32)pPager->sectorSize;
  42574. }
  42575. }
  42576. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  42577. {
  42578. int ii;
  42579. assert(SQLITE_IOCAP_ATOMIC512==(512>>8));
  42580. assert(SQLITE_IOCAP_ATOMIC64K==(65536>>8));
  42581. assert(SQLITE_MAX_DEFAULT_PAGE_SIZE<=65536);
  42582. for(ii=szPageDflt; ii<=SQLITE_MAX_DEFAULT_PAGE_SIZE; ii=ii*2){
  42583. if( iDc&(SQLITE_IOCAP_ATOMIC|(ii>>8)) ){
  42584. szPageDflt = ii;
  42585. }
  42586. }
  42587. }
  42588. #endif
  42589. }
  42590. pPager->noLock = sqlite3_uri_boolean(zFilename, "nolock", 0);
  42591. if( (iDc & SQLITE_IOCAP_IMMUTABLE)!=0
  42592. || sqlite3_uri_boolean(zFilename, "immutable", 0) ){
  42593. vfsFlags |= SQLITE_OPEN_READONLY;
  42594. goto act_like_temp_file;
  42595. }
  42596. }
  42597. }else{
  42598. /* If a temporary file is requested, it is not opened immediately.
  42599. ** In this case we accept the default page size and delay actually
  42600. ** opening the file until the first call to OsWrite().
  42601. **
  42602. ** This branch is also run for an in-memory database. An in-memory
  42603. ** database is the same as a temp-file that is never written out to
  42604. ** disk and uses an in-memory rollback journal.
  42605. **
  42606. ** This branch also runs for files marked as immutable.
  42607. */
  42608. act_like_temp_file:
  42609. tempFile = 1;
  42610. pPager->eState = PAGER_READER; /* Pretend we already have a lock */
  42611. pPager->eLock = EXCLUSIVE_LOCK; /* Pretend we are in EXCLUSIVE locking mode */
  42612. pPager->noLock = 1; /* Do no locking */
  42613. readOnly = (vfsFlags&SQLITE_OPEN_READONLY);
  42614. }
  42615. /* The following call to PagerSetPagesize() serves to set the value of
  42616. ** Pager.pageSize and to allocate the Pager.pTmpSpace buffer.
  42617. */
  42618. if( rc==SQLITE_OK ){
  42619. assert( pPager->memDb==0 );
  42620. rc = sqlite3PagerSetPagesize(pPager, &szPageDflt, -1);
  42621. testcase( rc!=SQLITE_OK );
  42622. }
  42623. /* Initialize the PCache object. */
  42624. if( rc==SQLITE_OK ){
  42625. assert( nExtra<1000 );
  42626. nExtra = ROUND8(nExtra);
  42627. rc = sqlite3PcacheOpen(szPageDflt, nExtra, !memDb,
  42628. !memDb?pagerStress:0, (void *)pPager, pPager->pPCache);
  42629. }
  42630. /* If an error occurred above, free the Pager structure and close the file.
  42631. */
  42632. if( rc!=SQLITE_OK ){
  42633. sqlite3OsClose(pPager->fd);
  42634. sqlite3PageFree(pPager->pTmpSpace);
  42635. sqlite3_free(pPager);
  42636. return rc;
  42637. }
  42638. PAGERTRACE(("OPEN %d %s\n", FILEHANDLEID(pPager->fd), pPager->zFilename));
  42639. IOTRACE(("OPEN %p %s\n", pPager, pPager->zFilename))
  42640. pPager->useJournal = (u8)useJournal;
  42641. /* pPager->stmtOpen = 0; */
  42642. /* pPager->stmtInUse = 0; */
  42643. /* pPager->nRef = 0; */
  42644. /* pPager->stmtSize = 0; */
  42645. /* pPager->stmtJSize = 0; */
  42646. /* pPager->nPage = 0; */
  42647. pPager->mxPgno = SQLITE_MAX_PAGE_COUNT;
  42648. /* pPager->state = PAGER_UNLOCK; */
  42649. /* pPager->errMask = 0; */
  42650. pPager->tempFile = (u8)tempFile;
  42651. assert( tempFile==PAGER_LOCKINGMODE_NORMAL
  42652. || tempFile==PAGER_LOCKINGMODE_EXCLUSIVE );
  42653. assert( PAGER_LOCKINGMODE_EXCLUSIVE==1 );
  42654. pPager->exclusiveMode = (u8)tempFile;
  42655. pPager->changeCountDone = pPager->tempFile;
  42656. pPager->memDb = (u8)memDb;
  42657. pPager->readOnly = (u8)readOnly;
  42658. assert( useJournal || pPager->tempFile );
  42659. pPager->noSync = pPager->tempFile;
  42660. if( pPager->noSync ){
  42661. assert( pPager->fullSync==0 );
  42662. assert( pPager->syncFlags==0 );
  42663. assert( pPager->walSyncFlags==0 );
  42664. assert( pPager->ckptSyncFlags==0 );
  42665. }else{
  42666. pPager->fullSync = 1;
  42667. pPager->syncFlags = SQLITE_SYNC_NORMAL;
  42668. pPager->walSyncFlags = SQLITE_SYNC_NORMAL | WAL_SYNC_TRANSACTIONS;
  42669. pPager->ckptSyncFlags = SQLITE_SYNC_NORMAL;
  42670. }
  42671. /* pPager->pFirst = 0; */
  42672. /* pPager->pFirstSynced = 0; */
  42673. /* pPager->pLast = 0; */
  42674. pPager->nExtra = (u16)nExtra;
  42675. pPager->journalSizeLimit = SQLITE_DEFAULT_JOURNAL_SIZE_LIMIT;
  42676. assert( isOpen(pPager->fd) || tempFile );
  42677. setSectorSize(pPager);
  42678. if( !useJournal ){
  42679. pPager->journalMode = PAGER_JOURNALMODE_OFF;
  42680. }else if( memDb ){
  42681. pPager->journalMode = PAGER_JOURNALMODE_MEMORY;
  42682. }
  42683. /* pPager->xBusyHandler = 0; */
  42684. /* pPager->pBusyHandlerArg = 0; */
  42685. pPager->xReiniter = xReinit;
  42686. /* memset(pPager->aHash, 0, sizeof(pPager->aHash)); */
  42687. /* pPager->szMmap = SQLITE_DEFAULT_MMAP_SIZE // will be set by btree.c */
  42688. *ppPager = pPager;
  42689. return SQLITE_OK;
  42690. }
  42691. /* Verify that the database file has not be deleted or renamed out from
  42692. ** under the pager. Return SQLITE_OK if the database is still were it ought
  42693. ** to be on disk. Return non-zero (SQLITE_READONLY_DBMOVED or some other error
  42694. ** code from sqlite3OsAccess()) if the database has gone missing.
  42695. */
  42696. static int databaseIsUnmoved(Pager *pPager){
  42697. int bHasMoved = 0;
  42698. int rc;
  42699. if( pPager->tempFile ) return SQLITE_OK;
  42700. if( pPager->dbSize==0 ) return SQLITE_OK;
  42701. assert( pPager->zFilename && pPager->zFilename[0] );
  42702. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_HAS_MOVED, &bHasMoved);
  42703. if( rc==SQLITE_NOTFOUND ){
  42704. /* If the HAS_MOVED file-control is unimplemented, assume that the file
  42705. ** has not been moved. That is the historical behavior of SQLite: prior to
  42706. ** version 3.8.3, it never checked */
  42707. rc = SQLITE_OK;
  42708. }else if( rc==SQLITE_OK && bHasMoved ){
  42709. rc = SQLITE_READONLY_DBMOVED;
  42710. }
  42711. return rc;
  42712. }
  42713. /*
  42714. ** This function is called after transitioning from PAGER_UNLOCK to
  42715. ** PAGER_SHARED state. It tests if there is a hot journal present in
  42716. ** the file-system for the given pager. A hot journal is one that
  42717. ** needs to be played back. According to this function, a hot-journal
  42718. ** file exists if the following criteria are met:
  42719. **
  42720. ** * The journal file exists in the file system, and
  42721. ** * No process holds a RESERVED or greater lock on the database file, and
  42722. ** * The database file itself is greater than 0 bytes in size, and
  42723. ** * The first byte of the journal file exists and is not 0x00.
  42724. **
  42725. ** If the current size of the database file is 0 but a journal file
  42726. ** exists, that is probably an old journal left over from a prior
  42727. ** database with the same name. In this case the journal file is
  42728. ** just deleted using OsDelete, *pExists is set to 0 and SQLITE_OK
  42729. ** is returned.
  42730. **
  42731. ** This routine does not check if there is a master journal filename
  42732. ** at the end of the file. If there is, and that master journal file
  42733. ** does not exist, then the journal file is not really hot. In this
  42734. ** case this routine will return a false-positive. The pager_playback()
  42735. ** routine will discover that the journal file is not really hot and
  42736. ** will not roll it back.
  42737. **
  42738. ** If a hot-journal file is found to exist, *pExists is set to 1 and
  42739. ** SQLITE_OK returned. If no hot-journal file is present, *pExists is
  42740. ** set to 0 and SQLITE_OK returned. If an IO error occurs while trying
  42741. ** to determine whether or not a hot-journal file exists, the IO error
  42742. ** code is returned and the value of *pExists is undefined.
  42743. */
  42744. static int hasHotJournal(Pager *pPager, int *pExists){
  42745. sqlite3_vfs * const pVfs = pPager->pVfs;
  42746. int rc = SQLITE_OK; /* Return code */
  42747. int exists = 1; /* True if a journal file is present */
  42748. int jrnlOpen = !!isOpen(pPager->jfd);
  42749. assert( pPager->useJournal );
  42750. assert( isOpen(pPager->fd) );
  42751. assert( pPager->eState==PAGER_OPEN );
  42752. assert( jrnlOpen==0 || ( sqlite3OsDeviceCharacteristics(pPager->jfd) &
  42753. SQLITE_IOCAP_UNDELETABLE_WHEN_OPEN
  42754. ));
  42755. *pExists = 0;
  42756. if( !jrnlOpen ){
  42757. rc = sqlite3OsAccess(pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &exists);
  42758. }
  42759. if( rc==SQLITE_OK && exists ){
  42760. int locked = 0; /* True if some process holds a RESERVED lock */
  42761. /* Race condition here: Another process might have been holding the
  42762. ** the RESERVED lock and have a journal open at the sqlite3OsAccess()
  42763. ** call above, but then delete the journal and drop the lock before
  42764. ** we get to the following sqlite3OsCheckReservedLock() call. If that
  42765. ** is the case, this routine might think there is a hot journal when
  42766. ** in fact there is none. This results in a false-positive which will
  42767. ** be dealt with by the playback routine. Ticket #3883.
  42768. */
  42769. rc = sqlite3OsCheckReservedLock(pPager->fd, &locked);
  42770. if( rc==SQLITE_OK && !locked ){
  42771. Pgno nPage; /* Number of pages in database file */
  42772. rc = pagerPagecount(pPager, &nPage);
  42773. if( rc==SQLITE_OK ){
  42774. /* If the database is zero pages in size, that means that either (1) the
  42775. ** journal is a remnant from a prior database with the same name where
  42776. ** the database file but not the journal was deleted, or (2) the initial
  42777. ** transaction that populates a new database is being rolled back.
  42778. ** In either case, the journal file can be deleted. However, take care
  42779. ** not to delete the journal file if it is already open due to
  42780. ** journal_mode=PERSIST.
  42781. */
  42782. if( nPage==0 && !jrnlOpen ){
  42783. sqlite3BeginBenignMalloc();
  42784. if( pagerLockDb(pPager, RESERVED_LOCK)==SQLITE_OK ){
  42785. sqlite3OsDelete(pVfs, pPager->zJournal, 0);
  42786. if( !pPager->exclusiveMode ) pagerUnlockDb(pPager, SHARED_LOCK);
  42787. }
  42788. sqlite3EndBenignMalloc();
  42789. }else{
  42790. /* The journal file exists and no other connection has a reserved
  42791. ** or greater lock on the database file. Now check that there is
  42792. ** at least one non-zero bytes at the start of the journal file.
  42793. ** If there is, then we consider this journal to be hot. If not,
  42794. ** it can be ignored.
  42795. */
  42796. if( !jrnlOpen ){
  42797. int f = SQLITE_OPEN_READONLY|SQLITE_OPEN_MAIN_JOURNAL;
  42798. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &f);
  42799. }
  42800. if( rc==SQLITE_OK ){
  42801. u8 first = 0;
  42802. rc = sqlite3OsRead(pPager->jfd, (void *)&first, 1, 0);
  42803. if( rc==SQLITE_IOERR_SHORT_READ ){
  42804. rc = SQLITE_OK;
  42805. }
  42806. if( !jrnlOpen ){
  42807. sqlite3OsClose(pPager->jfd);
  42808. }
  42809. *pExists = (first!=0);
  42810. }else if( rc==SQLITE_CANTOPEN ){
  42811. /* If we cannot open the rollback journal file in order to see if
  42812. ** it has a zero header, that might be due to an I/O error, or
  42813. ** it might be due to the race condition described above and in
  42814. ** ticket #3883. Either way, assume that the journal is hot.
  42815. ** This might be a false positive. But if it is, then the
  42816. ** automatic journal playback and recovery mechanism will deal
  42817. ** with it under an EXCLUSIVE lock where we do not need to
  42818. ** worry so much with race conditions.
  42819. */
  42820. *pExists = 1;
  42821. rc = SQLITE_OK;
  42822. }
  42823. }
  42824. }
  42825. }
  42826. }
  42827. return rc;
  42828. }
  42829. /*
  42830. ** This function is called to obtain a shared lock on the database file.
  42831. ** It is illegal to call sqlite3PagerAcquire() until after this function
  42832. ** has been successfully called. If a shared-lock is already held when
  42833. ** this function is called, it is a no-op.
  42834. **
  42835. ** The following operations are also performed by this function.
  42836. **
  42837. ** 1) If the pager is currently in PAGER_OPEN state (no lock held
  42838. ** on the database file), then an attempt is made to obtain a
  42839. ** SHARED lock on the database file. Immediately after obtaining
  42840. ** the SHARED lock, the file-system is checked for a hot-journal,
  42841. ** which is played back if present. Following any hot-journal
  42842. ** rollback, the contents of the cache are validated by checking
  42843. ** the 'change-counter' field of the database file header and
  42844. ** discarded if they are found to be invalid.
  42845. **
  42846. ** 2) If the pager is running in exclusive-mode, and there are currently
  42847. ** no outstanding references to any pages, and is in the error state,
  42848. ** then an attempt is made to clear the error state by discarding
  42849. ** the contents of the page cache and rolling back any open journal
  42850. ** file.
  42851. **
  42852. ** If everything is successful, SQLITE_OK is returned. If an IO error
  42853. ** occurs while locking the database, checking for a hot-journal file or
  42854. ** rolling back a journal file, the IO error code is returned.
  42855. */
  42856. SQLITE_PRIVATE int sqlite3PagerSharedLock(Pager *pPager){
  42857. int rc = SQLITE_OK; /* Return code */
  42858. /* This routine is only called from b-tree and only when there are no
  42859. ** outstanding pages. This implies that the pager state should either
  42860. ** be OPEN or READER. READER is only possible if the pager is or was in
  42861. ** exclusive access mode.
  42862. */
  42863. assert( sqlite3PcacheRefCount(pPager->pPCache)==0 );
  42864. assert( assert_pager_state(pPager) );
  42865. assert( pPager->eState==PAGER_OPEN || pPager->eState==PAGER_READER );
  42866. if( NEVER(MEMDB && pPager->errCode) ){ return pPager->errCode; }
  42867. if( !pagerUseWal(pPager) && pPager->eState==PAGER_OPEN ){
  42868. int bHotJournal = 1; /* True if there exists a hot journal-file */
  42869. assert( !MEMDB );
  42870. rc = pager_wait_on_lock(pPager, SHARED_LOCK);
  42871. if( rc!=SQLITE_OK ){
  42872. assert( pPager->eLock==NO_LOCK || pPager->eLock==UNKNOWN_LOCK );
  42873. goto failed;
  42874. }
  42875. /* If a journal file exists, and there is no RESERVED lock on the
  42876. ** database file, then it either needs to be played back or deleted.
  42877. */
  42878. if( pPager->eLock<=SHARED_LOCK ){
  42879. rc = hasHotJournal(pPager, &bHotJournal);
  42880. }
  42881. if( rc!=SQLITE_OK ){
  42882. goto failed;
  42883. }
  42884. if( bHotJournal ){
  42885. if( pPager->readOnly ){
  42886. rc = SQLITE_READONLY_ROLLBACK;
  42887. goto failed;
  42888. }
  42889. /* Get an EXCLUSIVE lock on the database file. At this point it is
  42890. ** important that a RESERVED lock is not obtained on the way to the
  42891. ** EXCLUSIVE lock. If it were, another process might open the
  42892. ** database file, detect the RESERVED lock, and conclude that the
  42893. ** database is safe to read while this process is still rolling the
  42894. ** hot-journal back.
  42895. **
  42896. ** Because the intermediate RESERVED lock is not requested, any
  42897. ** other process attempting to access the database file will get to
  42898. ** this point in the code and fail to obtain its own EXCLUSIVE lock
  42899. ** on the database file.
  42900. **
  42901. ** Unless the pager is in locking_mode=exclusive mode, the lock is
  42902. ** downgraded to SHARED_LOCK before this function returns.
  42903. */
  42904. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  42905. if( rc!=SQLITE_OK ){
  42906. goto failed;
  42907. }
  42908. /* If it is not already open and the file exists on disk, open the
  42909. ** journal for read/write access. Write access is required because
  42910. ** in exclusive-access mode the file descriptor will be kept open
  42911. ** and possibly used for a transaction later on. Also, write-access
  42912. ** is usually required to finalize the journal in journal_mode=persist
  42913. ** mode (and also for journal_mode=truncate on some systems).
  42914. **
  42915. ** If the journal does not exist, it usually means that some
  42916. ** other connection managed to get in and roll it back before
  42917. ** this connection obtained the exclusive lock above. Or, it
  42918. ** may mean that the pager was in the error-state when this
  42919. ** function was called and the journal file does not exist.
  42920. */
  42921. if( !isOpen(pPager->jfd) ){
  42922. sqlite3_vfs * const pVfs = pPager->pVfs;
  42923. int bExists; /* True if journal file exists */
  42924. rc = sqlite3OsAccess(
  42925. pVfs, pPager->zJournal, SQLITE_ACCESS_EXISTS, &bExists);
  42926. if( rc==SQLITE_OK && bExists ){
  42927. int fout = 0;
  42928. int f = SQLITE_OPEN_READWRITE|SQLITE_OPEN_MAIN_JOURNAL;
  42929. assert( !pPager->tempFile );
  42930. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, f, &fout);
  42931. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  42932. if( rc==SQLITE_OK && fout&SQLITE_OPEN_READONLY ){
  42933. rc = SQLITE_CANTOPEN_BKPT;
  42934. sqlite3OsClose(pPager->jfd);
  42935. }
  42936. }
  42937. }
  42938. /* Playback and delete the journal. Drop the database write
  42939. ** lock and reacquire the read lock. Purge the cache before
  42940. ** playing back the hot-journal so that we don't end up with
  42941. ** an inconsistent cache. Sync the hot journal before playing
  42942. ** it back since the process that crashed and left the hot journal
  42943. ** probably did not sync it and we are required to always sync
  42944. ** the journal before playing it back.
  42945. */
  42946. if( isOpen(pPager->jfd) ){
  42947. assert( rc==SQLITE_OK );
  42948. rc = pagerSyncHotJournal(pPager);
  42949. if( rc==SQLITE_OK ){
  42950. rc = pager_playback(pPager, 1);
  42951. pPager->eState = PAGER_OPEN;
  42952. }
  42953. }else if( !pPager->exclusiveMode ){
  42954. pagerUnlockDb(pPager, SHARED_LOCK);
  42955. }
  42956. if( rc!=SQLITE_OK ){
  42957. /* This branch is taken if an error occurs while trying to open
  42958. ** or roll back a hot-journal while holding an EXCLUSIVE lock. The
  42959. ** pager_unlock() routine will be called before returning to unlock
  42960. ** the file. If the unlock attempt fails, then Pager.eLock must be
  42961. ** set to UNKNOWN_LOCK (see the comment above the #define for
  42962. ** UNKNOWN_LOCK above for an explanation).
  42963. **
  42964. ** In order to get pager_unlock() to do this, set Pager.eState to
  42965. ** PAGER_ERROR now. This is not actually counted as a transition
  42966. ** to ERROR state in the state diagram at the top of this file,
  42967. ** since we know that the same call to pager_unlock() will very
  42968. ** shortly transition the pager object to the OPEN state. Calling
  42969. ** assert_pager_state() would fail now, as it should not be possible
  42970. ** to be in ERROR state when there are zero outstanding page
  42971. ** references.
  42972. */
  42973. pager_error(pPager, rc);
  42974. goto failed;
  42975. }
  42976. assert( pPager->eState==PAGER_OPEN );
  42977. assert( (pPager->eLock==SHARED_LOCK)
  42978. || (pPager->exclusiveMode && pPager->eLock>SHARED_LOCK)
  42979. );
  42980. }
  42981. if( !pPager->tempFile && (
  42982. pPager->pBackup
  42983. || sqlite3PcachePagecount(pPager->pPCache)>0
  42984. || USEFETCH(pPager)
  42985. )){
  42986. /* The shared-lock has just been acquired on the database file
  42987. ** and there are already pages in the cache (from a previous
  42988. ** read or write transaction). Check to see if the database
  42989. ** has been modified. If the database has changed, flush the
  42990. ** cache.
  42991. **
  42992. ** Database changes is detected by looking at 15 bytes beginning
  42993. ** at offset 24 into the file. The first 4 of these 16 bytes are
  42994. ** a 32-bit counter that is incremented with each change. The
  42995. ** other bytes change randomly with each file change when
  42996. ** a codec is in use.
  42997. **
  42998. ** There is a vanishingly small chance that a change will not be
  42999. ** detected. The chance of an undetected change is so small that
  43000. ** it can be neglected.
  43001. */
  43002. Pgno nPage = 0;
  43003. char dbFileVers[sizeof(pPager->dbFileVers)];
  43004. rc = pagerPagecount(pPager, &nPage);
  43005. if( rc ) goto failed;
  43006. if( nPage>0 ){
  43007. IOTRACE(("CKVERS %p %d\n", pPager, sizeof(dbFileVers)));
  43008. rc = sqlite3OsRead(pPager->fd, &dbFileVers, sizeof(dbFileVers), 24);
  43009. if( rc!=SQLITE_OK && rc!=SQLITE_IOERR_SHORT_READ ){
  43010. goto failed;
  43011. }
  43012. }else{
  43013. memset(dbFileVers, 0, sizeof(dbFileVers));
  43014. }
  43015. if( memcmp(pPager->dbFileVers, dbFileVers, sizeof(dbFileVers))!=0 ){
  43016. pager_reset(pPager);
  43017. /* Unmap the database file. It is possible that external processes
  43018. ** may have truncated the database file and then extended it back
  43019. ** to its original size while this process was not holding a lock.
  43020. ** In this case there may exist a Pager.pMap mapping that appears
  43021. ** to be the right size but is not actually valid. Avoid this
  43022. ** possibility by unmapping the db here. */
  43023. if( USEFETCH(pPager) ){
  43024. sqlite3OsUnfetch(pPager->fd, 0, 0);
  43025. }
  43026. }
  43027. }
  43028. /* If there is a WAL file in the file-system, open this database in WAL
  43029. ** mode. Otherwise, the following function call is a no-op.
  43030. */
  43031. rc = pagerOpenWalIfPresent(pPager);
  43032. #ifndef SQLITE_OMIT_WAL
  43033. assert( pPager->pWal==0 || rc==SQLITE_OK );
  43034. #endif
  43035. }
  43036. if( pagerUseWal(pPager) ){
  43037. assert( rc==SQLITE_OK );
  43038. rc = pagerBeginReadTransaction(pPager);
  43039. }
  43040. if( pPager->eState==PAGER_OPEN && rc==SQLITE_OK ){
  43041. rc = pagerPagecount(pPager, &pPager->dbSize);
  43042. }
  43043. failed:
  43044. if( rc!=SQLITE_OK ){
  43045. assert( !MEMDB );
  43046. pager_unlock(pPager);
  43047. assert( pPager->eState==PAGER_OPEN );
  43048. }else{
  43049. pPager->eState = PAGER_READER;
  43050. }
  43051. return rc;
  43052. }
  43053. /*
  43054. ** If the reference count has reached zero, rollback any active
  43055. ** transaction and unlock the pager.
  43056. **
  43057. ** Except, in locking_mode=EXCLUSIVE when there is nothing to in
  43058. ** the rollback journal, the unlock is not performed and there is
  43059. ** nothing to rollback, so this routine is a no-op.
  43060. */
  43061. static void pagerUnlockIfUnused(Pager *pPager){
  43062. if( pPager->nMmapOut==0 && (sqlite3PcacheRefCount(pPager->pPCache)==0) ){
  43063. pagerUnlockAndRollback(pPager);
  43064. }
  43065. }
  43066. /*
  43067. ** Acquire a reference to page number pgno in pager pPager (a page
  43068. ** reference has type DbPage*). If the requested reference is
  43069. ** successfully obtained, it is copied to *ppPage and SQLITE_OK returned.
  43070. **
  43071. ** If the requested page is already in the cache, it is returned.
  43072. ** Otherwise, a new page object is allocated and populated with data
  43073. ** read from the database file. In some cases, the pcache module may
  43074. ** choose not to allocate a new page object and may reuse an existing
  43075. ** object with no outstanding references.
  43076. **
  43077. ** The extra data appended to a page is always initialized to zeros the
  43078. ** first time a page is loaded into memory. If the page requested is
  43079. ** already in the cache when this function is called, then the extra
  43080. ** data is left as it was when the page object was last used.
  43081. **
  43082. ** If the database image is smaller than the requested page or if a
  43083. ** non-zero value is passed as the noContent parameter and the
  43084. ** requested page is not already stored in the cache, then no
  43085. ** actual disk read occurs. In this case the memory image of the
  43086. ** page is initialized to all zeros.
  43087. **
  43088. ** If noContent is true, it means that we do not care about the contents
  43089. ** of the page. This occurs in two scenarios:
  43090. **
  43091. ** a) When reading a free-list leaf page from the database, and
  43092. **
  43093. ** b) When a savepoint is being rolled back and we need to load
  43094. ** a new page into the cache to be filled with the data read
  43095. ** from the savepoint journal.
  43096. **
  43097. ** If noContent is true, then the data returned is zeroed instead of
  43098. ** being read from the database. Additionally, the bits corresponding
  43099. ** to pgno in Pager.pInJournal (bitvec of pages already written to the
  43100. ** journal file) and the PagerSavepoint.pInSavepoint bitvecs of any open
  43101. ** savepoints are set. This means if the page is made writable at any
  43102. ** point in the future, using a call to sqlite3PagerWrite(), its contents
  43103. ** will not be journaled. This saves IO.
  43104. **
  43105. ** The acquisition might fail for several reasons. In all cases,
  43106. ** an appropriate error code is returned and *ppPage is set to NULL.
  43107. **
  43108. ** See also sqlite3PagerLookup(). Both this routine and Lookup() attempt
  43109. ** to find a page in the in-memory cache first. If the page is not already
  43110. ** in memory, this routine goes to disk to read it in whereas Lookup()
  43111. ** just returns 0. This routine acquires a read-lock the first time it
  43112. ** has to go to disk, and could also playback an old journal if necessary.
  43113. ** Since Lookup() never goes to disk, it never has to deal with locks
  43114. ** or journal files.
  43115. */
  43116. SQLITE_PRIVATE int sqlite3PagerAcquire(
  43117. Pager *pPager, /* The pager open on the database file */
  43118. Pgno pgno, /* Page number to fetch */
  43119. DbPage **ppPage, /* Write a pointer to the page here */
  43120. int flags /* PAGER_GET_XXX flags */
  43121. ){
  43122. int rc = SQLITE_OK;
  43123. PgHdr *pPg = 0;
  43124. u32 iFrame = 0; /* Frame to read from WAL file */
  43125. const int noContent = (flags & PAGER_GET_NOCONTENT);
  43126. /* It is acceptable to use a read-only (mmap) page for any page except
  43127. ** page 1 if there is no write-transaction open or the ACQUIRE_READONLY
  43128. ** flag was specified by the caller. And so long as the db is not a
  43129. ** temporary or in-memory database. */
  43130. const int bMmapOk = (pgno!=1 && USEFETCH(pPager)
  43131. && (pPager->eState==PAGER_READER || (flags & PAGER_GET_READONLY))
  43132. #ifdef SQLITE_HAS_CODEC
  43133. && pPager->xCodec==0
  43134. #endif
  43135. );
  43136. assert( pPager->eState>=PAGER_READER );
  43137. assert( assert_pager_state(pPager) );
  43138. assert( noContent==0 || bMmapOk==0 );
  43139. if( pgno==0 ){
  43140. return SQLITE_CORRUPT_BKPT;
  43141. }
  43142. /* If the pager is in the error state, return an error immediately.
  43143. ** Otherwise, request the page from the PCache layer. */
  43144. if( pPager->errCode!=SQLITE_OK ){
  43145. rc = pPager->errCode;
  43146. }else{
  43147. if( bMmapOk && pagerUseWal(pPager) ){
  43148. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  43149. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43150. }
  43151. if( bMmapOk && iFrame==0 ){
  43152. void *pData = 0;
  43153. rc = sqlite3OsFetch(pPager->fd,
  43154. (i64)(pgno-1) * pPager->pageSize, pPager->pageSize, &pData
  43155. );
  43156. if( rc==SQLITE_OK && pData ){
  43157. if( pPager->eState>PAGER_READER ){
  43158. pPg = sqlite3PagerLookup(pPager, pgno);
  43159. }
  43160. if( pPg==0 ){
  43161. rc = pagerAcquireMapPage(pPager, pgno, pData, &pPg);
  43162. }else{
  43163. sqlite3OsUnfetch(pPager->fd, (i64)(pgno-1)*pPager->pageSize, pData);
  43164. }
  43165. if( pPg ){
  43166. assert( rc==SQLITE_OK );
  43167. *ppPage = pPg;
  43168. return SQLITE_OK;
  43169. }
  43170. }
  43171. if( rc!=SQLITE_OK ){
  43172. goto pager_acquire_err;
  43173. }
  43174. }
  43175. {
  43176. sqlite3_pcache_page *pBase;
  43177. pBase = sqlite3PcacheFetch(pPager->pPCache, pgno, 3);
  43178. if( pBase==0 ){
  43179. rc = sqlite3PcacheFetchStress(pPager->pPCache, pgno, &pBase);
  43180. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43181. }
  43182. pPg = *ppPage = sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pBase);
  43183. if( pPg==0 ) rc = SQLITE_NOMEM;
  43184. }
  43185. }
  43186. if( rc!=SQLITE_OK ){
  43187. /* Either the call to sqlite3PcacheFetch() returned an error or the
  43188. ** pager was already in the error-state when this function was called.
  43189. ** Set pPg to 0 and jump to the exception handler. */
  43190. pPg = 0;
  43191. goto pager_acquire_err;
  43192. }
  43193. assert( (*ppPage)->pgno==pgno );
  43194. assert( (*ppPage)->pPager==pPager || (*ppPage)->pPager==0 );
  43195. if( (*ppPage)->pPager && !noContent ){
  43196. /* In this case the pcache already contains an initialized copy of
  43197. ** the page. Return without further ado. */
  43198. assert( pgno<=PAGER_MAX_PGNO && pgno!=PAGER_MJ_PGNO(pPager) );
  43199. pPager->aStat[PAGER_STAT_HIT]++;
  43200. return SQLITE_OK;
  43201. }else{
  43202. /* The pager cache has created a new page. Its content needs to
  43203. ** be initialized. */
  43204. pPg = *ppPage;
  43205. pPg->pPager = pPager;
  43206. /* The maximum page number is 2^31. Return SQLITE_CORRUPT if a page
  43207. ** number greater than this, or the unused locking-page, is requested. */
  43208. if( pgno>PAGER_MAX_PGNO || pgno==PAGER_MJ_PGNO(pPager) ){
  43209. rc = SQLITE_CORRUPT_BKPT;
  43210. goto pager_acquire_err;
  43211. }
  43212. if( MEMDB || pPager->dbSize<pgno || noContent || !isOpen(pPager->fd) ){
  43213. if( pgno>pPager->mxPgno ){
  43214. rc = SQLITE_FULL;
  43215. goto pager_acquire_err;
  43216. }
  43217. if( noContent ){
  43218. /* Failure to set the bits in the InJournal bit-vectors is benign.
  43219. ** It merely means that we might do some extra work to journal a
  43220. ** page that does not need to be journaled. Nevertheless, be sure
  43221. ** to test the case where a malloc error occurs while trying to set
  43222. ** a bit in a bit vector.
  43223. */
  43224. sqlite3BeginBenignMalloc();
  43225. if( pgno<=pPager->dbOrigSize ){
  43226. TESTONLY( rc = ) sqlite3BitvecSet(pPager->pInJournal, pgno);
  43227. testcase( rc==SQLITE_NOMEM );
  43228. }
  43229. TESTONLY( rc = ) addToSavepointBitvecs(pPager, pgno);
  43230. testcase( rc==SQLITE_NOMEM );
  43231. sqlite3EndBenignMalloc();
  43232. }
  43233. memset(pPg->pData, 0, pPager->pageSize);
  43234. IOTRACE(("ZERO %p %d\n", pPager, pgno));
  43235. }else{
  43236. if( pagerUseWal(pPager) && bMmapOk==0 ){
  43237. rc = sqlite3WalFindFrame(pPager->pWal, pgno, &iFrame);
  43238. if( rc!=SQLITE_OK ) goto pager_acquire_err;
  43239. }
  43240. assert( pPg->pPager==pPager );
  43241. pPager->aStat[PAGER_STAT_MISS]++;
  43242. rc = readDbPage(pPg, iFrame);
  43243. if( rc!=SQLITE_OK ){
  43244. goto pager_acquire_err;
  43245. }
  43246. }
  43247. pager_set_pagehash(pPg);
  43248. }
  43249. return SQLITE_OK;
  43250. pager_acquire_err:
  43251. assert( rc!=SQLITE_OK );
  43252. if( pPg ){
  43253. sqlite3PcacheDrop(pPg);
  43254. }
  43255. pagerUnlockIfUnused(pPager);
  43256. *ppPage = 0;
  43257. return rc;
  43258. }
  43259. /*
  43260. ** Acquire a page if it is already in the in-memory cache. Do
  43261. ** not read the page from disk. Return a pointer to the page,
  43262. ** or 0 if the page is not in cache.
  43263. **
  43264. ** See also sqlite3PagerGet(). The difference between this routine
  43265. ** and sqlite3PagerGet() is that _get() will go to the disk and read
  43266. ** in the page if the page is not already in cache. This routine
  43267. ** returns NULL if the page is not in cache or if a disk I/O error
  43268. ** has ever happened.
  43269. */
  43270. SQLITE_PRIVATE DbPage *sqlite3PagerLookup(Pager *pPager, Pgno pgno){
  43271. sqlite3_pcache_page *pPage;
  43272. assert( pPager!=0 );
  43273. assert( pgno!=0 );
  43274. assert( pPager->pPCache!=0 );
  43275. pPage = sqlite3PcacheFetch(pPager->pPCache, pgno, 0);
  43276. return sqlite3PcacheFetchFinish(pPager->pPCache, pgno, pPage);
  43277. }
  43278. /*
  43279. ** Release a page reference.
  43280. **
  43281. ** If the number of references to the page drop to zero, then the
  43282. ** page is added to the LRU list. When all references to all pages
  43283. ** are released, a rollback occurs and the lock on the database is
  43284. ** removed.
  43285. */
  43286. SQLITE_PRIVATE void sqlite3PagerUnrefNotNull(DbPage *pPg){
  43287. Pager *pPager;
  43288. assert( pPg!=0 );
  43289. pPager = pPg->pPager;
  43290. if( pPg->flags & PGHDR_MMAP ){
  43291. pagerReleaseMapPage(pPg);
  43292. }else{
  43293. sqlite3PcacheRelease(pPg);
  43294. }
  43295. pagerUnlockIfUnused(pPager);
  43296. }
  43297. SQLITE_PRIVATE void sqlite3PagerUnref(DbPage *pPg){
  43298. if( pPg ) sqlite3PagerUnrefNotNull(pPg);
  43299. }
  43300. /*
  43301. ** This function is called at the start of every write transaction.
  43302. ** There must already be a RESERVED or EXCLUSIVE lock on the database
  43303. ** file when this routine is called.
  43304. **
  43305. ** Open the journal file for pager pPager and write a journal header
  43306. ** to the start of it. If there are active savepoints, open the sub-journal
  43307. ** as well. This function is only used when the journal file is being
  43308. ** opened to write a rollback log for a transaction. It is not used
  43309. ** when opening a hot journal file to roll it back.
  43310. **
  43311. ** If the journal file is already open (as it may be in exclusive mode),
  43312. ** then this function just writes a journal header to the start of the
  43313. ** already open file.
  43314. **
  43315. ** Whether or not the journal file is opened by this function, the
  43316. ** Pager.pInJournal bitvec structure is allocated.
  43317. **
  43318. ** Return SQLITE_OK if everything is successful. Otherwise, return
  43319. ** SQLITE_NOMEM if the attempt to allocate Pager.pInJournal fails, or
  43320. ** an IO error code if opening or writing the journal file fails.
  43321. */
  43322. static int pager_open_journal(Pager *pPager){
  43323. int rc = SQLITE_OK; /* Return code */
  43324. sqlite3_vfs * const pVfs = pPager->pVfs; /* Local cache of vfs pointer */
  43325. assert( pPager->eState==PAGER_WRITER_LOCKED );
  43326. assert( assert_pager_state(pPager) );
  43327. assert( pPager->pInJournal==0 );
  43328. /* If already in the error state, this function is a no-op. But on
  43329. ** the other hand, this routine is never called if we are already in
  43330. ** an error state. */
  43331. if( NEVER(pPager->errCode) ) return pPager->errCode;
  43332. if( !pagerUseWal(pPager) && pPager->journalMode!=PAGER_JOURNALMODE_OFF ){
  43333. pPager->pInJournal = sqlite3BitvecCreate(pPager->dbSize);
  43334. if( pPager->pInJournal==0 ){
  43335. return SQLITE_NOMEM;
  43336. }
  43337. /* Open the journal file if it is not already open. */
  43338. if( !isOpen(pPager->jfd) ){
  43339. if( pPager->journalMode==PAGER_JOURNALMODE_MEMORY ){
  43340. sqlite3MemJournalOpen(pPager->jfd);
  43341. }else{
  43342. const int flags = /* VFS flags to open journal file */
  43343. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  43344. (pPager->tempFile ?
  43345. (SQLITE_OPEN_DELETEONCLOSE|SQLITE_OPEN_TEMP_JOURNAL):
  43346. (SQLITE_OPEN_MAIN_JOURNAL)
  43347. );
  43348. /* Verify that the database still has the same name as it did when
  43349. ** it was originally opened. */
  43350. rc = databaseIsUnmoved(pPager);
  43351. if( rc==SQLITE_OK ){
  43352. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  43353. rc = sqlite3JournalOpen(
  43354. pVfs, pPager->zJournal, pPager->jfd, flags, jrnlBufferSize(pPager)
  43355. );
  43356. #else
  43357. rc = sqlite3OsOpen(pVfs, pPager->zJournal, pPager->jfd, flags, 0);
  43358. #endif
  43359. }
  43360. }
  43361. assert( rc!=SQLITE_OK || isOpen(pPager->jfd) );
  43362. }
  43363. /* Write the first journal header to the journal file and open
  43364. ** the sub-journal if necessary.
  43365. */
  43366. if( rc==SQLITE_OK ){
  43367. /* TODO: Check if all of these are really required. */
  43368. pPager->nRec = 0;
  43369. pPager->journalOff = 0;
  43370. pPager->setMaster = 0;
  43371. pPager->journalHdr = 0;
  43372. rc = writeJournalHdr(pPager);
  43373. }
  43374. }
  43375. if( rc!=SQLITE_OK ){
  43376. sqlite3BitvecDestroy(pPager->pInJournal);
  43377. pPager->pInJournal = 0;
  43378. }else{
  43379. assert( pPager->eState==PAGER_WRITER_LOCKED );
  43380. pPager->eState = PAGER_WRITER_CACHEMOD;
  43381. }
  43382. return rc;
  43383. }
  43384. /*
  43385. ** Begin a write-transaction on the specified pager object. If a
  43386. ** write-transaction has already been opened, this function is a no-op.
  43387. **
  43388. ** If the exFlag argument is false, then acquire at least a RESERVED
  43389. ** lock on the database file. If exFlag is true, then acquire at least
  43390. ** an EXCLUSIVE lock. If such a lock is already held, no locking
  43391. ** functions need be called.
  43392. **
  43393. ** If the subjInMemory argument is non-zero, then any sub-journal opened
  43394. ** within this transaction will be opened as an in-memory file. This
  43395. ** has no effect if the sub-journal is already opened (as it may be when
  43396. ** running in exclusive mode) or if the transaction does not require a
  43397. ** sub-journal. If the subjInMemory argument is zero, then any required
  43398. ** sub-journal is implemented in-memory if pPager is an in-memory database,
  43399. ** or using a temporary file otherwise.
  43400. */
  43401. SQLITE_PRIVATE int sqlite3PagerBegin(Pager *pPager, int exFlag, int subjInMemory){
  43402. int rc = SQLITE_OK;
  43403. if( pPager->errCode ) return pPager->errCode;
  43404. assert( pPager->eState>=PAGER_READER && pPager->eState<PAGER_ERROR );
  43405. pPager->subjInMemory = (u8)subjInMemory;
  43406. if( ALWAYS(pPager->eState==PAGER_READER) ){
  43407. assert( pPager->pInJournal==0 );
  43408. if( pagerUseWal(pPager) ){
  43409. /* If the pager is configured to use locking_mode=exclusive, and an
  43410. ** exclusive lock on the database is not already held, obtain it now.
  43411. */
  43412. if( pPager->exclusiveMode && sqlite3WalExclusiveMode(pPager->pWal, -1) ){
  43413. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  43414. if( rc!=SQLITE_OK ){
  43415. return rc;
  43416. }
  43417. sqlite3WalExclusiveMode(pPager->pWal, 1);
  43418. }
  43419. /* Grab the write lock on the log file. If successful, upgrade to
  43420. ** PAGER_RESERVED state. Otherwise, return an error code to the caller.
  43421. ** The busy-handler is not invoked if another connection already
  43422. ** holds the write-lock. If possible, the upper layer will call it.
  43423. */
  43424. rc = sqlite3WalBeginWriteTransaction(pPager->pWal);
  43425. }else{
  43426. /* Obtain a RESERVED lock on the database file. If the exFlag parameter
  43427. ** is true, then immediately upgrade this to an EXCLUSIVE lock. The
  43428. ** busy-handler callback can be used when upgrading to the EXCLUSIVE
  43429. ** lock, but not when obtaining the RESERVED lock.
  43430. */
  43431. rc = pagerLockDb(pPager, RESERVED_LOCK);
  43432. if( rc==SQLITE_OK && exFlag ){
  43433. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  43434. }
  43435. }
  43436. if( rc==SQLITE_OK ){
  43437. /* Change to WRITER_LOCKED state.
  43438. **
  43439. ** WAL mode sets Pager.eState to PAGER_WRITER_LOCKED or CACHEMOD
  43440. ** when it has an open transaction, but never to DBMOD or FINISHED.
  43441. ** This is because in those states the code to roll back savepoint
  43442. ** transactions may copy data from the sub-journal into the database
  43443. ** file as well as into the page cache. Which would be incorrect in
  43444. ** WAL mode.
  43445. */
  43446. pPager->eState = PAGER_WRITER_LOCKED;
  43447. pPager->dbHintSize = pPager->dbSize;
  43448. pPager->dbFileSize = pPager->dbSize;
  43449. pPager->dbOrigSize = pPager->dbSize;
  43450. pPager->journalOff = 0;
  43451. }
  43452. assert( rc==SQLITE_OK || pPager->eState==PAGER_READER );
  43453. assert( rc!=SQLITE_OK || pPager->eState==PAGER_WRITER_LOCKED );
  43454. assert( assert_pager_state(pPager) );
  43455. }
  43456. PAGERTRACE(("TRANSACTION %d\n", PAGERID(pPager)));
  43457. return rc;
  43458. }
  43459. /*
  43460. ** Mark a single data page as writeable. The page is written into the
  43461. ** main journal or sub-journal as required. If the page is written into
  43462. ** one of the journals, the corresponding bit is set in the
  43463. ** Pager.pInJournal bitvec and the PagerSavepoint.pInSavepoint bitvecs
  43464. ** of any open savepoints as appropriate.
  43465. */
  43466. static int pager_write(PgHdr *pPg){
  43467. Pager *pPager = pPg->pPager;
  43468. int rc = SQLITE_OK;
  43469. int inJournal;
  43470. /* This routine is not called unless a write-transaction has already
  43471. ** been started. The journal file may or may not be open at this point.
  43472. ** It is never called in the ERROR state.
  43473. */
  43474. assert( pPager->eState==PAGER_WRITER_LOCKED
  43475. || pPager->eState==PAGER_WRITER_CACHEMOD
  43476. || pPager->eState==PAGER_WRITER_DBMOD
  43477. );
  43478. assert( assert_pager_state(pPager) );
  43479. assert( pPager->errCode==0 );
  43480. assert( pPager->readOnly==0 );
  43481. CHECK_PAGE(pPg);
  43482. /* The journal file needs to be opened. Higher level routines have already
  43483. ** obtained the necessary locks to begin the write-transaction, but the
  43484. ** rollback journal might not yet be open. Open it now if this is the case.
  43485. **
  43486. ** This is done before calling sqlite3PcacheMakeDirty() on the page.
  43487. ** Otherwise, if it were done after calling sqlite3PcacheMakeDirty(), then
  43488. ** an error might occur and the pager would end up in WRITER_LOCKED state
  43489. ** with pages marked as dirty in the cache.
  43490. */
  43491. if( pPager->eState==PAGER_WRITER_LOCKED ){
  43492. rc = pager_open_journal(pPager);
  43493. if( rc!=SQLITE_OK ) return rc;
  43494. }
  43495. assert( pPager->eState>=PAGER_WRITER_CACHEMOD );
  43496. assert( assert_pager_state(pPager) );
  43497. /* Mark the page as dirty. If the page has already been written
  43498. ** to the journal then we can return right away.
  43499. */
  43500. sqlite3PcacheMakeDirty(pPg);
  43501. inJournal = pageInJournal(pPager, pPg);
  43502. if( inJournal && (pPager->nSavepoint==0 || !subjRequiresPage(pPg)) ){
  43503. assert( !pagerUseWal(pPager) );
  43504. }else{
  43505. /* The transaction journal now exists and we have a RESERVED or an
  43506. ** EXCLUSIVE lock on the main database file. Write the current page to
  43507. ** the transaction journal if it is not there already.
  43508. */
  43509. if( !inJournal && !pagerUseWal(pPager) ){
  43510. assert( pagerUseWal(pPager)==0 );
  43511. if( pPg->pgno<=pPager->dbOrigSize && isOpen(pPager->jfd) ){
  43512. u32 cksum;
  43513. char *pData2;
  43514. i64 iOff = pPager->journalOff;
  43515. /* We should never write to the journal file the page that
  43516. ** contains the database locks. The following assert verifies
  43517. ** that we do not. */
  43518. assert( pPg->pgno!=PAGER_MJ_PGNO(pPager) );
  43519. assert( pPager->journalHdr<=pPager->journalOff );
  43520. CODEC2(pPager, pPg->pData, pPg->pgno, 7, return SQLITE_NOMEM, pData2);
  43521. cksum = pager_cksum(pPager, (u8*)pData2);
  43522. /* Even if an IO or diskfull error occurs while journalling the
  43523. ** page in the block above, set the need-sync flag for the page.
  43524. ** Otherwise, when the transaction is rolled back, the logic in
  43525. ** playback_one_page() will think that the page needs to be restored
  43526. ** in the database file. And if an IO error occurs while doing so,
  43527. ** then corruption may follow.
  43528. */
  43529. pPg->flags |= PGHDR_NEED_SYNC;
  43530. rc = write32bits(pPager->jfd, iOff, pPg->pgno);
  43531. if( rc!=SQLITE_OK ) return rc;
  43532. rc = sqlite3OsWrite(pPager->jfd, pData2, pPager->pageSize, iOff+4);
  43533. if( rc!=SQLITE_OK ) return rc;
  43534. rc = write32bits(pPager->jfd, iOff+pPager->pageSize+4, cksum);
  43535. if( rc!=SQLITE_OK ) return rc;
  43536. IOTRACE(("JOUT %p %d %lld %d\n", pPager, pPg->pgno,
  43537. pPager->journalOff, pPager->pageSize));
  43538. PAGER_INCR(sqlite3_pager_writej_count);
  43539. PAGERTRACE(("JOURNAL %d page %d needSync=%d hash(%08x)\n",
  43540. PAGERID(pPager), pPg->pgno,
  43541. ((pPg->flags&PGHDR_NEED_SYNC)?1:0), pager_pagehash(pPg)));
  43542. pPager->journalOff += 8 + pPager->pageSize;
  43543. pPager->nRec++;
  43544. assert( pPager->pInJournal!=0 );
  43545. rc = sqlite3BitvecSet(pPager->pInJournal, pPg->pgno);
  43546. testcase( rc==SQLITE_NOMEM );
  43547. assert( rc==SQLITE_OK || rc==SQLITE_NOMEM );
  43548. rc |= addToSavepointBitvecs(pPager, pPg->pgno);
  43549. if( rc!=SQLITE_OK ){
  43550. assert( rc==SQLITE_NOMEM );
  43551. return rc;
  43552. }
  43553. }else{
  43554. if( pPager->eState!=PAGER_WRITER_DBMOD ){
  43555. pPg->flags |= PGHDR_NEED_SYNC;
  43556. }
  43557. PAGERTRACE(("APPEND %d page %d needSync=%d\n",
  43558. PAGERID(pPager), pPg->pgno,
  43559. ((pPg->flags&PGHDR_NEED_SYNC)?1:0)));
  43560. }
  43561. }
  43562. /* If the statement journal is open and the page is not in it,
  43563. ** then write the current page to the statement journal. Note that
  43564. ** the statement journal format differs from the standard journal format
  43565. ** in that it omits the checksums and the header.
  43566. */
  43567. if( pPager->nSavepoint>0 && subjRequiresPage(pPg) ){
  43568. rc = subjournalPage(pPg);
  43569. }
  43570. }
  43571. /* Update the database size and return.
  43572. */
  43573. if( pPager->dbSize<pPg->pgno ){
  43574. pPager->dbSize = pPg->pgno;
  43575. }
  43576. return rc;
  43577. }
  43578. /*
  43579. ** This is a variant of sqlite3PagerWrite() that runs when the sector size
  43580. ** is larger than the page size. SQLite makes the (reasonable) assumption that
  43581. ** all bytes of a sector are written together by hardware. Hence, all bytes of
  43582. ** a sector need to be journalled in case of a power loss in the middle of
  43583. ** a write.
  43584. **
  43585. ** Usually, the sector size is less than or equal to the page size, in which
  43586. ** case pages can be individually written. This routine only runs in the exceptional
  43587. ** case where the page size is smaller than the sector size.
  43588. */
  43589. static SQLITE_NOINLINE int pagerWriteLargeSector(PgHdr *pPg){
  43590. int rc = SQLITE_OK; /* Return code */
  43591. Pgno nPageCount; /* Total number of pages in database file */
  43592. Pgno pg1; /* First page of the sector pPg is located on. */
  43593. int nPage = 0; /* Number of pages starting at pg1 to journal */
  43594. int ii; /* Loop counter */
  43595. int needSync = 0; /* True if any page has PGHDR_NEED_SYNC */
  43596. Pager *pPager = pPg->pPager; /* The pager that owns pPg */
  43597. Pgno nPagePerSector = (pPager->sectorSize/pPager->pageSize);
  43598. /* Set the doNotSpill NOSYNC bit to 1. This is because we cannot allow
  43599. ** a journal header to be written between the pages journaled by
  43600. ** this function.
  43601. */
  43602. assert( !MEMDB );
  43603. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)==0 );
  43604. pPager->doNotSpill |= SPILLFLAG_NOSYNC;
  43605. /* This trick assumes that both the page-size and sector-size are
  43606. ** an integer power of 2. It sets variable pg1 to the identifier
  43607. ** of the first page of the sector pPg is located on.
  43608. */
  43609. pg1 = ((pPg->pgno-1) & ~(nPagePerSector-1)) + 1;
  43610. nPageCount = pPager->dbSize;
  43611. if( pPg->pgno>nPageCount ){
  43612. nPage = (pPg->pgno - pg1)+1;
  43613. }else if( (pg1+nPagePerSector-1)>nPageCount ){
  43614. nPage = nPageCount+1-pg1;
  43615. }else{
  43616. nPage = nPagePerSector;
  43617. }
  43618. assert(nPage>0);
  43619. assert(pg1<=pPg->pgno);
  43620. assert((pg1+nPage)>pPg->pgno);
  43621. for(ii=0; ii<nPage && rc==SQLITE_OK; ii++){
  43622. Pgno pg = pg1+ii;
  43623. PgHdr *pPage;
  43624. if( pg==pPg->pgno || !sqlite3BitvecTest(pPager->pInJournal, pg) ){
  43625. if( pg!=PAGER_MJ_PGNO(pPager) ){
  43626. rc = sqlite3PagerGet(pPager, pg, &pPage);
  43627. if( rc==SQLITE_OK ){
  43628. rc = pager_write(pPage);
  43629. if( pPage->flags&PGHDR_NEED_SYNC ){
  43630. needSync = 1;
  43631. }
  43632. sqlite3PagerUnrefNotNull(pPage);
  43633. }
  43634. }
  43635. }else if( (pPage = sqlite3PagerLookup(pPager, pg))!=0 ){
  43636. if( pPage->flags&PGHDR_NEED_SYNC ){
  43637. needSync = 1;
  43638. }
  43639. sqlite3PagerUnrefNotNull(pPage);
  43640. }
  43641. }
  43642. /* If the PGHDR_NEED_SYNC flag is set for any of the nPage pages
  43643. ** starting at pg1, then it needs to be set for all of them. Because
  43644. ** writing to any of these nPage pages may damage the others, the
  43645. ** journal file must contain sync()ed copies of all of them
  43646. ** before any of them can be written out to the database file.
  43647. */
  43648. if( rc==SQLITE_OK && needSync ){
  43649. assert( !MEMDB );
  43650. for(ii=0; ii<nPage; ii++){
  43651. PgHdr *pPage = sqlite3PagerLookup(pPager, pg1+ii);
  43652. if( pPage ){
  43653. pPage->flags |= PGHDR_NEED_SYNC;
  43654. sqlite3PagerUnrefNotNull(pPage);
  43655. }
  43656. }
  43657. }
  43658. assert( (pPager->doNotSpill & SPILLFLAG_NOSYNC)!=0 );
  43659. pPager->doNotSpill &= ~SPILLFLAG_NOSYNC;
  43660. return rc;
  43661. }
  43662. /*
  43663. ** Mark a data page as writeable. This routine must be called before
  43664. ** making changes to a page. The caller must check the return value
  43665. ** of this function and be careful not to change any page data unless
  43666. ** this routine returns SQLITE_OK.
  43667. **
  43668. ** The difference between this function and pager_write() is that this
  43669. ** function also deals with the special case where 2 or more pages
  43670. ** fit on a single disk sector. In this case all co-resident pages
  43671. ** must have been written to the journal file before returning.
  43672. **
  43673. ** If an error occurs, SQLITE_NOMEM or an IO error code is returned
  43674. ** as appropriate. Otherwise, SQLITE_OK.
  43675. */
  43676. SQLITE_PRIVATE int sqlite3PagerWrite(PgHdr *pPg){
  43677. assert( (pPg->flags & PGHDR_MMAP)==0 );
  43678. assert( pPg->pPager->eState>=PAGER_WRITER_LOCKED );
  43679. assert( pPg->pPager->eState!=PAGER_ERROR );
  43680. assert( assert_pager_state(pPg->pPager) );
  43681. if( pPg->pPager->sectorSize > (u32)pPg->pPager->pageSize ){
  43682. return pagerWriteLargeSector(pPg);
  43683. }else{
  43684. return pager_write(pPg);
  43685. }
  43686. }
  43687. /*
  43688. ** Return TRUE if the page given in the argument was previously passed
  43689. ** to sqlite3PagerWrite(). In other words, return TRUE if it is ok
  43690. ** to change the content of the page.
  43691. */
  43692. #ifndef NDEBUG
  43693. SQLITE_PRIVATE int sqlite3PagerIswriteable(DbPage *pPg){
  43694. return pPg->flags&PGHDR_DIRTY;
  43695. }
  43696. #endif
  43697. /*
  43698. ** A call to this routine tells the pager that it is not necessary to
  43699. ** write the information on page pPg back to the disk, even though
  43700. ** that page might be marked as dirty. This happens, for example, when
  43701. ** the page has been added as a leaf of the freelist and so its
  43702. ** content no longer matters.
  43703. **
  43704. ** The overlying software layer calls this routine when all of the data
  43705. ** on the given page is unused. The pager marks the page as clean so
  43706. ** that it does not get written to disk.
  43707. **
  43708. ** Tests show that this optimization can quadruple the speed of large
  43709. ** DELETE operations.
  43710. */
  43711. SQLITE_PRIVATE void sqlite3PagerDontWrite(PgHdr *pPg){
  43712. Pager *pPager = pPg->pPager;
  43713. if( (pPg->flags&PGHDR_DIRTY) && pPager->nSavepoint==0 ){
  43714. PAGERTRACE(("DONT_WRITE page %d of %d\n", pPg->pgno, PAGERID(pPager)));
  43715. IOTRACE(("CLEAN %p %d\n", pPager, pPg->pgno))
  43716. pPg->flags |= PGHDR_DONT_WRITE;
  43717. pager_set_pagehash(pPg);
  43718. }
  43719. }
  43720. /*
  43721. ** This routine is called to increment the value of the database file
  43722. ** change-counter, stored as a 4-byte big-endian integer starting at
  43723. ** byte offset 24 of the pager file. The secondary change counter at
  43724. ** 92 is also updated, as is the SQLite version number at offset 96.
  43725. **
  43726. ** But this only happens if the pPager->changeCountDone flag is false.
  43727. ** To avoid excess churning of page 1, the update only happens once.
  43728. ** See also the pager_write_changecounter() routine that does an
  43729. ** unconditional update of the change counters.
  43730. **
  43731. ** If the isDirectMode flag is zero, then this is done by calling
  43732. ** sqlite3PagerWrite() on page 1, then modifying the contents of the
  43733. ** page data. In this case the file will be updated when the current
  43734. ** transaction is committed.
  43735. **
  43736. ** The isDirectMode flag may only be non-zero if the library was compiled
  43737. ** with the SQLITE_ENABLE_ATOMIC_WRITE macro defined. In this case,
  43738. ** if isDirect is non-zero, then the database file is updated directly
  43739. ** by writing an updated version of page 1 using a call to the
  43740. ** sqlite3OsWrite() function.
  43741. */
  43742. static int pager_incr_changecounter(Pager *pPager, int isDirectMode){
  43743. int rc = SQLITE_OK;
  43744. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  43745. || pPager->eState==PAGER_WRITER_DBMOD
  43746. );
  43747. assert( assert_pager_state(pPager) );
  43748. /* Declare and initialize constant integer 'isDirect'. If the
  43749. ** atomic-write optimization is enabled in this build, then isDirect
  43750. ** is initialized to the value passed as the isDirectMode parameter
  43751. ** to this function. Otherwise, it is always set to zero.
  43752. **
  43753. ** The idea is that if the atomic-write optimization is not
  43754. ** enabled at compile time, the compiler can omit the tests of
  43755. ** 'isDirect' below, as well as the block enclosed in the
  43756. ** "if( isDirect )" condition.
  43757. */
  43758. #ifndef SQLITE_ENABLE_ATOMIC_WRITE
  43759. # define DIRECT_MODE 0
  43760. assert( isDirectMode==0 );
  43761. UNUSED_PARAMETER(isDirectMode);
  43762. #else
  43763. # define DIRECT_MODE isDirectMode
  43764. #endif
  43765. if( !pPager->changeCountDone && ALWAYS(pPager->dbSize>0) ){
  43766. PgHdr *pPgHdr; /* Reference to page 1 */
  43767. assert( !pPager->tempFile && isOpen(pPager->fd) );
  43768. /* Open page 1 of the file for writing. */
  43769. rc = sqlite3PagerGet(pPager, 1, &pPgHdr);
  43770. assert( pPgHdr==0 || rc==SQLITE_OK );
  43771. /* If page one was fetched successfully, and this function is not
  43772. ** operating in direct-mode, make page 1 writable. When not in
  43773. ** direct mode, page 1 is always held in cache and hence the PagerGet()
  43774. ** above is always successful - hence the ALWAYS on rc==SQLITE_OK.
  43775. */
  43776. if( !DIRECT_MODE && ALWAYS(rc==SQLITE_OK) ){
  43777. rc = sqlite3PagerWrite(pPgHdr);
  43778. }
  43779. if( rc==SQLITE_OK ){
  43780. /* Actually do the update of the change counter */
  43781. pager_write_changecounter(pPgHdr);
  43782. /* If running in direct mode, write the contents of page 1 to the file. */
  43783. if( DIRECT_MODE ){
  43784. const void *zBuf;
  43785. assert( pPager->dbFileSize>0 );
  43786. CODEC2(pPager, pPgHdr->pData, 1, 6, rc=SQLITE_NOMEM, zBuf);
  43787. if( rc==SQLITE_OK ){
  43788. rc = sqlite3OsWrite(pPager->fd, zBuf, pPager->pageSize, 0);
  43789. pPager->aStat[PAGER_STAT_WRITE]++;
  43790. }
  43791. if( rc==SQLITE_OK ){
  43792. /* Update the pager's copy of the change-counter. Otherwise, the
  43793. ** next time a read transaction is opened the cache will be
  43794. ** flushed (as the change-counter values will not match). */
  43795. const void *pCopy = (const void *)&((const char *)zBuf)[24];
  43796. memcpy(&pPager->dbFileVers, pCopy, sizeof(pPager->dbFileVers));
  43797. pPager->changeCountDone = 1;
  43798. }
  43799. }else{
  43800. pPager->changeCountDone = 1;
  43801. }
  43802. }
  43803. /* Release the page reference. */
  43804. sqlite3PagerUnref(pPgHdr);
  43805. }
  43806. return rc;
  43807. }
  43808. /*
  43809. ** Sync the database file to disk. This is a no-op for in-memory databases
  43810. ** or pages with the Pager.noSync flag set.
  43811. **
  43812. ** If successful, or if called on a pager for which it is a no-op, this
  43813. ** function returns SQLITE_OK. Otherwise, an IO error code is returned.
  43814. */
  43815. SQLITE_PRIVATE int sqlite3PagerSync(Pager *pPager, const char *zMaster){
  43816. int rc = SQLITE_OK;
  43817. if( isOpen(pPager->fd) ){
  43818. void *pArg = (void*)zMaster;
  43819. rc = sqlite3OsFileControl(pPager->fd, SQLITE_FCNTL_SYNC, pArg);
  43820. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  43821. }
  43822. if( rc==SQLITE_OK && !pPager->noSync ){
  43823. assert( !MEMDB );
  43824. rc = sqlite3OsSync(pPager->fd, pPager->syncFlags);
  43825. }
  43826. return rc;
  43827. }
  43828. /*
  43829. ** This function may only be called while a write-transaction is active in
  43830. ** rollback. If the connection is in WAL mode, this call is a no-op.
  43831. ** Otherwise, if the connection does not already have an EXCLUSIVE lock on
  43832. ** the database file, an attempt is made to obtain one.
  43833. **
  43834. ** If the EXCLUSIVE lock is already held or the attempt to obtain it is
  43835. ** successful, or the connection is in WAL mode, SQLITE_OK is returned.
  43836. ** Otherwise, either SQLITE_BUSY or an SQLITE_IOERR_XXX error code is
  43837. ** returned.
  43838. */
  43839. SQLITE_PRIVATE int sqlite3PagerExclusiveLock(Pager *pPager){
  43840. int rc = SQLITE_OK;
  43841. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  43842. || pPager->eState==PAGER_WRITER_DBMOD
  43843. || pPager->eState==PAGER_WRITER_LOCKED
  43844. );
  43845. assert( assert_pager_state(pPager) );
  43846. if( 0==pagerUseWal(pPager) ){
  43847. rc = pager_wait_on_lock(pPager, EXCLUSIVE_LOCK);
  43848. }
  43849. return rc;
  43850. }
  43851. /*
  43852. ** Sync the database file for the pager pPager. zMaster points to the name
  43853. ** of a master journal file that should be written into the individual
  43854. ** journal file. zMaster may be NULL, which is interpreted as no master
  43855. ** journal (a single database transaction).
  43856. **
  43857. ** This routine ensures that:
  43858. **
  43859. ** * The database file change-counter is updated,
  43860. ** * the journal is synced (unless the atomic-write optimization is used),
  43861. ** * all dirty pages are written to the database file,
  43862. ** * the database file is truncated (if required), and
  43863. ** * the database file synced.
  43864. **
  43865. ** The only thing that remains to commit the transaction is to finalize
  43866. ** (delete, truncate or zero the first part of) the journal file (or
  43867. ** delete the master journal file if specified).
  43868. **
  43869. ** Note that if zMaster==NULL, this does not overwrite a previous value
  43870. ** passed to an sqlite3PagerCommitPhaseOne() call.
  43871. **
  43872. ** If the final parameter - noSync - is true, then the database file itself
  43873. ** is not synced. The caller must call sqlite3PagerSync() directly to
  43874. ** sync the database file before calling CommitPhaseTwo() to delete the
  43875. ** journal file in this case.
  43876. */
  43877. SQLITE_PRIVATE int sqlite3PagerCommitPhaseOne(
  43878. Pager *pPager, /* Pager object */
  43879. const char *zMaster, /* If not NULL, the master journal name */
  43880. int noSync /* True to omit the xSync on the db file */
  43881. ){
  43882. int rc = SQLITE_OK; /* Return code */
  43883. assert( pPager->eState==PAGER_WRITER_LOCKED
  43884. || pPager->eState==PAGER_WRITER_CACHEMOD
  43885. || pPager->eState==PAGER_WRITER_DBMOD
  43886. || pPager->eState==PAGER_ERROR
  43887. );
  43888. assert( assert_pager_state(pPager) );
  43889. /* If a prior error occurred, report that error again. */
  43890. if( NEVER(pPager->errCode) ) return pPager->errCode;
  43891. PAGERTRACE(("DATABASE SYNC: File=%s zMaster=%s nSize=%d\n",
  43892. pPager->zFilename, zMaster, pPager->dbSize));
  43893. /* If no database changes have been made, return early. */
  43894. if( pPager->eState<PAGER_WRITER_CACHEMOD ) return SQLITE_OK;
  43895. if( MEMDB ){
  43896. /* If this is an in-memory db, or no pages have been written to, or this
  43897. ** function has already been called, it is mostly a no-op. However, any
  43898. ** backup in progress needs to be restarted.
  43899. */
  43900. sqlite3BackupRestart(pPager->pBackup);
  43901. }else{
  43902. if( pagerUseWal(pPager) ){
  43903. PgHdr *pList = sqlite3PcacheDirtyList(pPager->pPCache);
  43904. PgHdr *pPageOne = 0;
  43905. if( pList==0 ){
  43906. /* Must have at least one page for the WAL commit flag.
  43907. ** Ticket [2d1a5c67dfc2363e44f29d9bbd57f] 2011-05-18 */
  43908. rc = sqlite3PagerGet(pPager, 1, &pPageOne);
  43909. pList = pPageOne;
  43910. pList->pDirty = 0;
  43911. }
  43912. assert( rc==SQLITE_OK );
  43913. if( ALWAYS(pList) ){
  43914. rc = pagerWalFrames(pPager, pList, pPager->dbSize, 1);
  43915. }
  43916. sqlite3PagerUnref(pPageOne);
  43917. if( rc==SQLITE_OK ){
  43918. sqlite3PcacheCleanAll(pPager->pPCache);
  43919. }
  43920. }else{
  43921. /* The following block updates the change-counter. Exactly how it
  43922. ** does this depends on whether or not the atomic-update optimization
  43923. ** was enabled at compile time, and if this transaction meets the
  43924. ** runtime criteria to use the operation:
  43925. **
  43926. ** * The file-system supports the atomic-write property for
  43927. ** blocks of size page-size, and
  43928. ** * This commit is not part of a multi-file transaction, and
  43929. ** * Exactly one page has been modified and store in the journal file.
  43930. **
  43931. ** If the optimization was not enabled at compile time, then the
  43932. ** pager_incr_changecounter() function is called to update the change
  43933. ** counter in 'indirect-mode'. If the optimization is compiled in but
  43934. ** is not applicable to this transaction, call sqlite3JournalCreate()
  43935. ** to make sure the journal file has actually been created, then call
  43936. ** pager_incr_changecounter() to update the change-counter in indirect
  43937. ** mode.
  43938. **
  43939. ** Otherwise, if the optimization is both enabled and applicable,
  43940. ** then call pager_incr_changecounter() to update the change-counter
  43941. ** in 'direct' mode. In this case the journal file will never be
  43942. ** created for this transaction.
  43943. */
  43944. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  43945. PgHdr *pPg;
  43946. assert( isOpen(pPager->jfd)
  43947. || pPager->journalMode==PAGER_JOURNALMODE_OFF
  43948. || pPager->journalMode==PAGER_JOURNALMODE_WAL
  43949. );
  43950. if( !zMaster && isOpen(pPager->jfd)
  43951. && pPager->journalOff==jrnlBufferSize(pPager)
  43952. && pPager->dbSize>=pPager->dbOrigSize
  43953. && (0==(pPg = sqlite3PcacheDirtyList(pPager->pPCache)) || 0==pPg->pDirty)
  43954. ){
  43955. /* Update the db file change counter via the direct-write method. The
  43956. ** following call will modify the in-memory representation of page 1
  43957. ** to include the updated change counter and then write page 1
  43958. ** directly to the database file. Because of the atomic-write
  43959. ** property of the host file-system, this is safe.
  43960. */
  43961. rc = pager_incr_changecounter(pPager, 1);
  43962. }else{
  43963. rc = sqlite3JournalCreate(pPager->jfd);
  43964. if( rc==SQLITE_OK ){
  43965. rc = pager_incr_changecounter(pPager, 0);
  43966. }
  43967. }
  43968. #else
  43969. rc = pager_incr_changecounter(pPager, 0);
  43970. #endif
  43971. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  43972. /* Write the master journal name into the journal file. If a master
  43973. ** journal file name has already been written to the journal file,
  43974. ** or if zMaster is NULL (no master journal), then this call is a no-op.
  43975. */
  43976. rc = writeMasterJournal(pPager, zMaster);
  43977. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  43978. /* Sync the journal file and write all dirty pages to the database.
  43979. ** If the atomic-update optimization is being used, this sync will not
  43980. ** create the journal file or perform any real IO.
  43981. **
  43982. ** Because the change-counter page was just modified, unless the
  43983. ** atomic-update optimization is used it is almost certain that the
  43984. ** journal requires a sync here. However, in locking_mode=exclusive
  43985. ** on a system under memory pressure it is just possible that this is
  43986. ** not the case. In this case it is likely enough that the redundant
  43987. ** xSync() call will be changed to a no-op by the OS anyhow.
  43988. */
  43989. rc = syncJournal(pPager, 0);
  43990. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  43991. rc = pager_write_pagelist(pPager,sqlite3PcacheDirtyList(pPager->pPCache));
  43992. if( rc!=SQLITE_OK ){
  43993. assert( rc!=SQLITE_IOERR_BLOCKED );
  43994. goto commit_phase_one_exit;
  43995. }
  43996. sqlite3PcacheCleanAll(pPager->pPCache);
  43997. /* If the file on disk is smaller than the database image, use
  43998. ** pager_truncate to grow the file here. This can happen if the database
  43999. ** image was extended as part of the current transaction and then the
  44000. ** last page in the db image moved to the free-list. In this case the
  44001. ** last page is never written out to disk, leaving the database file
  44002. ** undersized. Fix this now if it is the case. */
  44003. if( pPager->dbSize>pPager->dbFileSize ){
  44004. Pgno nNew = pPager->dbSize - (pPager->dbSize==PAGER_MJ_PGNO(pPager));
  44005. assert( pPager->eState==PAGER_WRITER_DBMOD );
  44006. rc = pager_truncate(pPager, nNew);
  44007. if( rc!=SQLITE_OK ) goto commit_phase_one_exit;
  44008. }
  44009. /* Finally, sync the database file. */
  44010. if( !noSync ){
  44011. rc = sqlite3PagerSync(pPager, zMaster);
  44012. }
  44013. IOTRACE(("DBSYNC %p\n", pPager))
  44014. }
  44015. }
  44016. commit_phase_one_exit:
  44017. if( rc==SQLITE_OK && !pagerUseWal(pPager) ){
  44018. pPager->eState = PAGER_WRITER_FINISHED;
  44019. }
  44020. return rc;
  44021. }
  44022. /*
  44023. ** When this function is called, the database file has been completely
  44024. ** updated to reflect the changes made by the current transaction and
  44025. ** synced to disk. The journal file still exists in the file-system
  44026. ** though, and if a failure occurs at this point it will eventually
  44027. ** be used as a hot-journal and the current transaction rolled back.
  44028. **
  44029. ** This function finalizes the journal file, either by deleting,
  44030. ** truncating or partially zeroing it, so that it cannot be used
  44031. ** for hot-journal rollback. Once this is done the transaction is
  44032. ** irrevocably committed.
  44033. **
  44034. ** If an error occurs, an IO error code is returned and the pager
  44035. ** moves into the error state. Otherwise, SQLITE_OK is returned.
  44036. */
  44037. SQLITE_PRIVATE int sqlite3PagerCommitPhaseTwo(Pager *pPager){
  44038. int rc = SQLITE_OK; /* Return code */
  44039. /* This routine should not be called if a prior error has occurred.
  44040. ** But if (due to a coding error elsewhere in the system) it does get
  44041. ** called, just return the same error code without doing anything. */
  44042. if( NEVER(pPager->errCode) ) return pPager->errCode;
  44043. assert( pPager->eState==PAGER_WRITER_LOCKED
  44044. || pPager->eState==PAGER_WRITER_FINISHED
  44045. || (pagerUseWal(pPager) && pPager->eState==PAGER_WRITER_CACHEMOD)
  44046. );
  44047. assert( assert_pager_state(pPager) );
  44048. /* An optimization. If the database was not actually modified during
  44049. ** this transaction, the pager is running in exclusive-mode and is
  44050. ** using persistent journals, then this function is a no-op.
  44051. **
  44052. ** The start of the journal file currently contains a single journal
  44053. ** header with the nRec field set to 0. If such a journal is used as
  44054. ** a hot-journal during hot-journal rollback, 0 changes will be made
  44055. ** to the database file. So there is no need to zero the journal
  44056. ** header. Since the pager is in exclusive mode, there is no need
  44057. ** to drop any locks either.
  44058. */
  44059. if( pPager->eState==PAGER_WRITER_LOCKED
  44060. && pPager->exclusiveMode
  44061. && pPager->journalMode==PAGER_JOURNALMODE_PERSIST
  44062. ){
  44063. assert( pPager->journalOff==JOURNAL_HDR_SZ(pPager) || !pPager->journalOff );
  44064. pPager->eState = PAGER_READER;
  44065. return SQLITE_OK;
  44066. }
  44067. PAGERTRACE(("COMMIT %d\n", PAGERID(pPager)));
  44068. rc = pager_end_transaction(pPager, pPager->setMaster, 1);
  44069. return pager_error(pPager, rc);
  44070. }
  44071. /*
  44072. ** If a write transaction is open, then all changes made within the
  44073. ** transaction are reverted and the current write-transaction is closed.
  44074. ** The pager falls back to PAGER_READER state if successful, or PAGER_ERROR
  44075. ** state if an error occurs.
  44076. **
  44077. ** If the pager is already in PAGER_ERROR state when this function is called,
  44078. ** it returns Pager.errCode immediately. No work is performed in this case.
  44079. **
  44080. ** Otherwise, in rollback mode, this function performs two functions:
  44081. **
  44082. ** 1) It rolls back the journal file, restoring all database file and
  44083. ** in-memory cache pages to the state they were in when the transaction
  44084. ** was opened, and
  44085. **
  44086. ** 2) It finalizes the journal file, so that it is not used for hot
  44087. ** rollback at any point in the future.
  44088. **
  44089. ** Finalization of the journal file (task 2) is only performed if the
  44090. ** rollback is successful.
  44091. **
  44092. ** In WAL mode, all cache-entries containing data modified within the
  44093. ** current transaction are either expelled from the cache or reverted to
  44094. ** their pre-transaction state by re-reading data from the database or
  44095. ** WAL files. The WAL transaction is then closed.
  44096. */
  44097. SQLITE_PRIVATE int sqlite3PagerRollback(Pager *pPager){
  44098. int rc = SQLITE_OK; /* Return code */
  44099. PAGERTRACE(("ROLLBACK %d\n", PAGERID(pPager)));
  44100. /* PagerRollback() is a no-op if called in READER or OPEN state. If
  44101. ** the pager is already in the ERROR state, the rollback is not
  44102. ** attempted here. Instead, the error code is returned to the caller.
  44103. */
  44104. assert( assert_pager_state(pPager) );
  44105. if( pPager->eState==PAGER_ERROR ) return pPager->errCode;
  44106. if( pPager->eState<=PAGER_READER ) return SQLITE_OK;
  44107. if( pagerUseWal(pPager) ){
  44108. int rc2;
  44109. rc = sqlite3PagerSavepoint(pPager, SAVEPOINT_ROLLBACK, -1);
  44110. rc2 = pager_end_transaction(pPager, pPager->setMaster, 0);
  44111. if( rc==SQLITE_OK ) rc = rc2;
  44112. }else if( !isOpen(pPager->jfd) || pPager->eState==PAGER_WRITER_LOCKED ){
  44113. int eState = pPager->eState;
  44114. rc = pager_end_transaction(pPager, 0, 0);
  44115. if( !MEMDB && eState>PAGER_WRITER_LOCKED ){
  44116. /* This can happen using journal_mode=off. Move the pager to the error
  44117. ** state to indicate that the contents of the cache may not be trusted.
  44118. ** Any active readers will get SQLITE_ABORT.
  44119. */
  44120. pPager->errCode = SQLITE_ABORT;
  44121. pPager->eState = PAGER_ERROR;
  44122. return rc;
  44123. }
  44124. }else{
  44125. rc = pager_playback(pPager, 0);
  44126. }
  44127. assert( pPager->eState==PAGER_READER || rc!=SQLITE_OK );
  44128. assert( rc==SQLITE_OK || rc==SQLITE_FULL || rc==SQLITE_CORRUPT
  44129. || rc==SQLITE_NOMEM || (rc&0xFF)==SQLITE_IOERR
  44130. || rc==SQLITE_CANTOPEN
  44131. );
  44132. /* If an error occurs during a ROLLBACK, we can no longer trust the pager
  44133. ** cache. So call pager_error() on the way out to make any error persistent.
  44134. */
  44135. return pager_error(pPager, rc);
  44136. }
  44137. /*
  44138. ** Return TRUE if the database file is opened read-only. Return FALSE
  44139. ** if the database is (in theory) writable.
  44140. */
  44141. SQLITE_PRIVATE u8 sqlite3PagerIsreadonly(Pager *pPager){
  44142. return pPager->readOnly;
  44143. }
  44144. /*
  44145. ** Return the number of references to the pager.
  44146. */
  44147. SQLITE_PRIVATE int sqlite3PagerRefcount(Pager *pPager){
  44148. return sqlite3PcacheRefCount(pPager->pPCache);
  44149. }
  44150. /*
  44151. ** Return the approximate number of bytes of memory currently
  44152. ** used by the pager and its associated cache.
  44153. */
  44154. SQLITE_PRIVATE int sqlite3PagerMemUsed(Pager *pPager){
  44155. int perPageSize = pPager->pageSize + pPager->nExtra + sizeof(PgHdr)
  44156. + 5*sizeof(void*);
  44157. return perPageSize*sqlite3PcachePagecount(pPager->pPCache)
  44158. + sqlite3MallocSize(pPager)
  44159. + pPager->pageSize;
  44160. }
  44161. /*
  44162. ** Return the number of references to the specified page.
  44163. */
  44164. SQLITE_PRIVATE int sqlite3PagerPageRefcount(DbPage *pPage){
  44165. return sqlite3PcachePageRefcount(pPage);
  44166. }
  44167. #ifdef SQLITE_TEST
  44168. /*
  44169. ** This routine is used for testing and analysis only.
  44170. */
  44171. SQLITE_PRIVATE int *sqlite3PagerStats(Pager *pPager){
  44172. static int a[11];
  44173. a[0] = sqlite3PcacheRefCount(pPager->pPCache);
  44174. a[1] = sqlite3PcachePagecount(pPager->pPCache);
  44175. a[2] = sqlite3PcacheGetCachesize(pPager->pPCache);
  44176. a[3] = pPager->eState==PAGER_OPEN ? -1 : (int) pPager->dbSize;
  44177. a[4] = pPager->eState;
  44178. a[5] = pPager->errCode;
  44179. a[6] = pPager->aStat[PAGER_STAT_HIT];
  44180. a[7] = pPager->aStat[PAGER_STAT_MISS];
  44181. a[8] = 0; /* Used to be pPager->nOvfl */
  44182. a[9] = pPager->nRead;
  44183. a[10] = pPager->aStat[PAGER_STAT_WRITE];
  44184. return a;
  44185. }
  44186. #endif
  44187. /*
  44188. ** Parameter eStat must be either SQLITE_DBSTATUS_CACHE_HIT or
  44189. ** SQLITE_DBSTATUS_CACHE_MISS. Before returning, *pnVal is incremented by the
  44190. ** current cache hit or miss count, according to the value of eStat. If the
  44191. ** reset parameter is non-zero, the cache hit or miss count is zeroed before
  44192. ** returning.
  44193. */
  44194. SQLITE_PRIVATE void sqlite3PagerCacheStat(Pager *pPager, int eStat, int reset, int *pnVal){
  44195. assert( eStat==SQLITE_DBSTATUS_CACHE_HIT
  44196. || eStat==SQLITE_DBSTATUS_CACHE_MISS
  44197. || eStat==SQLITE_DBSTATUS_CACHE_WRITE
  44198. );
  44199. assert( SQLITE_DBSTATUS_CACHE_HIT+1==SQLITE_DBSTATUS_CACHE_MISS );
  44200. assert( SQLITE_DBSTATUS_CACHE_HIT+2==SQLITE_DBSTATUS_CACHE_WRITE );
  44201. assert( PAGER_STAT_HIT==0 && PAGER_STAT_MISS==1 && PAGER_STAT_WRITE==2 );
  44202. *pnVal += pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT];
  44203. if( reset ){
  44204. pPager->aStat[eStat - SQLITE_DBSTATUS_CACHE_HIT] = 0;
  44205. }
  44206. }
  44207. /*
  44208. ** Return true if this is an in-memory pager.
  44209. */
  44210. SQLITE_PRIVATE int sqlite3PagerIsMemdb(Pager *pPager){
  44211. return MEMDB;
  44212. }
  44213. /*
  44214. ** Check that there are at least nSavepoint savepoints open. If there are
  44215. ** currently less than nSavepoints open, then open one or more savepoints
  44216. ** to make up the difference. If the number of savepoints is already
  44217. ** equal to nSavepoint, then this function is a no-op.
  44218. **
  44219. ** If a memory allocation fails, SQLITE_NOMEM is returned. If an error
  44220. ** occurs while opening the sub-journal file, then an IO error code is
  44221. ** returned. Otherwise, SQLITE_OK.
  44222. */
  44223. SQLITE_PRIVATE int sqlite3PagerOpenSavepoint(Pager *pPager, int nSavepoint){
  44224. int rc = SQLITE_OK; /* Return code */
  44225. int nCurrent = pPager->nSavepoint; /* Current number of savepoints */
  44226. assert( pPager->eState>=PAGER_WRITER_LOCKED );
  44227. assert( assert_pager_state(pPager) );
  44228. if( nSavepoint>nCurrent && pPager->useJournal ){
  44229. int ii; /* Iterator variable */
  44230. PagerSavepoint *aNew; /* New Pager.aSavepoint array */
  44231. /* Grow the Pager.aSavepoint array using realloc(). Return SQLITE_NOMEM
  44232. ** if the allocation fails. Otherwise, zero the new portion in case a
  44233. ** malloc failure occurs while populating it in the for(...) loop below.
  44234. */
  44235. aNew = (PagerSavepoint *)sqlite3Realloc(
  44236. pPager->aSavepoint, sizeof(PagerSavepoint)*nSavepoint
  44237. );
  44238. if( !aNew ){
  44239. return SQLITE_NOMEM;
  44240. }
  44241. memset(&aNew[nCurrent], 0, (nSavepoint-nCurrent) * sizeof(PagerSavepoint));
  44242. pPager->aSavepoint = aNew;
  44243. /* Populate the PagerSavepoint structures just allocated. */
  44244. for(ii=nCurrent; ii<nSavepoint; ii++){
  44245. aNew[ii].nOrig = pPager->dbSize;
  44246. if( isOpen(pPager->jfd) && pPager->journalOff>0 ){
  44247. aNew[ii].iOffset = pPager->journalOff;
  44248. }else{
  44249. aNew[ii].iOffset = JOURNAL_HDR_SZ(pPager);
  44250. }
  44251. aNew[ii].iSubRec = pPager->nSubRec;
  44252. aNew[ii].pInSavepoint = sqlite3BitvecCreate(pPager->dbSize);
  44253. if( !aNew[ii].pInSavepoint ){
  44254. return SQLITE_NOMEM;
  44255. }
  44256. if( pagerUseWal(pPager) ){
  44257. sqlite3WalSavepoint(pPager->pWal, aNew[ii].aWalData);
  44258. }
  44259. pPager->nSavepoint = ii+1;
  44260. }
  44261. assert( pPager->nSavepoint==nSavepoint );
  44262. assertTruncateConstraint(pPager);
  44263. }
  44264. return rc;
  44265. }
  44266. /*
  44267. ** This function is called to rollback or release (commit) a savepoint.
  44268. ** The savepoint to release or rollback need not be the most recently
  44269. ** created savepoint.
  44270. **
  44271. ** Parameter op is always either SAVEPOINT_ROLLBACK or SAVEPOINT_RELEASE.
  44272. ** If it is SAVEPOINT_RELEASE, then release and destroy the savepoint with
  44273. ** index iSavepoint. If it is SAVEPOINT_ROLLBACK, then rollback all changes
  44274. ** that have occurred since the specified savepoint was created.
  44275. **
  44276. ** The savepoint to rollback or release is identified by parameter
  44277. ** iSavepoint. A value of 0 means to operate on the outermost savepoint
  44278. ** (the first created). A value of (Pager.nSavepoint-1) means operate
  44279. ** on the most recently created savepoint. If iSavepoint is greater than
  44280. ** (Pager.nSavepoint-1), then this function is a no-op.
  44281. **
  44282. ** If a negative value is passed to this function, then the current
  44283. ** transaction is rolled back. This is different to calling
  44284. ** sqlite3PagerRollback() because this function does not terminate
  44285. ** the transaction or unlock the database, it just restores the
  44286. ** contents of the database to its original state.
  44287. **
  44288. ** In any case, all savepoints with an index greater than iSavepoint
  44289. ** are destroyed. If this is a release operation (op==SAVEPOINT_RELEASE),
  44290. ** then savepoint iSavepoint is also destroyed.
  44291. **
  44292. ** This function may return SQLITE_NOMEM if a memory allocation fails,
  44293. ** or an IO error code if an IO error occurs while rolling back a
  44294. ** savepoint. If no errors occur, SQLITE_OK is returned.
  44295. */
  44296. SQLITE_PRIVATE int sqlite3PagerSavepoint(Pager *pPager, int op, int iSavepoint){
  44297. int rc = pPager->errCode; /* Return code */
  44298. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  44299. assert( iSavepoint>=0 || op==SAVEPOINT_ROLLBACK );
  44300. if( rc==SQLITE_OK && iSavepoint<pPager->nSavepoint ){
  44301. int ii; /* Iterator variable */
  44302. int nNew; /* Number of remaining savepoints after this op. */
  44303. /* Figure out how many savepoints will still be active after this
  44304. ** operation. Store this value in nNew. Then free resources associated
  44305. ** with any savepoints that are destroyed by this operation.
  44306. */
  44307. nNew = iSavepoint + (( op==SAVEPOINT_RELEASE ) ? 0 : 1);
  44308. for(ii=nNew; ii<pPager->nSavepoint; ii++){
  44309. sqlite3BitvecDestroy(pPager->aSavepoint[ii].pInSavepoint);
  44310. }
  44311. pPager->nSavepoint = nNew;
  44312. /* If this is a release of the outermost savepoint, truncate
  44313. ** the sub-journal to zero bytes in size. */
  44314. if( op==SAVEPOINT_RELEASE ){
  44315. if( nNew==0 && isOpen(pPager->sjfd) ){
  44316. /* Only truncate if it is an in-memory sub-journal. */
  44317. if( sqlite3IsMemJournal(pPager->sjfd) ){
  44318. rc = sqlite3OsTruncate(pPager->sjfd, 0);
  44319. assert( rc==SQLITE_OK );
  44320. }
  44321. pPager->nSubRec = 0;
  44322. }
  44323. }
  44324. /* Else this is a rollback operation, playback the specified savepoint.
  44325. ** If this is a temp-file, it is possible that the journal file has
  44326. ** not yet been opened. In this case there have been no changes to
  44327. ** the database file, so the playback operation can be skipped.
  44328. */
  44329. else if( pagerUseWal(pPager) || isOpen(pPager->jfd) ){
  44330. PagerSavepoint *pSavepoint = (nNew==0)?0:&pPager->aSavepoint[nNew-1];
  44331. rc = pagerPlaybackSavepoint(pPager, pSavepoint);
  44332. assert(rc!=SQLITE_DONE);
  44333. }
  44334. }
  44335. return rc;
  44336. }
  44337. /*
  44338. ** Return the full pathname of the database file.
  44339. **
  44340. ** Except, if the pager is in-memory only, then return an empty string if
  44341. ** nullIfMemDb is true. This routine is called with nullIfMemDb==1 when
  44342. ** used to report the filename to the user, for compatibility with legacy
  44343. ** behavior. But when the Btree needs to know the filename for matching to
  44344. ** shared cache, it uses nullIfMemDb==0 so that in-memory databases can
  44345. ** participate in shared-cache.
  44346. */
  44347. SQLITE_PRIVATE const char *sqlite3PagerFilename(Pager *pPager, int nullIfMemDb){
  44348. return (nullIfMemDb && pPager->memDb) ? "" : pPager->zFilename;
  44349. }
  44350. /*
  44351. ** Return the VFS structure for the pager.
  44352. */
  44353. SQLITE_PRIVATE const sqlite3_vfs *sqlite3PagerVfs(Pager *pPager){
  44354. return pPager->pVfs;
  44355. }
  44356. /*
  44357. ** Return the file handle for the database file associated
  44358. ** with the pager. This might return NULL if the file has
  44359. ** not yet been opened.
  44360. */
  44361. SQLITE_PRIVATE sqlite3_file *sqlite3PagerFile(Pager *pPager){
  44362. return pPager->fd;
  44363. }
  44364. /*
  44365. ** Return the full pathname of the journal file.
  44366. */
  44367. SQLITE_PRIVATE const char *sqlite3PagerJournalname(Pager *pPager){
  44368. return pPager->zJournal;
  44369. }
  44370. /*
  44371. ** Return true if fsync() calls are disabled for this pager. Return FALSE
  44372. ** if fsync()s are executed normally.
  44373. */
  44374. SQLITE_PRIVATE int sqlite3PagerNosync(Pager *pPager){
  44375. return pPager->noSync;
  44376. }
  44377. #ifdef SQLITE_HAS_CODEC
  44378. /*
  44379. ** Set or retrieve the codec for this pager
  44380. */
  44381. SQLITE_PRIVATE void sqlite3PagerSetCodec(
  44382. Pager *pPager,
  44383. void *(*xCodec)(void*,void*,Pgno,int),
  44384. void (*xCodecSizeChng)(void*,int,int),
  44385. void (*xCodecFree)(void*),
  44386. void *pCodec
  44387. ){
  44388. if( pPager->xCodecFree ) pPager->xCodecFree(pPager->pCodec);
  44389. pPager->xCodec = pPager->memDb ? 0 : xCodec;
  44390. pPager->xCodecSizeChng = xCodecSizeChng;
  44391. pPager->xCodecFree = xCodecFree;
  44392. pPager->pCodec = pCodec;
  44393. pagerReportSize(pPager);
  44394. }
  44395. SQLITE_PRIVATE void *sqlite3PagerGetCodec(Pager *pPager){
  44396. return pPager->pCodec;
  44397. }
  44398. /*
  44399. ** This function is called by the wal module when writing page content
  44400. ** into the log file.
  44401. **
  44402. ** This function returns a pointer to a buffer containing the encrypted
  44403. ** page content. If a malloc fails, this function may return NULL.
  44404. */
  44405. SQLITE_PRIVATE void *sqlite3PagerCodec(PgHdr *pPg){
  44406. void *aData = 0;
  44407. CODEC2(pPg->pPager, pPg->pData, pPg->pgno, 6, return 0, aData);
  44408. return aData;
  44409. }
  44410. /*
  44411. ** Return the current pager state
  44412. */
  44413. SQLITE_PRIVATE int sqlite3PagerState(Pager *pPager){
  44414. return pPager->eState;
  44415. }
  44416. #endif /* SQLITE_HAS_CODEC */
  44417. #ifndef SQLITE_OMIT_AUTOVACUUM
  44418. /*
  44419. ** Move the page pPg to location pgno in the file.
  44420. **
  44421. ** There must be no references to the page previously located at
  44422. ** pgno (which we call pPgOld) though that page is allowed to be
  44423. ** in cache. If the page previously located at pgno is not already
  44424. ** in the rollback journal, it is not put there by by this routine.
  44425. **
  44426. ** References to the page pPg remain valid. Updating any
  44427. ** meta-data associated with pPg (i.e. data stored in the nExtra bytes
  44428. ** allocated along with the page) is the responsibility of the caller.
  44429. **
  44430. ** A transaction must be active when this routine is called. It used to be
  44431. ** required that a statement transaction was not active, but this restriction
  44432. ** has been removed (CREATE INDEX needs to move a page when a statement
  44433. ** transaction is active).
  44434. **
  44435. ** If the fourth argument, isCommit, is non-zero, then this page is being
  44436. ** moved as part of a database reorganization just before the transaction
  44437. ** is being committed. In this case, it is guaranteed that the database page
  44438. ** pPg refers to will not be written to again within this transaction.
  44439. **
  44440. ** This function may return SQLITE_NOMEM or an IO error code if an error
  44441. ** occurs. Otherwise, it returns SQLITE_OK.
  44442. */
  44443. SQLITE_PRIVATE int sqlite3PagerMovepage(Pager *pPager, DbPage *pPg, Pgno pgno, int isCommit){
  44444. PgHdr *pPgOld; /* The page being overwritten. */
  44445. Pgno needSyncPgno = 0; /* Old value of pPg->pgno, if sync is required */
  44446. int rc; /* Return code */
  44447. Pgno origPgno; /* The original page number */
  44448. assert( pPg->nRef>0 );
  44449. assert( pPager->eState==PAGER_WRITER_CACHEMOD
  44450. || pPager->eState==PAGER_WRITER_DBMOD
  44451. );
  44452. assert( assert_pager_state(pPager) );
  44453. /* In order to be able to rollback, an in-memory database must journal
  44454. ** the page we are moving from.
  44455. */
  44456. if( MEMDB ){
  44457. rc = sqlite3PagerWrite(pPg);
  44458. if( rc ) return rc;
  44459. }
  44460. /* If the page being moved is dirty and has not been saved by the latest
  44461. ** savepoint, then save the current contents of the page into the
  44462. ** sub-journal now. This is required to handle the following scenario:
  44463. **
  44464. ** BEGIN;
  44465. ** <journal page X, then modify it in memory>
  44466. ** SAVEPOINT one;
  44467. ** <Move page X to location Y>
  44468. ** ROLLBACK TO one;
  44469. **
  44470. ** If page X were not written to the sub-journal here, it would not
  44471. ** be possible to restore its contents when the "ROLLBACK TO one"
  44472. ** statement were is processed.
  44473. **
  44474. ** subjournalPage() may need to allocate space to store pPg->pgno into
  44475. ** one or more savepoint bitvecs. This is the reason this function
  44476. ** may return SQLITE_NOMEM.
  44477. */
  44478. if( pPg->flags&PGHDR_DIRTY
  44479. && subjRequiresPage(pPg)
  44480. && SQLITE_OK!=(rc = subjournalPage(pPg))
  44481. ){
  44482. return rc;
  44483. }
  44484. PAGERTRACE(("MOVE %d page %d (needSync=%d) moves to %d\n",
  44485. PAGERID(pPager), pPg->pgno, (pPg->flags&PGHDR_NEED_SYNC)?1:0, pgno));
  44486. IOTRACE(("MOVE %p %d %d\n", pPager, pPg->pgno, pgno))
  44487. /* If the journal needs to be sync()ed before page pPg->pgno can
  44488. ** be written to, store pPg->pgno in local variable needSyncPgno.
  44489. **
  44490. ** If the isCommit flag is set, there is no need to remember that
  44491. ** the journal needs to be sync()ed before database page pPg->pgno
  44492. ** can be written to. The caller has already promised not to write to it.
  44493. */
  44494. if( (pPg->flags&PGHDR_NEED_SYNC) && !isCommit ){
  44495. needSyncPgno = pPg->pgno;
  44496. assert( pPager->journalMode==PAGER_JOURNALMODE_OFF ||
  44497. pageInJournal(pPager, pPg) || pPg->pgno>pPager->dbOrigSize );
  44498. assert( pPg->flags&PGHDR_DIRTY );
  44499. }
  44500. /* If the cache contains a page with page-number pgno, remove it
  44501. ** from its hash chain. Also, if the PGHDR_NEED_SYNC flag was set for
  44502. ** page pgno before the 'move' operation, it needs to be retained
  44503. ** for the page moved there.
  44504. */
  44505. pPg->flags &= ~PGHDR_NEED_SYNC;
  44506. pPgOld = sqlite3PagerLookup(pPager, pgno);
  44507. assert( !pPgOld || pPgOld->nRef==1 );
  44508. if( pPgOld ){
  44509. pPg->flags |= (pPgOld->flags&PGHDR_NEED_SYNC);
  44510. if( MEMDB ){
  44511. /* Do not discard pages from an in-memory database since we might
  44512. ** need to rollback later. Just move the page out of the way. */
  44513. sqlite3PcacheMove(pPgOld, pPager->dbSize+1);
  44514. }else{
  44515. sqlite3PcacheDrop(pPgOld);
  44516. }
  44517. }
  44518. origPgno = pPg->pgno;
  44519. sqlite3PcacheMove(pPg, pgno);
  44520. sqlite3PcacheMakeDirty(pPg);
  44521. /* For an in-memory database, make sure the original page continues
  44522. ** to exist, in case the transaction needs to roll back. Use pPgOld
  44523. ** as the original page since it has already been allocated.
  44524. */
  44525. if( MEMDB ){
  44526. assert( pPgOld );
  44527. sqlite3PcacheMove(pPgOld, origPgno);
  44528. sqlite3PagerUnrefNotNull(pPgOld);
  44529. }
  44530. if( needSyncPgno ){
  44531. /* If needSyncPgno is non-zero, then the journal file needs to be
  44532. ** sync()ed before any data is written to database file page needSyncPgno.
  44533. ** Currently, no such page exists in the page-cache and the
  44534. ** "is journaled" bitvec flag has been set. This needs to be remedied by
  44535. ** loading the page into the pager-cache and setting the PGHDR_NEED_SYNC
  44536. ** flag.
  44537. **
  44538. ** If the attempt to load the page into the page-cache fails, (due
  44539. ** to a malloc() or IO failure), clear the bit in the pInJournal[]
  44540. ** array. Otherwise, if the page is loaded and written again in
  44541. ** this transaction, it may be written to the database file before
  44542. ** it is synced into the journal file. This way, it may end up in
  44543. ** the journal file twice, but that is not a problem.
  44544. */
  44545. PgHdr *pPgHdr;
  44546. rc = sqlite3PagerGet(pPager, needSyncPgno, &pPgHdr);
  44547. if( rc!=SQLITE_OK ){
  44548. if( needSyncPgno<=pPager->dbOrigSize ){
  44549. assert( pPager->pTmpSpace!=0 );
  44550. sqlite3BitvecClear(pPager->pInJournal, needSyncPgno, pPager->pTmpSpace);
  44551. }
  44552. return rc;
  44553. }
  44554. pPgHdr->flags |= PGHDR_NEED_SYNC;
  44555. sqlite3PcacheMakeDirty(pPgHdr);
  44556. sqlite3PagerUnrefNotNull(pPgHdr);
  44557. }
  44558. return SQLITE_OK;
  44559. }
  44560. #endif
  44561. /*
  44562. ** Return a pointer to the data for the specified page.
  44563. */
  44564. SQLITE_PRIVATE void *sqlite3PagerGetData(DbPage *pPg){
  44565. assert( pPg->nRef>0 || pPg->pPager->memDb );
  44566. return pPg->pData;
  44567. }
  44568. /*
  44569. ** Return a pointer to the Pager.nExtra bytes of "extra" space
  44570. ** allocated along with the specified page.
  44571. */
  44572. SQLITE_PRIVATE void *sqlite3PagerGetExtra(DbPage *pPg){
  44573. return pPg->pExtra;
  44574. }
  44575. /*
  44576. ** Get/set the locking-mode for this pager. Parameter eMode must be one
  44577. ** of PAGER_LOCKINGMODE_QUERY, PAGER_LOCKINGMODE_NORMAL or
  44578. ** PAGER_LOCKINGMODE_EXCLUSIVE. If the parameter is not _QUERY, then
  44579. ** the locking-mode is set to the value specified.
  44580. **
  44581. ** The returned value is either PAGER_LOCKINGMODE_NORMAL or
  44582. ** PAGER_LOCKINGMODE_EXCLUSIVE, indicating the current (possibly updated)
  44583. ** locking-mode.
  44584. */
  44585. SQLITE_PRIVATE int sqlite3PagerLockingMode(Pager *pPager, int eMode){
  44586. assert( eMode==PAGER_LOCKINGMODE_QUERY
  44587. || eMode==PAGER_LOCKINGMODE_NORMAL
  44588. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  44589. assert( PAGER_LOCKINGMODE_QUERY<0 );
  44590. assert( PAGER_LOCKINGMODE_NORMAL>=0 && PAGER_LOCKINGMODE_EXCLUSIVE>=0 );
  44591. assert( pPager->exclusiveMode || 0==sqlite3WalHeapMemory(pPager->pWal) );
  44592. if( eMode>=0 && !pPager->tempFile && !sqlite3WalHeapMemory(pPager->pWal) ){
  44593. pPager->exclusiveMode = (u8)eMode;
  44594. }
  44595. return (int)pPager->exclusiveMode;
  44596. }
  44597. /*
  44598. ** Set the journal-mode for this pager. Parameter eMode must be one of:
  44599. **
  44600. ** PAGER_JOURNALMODE_DELETE
  44601. ** PAGER_JOURNALMODE_TRUNCATE
  44602. ** PAGER_JOURNALMODE_PERSIST
  44603. ** PAGER_JOURNALMODE_OFF
  44604. ** PAGER_JOURNALMODE_MEMORY
  44605. ** PAGER_JOURNALMODE_WAL
  44606. **
  44607. ** The journalmode is set to the value specified if the change is allowed.
  44608. ** The change may be disallowed for the following reasons:
  44609. **
  44610. ** * An in-memory database can only have its journal_mode set to _OFF
  44611. ** or _MEMORY.
  44612. **
  44613. ** * Temporary databases cannot have _WAL journalmode.
  44614. **
  44615. ** The returned indicate the current (possibly updated) journal-mode.
  44616. */
  44617. SQLITE_PRIVATE int sqlite3PagerSetJournalMode(Pager *pPager, int eMode){
  44618. u8 eOld = pPager->journalMode; /* Prior journalmode */
  44619. #ifdef SQLITE_DEBUG
  44620. /* The print_pager_state() routine is intended to be used by the debugger
  44621. ** only. We invoke it once here to suppress a compiler warning. */
  44622. print_pager_state(pPager);
  44623. #endif
  44624. /* The eMode parameter is always valid */
  44625. assert( eMode==PAGER_JOURNALMODE_DELETE
  44626. || eMode==PAGER_JOURNALMODE_TRUNCATE
  44627. || eMode==PAGER_JOURNALMODE_PERSIST
  44628. || eMode==PAGER_JOURNALMODE_OFF
  44629. || eMode==PAGER_JOURNALMODE_WAL
  44630. || eMode==PAGER_JOURNALMODE_MEMORY );
  44631. /* This routine is only called from the OP_JournalMode opcode, and
  44632. ** the logic there will never allow a temporary file to be changed
  44633. ** to WAL mode.
  44634. */
  44635. assert( pPager->tempFile==0 || eMode!=PAGER_JOURNALMODE_WAL );
  44636. /* Do allow the journalmode of an in-memory database to be set to
  44637. ** anything other than MEMORY or OFF
  44638. */
  44639. if( MEMDB ){
  44640. assert( eOld==PAGER_JOURNALMODE_MEMORY || eOld==PAGER_JOURNALMODE_OFF );
  44641. if( eMode!=PAGER_JOURNALMODE_MEMORY && eMode!=PAGER_JOURNALMODE_OFF ){
  44642. eMode = eOld;
  44643. }
  44644. }
  44645. if( eMode!=eOld ){
  44646. /* Change the journal mode. */
  44647. assert( pPager->eState!=PAGER_ERROR );
  44648. pPager->journalMode = (u8)eMode;
  44649. /* When transistioning from TRUNCATE or PERSIST to any other journal
  44650. ** mode except WAL, unless the pager is in locking_mode=exclusive mode,
  44651. ** delete the journal file.
  44652. */
  44653. assert( (PAGER_JOURNALMODE_TRUNCATE & 5)==1 );
  44654. assert( (PAGER_JOURNALMODE_PERSIST & 5)==1 );
  44655. assert( (PAGER_JOURNALMODE_DELETE & 5)==0 );
  44656. assert( (PAGER_JOURNALMODE_MEMORY & 5)==4 );
  44657. assert( (PAGER_JOURNALMODE_OFF & 5)==0 );
  44658. assert( (PAGER_JOURNALMODE_WAL & 5)==5 );
  44659. assert( isOpen(pPager->fd) || pPager->exclusiveMode );
  44660. if( !pPager->exclusiveMode && (eOld & 5)==1 && (eMode & 1)==0 ){
  44661. /* In this case we would like to delete the journal file. If it is
  44662. ** not possible, then that is not a problem. Deleting the journal file
  44663. ** here is an optimization only.
  44664. **
  44665. ** Before deleting the journal file, obtain a RESERVED lock on the
  44666. ** database file. This ensures that the journal file is not deleted
  44667. ** while it is in use by some other client.
  44668. */
  44669. sqlite3OsClose(pPager->jfd);
  44670. if( pPager->eLock>=RESERVED_LOCK ){
  44671. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  44672. }else{
  44673. int rc = SQLITE_OK;
  44674. int state = pPager->eState;
  44675. assert( state==PAGER_OPEN || state==PAGER_READER );
  44676. if( state==PAGER_OPEN ){
  44677. rc = sqlite3PagerSharedLock(pPager);
  44678. }
  44679. if( pPager->eState==PAGER_READER ){
  44680. assert( rc==SQLITE_OK );
  44681. rc = pagerLockDb(pPager, RESERVED_LOCK);
  44682. }
  44683. if( rc==SQLITE_OK ){
  44684. sqlite3OsDelete(pPager->pVfs, pPager->zJournal, 0);
  44685. }
  44686. if( rc==SQLITE_OK && state==PAGER_READER ){
  44687. pagerUnlockDb(pPager, SHARED_LOCK);
  44688. }else if( state==PAGER_OPEN ){
  44689. pager_unlock(pPager);
  44690. }
  44691. assert( state==pPager->eState );
  44692. }
  44693. }
  44694. }
  44695. /* Return the new journal mode */
  44696. return (int)pPager->journalMode;
  44697. }
  44698. /*
  44699. ** Return the current journal mode.
  44700. */
  44701. SQLITE_PRIVATE int sqlite3PagerGetJournalMode(Pager *pPager){
  44702. return (int)pPager->journalMode;
  44703. }
  44704. /*
  44705. ** Return TRUE if the pager is in a state where it is OK to change the
  44706. ** journalmode. Journalmode changes can only happen when the database
  44707. ** is unmodified.
  44708. */
  44709. SQLITE_PRIVATE int sqlite3PagerOkToChangeJournalMode(Pager *pPager){
  44710. assert( assert_pager_state(pPager) );
  44711. if( pPager->eState>=PAGER_WRITER_CACHEMOD ) return 0;
  44712. if( NEVER(isOpen(pPager->jfd) && pPager->journalOff>0) ) return 0;
  44713. return 1;
  44714. }
  44715. /*
  44716. ** Get/set the size-limit used for persistent journal files.
  44717. **
  44718. ** Setting the size limit to -1 means no limit is enforced.
  44719. ** An attempt to set a limit smaller than -1 is a no-op.
  44720. */
  44721. SQLITE_PRIVATE i64 sqlite3PagerJournalSizeLimit(Pager *pPager, i64 iLimit){
  44722. if( iLimit>=-1 ){
  44723. pPager->journalSizeLimit = iLimit;
  44724. sqlite3WalLimit(pPager->pWal, iLimit);
  44725. }
  44726. return pPager->journalSizeLimit;
  44727. }
  44728. /*
  44729. ** Return a pointer to the pPager->pBackup variable. The backup module
  44730. ** in backup.c maintains the content of this variable. This module
  44731. ** uses it opaquely as an argument to sqlite3BackupRestart() and
  44732. ** sqlite3BackupUpdate() only.
  44733. */
  44734. SQLITE_PRIVATE sqlite3_backup **sqlite3PagerBackupPtr(Pager *pPager){
  44735. return &pPager->pBackup;
  44736. }
  44737. #ifndef SQLITE_OMIT_VACUUM
  44738. /*
  44739. ** Unless this is an in-memory or temporary database, clear the pager cache.
  44740. */
  44741. SQLITE_PRIVATE void sqlite3PagerClearCache(Pager *pPager){
  44742. if( !MEMDB && pPager->tempFile==0 ) pager_reset(pPager);
  44743. }
  44744. #endif
  44745. #ifndef SQLITE_OMIT_WAL
  44746. /*
  44747. ** This function is called when the user invokes "PRAGMA wal_checkpoint",
  44748. ** "PRAGMA wal_blocking_checkpoint" or calls the sqlite3_wal_checkpoint()
  44749. ** or wal_blocking_checkpoint() API functions.
  44750. **
  44751. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  44752. */
  44753. SQLITE_PRIVATE int sqlite3PagerCheckpoint(Pager *pPager, int eMode, int *pnLog, int *pnCkpt){
  44754. int rc = SQLITE_OK;
  44755. if( pPager->pWal ){
  44756. rc = sqlite3WalCheckpoint(pPager->pWal, eMode,
  44757. pPager->xBusyHandler, pPager->pBusyHandlerArg,
  44758. pPager->ckptSyncFlags, pPager->pageSize, (u8 *)pPager->pTmpSpace,
  44759. pnLog, pnCkpt
  44760. );
  44761. }
  44762. return rc;
  44763. }
  44764. SQLITE_PRIVATE int sqlite3PagerWalCallback(Pager *pPager){
  44765. return sqlite3WalCallback(pPager->pWal);
  44766. }
  44767. /*
  44768. ** Return true if the underlying VFS for the given pager supports the
  44769. ** primitives necessary for write-ahead logging.
  44770. */
  44771. SQLITE_PRIVATE int sqlite3PagerWalSupported(Pager *pPager){
  44772. const sqlite3_io_methods *pMethods = pPager->fd->pMethods;
  44773. return pPager->exclusiveMode || (pMethods->iVersion>=2 && pMethods->xShmMap);
  44774. }
  44775. /*
  44776. ** Attempt to take an exclusive lock on the database file. If a PENDING lock
  44777. ** is obtained instead, immediately release it.
  44778. */
  44779. static int pagerExclusiveLock(Pager *pPager){
  44780. int rc; /* Return code */
  44781. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  44782. rc = pagerLockDb(pPager, EXCLUSIVE_LOCK);
  44783. if( rc!=SQLITE_OK ){
  44784. /* If the attempt to grab the exclusive lock failed, release the
  44785. ** pending lock that may have been obtained instead. */
  44786. pagerUnlockDb(pPager, SHARED_LOCK);
  44787. }
  44788. return rc;
  44789. }
  44790. /*
  44791. ** Call sqlite3WalOpen() to open the WAL handle. If the pager is in
  44792. ** exclusive-locking mode when this function is called, take an EXCLUSIVE
  44793. ** lock on the database file and use heap-memory to store the wal-index
  44794. ** in. Otherwise, use the normal shared-memory.
  44795. */
  44796. static int pagerOpenWal(Pager *pPager){
  44797. int rc = SQLITE_OK;
  44798. assert( pPager->pWal==0 && pPager->tempFile==0 );
  44799. assert( pPager->eLock==SHARED_LOCK || pPager->eLock==EXCLUSIVE_LOCK );
  44800. /* If the pager is already in exclusive-mode, the WAL module will use
  44801. ** heap-memory for the wal-index instead of the VFS shared-memory
  44802. ** implementation. Take the exclusive lock now, before opening the WAL
  44803. ** file, to make sure this is safe.
  44804. */
  44805. if( pPager->exclusiveMode ){
  44806. rc = pagerExclusiveLock(pPager);
  44807. }
  44808. /* Open the connection to the log file. If this operation fails,
  44809. ** (e.g. due to malloc() failure), return an error code.
  44810. */
  44811. if( rc==SQLITE_OK ){
  44812. rc = sqlite3WalOpen(pPager->pVfs,
  44813. pPager->fd, pPager->zWal, pPager->exclusiveMode,
  44814. pPager->journalSizeLimit, &pPager->pWal
  44815. );
  44816. }
  44817. pagerFixMaplimit(pPager);
  44818. return rc;
  44819. }
  44820. /*
  44821. ** The caller must be holding a SHARED lock on the database file to call
  44822. ** this function.
  44823. **
  44824. ** If the pager passed as the first argument is open on a real database
  44825. ** file (not a temp file or an in-memory database), and the WAL file
  44826. ** is not already open, make an attempt to open it now. If successful,
  44827. ** return SQLITE_OK. If an error occurs or the VFS used by the pager does
  44828. ** not support the xShmXXX() methods, return an error code. *pbOpen is
  44829. ** not modified in either case.
  44830. **
  44831. ** If the pager is open on a temp-file (or in-memory database), or if
  44832. ** the WAL file is already open, set *pbOpen to 1 and return SQLITE_OK
  44833. ** without doing anything.
  44834. */
  44835. SQLITE_PRIVATE int sqlite3PagerOpenWal(
  44836. Pager *pPager, /* Pager object */
  44837. int *pbOpen /* OUT: Set to true if call is a no-op */
  44838. ){
  44839. int rc = SQLITE_OK; /* Return code */
  44840. assert( assert_pager_state(pPager) );
  44841. assert( pPager->eState==PAGER_OPEN || pbOpen );
  44842. assert( pPager->eState==PAGER_READER || !pbOpen );
  44843. assert( pbOpen==0 || *pbOpen==0 );
  44844. assert( pbOpen!=0 || (!pPager->tempFile && !pPager->pWal) );
  44845. if( !pPager->tempFile && !pPager->pWal ){
  44846. if( !sqlite3PagerWalSupported(pPager) ) return SQLITE_CANTOPEN;
  44847. /* Close any rollback journal previously open */
  44848. sqlite3OsClose(pPager->jfd);
  44849. rc = pagerOpenWal(pPager);
  44850. if( rc==SQLITE_OK ){
  44851. pPager->journalMode = PAGER_JOURNALMODE_WAL;
  44852. pPager->eState = PAGER_OPEN;
  44853. }
  44854. }else{
  44855. *pbOpen = 1;
  44856. }
  44857. return rc;
  44858. }
  44859. /*
  44860. ** This function is called to close the connection to the log file prior
  44861. ** to switching from WAL to rollback mode.
  44862. **
  44863. ** Before closing the log file, this function attempts to take an
  44864. ** EXCLUSIVE lock on the database file. If this cannot be obtained, an
  44865. ** error (SQLITE_BUSY) is returned and the log connection is not closed.
  44866. ** If successful, the EXCLUSIVE lock is not released before returning.
  44867. */
  44868. SQLITE_PRIVATE int sqlite3PagerCloseWal(Pager *pPager){
  44869. int rc = SQLITE_OK;
  44870. assert( pPager->journalMode==PAGER_JOURNALMODE_WAL );
  44871. /* If the log file is not already open, but does exist in the file-system,
  44872. ** it may need to be checkpointed before the connection can switch to
  44873. ** rollback mode. Open it now so this can happen.
  44874. */
  44875. if( !pPager->pWal ){
  44876. int logexists = 0;
  44877. rc = pagerLockDb(pPager, SHARED_LOCK);
  44878. if( rc==SQLITE_OK ){
  44879. rc = sqlite3OsAccess(
  44880. pPager->pVfs, pPager->zWal, SQLITE_ACCESS_EXISTS, &logexists
  44881. );
  44882. }
  44883. if( rc==SQLITE_OK && logexists ){
  44884. rc = pagerOpenWal(pPager);
  44885. }
  44886. }
  44887. /* Checkpoint and close the log. Because an EXCLUSIVE lock is held on
  44888. ** the database file, the log and log-summary files will be deleted.
  44889. */
  44890. if( rc==SQLITE_OK && pPager->pWal ){
  44891. rc = pagerExclusiveLock(pPager);
  44892. if( rc==SQLITE_OK ){
  44893. rc = sqlite3WalClose(pPager->pWal, pPager->ckptSyncFlags,
  44894. pPager->pageSize, (u8*)pPager->pTmpSpace);
  44895. pPager->pWal = 0;
  44896. pagerFixMaplimit(pPager);
  44897. }
  44898. }
  44899. return rc;
  44900. }
  44901. #endif /* !SQLITE_OMIT_WAL */
  44902. #ifdef SQLITE_ENABLE_ZIPVFS
  44903. /*
  44904. ** A read-lock must be held on the pager when this function is called. If
  44905. ** the pager is in WAL mode and the WAL file currently contains one or more
  44906. ** frames, return the size in bytes of the page images stored within the
  44907. ** WAL frames. Otherwise, if this is not a WAL database or the WAL file
  44908. ** is empty, return 0.
  44909. */
  44910. SQLITE_PRIVATE int sqlite3PagerWalFramesize(Pager *pPager){
  44911. assert( pPager->eState>=PAGER_READER );
  44912. return sqlite3WalFramesize(pPager->pWal);
  44913. }
  44914. #endif
  44915. #endif /* SQLITE_OMIT_DISKIO */
  44916. /************** End of pager.c ***********************************************/
  44917. /************** Begin file wal.c *********************************************/
  44918. /*
  44919. ** 2010 February 1
  44920. **
  44921. ** The author disclaims copyright to this source code. In place of
  44922. ** a legal notice, here is a blessing:
  44923. **
  44924. ** May you do good and not evil.
  44925. ** May you find forgiveness for yourself and forgive others.
  44926. ** May you share freely, never taking more than you give.
  44927. **
  44928. *************************************************************************
  44929. **
  44930. ** This file contains the implementation of a write-ahead log (WAL) used in
  44931. ** "journal_mode=WAL" mode.
  44932. **
  44933. ** WRITE-AHEAD LOG (WAL) FILE FORMAT
  44934. **
  44935. ** A WAL file consists of a header followed by zero or more "frames".
  44936. ** Each frame records the revised content of a single page from the
  44937. ** database file. All changes to the database are recorded by writing
  44938. ** frames into the WAL. Transactions commit when a frame is written that
  44939. ** contains a commit marker. A single WAL can and usually does record
  44940. ** multiple transactions. Periodically, the content of the WAL is
  44941. ** transferred back into the database file in an operation called a
  44942. ** "checkpoint".
  44943. **
  44944. ** A single WAL file can be used multiple times. In other words, the
  44945. ** WAL can fill up with frames and then be checkpointed and then new
  44946. ** frames can overwrite the old ones. A WAL always grows from beginning
  44947. ** toward the end. Checksums and counters attached to each frame are
  44948. ** used to determine which frames within the WAL are valid and which
  44949. ** are leftovers from prior checkpoints.
  44950. **
  44951. ** The WAL header is 32 bytes in size and consists of the following eight
  44952. ** big-endian 32-bit unsigned integer values:
  44953. **
  44954. ** 0: Magic number. 0x377f0682 or 0x377f0683
  44955. ** 4: File format version. Currently 3007000
  44956. ** 8: Database page size. Example: 1024
  44957. ** 12: Checkpoint sequence number
  44958. ** 16: Salt-1, random integer incremented with each checkpoint
  44959. ** 20: Salt-2, a different random integer changing with each ckpt
  44960. ** 24: Checksum-1 (first part of checksum for first 24 bytes of header).
  44961. ** 28: Checksum-2 (second part of checksum for first 24 bytes of header).
  44962. **
  44963. ** Immediately following the wal-header are zero or more frames. Each
  44964. ** frame consists of a 24-byte frame-header followed by a <page-size> bytes
  44965. ** of page data. The frame-header is six big-endian 32-bit unsigned
  44966. ** integer values, as follows:
  44967. **
  44968. ** 0: Page number.
  44969. ** 4: For commit records, the size of the database image in pages
  44970. ** after the commit. For all other records, zero.
  44971. ** 8: Salt-1 (copied from the header)
  44972. ** 12: Salt-2 (copied from the header)
  44973. ** 16: Checksum-1.
  44974. ** 20: Checksum-2.
  44975. **
  44976. ** A frame is considered valid if and only if the following conditions are
  44977. ** true:
  44978. **
  44979. ** (1) The salt-1 and salt-2 values in the frame-header match
  44980. ** salt values in the wal-header
  44981. **
  44982. ** (2) The checksum values in the final 8 bytes of the frame-header
  44983. ** exactly match the checksum computed consecutively on the
  44984. ** WAL header and the first 8 bytes and the content of all frames
  44985. ** up to and including the current frame.
  44986. **
  44987. ** The checksum is computed using 32-bit big-endian integers if the
  44988. ** magic number in the first 4 bytes of the WAL is 0x377f0683 and it
  44989. ** is computed using little-endian if the magic number is 0x377f0682.
  44990. ** The checksum values are always stored in the frame header in a
  44991. ** big-endian format regardless of which byte order is used to compute
  44992. ** the checksum. The checksum is computed by interpreting the input as
  44993. ** an even number of unsigned 32-bit integers: x[0] through x[N]. The
  44994. ** algorithm used for the checksum is as follows:
  44995. **
  44996. ** for i from 0 to n-1 step 2:
  44997. ** s0 += x[i] + s1;
  44998. ** s1 += x[i+1] + s0;
  44999. ** endfor
  45000. **
  45001. ** Note that s0 and s1 are both weighted checksums using fibonacci weights
  45002. ** in reverse order (the largest fibonacci weight occurs on the first element
  45003. ** of the sequence being summed.) The s1 value spans all 32-bit
  45004. ** terms of the sequence whereas s0 omits the final term.
  45005. **
  45006. ** On a checkpoint, the WAL is first VFS.xSync-ed, then valid content of the
  45007. ** WAL is transferred into the database, then the database is VFS.xSync-ed.
  45008. ** The VFS.xSync operations serve as write barriers - all writes launched
  45009. ** before the xSync must complete before any write that launches after the
  45010. ** xSync begins.
  45011. **
  45012. ** After each checkpoint, the salt-1 value is incremented and the salt-2
  45013. ** value is randomized. This prevents old and new frames in the WAL from
  45014. ** being considered valid at the same time and being checkpointing together
  45015. ** following a crash.
  45016. **
  45017. ** READER ALGORITHM
  45018. **
  45019. ** To read a page from the database (call it page number P), a reader
  45020. ** first checks the WAL to see if it contains page P. If so, then the
  45021. ** last valid instance of page P that is a followed by a commit frame
  45022. ** or is a commit frame itself becomes the value read. If the WAL
  45023. ** contains no copies of page P that are valid and which are a commit
  45024. ** frame or are followed by a commit frame, then page P is read from
  45025. ** the database file.
  45026. **
  45027. ** To start a read transaction, the reader records the index of the last
  45028. ** valid frame in the WAL. The reader uses this recorded "mxFrame" value
  45029. ** for all subsequent read operations. New transactions can be appended
  45030. ** to the WAL, but as long as the reader uses its original mxFrame value
  45031. ** and ignores the newly appended content, it will see a consistent snapshot
  45032. ** of the database from a single point in time. This technique allows
  45033. ** multiple concurrent readers to view different versions of the database
  45034. ** content simultaneously.
  45035. **
  45036. ** The reader algorithm in the previous paragraphs works correctly, but
  45037. ** because frames for page P can appear anywhere within the WAL, the
  45038. ** reader has to scan the entire WAL looking for page P frames. If the
  45039. ** WAL is large (multiple megabytes is typical) that scan can be slow,
  45040. ** and read performance suffers. To overcome this problem, a separate
  45041. ** data structure called the wal-index is maintained to expedite the
  45042. ** search for frames of a particular page.
  45043. **
  45044. ** WAL-INDEX FORMAT
  45045. **
  45046. ** Conceptually, the wal-index is shared memory, though VFS implementations
  45047. ** might choose to implement the wal-index using a mmapped file. Because
  45048. ** the wal-index is shared memory, SQLite does not support journal_mode=WAL
  45049. ** on a network filesystem. All users of the database must be able to
  45050. ** share memory.
  45051. **
  45052. ** The wal-index is transient. After a crash, the wal-index can (and should
  45053. ** be) reconstructed from the original WAL file. In fact, the VFS is required
  45054. ** to either truncate or zero the header of the wal-index when the last
  45055. ** connection to it closes. Because the wal-index is transient, it can
  45056. ** use an architecture-specific format; it does not have to be cross-platform.
  45057. ** Hence, unlike the database and WAL file formats which store all values
  45058. ** as big endian, the wal-index can store multi-byte values in the native
  45059. ** byte order of the host computer.
  45060. **
  45061. ** The purpose of the wal-index is to answer this question quickly: Given
  45062. ** a page number P and a maximum frame index M, return the index of the
  45063. ** last frame in the wal before frame M for page P in the WAL, or return
  45064. ** NULL if there are no frames for page P in the WAL prior to M.
  45065. **
  45066. ** The wal-index consists of a header region, followed by an one or
  45067. ** more index blocks.
  45068. **
  45069. ** The wal-index header contains the total number of frames within the WAL
  45070. ** in the mxFrame field.
  45071. **
  45072. ** Each index block except for the first contains information on
  45073. ** HASHTABLE_NPAGE frames. The first index block contains information on
  45074. ** HASHTABLE_NPAGE_ONE frames. The values of HASHTABLE_NPAGE_ONE and
  45075. ** HASHTABLE_NPAGE are selected so that together the wal-index header and
  45076. ** first index block are the same size as all other index blocks in the
  45077. ** wal-index.
  45078. **
  45079. ** Each index block contains two sections, a page-mapping that contains the
  45080. ** database page number associated with each wal frame, and a hash-table
  45081. ** that allows readers to query an index block for a specific page number.
  45082. ** The page-mapping is an array of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE
  45083. ** for the first index block) 32-bit page numbers. The first entry in the
  45084. ** first index-block contains the database page number corresponding to the
  45085. ** first frame in the WAL file. The first entry in the second index block
  45086. ** in the WAL file corresponds to the (HASHTABLE_NPAGE_ONE+1)th frame in
  45087. ** the log, and so on.
  45088. **
  45089. ** The last index block in a wal-index usually contains less than the full
  45090. ** complement of HASHTABLE_NPAGE (or HASHTABLE_NPAGE_ONE) page-numbers,
  45091. ** depending on the contents of the WAL file. This does not change the
  45092. ** allocated size of the page-mapping array - the page-mapping array merely
  45093. ** contains unused entries.
  45094. **
  45095. ** Even without using the hash table, the last frame for page P
  45096. ** can be found by scanning the page-mapping sections of each index block
  45097. ** starting with the last index block and moving toward the first, and
  45098. ** within each index block, starting at the end and moving toward the
  45099. ** beginning. The first entry that equals P corresponds to the frame
  45100. ** holding the content for that page.
  45101. **
  45102. ** The hash table consists of HASHTABLE_NSLOT 16-bit unsigned integers.
  45103. ** HASHTABLE_NSLOT = 2*HASHTABLE_NPAGE, and there is one entry in the
  45104. ** hash table for each page number in the mapping section, so the hash
  45105. ** table is never more than half full. The expected number of collisions
  45106. ** prior to finding a match is 1. Each entry of the hash table is an
  45107. ** 1-based index of an entry in the mapping section of the same
  45108. ** index block. Let K be the 1-based index of the largest entry in
  45109. ** the mapping section. (For index blocks other than the last, K will
  45110. ** always be exactly HASHTABLE_NPAGE (4096) and for the last index block
  45111. ** K will be (mxFrame%HASHTABLE_NPAGE).) Unused slots of the hash table
  45112. ** contain a value of 0.
  45113. **
  45114. ** To look for page P in the hash table, first compute a hash iKey on
  45115. ** P as follows:
  45116. **
  45117. ** iKey = (P * 383) % HASHTABLE_NSLOT
  45118. **
  45119. ** Then start scanning entries of the hash table, starting with iKey
  45120. ** (wrapping around to the beginning when the end of the hash table is
  45121. ** reached) until an unused hash slot is found. Let the first unused slot
  45122. ** be at index iUnused. (iUnused might be less than iKey if there was
  45123. ** wrap-around.) Because the hash table is never more than half full,
  45124. ** the search is guaranteed to eventually hit an unused entry. Let
  45125. ** iMax be the value between iKey and iUnused, closest to iUnused,
  45126. ** where aHash[iMax]==P. If there is no iMax entry (if there exists
  45127. ** no hash slot such that aHash[i]==p) then page P is not in the
  45128. ** current index block. Otherwise the iMax-th mapping entry of the
  45129. ** current index block corresponds to the last entry that references
  45130. ** page P.
  45131. **
  45132. ** A hash search begins with the last index block and moves toward the
  45133. ** first index block, looking for entries corresponding to page P. On
  45134. ** average, only two or three slots in each index block need to be
  45135. ** examined in order to either find the last entry for page P, or to
  45136. ** establish that no such entry exists in the block. Each index block
  45137. ** holds over 4000 entries. So two or three index blocks are sufficient
  45138. ** to cover a typical 10 megabyte WAL file, assuming 1K pages. 8 or 10
  45139. ** comparisons (on average) suffice to either locate a frame in the
  45140. ** WAL or to establish that the frame does not exist in the WAL. This
  45141. ** is much faster than scanning the entire 10MB WAL.
  45142. **
  45143. ** Note that entries are added in order of increasing K. Hence, one
  45144. ** reader might be using some value K0 and a second reader that started
  45145. ** at a later time (after additional transactions were added to the WAL
  45146. ** and to the wal-index) might be using a different value K1, where K1>K0.
  45147. ** Both readers can use the same hash table and mapping section to get
  45148. ** the correct result. There may be entries in the hash table with
  45149. ** K>K0 but to the first reader, those entries will appear to be unused
  45150. ** slots in the hash table and so the first reader will get an answer as
  45151. ** if no values greater than K0 had ever been inserted into the hash table
  45152. ** in the first place - which is what reader one wants. Meanwhile, the
  45153. ** second reader using K1 will see additional values that were inserted
  45154. ** later, which is exactly what reader two wants.
  45155. **
  45156. ** When a rollback occurs, the value of K is decreased. Hash table entries
  45157. ** that correspond to frames greater than the new K value are removed
  45158. ** from the hash table at this point.
  45159. */
  45160. #ifndef SQLITE_OMIT_WAL
  45161. /*
  45162. ** Trace output macros
  45163. */
  45164. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  45165. SQLITE_PRIVATE int sqlite3WalTrace = 0;
  45166. # define WALTRACE(X) if(sqlite3WalTrace) sqlite3DebugPrintf X
  45167. #else
  45168. # define WALTRACE(X)
  45169. #endif
  45170. /*
  45171. ** The maximum (and only) versions of the wal and wal-index formats
  45172. ** that may be interpreted by this version of SQLite.
  45173. **
  45174. ** If a client begins recovering a WAL file and finds that (a) the checksum
  45175. ** values in the wal-header are correct and (b) the version field is not
  45176. ** WAL_MAX_VERSION, recovery fails and SQLite returns SQLITE_CANTOPEN.
  45177. **
  45178. ** Similarly, if a client successfully reads a wal-index header (i.e. the
  45179. ** checksum test is successful) and finds that the version field is not
  45180. ** WALINDEX_MAX_VERSION, then no read-transaction is opened and SQLite
  45181. ** returns SQLITE_CANTOPEN.
  45182. */
  45183. #define WAL_MAX_VERSION 3007000
  45184. #define WALINDEX_MAX_VERSION 3007000
  45185. /*
  45186. ** Indices of various locking bytes. WAL_NREADER is the number
  45187. ** of available reader locks and should be at least 3.
  45188. */
  45189. #define WAL_WRITE_LOCK 0
  45190. #define WAL_ALL_BUT_WRITE 1
  45191. #define WAL_CKPT_LOCK 1
  45192. #define WAL_RECOVER_LOCK 2
  45193. #define WAL_READ_LOCK(I) (3+(I))
  45194. #define WAL_NREADER (SQLITE_SHM_NLOCK-3)
  45195. /* Object declarations */
  45196. typedef struct WalIndexHdr WalIndexHdr;
  45197. typedef struct WalIterator WalIterator;
  45198. typedef struct WalCkptInfo WalCkptInfo;
  45199. /*
  45200. ** The following object holds a copy of the wal-index header content.
  45201. **
  45202. ** The actual header in the wal-index consists of two copies of this
  45203. ** object.
  45204. **
  45205. ** The szPage value can be any power of 2 between 512 and 32768, inclusive.
  45206. ** Or it can be 1 to represent a 65536-byte page. The latter case was
  45207. ** added in 3.7.1 when support for 64K pages was added.
  45208. */
  45209. struct WalIndexHdr {
  45210. u32 iVersion; /* Wal-index version */
  45211. u32 unused; /* Unused (padding) field */
  45212. u32 iChange; /* Counter incremented each transaction */
  45213. u8 isInit; /* 1 when initialized */
  45214. u8 bigEndCksum; /* True if checksums in WAL are big-endian */
  45215. u16 szPage; /* Database page size in bytes. 1==64K */
  45216. u32 mxFrame; /* Index of last valid frame in the WAL */
  45217. u32 nPage; /* Size of database in pages */
  45218. u32 aFrameCksum[2]; /* Checksum of last frame in log */
  45219. u32 aSalt[2]; /* Two salt values copied from WAL header */
  45220. u32 aCksum[2]; /* Checksum over all prior fields */
  45221. };
  45222. /*
  45223. ** A copy of the following object occurs in the wal-index immediately
  45224. ** following the second copy of the WalIndexHdr. This object stores
  45225. ** information used by checkpoint.
  45226. **
  45227. ** nBackfill is the number of frames in the WAL that have been written
  45228. ** back into the database. (We call the act of moving content from WAL to
  45229. ** database "backfilling".) The nBackfill number is never greater than
  45230. ** WalIndexHdr.mxFrame. nBackfill can only be increased by threads
  45231. ** holding the WAL_CKPT_LOCK lock (which includes a recovery thread).
  45232. ** However, a WAL_WRITE_LOCK thread can move the value of nBackfill from
  45233. ** mxFrame back to zero when the WAL is reset.
  45234. **
  45235. ** There is one entry in aReadMark[] for each reader lock. If a reader
  45236. ** holds read-lock K, then the value in aReadMark[K] is no greater than
  45237. ** the mxFrame for that reader. The value READMARK_NOT_USED (0xffffffff)
  45238. ** for any aReadMark[] means that entry is unused. aReadMark[0] is
  45239. ** a special case; its value is never used and it exists as a place-holder
  45240. ** to avoid having to offset aReadMark[] indexs by one. Readers holding
  45241. ** WAL_READ_LOCK(0) always ignore the entire WAL and read all content
  45242. ** directly from the database.
  45243. **
  45244. ** The value of aReadMark[K] may only be changed by a thread that
  45245. ** is holding an exclusive lock on WAL_READ_LOCK(K). Thus, the value of
  45246. ** aReadMark[K] cannot changed while there is a reader is using that mark
  45247. ** since the reader will be holding a shared lock on WAL_READ_LOCK(K).
  45248. **
  45249. ** The checkpointer may only transfer frames from WAL to database where
  45250. ** the frame numbers are less than or equal to every aReadMark[] that is
  45251. ** in use (that is, every aReadMark[j] for which there is a corresponding
  45252. ** WAL_READ_LOCK(j)). New readers (usually) pick the aReadMark[] with the
  45253. ** largest value and will increase an unused aReadMark[] to mxFrame if there
  45254. ** is not already an aReadMark[] equal to mxFrame. The exception to the
  45255. ** previous sentence is when nBackfill equals mxFrame (meaning that everything
  45256. ** in the WAL has been backfilled into the database) then new readers
  45257. ** will choose aReadMark[0] which has value 0 and hence such reader will
  45258. ** get all their all content directly from the database file and ignore
  45259. ** the WAL.
  45260. **
  45261. ** Writers normally append new frames to the end of the WAL. However,
  45262. ** if nBackfill equals mxFrame (meaning that all WAL content has been
  45263. ** written back into the database) and if no readers are using the WAL
  45264. ** (in other words, if there are no WAL_READ_LOCK(i) where i>0) then
  45265. ** the writer will first "reset" the WAL back to the beginning and start
  45266. ** writing new content beginning at frame 1.
  45267. **
  45268. ** We assume that 32-bit loads are atomic and so no locks are needed in
  45269. ** order to read from any aReadMark[] entries.
  45270. */
  45271. struct WalCkptInfo {
  45272. u32 nBackfill; /* Number of WAL frames backfilled into DB */
  45273. u32 aReadMark[WAL_NREADER]; /* Reader marks */
  45274. };
  45275. #define READMARK_NOT_USED 0xffffffff
  45276. /* A block of WALINDEX_LOCK_RESERVED bytes beginning at
  45277. ** WALINDEX_LOCK_OFFSET is reserved for locks. Since some systems
  45278. ** only support mandatory file-locks, we do not read or write data
  45279. ** from the region of the file on which locks are applied.
  45280. */
  45281. #define WALINDEX_LOCK_OFFSET (sizeof(WalIndexHdr)*2 + sizeof(WalCkptInfo))
  45282. #define WALINDEX_LOCK_RESERVED 16
  45283. #define WALINDEX_HDR_SIZE (WALINDEX_LOCK_OFFSET+WALINDEX_LOCK_RESERVED)
  45284. /* Size of header before each frame in wal */
  45285. #define WAL_FRAME_HDRSIZE 24
  45286. /* Size of write ahead log header, including checksum. */
  45287. /* #define WAL_HDRSIZE 24 */
  45288. #define WAL_HDRSIZE 32
  45289. /* WAL magic value. Either this value, or the same value with the least
  45290. ** significant bit also set (WAL_MAGIC | 0x00000001) is stored in 32-bit
  45291. ** big-endian format in the first 4 bytes of a WAL file.
  45292. **
  45293. ** If the LSB is set, then the checksums for each frame within the WAL
  45294. ** file are calculated by treating all data as an array of 32-bit
  45295. ** big-endian words. Otherwise, they are calculated by interpreting
  45296. ** all data as 32-bit little-endian words.
  45297. */
  45298. #define WAL_MAGIC 0x377f0682
  45299. /*
  45300. ** Return the offset of frame iFrame in the write-ahead log file,
  45301. ** assuming a database page size of szPage bytes. The offset returned
  45302. ** is to the start of the write-ahead log frame-header.
  45303. */
  45304. #define walFrameOffset(iFrame, szPage) ( \
  45305. WAL_HDRSIZE + ((iFrame)-1)*(i64)((szPage)+WAL_FRAME_HDRSIZE) \
  45306. )
  45307. /*
  45308. ** An open write-ahead log file is represented by an instance of the
  45309. ** following object.
  45310. */
  45311. struct Wal {
  45312. sqlite3_vfs *pVfs; /* The VFS used to create pDbFd */
  45313. sqlite3_file *pDbFd; /* File handle for the database file */
  45314. sqlite3_file *pWalFd; /* File handle for WAL file */
  45315. u32 iCallback; /* Value to pass to log callback (or 0) */
  45316. i64 mxWalSize; /* Truncate WAL to this size upon reset */
  45317. int nWiData; /* Size of array apWiData */
  45318. int szFirstBlock; /* Size of first block written to WAL file */
  45319. volatile u32 **apWiData; /* Pointer to wal-index content in memory */
  45320. u32 szPage; /* Database page size */
  45321. i16 readLock; /* Which read lock is being held. -1 for none */
  45322. u8 syncFlags; /* Flags to use to sync header writes */
  45323. u8 exclusiveMode; /* Non-zero if connection is in exclusive mode */
  45324. u8 writeLock; /* True if in a write transaction */
  45325. u8 ckptLock; /* True if holding a checkpoint lock */
  45326. u8 readOnly; /* WAL_RDWR, WAL_RDONLY, or WAL_SHM_RDONLY */
  45327. u8 truncateOnCommit; /* True to truncate WAL file on commit */
  45328. u8 syncHeader; /* Fsync the WAL header if true */
  45329. u8 padToSectorBoundary; /* Pad transactions out to the next sector */
  45330. WalIndexHdr hdr; /* Wal-index header for current transaction */
  45331. const char *zWalName; /* Name of WAL file */
  45332. u32 nCkpt; /* Checkpoint sequence counter in the wal-header */
  45333. #ifdef SQLITE_DEBUG
  45334. u8 lockError; /* True if a locking error has occurred */
  45335. #endif
  45336. };
  45337. /*
  45338. ** Candidate values for Wal.exclusiveMode.
  45339. */
  45340. #define WAL_NORMAL_MODE 0
  45341. #define WAL_EXCLUSIVE_MODE 1
  45342. #define WAL_HEAPMEMORY_MODE 2
  45343. /*
  45344. ** Possible values for WAL.readOnly
  45345. */
  45346. #define WAL_RDWR 0 /* Normal read/write connection */
  45347. #define WAL_RDONLY 1 /* The WAL file is readonly */
  45348. #define WAL_SHM_RDONLY 2 /* The SHM file is readonly */
  45349. /*
  45350. ** Each page of the wal-index mapping contains a hash-table made up of
  45351. ** an array of HASHTABLE_NSLOT elements of the following type.
  45352. */
  45353. typedef u16 ht_slot;
  45354. /*
  45355. ** This structure is used to implement an iterator that loops through
  45356. ** all frames in the WAL in database page order. Where two or more frames
  45357. ** correspond to the same database page, the iterator visits only the
  45358. ** frame most recently written to the WAL (in other words, the frame with
  45359. ** the largest index).
  45360. **
  45361. ** The internals of this structure are only accessed by:
  45362. **
  45363. ** walIteratorInit() - Create a new iterator,
  45364. ** walIteratorNext() - Step an iterator,
  45365. ** walIteratorFree() - Free an iterator.
  45366. **
  45367. ** This functionality is used by the checkpoint code (see walCheckpoint()).
  45368. */
  45369. struct WalIterator {
  45370. int iPrior; /* Last result returned from the iterator */
  45371. int nSegment; /* Number of entries in aSegment[] */
  45372. struct WalSegment {
  45373. int iNext; /* Next slot in aIndex[] not yet returned */
  45374. ht_slot *aIndex; /* i0, i1, i2... such that aPgno[iN] ascend */
  45375. u32 *aPgno; /* Array of page numbers. */
  45376. int nEntry; /* Nr. of entries in aPgno[] and aIndex[] */
  45377. int iZero; /* Frame number associated with aPgno[0] */
  45378. } aSegment[1]; /* One for every 32KB page in the wal-index */
  45379. };
  45380. /*
  45381. ** Define the parameters of the hash tables in the wal-index file. There
  45382. ** is a hash-table following every HASHTABLE_NPAGE page numbers in the
  45383. ** wal-index.
  45384. **
  45385. ** Changing any of these constants will alter the wal-index format and
  45386. ** create incompatibilities.
  45387. */
  45388. #define HASHTABLE_NPAGE 4096 /* Must be power of 2 */
  45389. #define HASHTABLE_HASH_1 383 /* Should be prime */
  45390. #define HASHTABLE_NSLOT (HASHTABLE_NPAGE*2) /* Must be a power of 2 */
  45391. /*
  45392. ** The block of page numbers associated with the first hash-table in a
  45393. ** wal-index is smaller than usual. This is so that there is a complete
  45394. ** hash-table on each aligned 32KB page of the wal-index.
  45395. */
  45396. #define HASHTABLE_NPAGE_ONE (HASHTABLE_NPAGE - (WALINDEX_HDR_SIZE/sizeof(u32)))
  45397. /* The wal-index is divided into pages of WALINDEX_PGSZ bytes each. */
  45398. #define WALINDEX_PGSZ ( \
  45399. sizeof(ht_slot)*HASHTABLE_NSLOT + HASHTABLE_NPAGE*sizeof(u32) \
  45400. )
  45401. /*
  45402. ** Obtain a pointer to the iPage'th page of the wal-index. The wal-index
  45403. ** is broken into pages of WALINDEX_PGSZ bytes. Wal-index pages are
  45404. ** numbered from zero.
  45405. **
  45406. ** If this call is successful, *ppPage is set to point to the wal-index
  45407. ** page and SQLITE_OK is returned. If an error (an OOM or VFS error) occurs,
  45408. ** then an SQLite error code is returned and *ppPage is set to 0.
  45409. */
  45410. static int walIndexPage(Wal *pWal, int iPage, volatile u32 **ppPage){
  45411. int rc = SQLITE_OK;
  45412. /* Enlarge the pWal->apWiData[] array if required */
  45413. if( pWal->nWiData<=iPage ){
  45414. int nByte = sizeof(u32*)*(iPage+1);
  45415. volatile u32 **apNew;
  45416. apNew = (volatile u32 **)sqlite3_realloc((void *)pWal->apWiData, nByte);
  45417. if( !apNew ){
  45418. *ppPage = 0;
  45419. return SQLITE_NOMEM;
  45420. }
  45421. memset((void*)&apNew[pWal->nWiData], 0,
  45422. sizeof(u32*)*(iPage+1-pWal->nWiData));
  45423. pWal->apWiData = apNew;
  45424. pWal->nWiData = iPage+1;
  45425. }
  45426. /* Request a pointer to the required page from the VFS */
  45427. if( pWal->apWiData[iPage]==0 ){
  45428. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  45429. pWal->apWiData[iPage] = (u32 volatile *)sqlite3MallocZero(WALINDEX_PGSZ);
  45430. if( !pWal->apWiData[iPage] ) rc = SQLITE_NOMEM;
  45431. }else{
  45432. rc = sqlite3OsShmMap(pWal->pDbFd, iPage, WALINDEX_PGSZ,
  45433. pWal->writeLock, (void volatile **)&pWal->apWiData[iPage]
  45434. );
  45435. if( rc==SQLITE_READONLY ){
  45436. pWal->readOnly |= WAL_SHM_RDONLY;
  45437. rc = SQLITE_OK;
  45438. }
  45439. }
  45440. }
  45441. *ppPage = pWal->apWiData[iPage];
  45442. assert( iPage==0 || *ppPage || rc!=SQLITE_OK );
  45443. return rc;
  45444. }
  45445. /*
  45446. ** Return a pointer to the WalCkptInfo structure in the wal-index.
  45447. */
  45448. static volatile WalCkptInfo *walCkptInfo(Wal *pWal){
  45449. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  45450. return (volatile WalCkptInfo*)&(pWal->apWiData[0][sizeof(WalIndexHdr)/2]);
  45451. }
  45452. /*
  45453. ** Return a pointer to the WalIndexHdr structure in the wal-index.
  45454. */
  45455. static volatile WalIndexHdr *walIndexHdr(Wal *pWal){
  45456. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  45457. return (volatile WalIndexHdr*)pWal->apWiData[0];
  45458. }
  45459. /*
  45460. ** The argument to this macro must be of type u32. On a little-endian
  45461. ** architecture, it returns the u32 value that results from interpreting
  45462. ** the 4 bytes as a big-endian value. On a big-endian architecture, it
  45463. ** returns the value that would be produced by interpreting the 4 bytes
  45464. ** of the input value as a little-endian integer.
  45465. */
  45466. #define BYTESWAP32(x) ( \
  45467. (((x)&0x000000FF)<<24) + (((x)&0x0000FF00)<<8) \
  45468. + (((x)&0x00FF0000)>>8) + (((x)&0xFF000000)>>24) \
  45469. )
  45470. /*
  45471. ** Generate or extend an 8 byte checksum based on the data in
  45472. ** array aByte[] and the initial values of aIn[0] and aIn[1] (or
  45473. ** initial values of 0 and 0 if aIn==NULL).
  45474. **
  45475. ** The checksum is written back into aOut[] before returning.
  45476. **
  45477. ** nByte must be a positive multiple of 8.
  45478. */
  45479. static void walChecksumBytes(
  45480. int nativeCksum, /* True for native byte-order, false for non-native */
  45481. u8 *a, /* Content to be checksummed */
  45482. int nByte, /* Bytes of content in a[]. Must be a multiple of 8. */
  45483. const u32 *aIn, /* Initial checksum value input */
  45484. u32 *aOut /* OUT: Final checksum value output */
  45485. ){
  45486. u32 s1, s2;
  45487. u32 *aData = (u32 *)a;
  45488. u32 *aEnd = (u32 *)&a[nByte];
  45489. if( aIn ){
  45490. s1 = aIn[0];
  45491. s2 = aIn[1];
  45492. }else{
  45493. s1 = s2 = 0;
  45494. }
  45495. assert( nByte>=8 );
  45496. assert( (nByte&0x00000007)==0 );
  45497. if( nativeCksum ){
  45498. do {
  45499. s1 += *aData++ + s2;
  45500. s2 += *aData++ + s1;
  45501. }while( aData<aEnd );
  45502. }else{
  45503. do {
  45504. s1 += BYTESWAP32(aData[0]) + s2;
  45505. s2 += BYTESWAP32(aData[1]) + s1;
  45506. aData += 2;
  45507. }while( aData<aEnd );
  45508. }
  45509. aOut[0] = s1;
  45510. aOut[1] = s2;
  45511. }
  45512. static void walShmBarrier(Wal *pWal){
  45513. if( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE ){
  45514. sqlite3OsShmBarrier(pWal->pDbFd);
  45515. }
  45516. }
  45517. /*
  45518. ** Write the header information in pWal->hdr into the wal-index.
  45519. **
  45520. ** The checksum on pWal->hdr is updated before it is written.
  45521. */
  45522. static void walIndexWriteHdr(Wal *pWal){
  45523. volatile WalIndexHdr *aHdr = walIndexHdr(pWal);
  45524. const int nCksum = offsetof(WalIndexHdr, aCksum);
  45525. assert( pWal->writeLock );
  45526. pWal->hdr.isInit = 1;
  45527. pWal->hdr.iVersion = WALINDEX_MAX_VERSION;
  45528. walChecksumBytes(1, (u8*)&pWal->hdr, nCksum, 0, pWal->hdr.aCksum);
  45529. memcpy((void *)&aHdr[1], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  45530. walShmBarrier(pWal);
  45531. memcpy((void *)&aHdr[0], (void *)&pWal->hdr, sizeof(WalIndexHdr));
  45532. }
  45533. /*
  45534. ** This function encodes a single frame header and writes it to a buffer
  45535. ** supplied by the caller. A frame-header is made up of a series of
  45536. ** 4-byte big-endian integers, as follows:
  45537. **
  45538. ** 0: Page number.
  45539. ** 4: For commit records, the size of the database image in pages
  45540. ** after the commit. For all other records, zero.
  45541. ** 8: Salt-1 (copied from the wal-header)
  45542. ** 12: Salt-2 (copied from the wal-header)
  45543. ** 16: Checksum-1.
  45544. ** 20: Checksum-2.
  45545. */
  45546. static void walEncodeFrame(
  45547. Wal *pWal, /* The write-ahead log */
  45548. u32 iPage, /* Database page number for frame */
  45549. u32 nTruncate, /* New db size (or 0 for non-commit frames) */
  45550. u8 *aData, /* Pointer to page data */
  45551. u8 *aFrame /* OUT: Write encoded frame here */
  45552. ){
  45553. int nativeCksum; /* True for native byte-order checksums */
  45554. u32 *aCksum = pWal->hdr.aFrameCksum;
  45555. assert( WAL_FRAME_HDRSIZE==24 );
  45556. sqlite3Put4byte(&aFrame[0], iPage);
  45557. sqlite3Put4byte(&aFrame[4], nTruncate);
  45558. memcpy(&aFrame[8], pWal->hdr.aSalt, 8);
  45559. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  45560. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  45561. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  45562. sqlite3Put4byte(&aFrame[16], aCksum[0]);
  45563. sqlite3Put4byte(&aFrame[20], aCksum[1]);
  45564. }
  45565. /*
  45566. ** Check to see if the frame with header in aFrame[] and content
  45567. ** in aData[] is valid. If it is a valid frame, fill *piPage and
  45568. ** *pnTruncate and return true. Return if the frame is not valid.
  45569. */
  45570. static int walDecodeFrame(
  45571. Wal *pWal, /* The write-ahead log */
  45572. u32 *piPage, /* OUT: Database page number for frame */
  45573. u32 *pnTruncate, /* OUT: New db size (or 0 if not commit) */
  45574. u8 *aData, /* Pointer to page data (for checksum) */
  45575. u8 *aFrame /* Frame data */
  45576. ){
  45577. int nativeCksum; /* True for native byte-order checksums */
  45578. u32 *aCksum = pWal->hdr.aFrameCksum;
  45579. u32 pgno; /* Page number of the frame */
  45580. assert( WAL_FRAME_HDRSIZE==24 );
  45581. /* A frame is only valid if the salt values in the frame-header
  45582. ** match the salt values in the wal-header.
  45583. */
  45584. if( memcmp(&pWal->hdr.aSalt, &aFrame[8], 8)!=0 ){
  45585. return 0;
  45586. }
  45587. /* A frame is only valid if the page number is creater than zero.
  45588. */
  45589. pgno = sqlite3Get4byte(&aFrame[0]);
  45590. if( pgno==0 ){
  45591. return 0;
  45592. }
  45593. /* A frame is only valid if a checksum of the WAL header,
  45594. ** all prior frams, the first 16 bytes of this frame-header,
  45595. ** and the frame-data matches the checksum in the last 8
  45596. ** bytes of this frame-header.
  45597. */
  45598. nativeCksum = (pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN);
  45599. walChecksumBytes(nativeCksum, aFrame, 8, aCksum, aCksum);
  45600. walChecksumBytes(nativeCksum, aData, pWal->szPage, aCksum, aCksum);
  45601. if( aCksum[0]!=sqlite3Get4byte(&aFrame[16])
  45602. || aCksum[1]!=sqlite3Get4byte(&aFrame[20])
  45603. ){
  45604. /* Checksum failed. */
  45605. return 0;
  45606. }
  45607. /* If we reach this point, the frame is valid. Return the page number
  45608. ** and the new database size.
  45609. */
  45610. *piPage = pgno;
  45611. *pnTruncate = sqlite3Get4byte(&aFrame[4]);
  45612. return 1;
  45613. }
  45614. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  45615. /*
  45616. ** Names of locks. This routine is used to provide debugging output and is not
  45617. ** a part of an ordinary build.
  45618. */
  45619. static const char *walLockName(int lockIdx){
  45620. if( lockIdx==WAL_WRITE_LOCK ){
  45621. return "WRITE-LOCK";
  45622. }else if( lockIdx==WAL_CKPT_LOCK ){
  45623. return "CKPT-LOCK";
  45624. }else if( lockIdx==WAL_RECOVER_LOCK ){
  45625. return "RECOVER-LOCK";
  45626. }else{
  45627. static char zName[15];
  45628. sqlite3_snprintf(sizeof(zName), zName, "READ-LOCK[%d]",
  45629. lockIdx-WAL_READ_LOCK(0));
  45630. return zName;
  45631. }
  45632. }
  45633. #endif /*defined(SQLITE_TEST) || defined(SQLITE_DEBUG) */
  45634. /*
  45635. ** Set or release locks on the WAL. Locks are either shared or exclusive.
  45636. ** A lock cannot be moved directly between shared and exclusive - it must go
  45637. ** through the unlocked state first.
  45638. **
  45639. ** In locking_mode=EXCLUSIVE, all of these routines become no-ops.
  45640. */
  45641. static int walLockShared(Wal *pWal, int lockIdx){
  45642. int rc;
  45643. if( pWal->exclusiveMode ) return SQLITE_OK;
  45644. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  45645. SQLITE_SHM_LOCK | SQLITE_SHM_SHARED);
  45646. WALTRACE(("WAL%p: acquire SHARED-%s %s\n", pWal,
  45647. walLockName(lockIdx), rc ? "failed" : "ok"));
  45648. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  45649. return rc;
  45650. }
  45651. static void walUnlockShared(Wal *pWal, int lockIdx){
  45652. if( pWal->exclusiveMode ) return;
  45653. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, 1,
  45654. SQLITE_SHM_UNLOCK | SQLITE_SHM_SHARED);
  45655. WALTRACE(("WAL%p: release SHARED-%s\n", pWal, walLockName(lockIdx)));
  45656. }
  45657. static int walLockExclusive(Wal *pWal, int lockIdx, int n){
  45658. int rc;
  45659. if( pWal->exclusiveMode ) return SQLITE_OK;
  45660. rc = sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  45661. SQLITE_SHM_LOCK | SQLITE_SHM_EXCLUSIVE);
  45662. WALTRACE(("WAL%p: acquire EXCLUSIVE-%s cnt=%d %s\n", pWal,
  45663. walLockName(lockIdx), n, rc ? "failed" : "ok"));
  45664. VVA_ONLY( pWal->lockError = (u8)(rc!=SQLITE_OK && rc!=SQLITE_BUSY); )
  45665. return rc;
  45666. }
  45667. static void walUnlockExclusive(Wal *pWal, int lockIdx, int n){
  45668. if( pWal->exclusiveMode ) return;
  45669. (void)sqlite3OsShmLock(pWal->pDbFd, lockIdx, n,
  45670. SQLITE_SHM_UNLOCK | SQLITE_SHM_EXCLUSIVE);
  45671. WALTRACE(("WAL%p: release EXCLUSIVE-%s cnt=%d\n", pWal,
  45672. walLockName(lockIdx), n));
  45673. }
  45674. /*
  45675. ** Compute a hash on a page number. The resulting hash value must land
  45676. ** between 0 and (HASHTABLE_NSLOT-1). The walHashNext() function advances
  45677. ** the hash to the next value in the event of a collision.
  45678. */
  45679. static int walHash(u32 iPage){
  45680. assert( iPage>0 );
  45681. assert( (HASHTABLE_NSLOT & (HASHTABLE_NSLOT-1))==0 );
  45682. return (iPage*HASHTABLE_HASH_1) & (HASHTABLE_NSLOT-1);
  45683. }
  45684. static int walNextHash(int iPriorHash){
  45685. return (iPriorHash+1)&(HASHTABLE_NSLOT-1);
  45686. }
  45687. /*
  45688. ** Return pointers to the hash table and page number array stored on
  45689. ** page iHash of the wal-index. The wal-index is broken into 32KB pages
  45690. ** numbered starting from 0.
  45691. **
  45692. ** Set output variable *paHash to point to the start of the hash table
  45693. ** in the wal-index file. Set *piZero to one less than the frame
  45694. ** number of the first frame indexed by this hash table. If a
  45695. ** slot in the hash table is set to N, it refers to frame number
  45696. ** (*piZero+N) in the log.
  45697. **
  45698. ** Finally, set *paPgno so that *paPgno[1] is the page number of the
  45699. ** first frame indexed by the hash table, frame (*piZero+1).
  45700. */
  45701. static int walHashGet(
  45702. Wal *pWal, /* WAL handle */
  45703. int iHash, /* Find the iHash'th table */
  45704. volatile ht_slot **paHash, /* OUT: Pointer to hash index */
  45705. volatile u32 **paPgno, /* OUT: Pointer to page number array */
  45706. u32 *piZero /* OUT: Frame associated with *paPgno[0] */
  45707. ){
  45708. int rc; /* Return code */
  45709. volatile u32 *aPgno;
  45710. rc = walIndexPage(pWal, iHash, &aPgno);
  45711. assert( rc==SQLITE_OK || iHash>0 );
  45712. if( rc==SQLITE_OK ){
  45713. u32 iZero;
  45714. volatile ht_slot *aHash;
  45715. aHash = (volatile ht_slot *)&aPgno[HASHTABLE_NPAGE];
  45716. if( iHash==0 ){
  45717. aPgno = &aPgno[WALINDEX_HDR_SIZE/sizeof(u32)];
  45718. iZero = 0;
  45719. }else{
  45720. iZero = HASHTABLE_NPAGE_ONE + (iHash-1)*HASHTABLE_NPAGE;
  45721. }
  45722. *paPgno = &aPgno[-1];
  45723. *paHash = aHash;
  45724. *piZero = iZero;
  45725. }
  45726. return rc;
  45727. }
  45728. /*
  45729. ** Return the number of the wal-index page that contains the hash-table
  45730. ** and page-number array that contain entries corresponding to WAL frame
  45731. ** iFrame. The wal-index is broken up into 32KB pages. Wal-index pages
  45732. ** are numbered starting from 0.
  45733. */
  45734. static int walFramePage(u32 iFrame){
  45735. int iHash = (iFrame+HASHTABLE_NPAGE-HASHTABLE_NPAGE_ONE-1) / HASHTABLE_NPAGE;
  45736. assert( (iHash==0 || iFrame>HASHTABLE_NPAGE_ONE)
  45737. && (iHash>=1 || iFrame<=HASHTABLE_NPAGE_ONE)
  45738. && (iHash<=1 || iFrame>(HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE))
  45739. && (iHash>=2 || iFrame<=HASHTABLE_NPAGE_ONE+HASHTABLE_NPAGE)
  45740. && (iHash<=2 || iFrame>(HASHTABLE_NPAGE_ONE+2*HASHTABLE_NPAGE))
  45741. );
  45742. return iHash;
  45743. }
  45744. /*
  45745. ** Return the page number associated with frame iFrame in this WAL.
  45746. */
  45747. static u32 walFramePgno(Wal *pWal, u32 iFrame){
  45748. int iHash = walFramePage(iFrame);
  45749. if( iHash==0 ){
  45750. return pWal->apWiData[0][WALINDEX_HDR_SIZE/sizeof(u32) + iFrame - 1];
  45751. }
  45752. return pWal->apWiData[iHash][(iFrame-1-HASHTABLE_NPAGE_ONE)%HASHTABLE_NPAGE];
  45753. }
  45754. /*
  45755. ** Remove entries from the hash table that point to WAL slots greater
  45756. ** than pWal->hdr.mxFrame.
  45757. **
  45758. ** This function is called whenever pWal->hdr.mxFrame is decreased due
  45759. ** to a rollback or savepoint.
  45760. **
  45761. ** At most only the hash table containing pWal->hdr.mxFrame needs to be
  45762. ** updated. Any later hash tables will be automatically cleared when
  45763. ** pWal->hdr.mxFrame advances to the point where those hash tables are
  45764. ** actually needed.
  45765. */
  45766. static void walCleanupHash(Wal *pWal){
  45767. volatile ht_slot *aHash = 0; /* Pointer to hash table to clear */
  45768. volatile u32 *aPgno = 0; /* Page number array for hash table */
  45769. u32 iZero = 0; /* frame == (aHash[x]+iZero) */
  45770. int iLimit = 0; /* Zero values greater than this */
  45771. int nByte; /* Number of bytes to zero in aPgno[] */
  45772. int i; /* Used to iterate through aHash[] */
  45773. assert( pWal->writeLock );
  45774. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE-1 );
  45775. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE );
  45776. testcase( pWal->hdr.mxFrame==HASHTABLE_NPAGE_ONE+1 );
  45777. if( pWal->hdr.mxFrame==0 ) return;
  45778. /* Obtain pointers to the hash-table and page-number array containing
  45779. ** the entry that corresponds to frame pWal->hdr.mxFrame. It is guaranteed
  45780. ** that the page said hash-table and array reside on is already mapped.
  45781. */
  45782. assert( pWal->nWiData>walFramePage(pWal->hdr.mxFrame) );
  45783. assert( pWal->apWiData[walFramePage(pWal->hdr.mxFrame)] );
  45784. walHashGet(pWal, walFramePage(pWal->hdr.mxFrame), &aHash, &aPgno, &iZero);
  45785. /* Zero all hash-table entries that correspond to frame numbers greater
  45786. ** than pWal->hdr.mxFrame.
  45787. */
  45788. iLimit = pWal->hdr.mxFrame - iZero;
  45789. assert( iLimit>0 );
  45790. for(i=0; i<HASHTABLE_NSLOT; i++){
  45791. if( aHash[i]>iLimit ){
  45792. aHash[i] = 0;
  45793. }
  45794. }
  45795. /* Zero the entries in the aPgno array that correspond to frames with
  45796. ** frame numbers greater than pWal->hdr.mxFrame.
  45797. */
  45798. nByte = (int)((char *)aHash - (char *)&aPgno[iLimit+1]);
  45799. memset((void *)&aPgno[iLimit+1], 0, nByte);
  45800. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  45801. /* Verify that the every entry in the mapping region is still reachable
  45802. ** via the hash table even after the cleanup.
  45803. */
  45804. if( iLimit ){
  45805. int i; /* Loop counter */
  45806. int iKey; /* Hash key */
  45807. for(i=1; i<=iLimit; i++){
  45808. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  45809. if( aHash[iKey]==i ) break;
  45810. }
  45811. assert( aHash[iKey]==i );
  45812. }
  45813. }
  45814. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  45815. }
  45816. /*
  45817. ** Set an entry in the wal-index that will map database page number
  45818. ** pPage into WAL frame iFrame.
  45819. */
  45820. static int walIndexAppend(Wal *pWal, u32 iFrame, u32 iPage){
  45821. int rc; /* Return code */
  45822. u32 iZero = 0; /* One less than frame number of aPgno[1] */
  45823. volatile u32 *aPgno = 0; /* Page number array */
  45824. volatile ht_slot *aHash = 0; /* Hash table */
  45825. rc = walHashGet(pWal, walFramePage(iFrame), &aHash, &aPgno, &iZero);
  45826. /* Assuming the wal-index file was successfully mapped, populate the
  45827. ** page number array and hash table entry.
  45828. */
  45829. if( rc==SQLITE_OK ){
  45830. int iKey; /* Hash table key */
  45831. int idx; /* Value to write to hash-table slot */
  45832. int nCollide; /* Number of hash collisions */
  45833. idx = iFrame - iZero;
  45834. assert( idx <= HASHTABLE_NSLOT/2 + 1 );
  45835. /* If this is the first entry to be added to this hash-table, zero the
  45836. ** entire hash table and aPgno[] array before proceeding.
  45837. */
  45838. if( idx==1 ){
  45839. int nByte = (int)((u8 *)&aHash[HASHTABLE_NSLOT] - (u8 *)&aPgno[1]);
  45840. memset((void*)&aPgno[1], 0, nByte);
  45841. }
  45842. /* If the entry in aPgno[] is already set, then the previous writer
  45843. ** must have exited unexpectedly in the middle of a transaction (after
  45844. ** writing one or more dirty pages to the WAL to free up memory).
  45845. ** Remove the remnants of that writers uncommitted transaction from
  45846. ** the hash-table before writing any new entries.
  45847. */
  45848. if( aPgno[idx] ){
  45849. walCleanupHash(pWal);
  45850. assert( !aPgno[idx] );
  45851. }
  45852. /* Write the aPgno[] array entry and the hash-table slot. */
  45853. nCollide = idx;
  45854. for(iKey=walHash(iPage); aHash[iKey]; iKey=walNextHash(iKey)){
  45855. if( (nCollide--)==0 ) return SQLITE_CORRUPT_BKPT;
  45856. }
  45857. aPgno[idx] = iPage;
  45858. aHash[iKey] = (ht_slot)idx;
  45859. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  45860. /* Verify that the number of entries in the hash table exactly equals
  45861. ** the number of entries in the mapping region.
  45862. */
  45863. {
  45864. int i; /* Loop counter */
  45865. int nEntry = 0; /* Number of entries in the hash table */
  45866. for(i=0; i<HASHTABLE_NSLOT; i++){ if( aHash[i] ) nEntry++; }
  45867. assert( nEntry==idx );
  45868. }
  45869. /* Verify that the every entry in the mapping region is reachable
  45870. ** via the hash table. This turns out to be a really, really expensive
  45871. ** thing to check, so only do this occasionally - not on every
  45872. ** iteration.
  45873. */
  45874. if( (idx&0x3ff)==0 ){
  45875. int i; /* Loop counter */
  45876. for(i=1; i<=idx; i++){
  45877. for(iKey=walHash(aPgno[i]); aHash[iKey]; iKey=walNextHash(iKey)){
  45878. if( aHash[iKey]==i ) break;
  45879. }
  45880. assert( aHash[iKey]==i );
  45881. }
  45882. }
  45883. #endif /* SQLITE_ENABLE_EXPENSIVE_ASSERT */
  45884. }
  45885. return rc;
  45886. }
  45887. /*
  45888. ** Recover the wal-index by reading the write-ahead log file.
  45889. **
  45890. ** This routine first tries to establish an exclusive lock on the
  45891. ** wal-index to prevent other threads/processes from doing anything
  45892. ** with the WAL or wal-index while recovery is running. The
  45893. ** WAL_RECOVER_LOCK is also held so that other threads will know
  45894. ** that this thread is running recovery. If unable to establish
  45895. ** the necessary locks, this routine returns SQLITE_BUSY.
  45896. */
  45897. static int walIndexRecover(Wal *pWal){
  45898. int rc; /* Return Code */
  45899. i64 nSize; /* Size of log file */
  45900. u32 aFrameCksum[2] = {0, 0};
  45901. int iLock; /* Lock offset to lock for checkpoint */
  45902. int nLock; /* Number of locks to hold */
  45903. /* Obtain an exclusive lock on all byte in the locking range not already
  45904. ** locked by the caller. The caller is guaranteed to have locked the
  45905. ** WAL_WRITE_LOCK byte, and may have also locked the WAL_CKPT_LOCK byte.
  45906. ** If successful, the same bytes that are locked here are unlocked before
  45907. ** this function returns.
  45908. */
  45909. assert( pWal->ckptLock==1 || pWal->ckptLock==0 );
  45910. assert( WAL_ALL_BUT_WRITE==WAL_WRITE_LOCK+1 );
  45911. assert( WAL_CKPT_LOCK==WAL_ALL_BUT_WRITE );
  45912. assert( pWal->writeLock );
  45913. iLock = WAL_ALL_BUT_WRITE + pWal->ckptLock;
  45914. nLock = SQLITE_SHM_NLOCK - iLock;
  45915. rc = walLockExclusive(pWal, iLock, nLock);
  45916. if( rc ){
  45917. return rc;
  45918. }
  45919. WALTRACE(("WAL%p: recovery begin...\n", pWal));
  45920. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  45921. rc = sqlite3OsFileSize(pWal->pWalFd, &nSize);
  45922. if( rc!=SQLITE_OK ){
  45923. goto recovery_error;
  45924. }
  45925. if( nSize>WAL_HDRSIZE ){
  45926. u8 aBuf[WAL_HDRSIZE]; /* Buffer to load WAL header into */
  45927. u8 *aFrame = 0; /* Malloc'd buffer to load entire frame */
  45928. int szFrame; /* Number of bytes in buffer aFrame[] */
  45929. u8 *aData; /* Pointer to data part of aFrame buffer */
  45930. int iFrame; /* Index of last frame read */
  45931. i64 iOffset; /* Next offset to read from log file */
  45932. int szPage; /* Page size according to the log */
  45933. u32 magic; /* Magic value read from WAL header */
  45934. u32 version; /* Magic value read from WAL header */
  45935. int isValid; /* True if this frame is valid */
  45936. /* Read in the WAL header. */
  45937. rc = sqlite3OsRead(pWal->pWalFd, aBuf, WAL_HDRSIZE, 0);
  45938. if( rc!=SQLITE_OK ){
  45939. goto recovery_error;
  45940. }
  45941. /* If the database page size is not a power of two, or is greater than
  45942. ** SQLITE_MAX_PAGE_SIZE, conclude that the WAL file contains no valid
  45943. ** data. Similarly, if the 'magic' value is invalid, ignore the whole
  45944. ** WAL file.
  45945. */
  45946. magic = sqlite3Get4byte(&aBuf[0]);
  45947. szPage = sqlite3Get4byte(&aBuf[8]);
  45948. if( (magic&0xFFFFFFFE)!=WAL_MAGIC
  45949. || szPage&(szPage-1)
  45950. || szPage>SQLITE_MAX_PAGE_SIZE
  45951. || szPage<512
  45952. ){
  45953. goto finished;
  45954. }
  45955. pWal->hdr.bigEndCksum = (u8)(magic&0x00000001);
  45956. pWal->szPage = szPage;
  45957. pWal->nCkpt = sqlite3Get4byte(&aBuf[12]);
  45958. memcpy(&pWal->hdr.aSalt, &aBuf[16], 8);
  45959. /* Verify that the WAL header checksum is correct */
  45960. walChecksumBytes(pWal->hdr.bigEndCksum==SQLITE_BIGENDIAN,
  45961. aBuf, WAL_HDRSIZE-2*4, 0, pWal->hdr.aFrameCksum
  45962. );
  45963. if( pWal->hdr.aFrameCksum[0]!=sqlite3Get4byte(&aBuf[24])
  45964. || pWal->hdr.aFrameCksum[1]!=sqlite3Get4byte(&aBuf[28])
  45965. ){
  45966. goto finished;
  45967. }
  45968. /* Verify that the version number on the WAL format is one that
  45969. ** are able to understand */
  45970. version = sqlite3Get4byte(&aBuf[4]);
  45971. if( version!=WAL_MAX_VERSION ){
  45972. rc = SQLITE_CANTOPEN_BKPT;
  45973. goto finished;
  45974. }
  45975. /* Malloc a buffer to read frames into. */
  45976. szFrame = szPage + WAL_FRAME_HDRSIZE;
  45977. aFrame = (u8 *)sqlite3_malloc(szFrame);
  45978. if( !aFrame ){
  45979. rc = SQLITE_NOMEM;
  45980. goto recovery_error;
  45981. }
  45982. aData = &aFrame[WAL_FRAME_HDRSIZE];
  45983. /* Read all frames from the log file. */
  45984. iFrame = 0;
  45985. for(iOffset=WAL_HDRSIZE; (iOffset+szFrame)<=nSize; iOffset+=szFrame){
  45986. u32 pgno; /* Database page number for frame */
  45987. u32 nTruncate; /* dbsize field from frame header */
  45988. /* Read and decode the next log frame. */
  45989. iFrame++;
  45990. rc = sqlite3OsRead(pWal->pWalFd, aFrame, szFrame, iOffset);
  45991. if( rc!=SQLITE_OK ) break;
  45992. isValid = walDecodeFrame(pWal, &pgno, &nTruncate, aData, aFrame);
  45993. if( !isValid ) break;
  45994. rc = walIndexAppend(pWal, iFrame, pgno);
  45995. if( rc!=SQLITE_OK ) break;
  45996. /* If nTruncate is non-zero, this is a commit record. */
  45997. if( nTruncate ){
  45998. pWal->hdr.mxFrame = iFrame;
  45999. pWal->hdr.nPage = nTruncate;
  46000. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  46001. testcase( szPage<=32768 );
  46002. testcase( szPage>=65536 );
  46003. aFrameCksum[0] = pWal->hdr.aFrameCksum[0];
  46004. aFrameCksum[1] = pWal->hdr.aFrameCksum[1];
  46005. }
  46006. }
  46007. sqlite3_free(aFrame);
  46008. }
  46009. finished:
  46010. if( rc==SQLITE_OK ){
  46011. volatile WalCkptInfo *pInfo;
  46012. int i;
  46013. pWal->hdr.aFrameCksum[0] = aFrameCksum[0];
  46014. pWal->hdr.aFrameCksum[1] = aFrameCksum[1];
  46015. walIndexWriteHdr(pWal);
  46016. /* Reset the checkpoint-header. This is safe because this thread is
  46017. ** currently holding locks that exclude all other readers, writers and
  46018. ** checkpointers.
  46019. */
  46020. pInfo = walCkptInfo(pWal);
  46021. pInfo->nBackfill = 0;
  46022. pInfo->aReadMark[0] = 0;
  46023. for(i=1; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  46024. if( pWal->hdr.mxFrame ) pInfo->aReadMark[1] = pWal->hdr.mxFrame;
  46025. /* If more than one frame was recovered from the log file, report an
  46026. ** event via sqlite3_log(). This is to help with identifying performance
  46027. ** problems caused by applications routinely shutting down without
  46028. ** checkpointing the log file.
  46029. */
  46030. if( pWal->hdr.nPage ){
  46031. sqlite3_log(SQLITE_NOTICE_RECOVER_WAL,
  46032. "recovered %d frames from WAL file %s",
  46033. pWal->hdr.mxFrame, pWal->zWalName
  46034. );
  46035. }
  46036. }
  46037. recovery_error:
  46038. WALTRACE(("WAL%p: recovery %s\n", pWal, rc ? "failed" : "ok"));
  46039. walUnlockExclusive(pWal, iLock, nLock);
  46040. return rc;
  46041. }
  46042. /*
  46043. ** Close an open wal-index.
  46044. */
  46045. static void walIndexClose(Wal *pWal, int isDelete){
  46046. if( pWal->exclusiveMode==WAL_HEAPMEMORY_MODE ){
  46047. int i;
  46048. for(i=0; i<pWal->nWiData; i++){
  46049. sqlite3_free((void *)pWal->apWiData[i]);
  46050. pWal->apWiData[i] = 0;
  46051. }
  46052. }else{
  46053. sqlite3OsShmUnmap(pWal->pDbFd, isDelete);
  46054. }
  46055. }
  46056. /*
  46057. ** Open a connection to the WAL file zWalName. The database file must
  46058. ** already be opened on connection pDbFd. The buffer that zWalName points
  46059. ** to must remain valid for the lifetime of the returned Wal* handle.
  46060. **
  46061. ** A SHARED lock should be held on the database file when this function
  46062. ** is called. The purpose of this SHARED lock is to prevent any other
  46063. ** client from unlinking the WAL or wal-index file. If another process
  46064. ** were to do this just after this client opened one of these files, the
  46065. ** system would be badly broken.
  46066. **
  46067. ** If the log file is successfully opened, SQLITE_OK is returned and
  46068. ** *ppWal is set to point to a new WAL handle. If an error occurs,
  46069. ** an SQLite error code is returned and *ppWal is left unmodified.
  46070. */
  46071. SQLITE_PRIVATE int sqlite3WalOpen(
  46072. sqlite3_vfs *pVfs, /* vfs module to open wal and wal-index */
  46073. sqlite3_file *pDbFd, /* The open database file */
  46074. const char *zWalName, /* Name of the WAL file */
  46075. int bNoShm, /* True to run in heap-memory mode */
  46076. i64 mxWalSize, /* Truncate WAL to this size on reset */
  46077. Wal **ppWal /* OUT: Allocated Wal handle */
  46078. ){
  46079. int rc; /* Return Code */
  46080. Wal *pRet; /* Object to allocate and return */
  46081. int flags; /* Flags passed to OsOpen() */
  46082. assert( zWalName && zWalName[0] );
  46083. assert( pDbFd );
  46084. /* In the amalgamation, the os_unix.c and os_win.c source files come before
  46085. ** this source file. Verify that the #defines of the locking byte offsets
  46086. ** in os_unix.c and os_win.c agree with the WALINDEX_LOCK_OFFSET value.
  46087. */
  46088. #ifdef WIN_SHM_BASE
  46089. assert( WIN_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46090. #endif
  46091. #ifdef UNIX_SHM_BASE
  46092. assert( UNIX_SHM_BASE==WALINDEX_LOCK_OFFSET );
  46093. #endif
  46094. /* Allocate an instance of struct Wal to return. */
  46095. *ppWal = 0;
  46096. pRet = (Wal*)sqlite3MallocZero(sizeof(Wal) + pVfs->szOsFile);
  46097. if( !pRet ){
  46098. return SQLITE_NOMEM;
  46099. }
  46100. pRet->pVfs = pVfs;
  46101. pRet->pWalFd = (sqlite3_file *)&pRet[1];
  46102. pRet->pDbFd = pDbFd;
  46103. pRet->readLock = -1;
  46104. pRet->mxWalSize = mxWalSize;
  46105. pRet->zWalName = zWalName;
  46106. pRet->syncHeader = 1;
  46107. pRet->padToSectorBoundary = 1;
  46108. pRet->exclusiveMode = (bNoShm ? WAL_HEAPMEMORY_MODE: WAL_NORMAL_MODE);
  46109. /* Open file handle on the write-ahead log file. */
  46110. flags = (SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|SQLITE_OPEN_WAL);
  46111. rc = sqlite3OsOpen(pVfs, zWalName, pRet->pWalFd, flags, &flags);
  46112. if( rc==SQLITE_OK && flags&SQLITE_OPEN_READONLY ){
  46113. pRet->readOnly = WAL_RDONLY;
  46114. }
  46115. if( rc!=SQLITE_OK ){
  46116. walIndexClose(pRet, 0);
  46117. sqlite3OsClose(pRet->pWalFd);
  46118. sqlite3_free(pRet);
  46119. }else{
  46120. int iDC = sqlite3OsDeviceCharacteristics(pDbFd);
  46121. if( iDC & SQLITE_IOCAP_SEQUENTIAL ){ pRet->syncHeader = 0; }
  46122. if( iDC & SQLITE_IOCAP_POWERSAFE_OVERWRITE ){
  46123. pRet->padToSectorBoundary = 0;
  46124. }
  46125. *ppWal = pRet;
  46126. WALTRACE(("WAL%d: opened\n", pRet));
  46127. }
  46128. return rc;
  46129. }
  46130. /*
  46131. ** Change the size to which the WAL file is trucated on each reset.
  46132. */
  46133. SQLITE_PRIVATE void sqlite3WalLimit(Wal *pWal, i64 iLimit){
  46134. if( pWal ) pWal->mxWalSize = iLimit;
  46135. }
  46136. /*
  46137. ** Find the smallest page number out of all pages held in the WAL that
  46138. ** has not been returned by any prior invocation of this method on the
  46139. ** same WalIterator object. Write into *piFrame the frame index where
  46140. ** that page was last written into the WAL. Write into *piPage the page
  46141. ** number.
  46142. **
  46143. ** Return 0 on success. If there are no pages in the WAL with a page
  46144. ** number larger than *piPage, then return 1.
  46145. */
  46146. static int walIteratorNext(
  46147. WalIterator *p, /* Iterator */
  46148. u32 *piPage, /* OUT: The page number of the next page */
  46149. u32 *piFrame /* OUT: Wal frame index of next page */
  46150. ){
  46151. u32 iMin; /* Result pgno must be greater than iMin */
  46152. u32 iRet = 0xFFFFFFFF; /* 0xffffffff is never a valid page number */
  46153. int i; /* For looping through segments */
  46154. iMin = p->iPrior;
  46155. assert( iMin<0xffffffff );
  46156. for(i=p->nSegment-1; i>=0; i--){
  46157. struct WalSegment *pSegment = &p->aSegment[i];
  46158. while( pSegment->iNext<pSegment->nEntry ){
  46159. u32 iPg = pSegment->aPgno[pSegment->aIndex[pSegment->iNext]];
  46160. if( iPg>iMin ){
  46161. if( iPg<iRet ){
  46162. iRet = iPg;
  46163. *piFrame = pSegment->iZero + pSegment->aIndex[pSegment->iNext];
  46164. }
  46165. break;
  46166. }
  46167. pSegment->iNext++;
  46168. }
  46169. }
  46170. *piPage = p->iPrior = iRet;
  46171. return (iRet==0xFFFFFFFF);
  46172. }
  46173. /*
  46174. ** This function merges two sorted lists into a single sorted list.
  46175. **
  46176. ** aLeft[] and aRight[] are arrays of indices. The sort key is
  46177. ** aContent[aLeft[]] and aContent[aRight[]]. Upon entry, the following
  46178. ** is guaranteed for all J<K:
  46179. **
  46180. ** aContent[aLeft[J]] < aContent[aLeft[K]]
  46181. ** aContent[aRight[J]] < aContent[aRight[K]]
  46182. **
  46183. ** This routine overwrites aRight[] with a new (probably longer) sequence
  46184. ** of indices such that the aRight[] contains every index that appears in
  46185. ** either aLeft[] or the old aRight[] and such that the second condition
  46186. ** above is still met.
  46187. **
  46188. ** The aContent[aLeft[X]] values will be unique for all X. And the
  46189. ** aContent[aRight[X]] values will be unique too. But there might be
  46190. ** one or more combinations of X and Y such that
  46191. **
  46192. ** aLeft[X]!=aRight[Y] && aContent[aLeft[X]] == aContent[aRight[Y]]
  46193. **
  46194. ** When that happens, omit the aLeft[X] and use the aRight[Y] index.
  46195. */
  46196. static void walMerge(
  46197. const u32 *aContent, /* Pages in wal - keys for the sort */
  46198. ht_slot *aLeft, /* IN: Left hand input list */
  46199. int nLeft, /* IN: Elements in array *paLeft */
  46200. ht_slot **paRight, /* IN/OUT: Right hand input list */
  46201. int *pnRight, /* IN/OUT: Elements in *paRight */
  46202. ht_slot *aTmp /* Temporary buffer */
  46203. ){
  46204. int iLeft = 0; /* Current index in aLeft */
  46205. int iRight = 0; /* Current index in aRight */
  46206. int iOut = 0; /* Current index in output buffer */
  46207. int nRight = *pnRight;
  46208. ht_slot *aRight = *paRight;
  46209. assert( nLeft>0 && nRight>0 );
  46210. while( iRight<nRight || iLeft<nLeft ){
  46211. ht_slot logpage;
  46212. Pgno dbpage;
  46213. if( (iLeft<nLeft)
  46214. && (iRight>=nRight || aContent[aLeft[iLeft]]<aContent[aRight[iRight]])
  46215. ){
  46216. logpage = aLeft[iLeft++];
  46217. }else{
  46218. logpage = aRight[iRight++];
  46219. }
  46220. dbpage = aContent[logpage];
  46221. aTmp[iOut++] = logpage;
  46222. if( iLeft<nLeft && aContent[aLeft[iLeft]]==dbpage ) iLeft++;
  46223. assert( iLeft>=nLeft || aContent[aLeft[iLeft]]>dbpage );
  46224. assert( iRight>=nRight || aContent[aRight[iRight]]>dbpage );
  46225. }
  46226. *paRight = aLeft;
  46227. *pnRight = iOut;
  46228. memcpy(aLeft, aTmp, sizeof(aTmp[0])*iOut);
  46229. }
  46230. /*
  46231. ** Sort the elements in list aList using aContent[] as the sort key.
  46232. ** Remove elements with duplicate keys, preferring to keep the
  46233. ** larger aList[] values.
  46234. **
  46235. ** The aList[] entries are indices into aContent[]. The values in
  46236. ** aList[] are to be sorted so that for all J<K:
  46237. **
  46238. ** aContent[aList[J]] < aContent[aList[K]]
  46239. **
  46240. ** For any X and Y such that
  46241. **
  46242. ** aContent[aList[X]] == aContent[aList[Y]]
  46243. **
  46244. ** Keep the larger of the two values aList[X] and aList[Y] and discard
  46245. ** the smaller.
  46246. */
  46247. static void walMergesort(
  46248. const u32 *aContent, /* Pages in wal */
  46249. ht_slot *aBuffer, /* Buffer of at least *pnList items to use */
  46250. ht_slot *aList, /* IN/OUT: List to sort */
  46251. int *pnList /* IN/OUT: Number of elements in aList[] */
  46252. ){
  46253. struct Sublist {
  46254. int nList; /* Number of elements in aList */
  46255. ht_slot *aList; /* Pointer to sub-list content */
  46256. };
  46257. const int nList = *pnList; /* Size of input list */
  46258. int nMerge = 0; /* Number of elements in list aMerge */
  46259. ht_slot *aMerge = 0; /* List to be merged */
  46260. int iList; /* Index into input list */
  46261. int iSub = 0; /* Index into aSub array */
  46262. struct Sublist aSub[13]; /* Array of sub-lists */
  46263. memset(aSub, 0, sizeof(aSub));
  46264. assert( nList<=HASHTABLE_NPAGE && nList>0 );
  46265. assert( HASHTABLE_NPAGE==(1<<(ArraySize(aSub)-1)) );
  46266. for(iList=0; iList<nList; iList++){
  46267. nMerge = 1;
  46268. aMerge = &aList[iList];
  46269. for(iSub=0; iList & (1<<iSub); iSub++){
  46270. struct Sublist *p = &aSub[iSub];
  46271. assert( p->aList && p->nList<=(1<<iSub) );
  46272. assert( p->aList==&aList[iList&~((2<<iSub)-1)] );
  46273. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  46274. }
  46275. aSub[iSub].aList = aMerge;
  46276. aSub[iSub].nList = nMerge;
  46277. }
  46278. for(iSub++; iSub<ArraySize(aSub); iSub++){
  46279. if( nList & (1<<iSub) ){
  46280. struct Sublist *p = &aSub[iSub];
  46281. assert( p->nList<=(1<<iSub) );
  46282. assert( p->aList==&aList[nList&~((2<<iSub)-1)] );
  46283. walMerge(aContent, p->aList, p->nList, &aMerge, &nMerge, aBuffer);
  46284. }
  46285. }
  46286. assert( aMerge==aList );
  46287. *pnList = nMerge;
  46288. #ifdef SQLITE_DEBUG
  46289. {
  46290. int i;
  46291. for(i=1; i<*pnList; i++){
  46292. assert( aContent[aList[i]] > aContent[aList[i-1]] );
  46293. }
  46294. }
  46295. #endif
  46296. }
  46297. /*
  46298. ** Free an iterator allocated by walIteratorInit().
  46299. */
  46300. static void walIteratorFree(WalIterator *p){
  46301. sqlite3ScratchFree(p);
  46302. }
  46303. /*
  46304. ** Construct a WalInterator object that can be used to loop over all
  46305. ** pages in the WAL in ascending order. The caller must hold the checkpoint
  46306. ** lock.
  46307. **
  46308. ** On success, make *pp point to the newly allocated WalInterator object
  46309. ** return SQLITE_OK. Otherwise, return an error code. If this routine
  46310. ** returns an error, the value of *pp is undefined.
  46311. **
  46312. ** The calling routine should invoke walIteratorFree() to destroy the
  46313. ** WalIterator object when it has finished with it.
  46314. */
  46315. static int walIteratorInit(Wal *pWal, WalIterator **pp){
  46316. WalIterator *p; /* Return value */
  46317. int nSegment; /* Number of segments to merge */
  46318. u32 iLast; /* Last frame in log */
  46319. int nByte; /* Number of bytes to allocate */
  46320. int i; /* Iterator variable */
  46321. ht_slot *aTmp; /* Temp space used by merge-sort */
  46322. int rc = SQLITE_OK; /* Return Code */
  46323. /* This routine only runs while holding the checkpoint lock. And
  46324. ** it only runs if there is actually content in the log (mxFrame>0).
  46325. */
  46326. assert( pWal->ckptLock && pWal->hdr.mxFrame>0 );
  46327. iLast = pWal->hdr.mxFrame;
  46328. /* Allocate space for the WalIterator object. */
  46329. nSegment = walFramePage(iLast) + 1;
  46330. nByte = sizeof(WalIterator)
  46331. + (nSegment-1)*sizeof(struct WalSegment)
  46332. + iLast*sizeof(ht_slot);
  46333. p = (WalIterator *)sqlite3ScratchMalloc(nByte);
  46334. if( !p ){
  46335. return SQLITE_NOMEM;
  46336. }
  46337. memset(p, 0, nByte);
  46338. p->nSegment = nSegment;
  46339. /* Allocate temporary space used by the merge-sort routine. This block
  46340. ** of memory will be freed before this function returns.
  46341. */
  46342. aTmp = (ht_slot *)sqlite3ScratchMalloc(
  46343. sizeof(ht_slot) * (iLast>HASHTABLE_NPAGE?HASHTABLE_NPAGE:iLast)
  46344. );
  46345. if( !aTmp ){
  46346. rc = SQLITE_NOMEM;
  46347. }
  46348. for(i=0; rc==SQLITE_OK && i<nSegment; i++){
  46349. volatile ht_slot *aHash;
  46350. u32 iZero;
  46351. volatile u32 *aPgno;
  46352. rc = walHashGet(pWal, i, &aHash, &aPgno, &iZero);
  46353. if( rc==SQLITE_OK ){
  46354. int j; /* Counter variable */
  46355. int nEntry; /* Number of entries in this segment */
  46356. ht_slot *aIndex; /* Sorted index for this segment */
  46357. aPgno++;
  46358. if( (i+1)==nSegment ){
  46359. nEntry = (int)(iLast - iZero);
  46360. }else{
  46361. nEntry = (int)((u32*)aHash - (u32*)aPgno);
  46362. }
  46363. aIndex = &((ht_slot *)&p->aSegment[p->nSegment])[iZero];
  46364. iZero++;
  46365. for(j=0; j<nEntry; j++){
  46366. aIndex[j] = (ht_slot)j;
  46367. }
  46368. walMergesort((u32 *)aPgno, aTmp, aIndex, &nEntry);
  46369. p->aSegment[i].iZero = iZero;
  46370. p->aSegment[i].nEntry = nEntry;
  46371. p->aSegment[i].aIndex = aIndex;
  46372. p->aSegment[i].aPgno = (u32 *)aPgno;
  46373. }
  46374. }
  46375. sqlite3ScratchFree(aTmp);
  46376. if( rc!=SQLITE_OK ){
  46377. walIteratorFree(p);
  46378. }
  46379. *pp = p;
  46380. return rc;
  46381. }
  46382. /*
  46383. ** Attempt to obtain the exclusive WAL lock defined by parameters lockIdx and
  46384. ** n. If the attempt fails and parameter xBusy is not NULL, then it is a
  46385. ** busy-handler function. Invoke it and retry the lock until either the
  46386. ** lock is successfully obtained or the busy-handler returns 0.
  46387. */
  46388. static int walBusyLock(
  46389. Wal *pWal, /* WAL connection */
  46390. int (*xBusy)(void*), /* Function to call when busy */
  46391. void *pBusyArg, /* Context argument for xBusyHandler */
  46392. int lockIdx, /* Offset of first byte to lock */
  46393. int n /* Number of bytes to lock */
  46394. ){
  46395. int rc;
  46396. do {
  46397. rc = walLockExclusive(pWal, lockIdx, n);
  46398. }while( xBusy && rc==SQLITE_BUSY && xBusy(pBusyArg) );
  46399. return rc;
  46400. }
  46401. /*
  46402. ** The cache of the wal-index header must be valid to call this function.
  46403. ** Return the page-size in bytes used by the database.
  46404. */
  46405. static int walPagesize(Wal *pWal){
  46406. return (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  46407. }
  46408. /*
  46409. ** Copy as much content as we can from the WAL back into the database file
  46410. ** in response to an sqlite3_wal_checkpoint() request or the equivalent.
  46411. **
  46412. ** The amount of information copies from WAL to database might be limited
  46413. ** by active readers. This routine will never overwrite a database page
  46414. ** that a concurrent reader might be using.
  46415. **
  46416. ** All I/O barrier operations (a.k.a fsyncs) occur in this routine when
  46417. ** SQLite is in WAL-mode in synchronous=NORMAL. That means that if
  46418. ** checkpoints are always run by a background thread or background
  46419. ** process, foreground threads will never block on a lengthy fsync call.
  46420. **
  46421. ** Fsync is called on the WAL before writing content out of the WAL and
  46422. ** into the database. This ensures that if the new content is persistent
  46423. ** in the WAL and can be recovered following a power-loss or hard reset.
  46424. **
  46425. ** Fsync is also called on the database file if (and only if) the entire
  46426. ** WAL content is copied into the database file. This second fsync makes
  46427. ** it safe to delete the WAL since the new content will persist in the
  46428. ** database file.
  46429. **
  46430. ** This routine uses and updates the nBackfill field of the wal-index header.
  46431. ** This is the only routine that will increase the value of nBackfill.
  46432. ** (A WAL reset or recovery will revert nBackfill to zero, but not increase
  46433. ** its value.)
  46434. **
  46435. ** The caller must be holding sufficient locks to ensure that no other
  46436. ** checkpoint is running (in any other thread or process) at the same
  46437. ** time.
  46438. */
  46439. static int walCheckpoint(
  46440. Wal *pWal, /* Wal connection */
  46441. int eMode, /* One of PASSIVE, FULL or RESTART */
  46442. int (*xBusyCall)(void*), /* Function to call when busy */
  46443. void *pBusyArg, /* Context argument for xBusyHandler */
  46444. int sync_flags, /* Flags for OsSync() (or 0) */
  46445. u8 *zBuf /* Temporary buffer to use */
  46446. ){
  46447. int rc; /* Return code */
  46448. int szPage; /* Database page-size */
  46449. WalIterator *pIter = 0; /* Wal iterator context */
  46450. u32 iDbpage = 0; /* Next database page to write */
  46451. u32 iFrame = 0; /* Wal frame containing data for iDbpage */
  46452. u32 mxSafeFrame; /* Max frame that can be backfilled */
  46453. u32 mxPage; /* Max database page to write */
  46454. int i; /* Loop counter */
  46455. volatile WalCkptInfo *pInfo; /* The checkpoint status information */
  46456. int (*xBusy)(void*) = 0; /* Function to call when waiting for locks */
  46457. szPage = walPagesize(pWal);
  46458. testcase( szPage<=32768 );
  46459. testcase( szPage>=65536 );
  46460. pInfo = walCkptInfo(pWal);
  46461. if( pInfo->nBackfill>=pWal->hdr.mxFrame ) return SQLITE_OK;
  46462. /* Allocate the iterator */
  46463. rc = walIteratorInit(pWal, &pIter);
  46464. if( rc!=SQLITE_OK ){
  46465. return rc;
  46466. }
  46467. assert( pIter );
  46468. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ) xBusy = xBusyCall;
  46469. /* Compute in mxSafeFrame the index of the last frame of the WAL that is
  46470. ** safe to write into the database. Frames beyond mxSafeFrame might
  46471. ** overwrite database pages that are in use by active readers and thus
  46472. ** cannot be backfilled from the WAL.
  46473. */
  46474. mxSafeFrame = pWal->hdr.mxFrame;
  46475. mxPage = pWal->hdr.nPage;
  46476. for(i=1; i<WAL_NREADER; i++){
  46477. u32 y = pInfo->aReadMark[i];
  46478. if( mxSafeFrame>y ){
  46479. assert( y<=pWal->hdr.mxFrame );
  46480. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(i), 1);
  46481. if( rc==SQLITE_OK ){
  46482. pInfo->aReadMark[i] = (i==1 ? mxSafeFrame : READMARK_NOT_USED);
  46483. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  46484. }else if( rc==SQLITE_BUSY ){
  46485. mxSafeFrame = y;
  46486. xBusy = 0;
  46487. }else{
  46488. goto walcheckpoint_out;
  46489. }
  46490. }
  46491. }
  46492. if( pInfo->nBackfill<mxSafeFrame
  46493. && (rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(0), 1))==SQLITE_OK
  46494. ){
  46495. i64 nSize; /* Current size of database file */
  46496. u32 nBackfill = pInfo->nBackfill;
  46497. /* Sync the WAL to disk */
  46498. if( sync_flags ){
  46499. rc = sqlite3OsSync(pWal->pWalFd, sync_flags);
  46500. }
  46501. /* If the database may grow as a result of this checkpoint, hint
  46502. ** about the eventual size of the db file to the VFS layer.
  46503. */
  46504. if( rc==SQLITE_OK ){
  46505. i64 nReq = ((i64)mxPage * szPage);
  46506. rc = sqlite3OsFileSize(pWal->pDbFd, &nSize);
  46507. if( rc==SQLITE_OK && nSize<nReq ){
  46508. sqlite3OsFileControlHint(pWal->pDbFd, SQLITE_FCNTL_SIZE_HINT, &nReq);
  46509. }
  46510. }
  46511. /* Iterate through the contents of the WAL, copying data to the db file. */
  46512. while( rc==SQLITE_OK && 0==walIteratorNext(pIter, &iDbpage, &iFrame) ){
  46513. i64 iOffset;
  46514. assert( walFramePgno(pWal, iFrame)==iDbpage );
  46515. if( iFrame<=nBackfill || iFrame>mxSafeFrame || iDbpage>mxPage ) continue;
  46516. iOffset = walFrameOffset(iFrame, szPage) + WAL_FRAME_HDRSIZE;
  46517. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL file */
  46518. rc = sqlite3OsRead(pWal->pWalFd, zBuf, szPage, iOffset);
  46519. if( rc!=SQLITE_OK ) break;
  46520. iOffset = (iDbpage-1)*(i64)szPage;
  46521. testcase( IS_BIG_INT(iOffset) );
  46522. rc = sqlite3OsWrite(pWal->pDbFd, zBuf, szPage, iOffset);
  46523. if( rc!=SQLITE_OK ) break;
  46524. }
  46525. /* If work was actually accomplished... */
  46526. if( rc==SQLITE_OK ){
  46527. if( mxSafeFrame==walIndexHdr(pWal)->mxFrame ){
  46528. i64 szDb = pWal->hdr.nPage*(i64)szPage;
  46529. testcase( IS_BIG_INT(szDb) );
  46530. rc = sqlite3OsTruncate(pWal->pDbFd, szDb);
  46531. if( rc==SQLITE_OK && sync_flags ){
  46532. rc = sqlite3OsSync(pWal->pDbFd, sync_flags);
  46533. }
  46534. }
  46535. if( rc==SQLITE_OK ){
  46536. pInfo->nBackfill = mxSafeFrame;
  46537. }
  46538. }
  46539. /* Release the reader lock held while backfilling */
  46540. walUnlockExclusive(pWal, WAL_READ_LOCK(0), 1);
  46541. }
  46542. if( rc==SQLITE_BUSY ){
  46543. /* Reset the return code so as not to report a checkpoint failure
  46544. ** just because there are active readers. */
  46545. rc = SQLITE_OK;
  46546. }
  46547. /* If this is an SQLITE_CHECKPOINT_RESTART operation, and the entire wal
  46548. ** file has been copied into the database file, then block until all
  46549. ** readers have finished using the wal file. This ensures that the next
  46550. ** process to write to the database restarts the wal file.
  46551. */
  46552. if( rc==SQLITE_OK && eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  46553. assert( pWal->writeLock );
  46554. if( pInfo->nBackfill<pWal->hdr.mxFrame ){
  46555. rc = SQLITE_BUSY;
  46556. }else if( eMode==SQLITE_CHECKPOINT_RESTART ){
  46557. assert( mxSafeFrame==pWal->hdr.mxFrame );
  46558. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_READ_LOCK(1), WAL_NREADER-1);
  46559. if( rc==SQLITE_OK ){
  46560. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  46561. }
  46562. }
  46563. }
  46564. walcheckpoint_out:
  46565. walIteratorFree(pIter);
  46566. return rc;
  46567. }
  46568. /*
  46569. ** If the WAL file is currently larger than nMax bytes in size, truncate
  46570. ** it to exactly nMax bytes. If an error occurs while doing so, ignore it.
  46571. */
  46572. static void walLimitSize(Wal *pWal, i64 nMax){
  46573. i64 sz;
  46574. int rx;
  46575. sqlite3BeginBenignMalloc();
  46576. rx = sqlite3OsFileSize(pWal->pWalFd, &sz);
  46577. if( rx==SQLITE_OK && (sz > nMax ) ){
  46578. rx = sqlite3OsTruncate(pWal->pWalFd, nMax);
  46579. }
  46580. sqlite3EndBenignMalloc();
  46581. if( rx ){
  46582. sqlite3_log(rx, "cannot limit WAL size: %s", pWal->zWalName);
  46583. }
  46584. }
  46585. /*
  46586. ** Close a connection to a log file.
  46587. */
  46588. SQLITE_PRIVATE int sqlite3WalClose(
  46589. Wal *pWal, /* Wal to close */
  46590. int sync_flags, /* Flags to pass to OsSync() (or 0) */
  46591. int nBuf,
  46592. u8 *zBuf /* Buffer of at least nBuf bytes */
  46593. ){
  46594. int rc = SQLITE_OK;
  46595. if( pWal ){
  46596. int isDelete = 0; /* True to unlink wal and wal-index files */
  46597. /* If an EXCLUSIVE lock can be obtained on the database file (using the
  46598. ** ordinary, rollback-mode locking methods, this guarantees that the
  46599. ** connection associated with this log file is the only connection to
  46600. ** the database. In this case checkpoint the database and unlink both
  46601. ** the wal and wal-index files.
  46602. **
  46603. ** The EXCLUSIVE lock is not released before returning.
  46604. */
  46605. rc = sqlite3OsLock(pWal->pDbFd, SQLITE_LOCK_EXCLUSIVE);
  46606. if( rc==SQLITE_OK ){
  46607. if( pWal->exclusiveMode==WAL_NORMAL_MODE ){
  46608. pWal->exclusiveMode = WAL_EXCLUSIVE_MODE;
  46609. }
  46610. rc = sqlite3WalCheckpoint(
  46611. pWal, SQLITE_CHECKPOINT_PASSIVE, 0, 0, sync_flags, nBuf, zBuf, 0, 0
  46612. );
  46613. if( rc==SQLITE_OK ){
  46614. int bPersist = -1;
  46615. sqlite3OsFileControlHint(
  46616. pWal->pDbFd, SQLITE_FCNTL_PERSIST_WAL, &bPersist
  46617. );
  46618. if( bPersist!=1 ){
  46619. /* Try to delete the WAL file if the checkpoint completed and
  46620. ** fsyned (rc==SQLITE_OK) and if we are not in persistent-wal
  46621. ** mode (!bPersist) */
  46622. isDelete = 1;
  46623. }else if( pWal->mxWalSize>=0 ){
  46624. /* Try to truncate the WAL file to zero bytes if the checkpoint
  46625. ** completed and fsynced (rc==SQLITE_OK) and we are in persistent
  46626. ** WAL mode (bPersist) and if the PRAGMA journal_size_limit is a
  46627. ** non-negative value (pWal->mxWalSize>=0). Note that we truncate
  46628. ** to zero bytes as truncating to the journal_size_limit might
  46629. ** leave a corrupt WAL file on disk. */
  46630. walLimitSize(pWal, 0);
  46631. }
  46632. }
  46633. }
  46634. walIndexClose(pWal, isDelete);
  46635. sqlite3OsClose(pWal->pWalFd);
  46636. if( isDelete ){
  46637. sqlite3BeginBenignMalloc();
  46638. sqlite3OsDelete(pWal->pVfs, pWal->zWalName, 0);
  46639. sqlite3EndBenignMalloc();
  46640. }
  46641. WALTRACE(("WAL%p: closed\n", pWal));
  46642. sqlite3_free((void *)pWal->apWiData);
  46643. sqlite3_free(pWal);
  46644. }
  46645. return rc;
  46646. }
  46647. /*
  46648. ** Try to read the wal-index header. Return 0 on success and 1 if
  46649. ** there is a problem.
  46650. **
  46651. ** The wal-index is in shared memory. Another thread or process might
  46652. ** be writing the header at the same time this procedure is trying to
  46653. ** read it, which might result in inconsistency. A dirty read is detected
  46654. ** by verifying that both copies of the header are the same and also by
  46655. ** a checksum on the header.
  46656. **
  46657. ** If and only if the read is consistent and the header is different from
  46658. ** pWal->hdr, then pWal->hdr is updated to the content of the new header
  46659. ** and *pChanged is set to 1.
  46660. **
  46661. ** If the checksum cannot be verified return non-zero. If the header
  46662. ** is read successfully and the checksum verified, return zero.
  46663. */
  46664. static int walIndexTryHdr(Wal *pWal, int *pChanged){
  46665. u32 aCksum[2]; /* Checksum on the header content */
  46666. WalIndexHdr h1, h2; /* Two copies of the header content */
  46667. WalIndexHdr volatile *aHdr; /* Header in shared memory */
  46668. /* The first page of the wal-index must be mapped at this point. */
  46669. assert( pWal->nWiData>0 && pWal->apWiData[0] );
  46670. /* Read the header. This might happen concurrently with a write to the
  46671. ** same area of shared memory on a different CPU in a SMP,
  46672. ** meaning it is possible that an inconsistent snapshot is read
  46673. ** from the file. If this happens, return non-zero.
  46674. **
  46675. ** There are two copies of the header at the beginning of the wal-index.
  46676. ** When reading, read [0] first then [1]. Writes are in the reverse order.
  46677. ** Memory barriers are used to prevent the compiler or the hardware from
  46678. ** reordering the reads and writes.
  46679. */
  46680. aHdr = walIndexHdr(pWal);
  46681. memcpy(&h1, (void *)&aHdr[0], sizeof(h1));
  46682. walShmBarrier(pWal);
  46683. memcpy(&h2, (void *)&aHdr[1], sizeof(h2));
  46684. if( memcmp(&h1, &h2, sizeof(h1))!=0 ){
  46685. return 1; /* Dirty read */
  46686. }
  46687. if( h1.isInit==0 ){
  46688. return 1; /* Malformed header - probably all zeros */
  46689. }
  46690. walChecksumBytes(1, (u8*)&h1, sizeof(h1)-sizeof(h1.aCksum), 0, aCksum);
  46691. if( aCksum[0]!=h1.aCksum[0] || aCksum[1]!=h1.aCksum[1] ){
  46692. return 1; /* Checksum does not match */
  46693. }
  46694. if( memcmp(&pWal->hdr, &h1, sizeof(WalIndexHdr)) ){
  46695. *pChanged = 1;
  46696. memcpy(&pWal->hdr, &h1, sizeof(WalIndexHdr));
  46697. pWal->szPage = (pWal->hdr.szPage&0xfe00) + ((pWal->hdr.szPage&0x0001)<<16);
  46698. testcase( pWal->szPage<=32768 );
  46699. testcase( pWal->szPage>=65536 );
  46700. }
  46701. /* The header was successfully read. Return zero. */
  46702. return 0;
  46703. }
  46704. /*
  46705. ** Read the wal-index header from the wal-index and into pWal->hdr.
  46706. ** If the wal-header appears to be corrupt, try to reconstruct the
  46707. ** wal-index from the WAL before returning.
  46708. **
  46709. ** Set *pChanged to 1 if the wal-index header value in pWal->hdr is
  46710. ** changed by this operation. If pWal->hdr is unchanged, set *pChanged
  46711. ** to 0.
  46712. **
  46713. ** If the wal-index header is successfully read, return SQLITE_OK.
  46714. ** Otherwise an SQLite error code.
  46715. */
  46716. static int walIndexReadHdr(Wal *pWal, int *pChanged){
  46717. int rc; /* Return code */
  46718. int badHdr; /* True if a header read failed */
  46719. volatile u32 *page0; /* Chunk of wal-index containing header */
  46720. /* Ensure that page 0 of the wal-index (the page that contains the
  46721. ** wal-index header) is mapped. Return early if an error occurs here.
  46722. */
  46723. assert( pChanged );
  46724. rc = walIndexPage(pWal, 0, &page0);
  46725. if( rc!=SQLITE_OK ){
  46726. return rc;
  46727. };
  46728. assert( page0 || pWal->writeLock==0 );
  46729. /* If the first page of the wal-index has been mapped, try to read the
  46730. ** wal-index header immediately, without holding any lock. This usually
  46731. ** works, but may fail if the wal-index header is corrupt or currently
  46732. ** being modified by another thread or process.
  46733. */
  46734. badHdr = (page0 ? walIndexTryHdr(pWal, pChanged) : 1);
  46735. /* If the first attempt failed, it might have been due to a race
  46736. ** with a writer. So get a WRITE lock and try again.
  46737. */
  46738. assert( badHdr==0 || pWal->writeLock==0 );
  46739. if( badHdr ){
  46740. if( pWal->readOnly & WAL_SHM_RDONLY ){
  46741. if( SQLITE_OK==(rc = walLockShared(pWal, WAL_WRITE_LOCK)) ){
  46742. walUnlockShared(pWal, WAL_WRITE_LOCK);
  46743. rc = SQLITE_READONLY_RECOVERY;
  46744. }
  46745. }else if( SQLITE_OK==(rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1)) ){
  46746. pWal->writeLock = 1;
  46747. if( SQLITE_OK==(rc = walIndexPage(pWal, 0, &page0)) ){
  46748. badHdr = walIndexTryHdr(pWal, pChanged);
  46749. if( badHdr ){
  46750. /* If the wal-index header is still malformed even while holding
  46751. ** a WRITE lock, it can only mean that the header is corrupted and
  46752. ** needs to be reconstructed. So run recovery to do exactly that.
  46753. */
  46754. rc = walIndexRecover(pWal);
  46755. *pChanged = 1;
  46756. }
  46757. }
  46758. pWal->writeLock = 0;
  46759. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  46760. }
  46761. }
  46762. /* If the header is read successfully, check the version number to make
  46763. ** sure the wal-index was not constructed with some future format that
  46764. ** this version of SQLite cannot understand.
  46765. */
  46766. if( badHdr==0 && pWal->hdr.iVersion!=WALINDEX_MAX_VERSION ){
  46767. rc = SQLITE_CANTOPEN_BKPT;
  46768. }
  46769. return rc;
  46770. }
  46771. /*
  46772. ** This is the value that walTryBeginRead returns when it needs to
  46773. ** be retried.
  46774. */
  46775. #define WAL_RETRY (-1)
  46776. /*
  46777. ** Attempt to start a read transaction. This might fail due to a race or
  46778. ** other transient condition. When that happens, it returns WAL_RETRY to
  46779. ** indicate to the caller that it is safe to retry immediately.
  46780. **
  46781. ** On success return SQLITE_OK. On a permanent failure (such an
  46782. ** I/O error or an SQLITE_BUSY because another process is running
  46783. ** recovery) return a positive error code.
  46784. **
  46785. ** The useWal parameter is true to force the use of the WAL and disable
  46786. ** the case where the WAL is bypassed because it has been completely
  46787. ** checkpointed. If useWal==0 then this routine calls walIndexReadHdr()
  46788. ** to make a copy of the wal-index header into pWal->hdr. If the
  46789. ** wal-index header has changed, *pChanged is set to 1 (as an indication
  46790. ** to the caller that the local paget cache is obsolete and needs to be
  46791. ** flushed.) When useWal==1, the wal-index header is assumed to already
  46792. ** be loaded and the pChanged parameter is unused.
  46793. **
  46794. ** The caller must set the cnt parameter to the number of prior calls to
  46795. ** this routine during the current read attempt that returned WAL_RETRY.
  46796. ** This routine will start taking more aggressive measures to clear the
  46797. ** race conditions after multiple WAL_RETRY returns, and after an excessive
  46798. ** number of errors will ultimately return SQLITE_PROTOCOL. The
  46799. ** SQLITE_PROTOCOL return indicates that some other process has gone rogue
  46800. ** and is not honoring the locking protocol. There is a vanishingly small
  46801. ** chance that SQLITE_PROTOCOL could be returned because of a run of really
  46802. ** bad luck when there is lots of contention for the wal-index, but that
  46803. ** possibility is so small that it can be safely neglected, we believe.
  46804. **
  46805. ** On success, this routine obtains a read lock on
  46806. ** WAL_READ_LOCK(pWal->readLock). The pWal->readLock integer is
  46807. ** in the range 0 <= pWal->readLock < WAL_NREADER. If pWal->readLock==(-1)
  46808. ** that means the Wal does not hold any read lock. The reader must not
  46809. ** access any database page that is modified by a WAL frame up to and
  46810. ** including frame number aReadMark[pWal->readLock]. The reader will
  46811. ** use WAL frames up to and including pWal->hdr.mxFrame if pWal->readLock>0
  46812. ** Or if pWal->readLock==0, then the reader will ignore the WAL
  46813. ** completely and get all content directly from the database file.
  46814. ** If the useWal parameter is 1 then the WAL will never be ignored and
  46815. ** this routine will always set pWal->readLock>0 on success.
  46816. ** When the read transaction is completed, the caller must release the
  46817. ** lock on WAL_READ_LOCK(pWal->readLock) and set pWal->readLock to -1.
  46818. **
  46819. ** This routine uses the nBackfill and aReadMark[] fields of the header
  46820. ** to select a particular WAL_READ_LOCK() that strives to let the
  46821. ** checkpoint process do as much work as possible. This routine might
  46822. ** update values of the aReadMark[] array in the header, but if it does
  46823. ** so it takes care to hold an exclusive lock on the corresponding
  46824. ** WAL_READ_LOCK() while changing values.
  46825. */
  46826. static int walTryBeginRead(Wal *pWal, int *pChanged, int useWal, int cnt){
  46827. volatile WalCkptInfo *pInfo; /* Checkpoint information in wal-index */
  46828. u32 mxReadMark; /* Largest aReadMark[] value */
  46829. int mxI; /* Index of largest aReadMark[] value */
  46830. int i; /* Loop counter */
  46831. int rc = SQLITE_OK; /* Return code */
  46832. assert( pWal->readLock<0 ); /* Not currently locked */
  46833. /* Take steps to avoid spinning forever if there is a protocol error.
  46834. **
  46835. ** Circumstances that cause a RETRY should only last for the briefest
  46836. ** instances of time. No I/O or other system calls are done while the
  46837. ** locks are held, so the locks should not be held for very long. But
  46838. ** if we are unlucky, another process that is holding a lock might get
  46839. ** paged out or take a page-fault that is time-consuming to resolve,
  46840. ** during the few nanoseconds that it is holding the lock. In that case,
  46841. ** it might take longer than normal for the lock to free.
  46842. **
  46843. ** After 5 RETRYs, we begin calling sqlite3OsSleep(). The first few
  46844. ** calls to sqlite3OsSleep() have a delay of 1 microsecond. Really this
  46845. ** is more of a scheduler yield than an actual delay. But on the 10th
  46846. ** an subsequent retries, the delays start becoming longer and longer,
  46847. ** so that on the 100th (and last) RETRY we delay for 323 milliseconds.
  46848. ** The total delay time before giving up is less than 10 seconds.
  46849. */
  46850. if( cnt>5 ){
  46851. int nDelay = 1; /* Pause time in microseconds */
  46852. if( cnt>100 ){
  46853. VVA_ONLY( pWal->lockError = 1; )
  46854. return SQLITE_PROTOCOL;
  46855. }
  46856. if( cnt>=10 ) nDelay = (cnt-9)*(cnt-9)*39;
  46857. sqlite3OsSleep(pWal->pVfs, nDelay);
  46858. }
  46859. if( !useWal ){
  46860. rc = walIndexReadHdr(pWal, pChanged);
  46861. if( rc==SQLITE_BUSY ){
  46862. /* If there is not a recovery running in another thread or process
  46863. ** then convert BUSY errors to WAL_RETRY. If recovery is known to
  46864. ** be running, convert BUSY to BUSY_RECOVERY. There is a race here
  46865. ** which might cause WAL_RETRY to be returned even if BUSY_RECOVERY
  46866. ** would be technically correct. But the race is benign since with
  46867. ** WAL_RETRY this routine will be called again and will probably be
  46868. ** right on the second iteration.
  46869. */
  46870. if( pWal->apWiData[0]==0 ){
  46871. /* This branch is taken when the xShmMap() method returns SQLITE_BUSY.
  46872. ** We assume this is a transient condition, so return WAL_RETRY. The
  46873. ** xShmMap() implementation used by the default unix and win32 VFS
  46874. ** modules may return SQLITE_BUSY due to a race condition in the
  46875. ** code that determines whether or not the shared-memory region
  46876. ** must be zeroed before the requested page is returned.
  46877. */
  46878. rc = WAL_RETRY;
  46879. }else if( SQLITE_OK==(rc = walLockShared(pWal, WAL_RECOVER_LOCK)) ){
  46880. walUnlockShared(pWal, WAL_RECOVER_LOCK);
  46881. rc = WAL_RETRY;
  46882. }else if( rc==SQLITE_BUSY ){
  46883. rc = SQLITE_BUSY_RECOVERY;
  46884. }
  46885. }
  46886. if( rc!=SQLITE_OK ){
  46887. return rc;
  46888. }
  46889. }
  46890. pInfo = walCkptInfo(pWal);
  46891. if( !useWal && pInfo->nBackfill==pWal->hdr.mxFrame ){
  46892. /* The WAL has been completely backfilled (or it is empty).
  46893. ** and can be safely ignored.
  46894. */
  46895. rc = walLockShared(pWal, WAL_READ_LOCK(0));
  46896. walShmBarrier(pWal);
  46897. if( rc==SQLITE_OK ){
  46898. if( memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr)) ){
  46899. /* It is not safe to allow the reader to continue here if frames
  46900. ** may have been appended to the log before READ_LOCK(0) was obtained.
  46901. ** When holding READ_LOCK(0), the reader ignores the entire log file,
  46902. ** which implies that the database file contains a trustworthy
  46903. ** snapshot. Since holding READ_LOCK(0) prevents a checkpoint from
  46904. ** happening, this is usually correct.
  46905. **
  46906. ** However, if frames have been appended to the log (or if the log
  46907. ** is wrapped and written for that matter) before the READ_LOCK(0)
  46908. ** is obtained, that is not necessarily true. A checkpointer may
  46909. ** have started to backfill the appended frames but crashed before
  46910. ** it finished. Leaving a corrupt image in the database file.
  46911. */
  46912. walUnlockShared(pWal, WAL_READ_LOCK(0));
  46913. return WAL_RETRY;
  46914. }
  46915. pWal->readLock = 0;
  46916. return SQLITE_OK;
  46917. }else if( rc!=SQLITE_BUSY ){
  46918. return rc;
  46919. }
  46920. }
  46921. /* If we get this far, it means that the reader will want to use
  46922. ** the WAL to get at content from recent commits. The job now is
  46923. ** to select one of the aReadMark[] entries that is closest to
  46924. ** but not exceeding pWal->hdr.mxFrame and lock that entry.
  46925. */
  46926. mxReadMark = 0;
  46927. mxI = 0;
  46928. for(i=1; i<WAL_NREADER; i++){
  46929. u32 thisMark = pInfo->aReadMark[i];
  46930. if( mxReadMark<=thisMark && thisMark<=pWal->hdr.mxFrame ){
  46931. assert( thisMark!=READMARK_NOT_USED );
  46932. mxReadMark = thisMark;
  46933. mxI = i;
  46934. }
  46935. }
  46936. /* There was once an "if" here. The extra "{" is to preserve indentation. */
  46937. {
  46938. if( (pWal->readOnly & WAL_SHM_RDONLY)==0
  46939. && (mxReadMark<pWal->hdr.mxFrame || mxI==0)
  46940. ){
  46941. for(i=1; i<WAL_NREADER; i++){
  46942. rc = walLockExclusive(pWal, WAL_READ_LOCK(i), 1);
  46943. if( rc==SQLITE_OK ){
  46944. mxReadMark = pInfo->aReadMark[i] = pWal->hdr.mxFrame;
  46945. mxI = i;
  46946. walUnlockExclusive(pWal, WAL_READ_LOCK(i), 1);
  46947. break;
  46948. }else if( rc!=SQLITE_BUSY ){
  46949. return rc;
  46950. }
  46951. }
  46952. }
  46953. if( mxI==0 ){
  46954. assert( rc==SQLITE_BUSY || (pWal->readOnly & WAL_SHM_RDONLY)!=0 );
  46955. return rc==SQLITE_BUSY ? WAL_RETRY : SQLITE_READONLY_CANTLOCK;
  46956. }
  46957. rc = walLockShared(pWal, WAL_READ_LOCK(mxI));
  46958. if( rc ){
  46959. return rc==SQLITE_BUSY ? WAL_RETRY : rc;
  46960. }
  46961. /* Now that the read-lock has been obtained, check that neither the
  46962. ** value in the aReadMark[] array or the contents of the wal-index
  46963. ** header have changed.
  46964. **
  46965. ** It is necessary to check that the wal-index header did not change
  46966. ** between the time it was read and when the shared-lock was obtained
  46967. ** on WAL_READ_LOCK(mxI) was obtained to account for the possibility
  46968. ** that the log file may have been wrapped by a writer, or that frames
  46969. ** that occur later in the log than pWal->hdr.mxFrame may have been
  46970. ** copied into the database by a checkpointer. If either of these things
  46971. ** happened, then reading the database with the current value of
  46972. ** pWal->hdr.mxFrame risks reading a corrupted snapshot. So, retry
  46973. ** instead.
  46974. **
  46975. ** This does not guarantee that the copy of the wal-index header is up to
  46976. ** date before proceeding. That would not be possible without somehow
  46977. ** blocking writers. It only guarantees that a dangerous checkpoint or
  46978. ** log-wrap (either of which would require an exclusive lock on
  46979. ** WAL_READ_LOCK(mxI)) has not occurred since the snapshot was valid.
  46980. */
  46981. walShmBarrier(pWal);
  46982. if( pInfo->aReadMark[mxI]!=mxReadMark
  46983. || memcmp((void *)walIndexHdr(pWal), &pWal->hdr, sizeof(WalIndexHdr))
  46984. ){
  46985. walUnlockShared(pWal, WAL_READ_LOCK(mxI));
  46986. return WAL_RETRY;
  46987. }else{
  46988. assert( mxReadMark<=pWal->hdr.mxFrame );
  46989. pWal->readLock = (i16)mxI;
  46990. }
  46991. }
  46992. return rc;
  46993. }
  46994. /*
  46995. ** Begin a read transaction on the database.
  46996. **
  46997. ** This routine used to be called sqlite3OpenSnapshot() and with good reason:
  46998. ** it takes a snapshot of the state of the WAL and wal-index for the current
  46999. ** instant in time. The current thread will continue to use this snapshot.
  47000. ** Other threads might append new content to the WAL and wal-index but
  47001. ** that extra content is ignored by the current thread.
  47002. **
  47003. ** If the database contents have changes since the previous read
  47004. ** transaction, then *pChanged is set to 1 before returning. The
  47005. ** Pager layer will use this to know that is cache is stale and
  47006. ** needs to be flushed.
  47007. */
  47008. SQLITE_PRIVATE int sqlite3WalBeginReadTransaction(Wal *pWal, int *pChanged){
  47009. int rc; /* Return code */
  47010. int cnt = 0; /* Number of TryBeginRead attempts */
  47011. do{
  47012. rc = walTryBeginRead(pWal, pChanged, 0, ++cnt);
  47013. }while( rc==WAL_RETRY );
  47014. testcase( (rc&0xff)==SQLITE_BUSY );
  47015. testcase( (rc&0xff)==SQLITE_IOERR );
  47016. testcase( rc==SQLITE_PROTOCOL );
  47017. testcase( rc==SQLITE_OK );
  47018. return rc;
  47019. }
  47020. /*
  47021. ** Finish with a read transaction. All this does is release the
  47022. ** read-lock.
  47023. */
  47024. SQLITE_PRIVATE void sqlite3WalEndReadTransaction(Wal *pWal){
  47025. sqlite3WalEndWriteTransaction(pWal);
  47026. if( pWal->readLock>=0 ){
  47027. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  47028. pWal->readLock = -1;
  47029. }
  47030. }
  47031. /*
  47032. ** Search the wal file for page pgno. If found, set *piRead to the frame that
  47033. ** contains the page. Otherwise, if pgno is not in the wal file, set *piRead
  47034. ** to zero.
  47035. **
  47036. ** Return SQLITE_OK if successful, or an error code if an error occurs. If an
  47037. ** error does occur, the final value of *piRead is undefined.
  47038. */
  47039. SQLITE_PRIVATE int sqlite3WalFindFrame(
  47040. Wal *pWal, /* WAL handle */
  47041. Pgno pgno, /* Database page number to read data for */
  47042. u32 *piRead /* OUT: Frame number (or zero) */
  47043. ){
  47044. u32 iRead = 0; /* If !=0, WAL frame to return data from */
  47045. u32 iLast = pWal->hdr.mxFrame; /* Last page in WAL for this reader */
  47046. int iHash; /* Used to loop through N hash tables */
  47047. /* This routine is only be called from within a read transaction. */
  47048. assert( pWal->readLock>=0 || pWal->lockError );
  47049. /* If the "last page" field of the wal-index header snapshot is 0, then
  47050. ** no data will be read from the wal under any circumstances. Return early
  47051. ** in this case as an optimization. Likewise, if pWal->readLock==0,
  47052. ** then the WAL is ignored by the reader so return early, as if the
  47053. ** WAL were empty.
  47054. */
  47055. if( iLast==0 || pWal->readLock==0 ){
  47056. *piRead = 0;
  47057. return SQLITE_OK;
  47058. }
  47059. /* Search the hash table or tables for an entry matching page number
  47060. ** pgno. Each iteration of the following for() loop searches one
  47061. ** hash table (each hash table indexes up to HASHTABLE_NPAGE frames).
  47062. **
  47063. ** This code might run concurrently to the code in walIndexAppend()
  47064. ** that adds entries to the wal-index (and possibly to this hash
  47065. ** table). This means the value just read from the hash
  47066. ** slot (aHash[iKey]) may have been added before or after the
  47067. ** current read transaction was opened. Values added after the
  47068. ** read transaction was opened may have been written incorrectly -
  47069. ** i.e. these slots may contain garbage data. However, we assume
  47070. ** that any slots written before the current read transaction was
  47071. ** opened remain unmodified.
  47072. **
  47073. ** For the reasons above, the if(...) condition featured in the inner
  47074. ** loop of the following block is more stringent that would be required
  47075. ** if we had exclusive access to the hash-table:
  47076. **
  47077. ** (aPgno[iFrame]==pgno):
  47078. ** This condition filters out normal hash-table collisions.
  47079. **
  47080. ** (iFrame<=iLast):
  47081. ** This condition filters out entries that were added to the hash
  47082. ** table after the current read-transaction had started.
  47083. */
  47084. for(iHash=walFramePage(iLast); iHash>=0 && iRead==0; iHash--){
  47085. volatile ht_slot *aHash; /* Pointer to hash table */
  47086. volatile u32 *aPgno; /* Pointer to array of page numbers */
  47087. u32 iZero; /* Frame number corresponding to aPgno[0] */
  47088. int iKey; /* Hash slot index */
  47089. int nCollide; /* Number of hash collisions remaining */
  47090. int rc; /* Error code */
  47091. rc = walHashGet(pWal, iHash, &aHash, &aPgno, &iZero);
  47092. if( rc!=SQLITE_OK ){
  47093. return rc;
  47094. }
  47095. nCollide = HASHTABLE_NSLOT;
  47096. for(iKey=walHash(pgno); aHash[iKey]; iKey=walNextHash(iKey)){
  47097. u32 iFrame = aHash[iKey] + iZero;
  47098. if( iFrame<=iLast && aPgno[aHash[iKey]]==pgno ){
  47099. /* assert( iFrame>iRead ); -- not true if there is corruption */
  47100. iRead = iFrame;
  47101. }
  47102. if( (nCollide--)==0 ){
  47103. return SQLITE_CORRUPT_BKPT;
  47104. }
  47105. }
  47106. }
  47107. #ifdef SQLITE_ENABLE_EXPENSIVE_ASSERT
  47108. /* If expensive assert() statements are available, do a linear search
  47109. ** of the wal-index file content. Make sure the results agree with the
  47110. ** result obtained using the hash indexes above. */
  47111. {
  47112. u32 iRead2 = 0;
  47113. u32 iTest;
  47114. for(iTest=iLast; iTest>0; iTest--){
  47115. if( walFramePgno(pWal, iTest)==pgno ){
  47116. iRead2 = iTest;
  47117. break;
  47118. }
  47119. }
  47120. assert( iRead==iRead2 );
  47121. }
  47122. #endif
  47123. *piRead = iRead;
  47124. return SQLITE_OK;
  47125. }
  47126. /*
  47127. ** Read the contents of frame iRead from the wal file into buffer pOut
  47128. ** (which is nOut bytes in size). Return SQLITE_OK if successful, or an
  47129. ** error code otherwise.
  47130. */
  47131. SQLITE_PRIVATE int sqlite3WalReadFrame(
  47132. Wal *pWal, /* WAL handle */
  47133. u32 iRead, /* Frame to read */
  47134. int nOut, /* Size of buffer pOut in bytes */
  47135. u8 *pOut /* Buffer to write page data to */
  47136. ){
  47137. int sz;
  47138. i64 iOffset;
  47139. sz = pWal->hdr.szPage;
  47140. sz = (sz&0xfe00) + ((sz&0x0001)<<16);
  47141. testcase( sz<=32768 );
  47142. testcase( sz>=65536 );
  47143. iOffset = walFrameOffset(iRead, sz) + WAL_FRAME_HDRSIZE;
  47144. /* testcase( IS_BIG_INT(iOffset) ); // requires a 4GiB WAL */
  47145. return sqlite3OsRead(pWal->pWalFd, pOut, (nOut>sz ? sz : nOut), iOffset);
  47146. }
  47147. /*
  47148. ** Return the size of the database in pages (or zero, if unknown).
  47149. */
  47150. SQLITE_PRIVATE Pgno sqlite3WalDbsize(Wal *pWal){
  47151. if( pWal && ALWAYS(pWal->readLock>=0) ){
  47152. return pWal->hdr.nPage;
  47153. }
  47154. return 0;
  47155. }
  47156. /*
  47157. ** This function starts a write transaction on the WAL.
  47158. **
  47159. ** A read transaction must have already been started by a prior call
  47160. ** to sqlite3WalBeginReadTransaction().
  47161. **
  47162. ** If another thread or process has written into the database since
  47163. ** the read transaction was started, then it is not possible for this
  47164. ** thread to write as doing so would cause a fork. So this routine
  47165. ** returns SQLITE_BUSY in that case and no write transaction is started.
  47166. **
  47167. ** There can only be a single writer active at a time.
  47168. */
  47169. SQLITE_PRIVATE int sqlite3WalBeginWriteTransaction(Wal *pWal){
  47170. int rc;
  47171. /* Cannot start a write transaction without first holding a read
  47172. ** transaction. */
  47173. assert( pWal->readLock>=0 );
  47174. if( pWal->readOnly ){
  47175. return SQLITE_READONLY;
  47176. }
  47177. /* Only one writer allowed at a time. Get the write lock. Return
  47178. ** SQLITE_BUSY if unable.
  47179. */
  47180. rc = walLockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47181. if( rc ){
  47182. return rc;
  47183. }
  47184. pWal->writeLock = 1;
  47185. /* If another connection has written to the database file since the
  47186. ** time the read transaction on this connection was started, then
  47187. ** the write is disallowed.
  47188. */
  47189. if( memcmp(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr))!=0 ){
  47190. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47191. pWal->writeLock = 0;
  47192. rc = SQLITE_BUSY_SNAPSHOT;
  47193. }
  47194. return rc;
  47195. }
  47196. /*
  47197. ** End a write transaction. The commit has already been done. This
  47198. ** routine merely releases the lock.
  47199. */
  47200. SQLITE_PRIVATE int sqlite3WalEndWriteTransaction(Wal *pWal){
  47201. if( pWal->writeLock ){
  47202. walUnlockExclusive(pWal, WAL_WRITE_LOCK, 1);
  47203. pWal->writeLock = 0;
  47204. pWal->truncateOnCommit = 0;
  47205. }
  47206. return SQLITE_OK;
  47207. }
  47208. /*
  47209. ** If any data has been written (but not committed) to the log file, this
  47210. ** function moves the write-pointer back to the start of the transaction.
  47211. **
  47212. ** Additionally, the callback function is invoked for each frame written
  47213. ** to the WAL since the start of the transaction. If the callback returns
  47214. ** other than SQLITE_OK, it is not invoked again and the error code is
  47215. ** returned to the caller.
  47216. **
  47217. ** Otherwise, if the callback function does not return an error, this
  47218. ** function returns SQLITE_OK.
  47219. */
  47220. SQLITE_PRIVATE int sqlite3WalUndo(Wal *pWal, int (*xUndo)(void *, Pgno), void *pUndoCtx){
  47221. int rc = SQLITE_OK;
  47222. if( ALWAYS(pWal->writeLock) ){
  47223. Pgno iMax = pWal->hdr.mxFrame;
  47224. Pgno iFrame;
  47225. /* Restore the clients cache of the wal-index header to the state it
  47226. ** was in before the client began writing to the database.
  47227. */
  47228. memcpy(&pWal->hdr, (void *)walIndexHdr(pWal), sizeof(WalIndexHdr));
  47229. for(iFrame=pWal->hdr.mxFrame+1;
  47230. ALWAYS(rc==SQLITE_OK) && iFrame<=iMax;
  47231. iFrame++
  47232. ){
  47233. /* This call cannot fail. Unless the page for which the page number
  47234. ** is passed as the second argument is (a) in the cache and
  47235. ** (b) has an outstanding reference, then xUndo is either a no-op
  47236. ** (if (a) is false) or simply expels the page from the cache (if (b)
  47237. ** is false).
  47238. **
  47239. ** If the upper layer is doing a rollback, it is guaranteed that there
  47240. ** are no outstanding references to any page other than page 1. And
  47241. ** page 1 is never written to the log until the transaction is
  47242. ** committed. As a result, the call to xUndo may not fail.
  47243. */
  47244. assert( walFramePgno(pWal, iFrame)!=1 );
  47245. rc = xUndo(pUndoCtx, walFramePgno(pWal, iFrame));
  47246. }
  47247. if( iMax!=pWal->hdr.mxFrame ) walCleanupHash(pWal);
  47248. }
  47249. return rc;
  47250. }
  47251. /*
  47252. ** Argument aWalData must point to an array of WAL_SAVEPOINT_NDATA u32
  47253. ** values. This function populates the array with values required to
  47254. ** "rollback" the write position of the WAL handle back to the current
  47255. ** point in the event of a savepoint rollback (via WalSavepointUndo()).
  47256. */
  47257. SQLITE_PRIVATE void sqlite3WalSavepoint(Wal *pWal, u32 *aWalData){
  47258. assert( pWal->writeLock );
  47259. aWalData[0] = pWal->hdr.mxFrame;
  47260. aWalData[1] = pWal->hdr.aFrameCksum[0];
  47261. aWalData[2] = pWal->hdr.aFrameCksum[1];
  47262. aWalData[3] = pWal->nCkpt;
  47263. }
  47264. /*
  47265. ** Move the write position of the WAL back to the point identified by
  47266. ** the values in the aWalData[] array. aWalData must point to an array
  47267. ** of WAL_SAVEPOINT_NDATA u32 values that has been previously populated
  47268. ** by a call to WalSavepoint().
  47269. */
  47270. SQLITE_PRIVATE int sqlite3WalSavepointUndo(Wal *pWal, u32 *aWalData){
  47271. int rc = SQLITE_OK;
  47272. assert( pWal->writeLock );
  47273. assert( aWalData[3]!=pWal->nCkpt || aWalData[0]<=pWal->hdr.mxFrame );
  47274. if( aWalData[3]!=pWal->nCkpt ){
  47275. /* This savepoint was opened immediately after the write-transaction
  47276. ** was started. Right after that, the writer decided to wrap around
  47277. ** to the start of the log. Update the savepoint values to match.
  47278. */
  47279. aWalData[0] = 0;
  47280. aWalData[3] = pWal->nCkpt;
  47281. }
  47282. if( aWalData[0]<pWal->hdr.mxFrame ){
  47283. pWal->hdr.mxFrame = aWalData[0];
  47284. pWal->hdr.aFrameCksum[0] = aWalData[1];
  47285. pWal->hdr.aFrameCksum[1] = aWalData[2];
  47286. walCleanupHash(pWal);
  47287. }
  47288. return rc;
  47289. }
  47290. /*
  47291. ** This function is called just before writing a set of frames to the log
  47292. ** file (see sqlite3WalFrames()). It checks to see if, instead of appending
  47293. ** to the current log file, it is possible to overwrite the start of the
  47294. ** existing log file with the new frames (i.e. "reset" the log). If so,
  47295. ** it sets pWal->hdr.mxFrame to 0. Otherwise, pWal->hdr.mxFrame is left
  47296. ** unchanged.
  47297. **
  47298. ** SQLITE_OK is returned if no error is encountered (regardless of whether
  47299. ** or not pWal->hdr.mxFrame is modified). An SQLite error code is returned
  47300. ** if an error occurs.
  47301. */
  47302. static int walRestartLog(Wal *pWal){
  47303. int rc = SQLITE_OK;
  47304. int cnt;
  47305. if( pWal->readLock==0 ){
  47306. volatile WalCkptInfo *pInfo = walCkptInfo(pWal);
  47307. assert( pInfo->nBackfill==pWal->hdr.mxFrame );
  47308. if( pInfo->nBackfill>0 ){
  47309. u32 salt1;
  47310. sqlite3_randomness(4, &salt1);
  47311. rc = walLockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  47312. if( rc==SQLITE_OK ){
  47313. /* If all readers are using WAL_READ_LOCK(0) (in other words if no
  47314. ** readers are currently using the WAL), then the transactions
  47315. ** frames will overwrite the start of the existing log. Update the
  47316. ** wal-index header to reflect this.
  47317. **
  47318. ** In theory it would be Ok to update the cache of the header only
  47319. ** at this point. But updating the actual wal-index header is also
  47320. ** safe and means there is no special case for sqlite3WalUndo()
  47321. ** to handle if this transaction is rolled back.
  47322. */
  47323. int i; /* Loop counter */
  47324. u32 *aSalt = pWal->hdr.aSalt; /* Big-endian salt values */
  47325. pWal->nCkpt++;
  47326. pWal->hdr.mxFrame = 0;
  47327. sqlite3Put4byte((u8*)&aSalt[0], 1 + sqlite3Get4byte((u8*)&aSalt[0]));
  47328. aSalt[1] = salt1;
  47329. walIndexWriteHdr(pWal);
  47330. pInfo->nBackfill = 0;
  47331. pInfo->aReadMark[1] = 0;
  47332. for(i=2; i<WAL_NREADER; i++) pInfo->aReadMark[i] = READMARK_NOT_USED;
  47333. assert( pInfo->aReadMark[0]==0 );
  47334. walUnlockExclusive(pWal, WAL_READ_LOCK(1), WAL_NREADER-1);
  47335. }else if( rc!=SQLITE_BUSY ){
  47336. return rc;
  47337. }
  47338. }
  47339. walUnlockShared(pWal, WAL_READ_LOCK(0));
  47340. pWal->readLock = -1;
  47341. cnt = 0;
  47342. do{
  47343. int notUsed;
  47344. rc = walTryBeginRead(pWal, &notUsed, 1, ++cnt);
  47345. }while( rc==WAL_RETRY );
  47346. assert( (rc&0xff)!=SQLITE_BUSY ); /* BUSY not possible when useWal==1 */
  47347. testcase( (rc&0xff)==SQLITE_IOERR );
  47348. testcase( rc==SQLITE_PROTOCOL );
  47349. testcase( rc==SQLITE_OK );
  47350. }
  47351. return rc;
  47352. }
  47353. /*
  47354. ** Information about the current state of the WAL file and where
  47355. ** the next fsync should occur - passed from sqlite3WalFrames() into
  47356. ** walWriteToLog().
  47357. */
  47358. typedef struct WalWriter {
  47359. Wal *pWal; /* The complete WAL information */
  47360. sqlite3_file *pFd; /* The WAL file to which we write */
  47361. sqlite3_int64 iSyncPoint; /* Fsync at this offset */
  47362. int syncFlags; /* Flags for the fsync */
  47363. int szPage; /* Size of one page */
  47364. } WalWriter;
  47365. /*
  47366. ** Write iAmt bytes of content into the WAL file beginning at iOffset.
  47367. ** Do a sync when crossing the p->iSyncPoint boundary.
  47368. **
  47369. ** In other words, if iSyncPoint is in between iOffset and iOffset+iAmt,
  47370. ** first write the part before iSyncPoint, then sync, then write the
  47371. ** rest.
  47372. */
  47373. static int walWriteToLog(
  47374. WalWriter *p, /* WAL to write to */
  47375. void *pContent, /* Content to be written */
  47376. int iAmt, /* Number of bytes to write */
  47377. sqlite3_int64 iOffset /* Start writing at this offset */
  47378. ){
  47379. int rc;
  47380. if( iOffset<p->iSyncPoint && iOffset+iAmt>=p->iSyncPoint ){
  47381. int iFirstAmt = (int)(p->iSyncPoint - iOffset);
  47382. rc = sqlite3OsWrite(p->pFd, pContent, iFirstAmt, iOffset);
  47383. if( rc ) return rc;
  47384. iOffset += iFirstAmt;
  47385. iAmt -= iFirstAmt;
  47386. pContent = (void*)(iFirstAmt + (char*)pContent);
  47387. assert( p->syncFlags & (SQLITE_SYNC_NORMAL|SQLITE_SYNC_FULL) );
  47388. rc = sqlite3OsSync(p->pFd, p->syncFlags & SQLITE_SYNC_MASK);
  47389. if( iAmt==0 || rc ) return rc;
  47390. }
  47391. rc = sqlite3OsWrite(p->pFd, pContent, iAmt, iOffset);
  47392. return rc;
  47393. }
  47394. /*
  47395. ** Write out a single frame of the WAL
  47396. */
  47397. static int walWriteOneFrame(
  47398. WalWriter *p, /* Where to write the frame */
  47399. PgHdr *pPage, /* The page of the frame to be written */
  47400. int nTruncate, /* The commit flag. Usually 0. >0 for commit */
  47401. sqlite3_int64 iOffset /* Byte offset at which to write */
  47402. ){
  47403. int rc; /* Result code from subfunctions */
  47404. void *pData; /* Data actually written */
  47405. u8 aFrame[WAL_FRAME_HDRSIZE]; /* Buffer to assemble frame-header in */
  47406. #if defined(SQLITE_HAS_CODEC)
  47407. if( (pData = sqlite3PagerCodec(pPage))==0 ) return SQLITE_NOMEM;
  47408. #else
  47409. pData = pPage->pData;
  47410. #endif
  47411. walEncodeFrame(p->pWal, pPage->pgno, nTruncate, pData, aFrame);
  47412. rc = walWriteToLog(p, aFrame, sizeof(aFrame), iOffset);
  47413. if( rc ) return rc;
  47414. /* Write the page data */
  47415. rc = walWriteToLog(p, pData, p->szPage, iOffset+sizeof(aFrame));
  47416. return rc;
  47417. }
  47418. /*
  47419. ** Write a set of frames to the log. The caller must hold the write-lock
  47420. ** on the log file (obtained using sqlite3WalBeginWriteTransaction()).
  47421. */
  47422. SQLITE_PRIVATE int sqlite3WalFrames(
  47423. Wal *pWal, /* Wal handle to write to */
  47424. int szPage, /* Database page-size in bytes */
  47425. PgHdr *pList, /* List of dirty pages to write */
  47426. Pgno nTruncate, /* Database size after this commit */
  47427. int isCommit, /* True if this is a commit */
  47428. int sync_flags /* Flags to pass to OsSync() (or 0) */
  47429. ){
  47430. int rc; /* Used to catch return codes */
  47431. u32 iFrame; /* Next frame address */
  47432. PgHdr *p; /* Iterator to run through pList with. */
  47433. PgHdr *pLast = 0; /* Last frame in list */
  47434. int nExtra = 0; /* Number of extra copies of last page */
  47435. int szFrame; /* The size of a single frame */
  47436. i64 iOffset; /* Next byte to write in WAL file */
  47437. WalWriter w; /* The writer */
  47438. assert( pList );
  47439. assert( pWal->writeLock );
  47440. /* If this frame set completes a transaction, then nTruncate>0. If
  47441. ** nTruncate==0 then this frame set does not complete the transaction. */
  47442. assert( (isCommit!=0)==(nTruncate!=0) );
  47443. #if defined(SQLITE_TEST) && defined(SQLITE_DEBUG)
  47444. { int cnt; for(cnt=0, p=pList; p; p=p->pDirty, cnt++){}
  47445. WALTRACE(("WAL%p: frame write begin. %d frames. mxFrame=%d. %s\n",
  47446. pWal, cnt, pWal->hdr.mxFrame, isCommit ? "Commit" : "Spill"));
  47447. }
  47448. #endif
  47449. /* See if it is possible to write these frames into the start of the
  47450. ** log file, instead of appending to it at pWal->hdr.mxFrame.
  47451. */
  47452. if( SQLITE_OK!=(rc = walRestartLog(pWal)) ){
  47453. return rc;
  47454. }
  47455. /* If this is the first frame written into the log, write the WAL
  47456. ** header to the start of the WAL file. See comments at the top of
  47457. ** this source file for a description of the WAL header format.
  47458. */
  47459. iFrame = pWal->hdr.mxFrame;
  47460. if( iFrame==0 ){
  47461. u8 aWalHdr[WAL_HDRSIZE]; /* Buffer to assemble wal-header in */
  47462. u32 aCksum[2]; /* Checksum for wal-header */
  47463. sqlite3Put4byte(&aWalHdr[0], (WAL_MAGIC | SQLITE_BIGENDIAN));
  47464. sqlite3Put4byte(&aWalHdr[4], WAL_MAX_VERSION);
  47465. sqlite3Put4byte(&aWalHdr[8], szPage);
  47466. sqlite3Put4byte(&aWalHdr[12], pWal->nCkpt);
  47467. if( pWal->nCkpt==0 ) sqlite3_randomness(8, pWal->hdr.aSalt);
  47468. memcpy(&aWalHdr[16], pWal->hdr.aSalt, 8);
  47469. walChecksumBytes(1, aWalHdr, WAL_HDRSIZE-2*4, 0, aCksum);
  47470. sqlite3Put4byte(&aWalHdr[24], aCksum[0]);
  47471. sqlite3Put4byte(&aWalHdr[28], aCksum[1]);
  47472. pWal->szPage = szPage;
  47473. pWal->hdr.bigEndCksum = SQLITE_BIGENDIAN;
  47474. pWal->hdr.aFrameCksum[0] = aCksum[0];
  47475. pWal->hdr.aFrameCksum[1] = aCksum[1];
  47476. pWal->truncateOnCommit = 1;
  47477. rc = sqlite3OsWrite(pWal->pWalFd, aWalHdr, sizeof(aWalHdr), 0);
  47478. WALTRACE(("WAL%p: wal-header write %s\n", pWal, rc ? "failed" : "ok"));
  47479. if( rc!=SQLITE_OK ){
  47480. return rc;
  47481. }
  47482. /* Sync the header (unless SQLITE_IOCAP_SEQUENTIAL is true or unless
  47483. ** all syncing is turned off by PRAGMA synchronous=OFF). Otherwise
  47484. ** an out-of-order write following a WAL restart could result in
  47485. ** database corruption. See the ticket:
  47486. **
  47487. ** http://localhost:591/sqlite/info/ff5be73dee
  47488. */
  47489. if( pWal->syncHeader && sync_flags ){
  47490. rc = sqlite3OsSync(pWal->pWalFd, sync_flags & SQLITE_SYNC_MASK);
  47491. if( rc ) return rc;
  47492. }
  47493. }
  47494. assert( (int)pWal->szPage==szPage );
  47495. /* Setup information needed to write frames into the WAL */
  47496. w.pWal = pWal;
  47497. w.pFd = pWal->pWalFd;
  47498. w.iSyncPoint = 0;
  47499. w.syncFlags = sync_flags;
  47500. w.szPage = szPage;
  47501. iOffset = walFrameOffset(iFrame+1, szPage);
  47502. szFrame = szPage + WAL_FRAME_HDRSIZE;
  47503. /* Write all frames into the log file exactly once */
  47504. for(p=pList; p; p=p->pDirty){
  47505. int nDbSize; /* 0 normally. Positive == commit flag */
  47506. iFrame++;
  47507. assert( iOffset==walFrameOffset(iFrame, szPage) );
  47508. nDbSize = (isCommit && p->pDirty==0) ? nTruncate : 0;
  47509. rc = walWriteOneFrame(&w, p, nDbSize, iOffset);
  47510. if( rc ) return rc;
  47511. pLast = p;
  47512. iOffset += szFrame;
  47513. }
  47514. /* If this is the end of a transaction, then we might need to pad
  47515. ** the transaction and/or sync the WAL file.
  47516. **
  47517. ** Padding and syncing only occur if this set of frames complete a
  47518. ** transaction and if PRAGMA synchronous=FULL. If synchronous==NORMAL
  47519. ** or synchronous==OFF, then no padding or syncing are needed.
  47520. **
  47521. ** If SQLITE_IOCAP_POWERSAFE_OVERWRITE is defined, then padding is not
  47522. ** needed and only the sync is done. If padding is needed, then the
  47523. ** final frame is repeated (with its commit mark) until the next sector
  47524. ** boundary is crossed. Only the part of the WAL prior to the last
  47525. ** sector boundary is synced; the part of the last frame that extends
  47526. ** past the sector boundary is written after the sync.
  47527. */
  47528. if( isCommit && (sync_flags & WAL_SYNC_TRANSACTIONS)!=0 ){
  47529. if( pWal->padToSectorBoundary ){
  47530. int sectorSize = sqlite3SectorSize(pWal->pWalFd);
  47531. w.iSyncPoint = ((iOffset+sectorSize-1)/sectorSize)*sectorSize;
  47532. while( iOffset<w.iSyncPoint ){
  47533. rc = walWriteOneFrame(&w, pLast, nTruncate, iOffset);
  47534. if( rc ) return rc;
  47535. iOffset += szFrame;
  47536. nExtra++;
  47537. }
  47538. }else{
  47539. rc = sqlite3OsSync(w.pFd, sync_flags & SQLITE_SYNC_MASK);
  47540. }
  47541. }
  47542. /* If this frame set completes the first transaction in the WAL and
  47543. ** if PRAGMA journal_size_limit is set, then truncate the WAL to the
  47544. ** journal size limit, if possible.
  47545. */
  47546. if( isCommit && pWal->truncateOnCommit && pWal->mxWalSize>=0 ){
  47547. i64 sz = pWal->mxWalSize;
  47548. if( walFrameOffset(iFrame+nExtra+1, szPage)>pWal->mxWalSize ){
  47549. sz = walFrameOffset(iFrame+nExtra+1, szPage);
  47550. }
  47551. walLimitSize(pWal, sz);
  47552. pWal->truncateOnCommit = 0;
  47553. }
  47554. /* Append data to the wal-index. It is not necessary to lock the
  47555. ** wal-index to do this as the SQLITE_SHM_WRITE lock held on the wal-index
  47556. ** guarantees that there are no other writers, and no data that may
  47557. ** be in use by existing readers is being overwritten.
  47558. */
  47559. iFrame = pWal->hdr.mxFrame;
  47560. for(p=pList; p && rc==SQLITE_OK; p=p->pDirty){
  47561. iFrame++;
  47562. rc = walIndexAppend(pWal, iFrame, p->pgno);
  47563. }
  47564. while( rc==SQLITE_OK && nExtra>0 ){
  47565. iFrame++;
  47566. nExtra--;
  47567. rc = walIndexAppend(pWal, iFrame, pLast->pgno);
  47568. }
  47569. if( rc==SQLITE_OK ){
  47570. /* Update the private copy of the header. */
  47571. pWal->hdr.szPage = (u16)((szPage&0xff00) | (szPage>>16));
  47572. testcase( szPage<=32768 );
  47573. testcase( szPage>=65536 );
  47574. pWal->hdr.mxFrame = iFrame;
  47575. if( isCommit ){
  47576. pWal->hdr.iChange++;
  47577. pWal->hdr.nPage = nTruncate;
  47578. }
  47579. /* If this is a commit, update the wal-index header too. */
  47580. if( isCommit ){
  47581. walIndexWriteHdr(pWal);
  47582. pWal->iCallback = iFrame;
  47583. }
  47584. }
  47585. WALTRACE(("WAL%p: frame write %s\n", pWal, rc ? "failed" : "ok"));
  47586. return rc;
  47587. }
  47588. /*
  47589. ** This routine is called to implement sqlite3_wal_checkpoint() and
  47590. ** related interfaces.
  47591. **
  47592. ** Obtain a CHECKPOINT lock and then backfill as much information as
  47593. ** we can from WAL into the database.
  47594. **
  47595. ** If parameter xBusy is not NULL, it is a pointer to a busy-handler
  47596. ** callback. In this case this function runs a blocking checkpoint.
  47597. */
  47598. SQLITE_PRIVATE int sqlite3WalCheckpoint(
  47599. Wal *pWal, /* Wal connection */
  47600. int eMode, /* PASSIVE, FULL or RESTART */
  47601. int (*xBusy)(void*), /* Function to call when busy */
  47602. void *pBusyArg, /* Context argument for xBusyHandler */
  47603. int sync_flags, /* Flags to sync db file with (or 0) */
  47604. int nBuf, /* Size of temporary buffer */
  47605. u8 *zBuf, /* Temporary buffer to use */
  47606. int *pnLog, /* OUT: Number of frames in WAL */
  47607. int *pnCkpt /* OUT: Number of backfilled frames in WAL */
  47608. ){
  47609. int rc; /* Return code */
  47610. int isChanged = 0; /* True if a new wal-index header is loaded */
  47611. int eMode2 = eMode; /* Mode to pass to walCheckpoint() */
  47612. assert( pWal->ckptLock==0 );
  47613. assert( pWal->writeLock==0 );
  47614. if( pWal->readOnly ) return SQLITE_READONLY;
  47615. WALTRACE(("WAL%p: checkpoint begins\n", pWal));
  47616. rc = walLockExclusive(pWal, WAL_CKPT_LOCK, 1);
  47617. if( rc ){
  47618. /* Usually this is SQLITE_BUSY meaning that another thread or process
  47619. ** is already running a checkpoint, or maybe a recovery. But it might
  47620. ** also be SQLITE_IOERR. */
  47621. return rc;
  47622. }
  47623. pWal->ckptLock = 1;
  47624. /* If this is a blocking-checkpoint, then obtain the write-lock as well
  47625. ** to prevent any writers from running while the checkpoint is underway.
  47626. ** This has to be done before the call to walIndexReadHdr() below.
  47627. **
  47628. ** If the writer lock cannot be obtained, then a passive checkpoint is
  47629. ** run instead. Since the checkpointer is not holding the writer lock,
  47630. ** there is no point in blocking waiting for any readers. Assuming no
  47631. ** other error occurs, this function will return SQLITE_BUSY to the caller.
  47632. */
  47633. if( eMode!=SQLITE_CHECKPOINT_PASSIVE ){
  47634. rc = walBusyLock(pWal, xBusy, pBusyArg, WAL_WRITE_LOCK, 1);
  47635. if( rc==SQLITE_OK ){
  47636. pWal->writeLock = 1;
  47637. }else if( rc==SQLITE_BUSY ){
  47638. eMode2 = SQLITE_CHECKPOINT_PASSIVE;
  47639. rc = SQLITE_OK;
  47640. }
  47641. }
  47642. /* Read the wal-index header. */
  47643. if( rc==SQLITE_OK ){
  47644. rc = walIndexReadHdr(pWal, &isChanged);
  47645. if( isChanged && pWal->pDbFd->pMethods->iVersion>=3 ){
  47646. sqlite3OsUnfetch(pWal->pDbFd, 0, 0);
  47647. }
  47648. }
  47649. /* Copy data from the log to the database file. */
  47650. if( rc==SQLITE_OK ){
  47651. if( pWal->hdr.mxFrame && walPagesize(pWal)!=nBuf ){
  47652. rc = SQLITE_CORRUPT_BKPT;
  47653. }else{
  47654. rc = walCheckpoint(pWal, eMode2, xBusy, pBusyArg, sync_flags, zBuf);
  47655. }
  47656. /* If no error occurred, set the output variables. */
  47657. if( rc==SQLITE_OK || rc==SQLITE_BUSY ){
  47658. if( pnLog ) *pnLog = (int)pWal->hdr.mxFrame;
  47659. if( pnCkpt ) *pnCkpt = (int)(walCkptInfo(pWal)->nBackfill);
  47660. }
  47661. }
  47662. if( isChanged ){
  47663. /* If a new wal-index header was loaded before the checkpoint was
  47664. ** performed, then the pager-cache associated with pWal is now
  47665. ** out of date. So zero the cached wal-index header to ensure that
  47666. ** next time the pager opens a snapshot on this database it knows that
  47667. ** the cache needs to be reset.
  47668. */
  47669. memset(&pWal->hdr, 0, sizeof(WalIndexHdr));
  47670. }
  47671. /* Release the locks. */
  47672. sqlite3WalEndWriteTransaction(pWal);
  47673. walUnlockExclusive(pWal, WAL_CKPT_LOCK, 1);
  47674. pWal->ckptLock = 0;
  47675. WALTRACE(("WAL%p: checkpoint %s\n", pWal, rc ? "failed" : "ok"));
  47676. return (rc==SQLITE_OK && eMode!=eMode2 ? SQLITE_BUSY : rc);
  47677. }
  47678. /* Return the value to pass to a sqlite3_wal_hook callback, the
  47679. ** number of frames in the WAL at the point of the last commit since
  47680. ** sqlite3WalCallback() was called. If no commits have occurred since
  47681. ** the last call, then return 0.
  47682. */
  47683. SQLITE_PRIVATE int sqlite3WalCallback(Wal *pWal){
  47684. u32 ret = 0;
  47685. if( pWal ){
  47686. ret = pWal->iCallback;
  47687. pWal->iCallback = 0;
  47688. }
  47689. return (int)ret;
  47690. }
  47691. /*
  47692. ** This function is called to change the WAL subsystem into or out
  47693. ** of locking_mode=EXCLUSIVE.
  47694. **
  47695. ** If op is zero, then attempt to change from locking_mode=EXCLUSIVE
  47696. ** into locking_mode=NORMAL. This means that we must acquire a lock
  47697. ** on the pWal->readLock byte. If the WAL is already in locking_mode=NORMAL
  47698. ** or if the acquisition of the lock fails, then return 0. If the
  47699. ** transition out of exclusive-mode is successful, return 1. This
  47700. ** operation must occur while the pager is still holding the exclusive
  47701. ** lock on the main database file.
  47702. **
  47703. ** If op is one, then change from locking_mode=NORMAL into
  47704. ** locking_mode=EXCLUSIVE. This means that the pWal->readLock must
  47705. ** be released. Return 1 if the transition is made and 0 if the
  47706. ** WAL is already in exclusive-locking mode - meaning that this
  47707. ** routine is a no-op. The pager must already hold the exclusive lock
  47708. ** on the main database file before invoking this operation.
  47709. **
  47710. ** If op is negative, then do a dry-run of the op==1 case but do
  47711. ** not actually change anything. The pager uses this to see if it
  47712. ** should acquire the database exclusive lock prior to invoking
  47713. ** the op==1 case.
  47714. */
  47715. SQLITE_PRIVATE int sqlite3WalExclusiveMode(Wal *pWal, int op){
  47716. int rc;
  47717. assert( pWal->writeLock==0 );
  47718. assert( pWal->exclusiveMode!=WAL_HEAPMEMORY_MODE || op==-1 );
  47719. /* pWal->readLock is usually set, but might be -1 if there was a
  47720. ** prior error while attempting to acquire are read-lock. This cannot
  47721. ** happen if the connection is actually in exclusive mode (as no xShmLock
  47722. ** locks are taken in this case). Nor should the pager attempt to
  47723. ** upgrade to exclusive-mode following such an error.
  47724. */
  47725. assert( pWal->readLock>=0 || pWal->lockError );
  47726. assert( pWal->readLock>=0 || (op<=0 && pWal->exclusiveMode==0) );
  47727. if( op==0 ){
  47728. if( pWal->exclusiveMode ){
  47729. pWal->exclusiveMode = 0;
  47730. if( walLockShared(pWal, WAL_READ_LOCK(pWal->readLock))!=SQLITE_OK ){
  47731. pWal->exclusiveMode = 1;
  47732. }
  47733. rc = pWal->exclusiveMode==0;
  47734. }else{
  47735. /* Already in locking_mode=NORMAL */
  47736. rc = 0;
  47737. }
  47738. }else if( op>0 ){
  47739. assert( pWal->exclusiveMode==0 );
  47740. assert( pWal->readLock>=0 );
  47741. walUnlockShared(pWal, WAL_READ_LOCK(pWal->readLock));
  47742. pWal->exclusiveMode = 1;
  47743. rc = 1;
  47744. }else{
  47745. rc = pWal->exclusiveMode==0;
  47746. }
  47747. return rc;
  47748. }
  47749. /*
  47750. ** Return true if the argument is non-NULL and the WAL module is using
  47751. ** heap-memory for the wal-index. Otherwise, if the argument is NULL or the
  47752. ** WAL module is using shared-memory, return false.
  47753. */
  47754. SQLITE_PRIVATE int sqlite3WalHeapMemory(Wal *pWal){
  47755. return (pWal && pWal->exclusiveMode==WAL_HEAPMEMORY_MODE );
  47756. }
  47757. #ifdef SQLITE_ENABLE_ZIPVFS
  47758. /*
  47759. ** If the argument is not NULL, it points to a Wal object that holds a
  47760. ** read-lock. This function returns the database page-size if it is known,
  47761. ** or zero if it is not (or if pWal is NULL).
  47762. */
  47763. SQLITE_PRIVATE int sqlite3WalFramesize(Wal *pWal){
  47764. assert( pWal==0 || pWal->readLock>=0 );
  47765. return (pWal ? pWal->szPage : 0);
  47766. }
  47767. #endif
  47768. #endif /* #ifndef SQLITE_OMIT_WAL */
  47769. /************** End of wal.c *************************************************/
  47770. /************** Begin file btmutex.c *****************************************/
  47771. /*
  47772. ** 2007 August 27
  47773. **
  47774. ** The author disclaims copyright to this source code. In place of
  47775. ** a legal notice, here is a blessing:
  47776. **
  47777. ** May you do good and not evil.
  47778. ** May you find forgiveness for yourself and forgive others.
  47779. ** May you share freely, never taking more than you give.
  47780. **
  47781. *************************************************************************
  47782. **
  47783. ** This file contains code used to implement mutexes on Btree objects.
  47784. ** This code really belongs in btree.c. But btree.c is getting too
  47785. ** big and we want to break it down some. This packaged seemed like
  47786. ** a good breakout.
  47787. */
  47788. /************** Include btreeInt.h in the middle of btmutex.c ****************/
  47789. /************** Begin file btreeInt.h ****************************************/
  47790. /*
  47791. ** 2004 April 6
  47792. **
  47793. ** The author disclaims copyright to this source code. In place of
  47794. ** a legal notice, here is a blessing:
  47795. **
  47796. ** May you do good and not evil.
  47797. ** May you find forgiveness for yourself and forgive others.
  47798. ** May you share freely, never taking more than you give.
  47799. **
  47800. *************************************************************************
  47801. ** This file implements an external (disk-based) database using BTrees.
  47802. ** For a detailed discussion of BTrees, refer to
  47803. **
  47804. ** Donald E. Knuth, THE ART OF COMPUTER PROGRAMMING, Volume 3:
  47805. ** "Sorting And Searching", pages 473-480. Addison-Wesley
  47806. ** Publishing Company, Reading, Massachusetts.
  47807. **
  47808. ** The basic idea is that each page of the file contains N database
  47809. ** entries and N+1 pointers to subpages.
  47810. **
  47811. ** ----------------------------------------------------------------
  47812. ** | Ptr(0) | Key(0) | Ptr(1) | Key(1) | ... | Key(N-1) | Ptr(N) |
  47813. ** ----------------------------------------------------------------
  47814. **
  47815. ** All of the keys on the page that Ptr(0) points to have values less
  47816. ** than Key(0). All of the keys on page Ptr(1) and its subpages have
  47817. ** values greater than Key(0) and less than Key(1). All of the keys
  47818. ** on Ptr(N) and its subpages have values greater than Key(N-1). And
  47819. ** so forth.
  47820. **
  47821. ** Finding a particular key requires reading O(log(M)) pages from the
  47822. ** disk where M is the number of entries in the tree.
  47823. **
  47824. ** In this implementation, a single file can hold one or more separate
  47825. ** BTrees. Each BTree is identified by the index of its root page. The
  47826. ** key and data for any entry are combined to form the "payload". A
  47827. ** fixed amount of payload can be carried directly on the database
  47828. ** page. If the payload is larger than the preset amount then surplus
  47829. ** bytes are stored on overflow pages. The payload for an entry
  47830. ** and the preceding pointer are combined to form a "Cell". Each
  47831. ** page has a small header which contains the Ptr(N) pointer and other
  47832. ** information such as the size of key and data.
  47833. **
  47834. ** FORMAT DETAILS
  47835. **
  47836. ** The file is divided into pages. The first page is called page 1,
  47837. ** the second is page 2, and so forth. A page number of zero indicates
  47838. ** "no such page". The page size can be any power of 2 between 512 and 65536.
  47839. ** Each page can be either a btree page, a freelist page, an overflow
  47840. ** page, or a pointer-map page.
  47841. **
  47842. ** The first page is always a btree page. The first 100 bytes of the first
  47843. ** page contain a special header (the "file header") that describes the file.
  47844. ** The format of the file header is as follows:
  47845. **
  47846. ** OFFSET SIZE DESCRIPTION
  47847. ** 0 16 Header string: "SQLite format 3\000"
  47848. ** 16 2 Page size in bytes. (1 means 65536)
  47849. ** 18 1 File format write version
  47850. ** 19 1 File format read version
  47851. ** 20 1 Bytes of unused space at the end of each page
  47852. ** 21 1 Max embedded payload fraction (must be 64)
  47853. ** 22 1 Min embedded payload fraction (must be 32)
  47854. ** 23 1 Min leaf payload fraction (must be 32)
  47855. ** 24 4 File change counter
  47856. ** 28 4 Reserved for future use
  47857. ** 32 4 First freelist page
  47858. ** 36 4 Number of freelist pages in the file
  47859. ** 40 60 15 4-byte meta values passed to higher layers
  47860. **
  47861. ** 40 4 Schema cookie
  47862. ** 44 4 File format of schema layer
  47863. ** 48 4 Size of page cache
  47864. ** 52 4 Largest root-page (auto/incr_vacuum)
  47865. ** 56 4 1=UTF-8 2=UTF16le 3=UTF16be
  47866. ** 60 4 User version
  47867. ** 64 4 Incremental vacuum mode
  47868. ** 68 4 Application-ID
  47869. ** 72 20 unused
  47870. ** 92 4 The version-valid-for number
  47871. ** 96 4 SQLITE_VERSION_NUMBER
  47872. **
  47873. ** All of the integer values are big-endian (most significant byte first).
  47874. **
  47875. ** The file change counter is incremented when the database is changed
  47876. ** This counter allows other processes to know when the file has changed
  47877. ** and thus when they need to flush their cache.
  47878. **
  47879. ** The max embedded payload fraction is the amount of the total usable
  47880. ** space in a page that can be consumed by a single cell for standard
  47881. ** B-tree (non-LEAFDATA) tables. A value of 255 means 100%. The default
  47882. ** is to limit the maximum cell size so that at least 4 cells will fit
  47883. ** on one page. Thus the default max embedded payload fraction is 64.
  47884. **
  47885. ** If the payload for a cell is larger than the max payload, then extra
  47886. ** payload is spilled to overflow pages. Once an overflow page is allocated,
  47887. ** as many bytes as possible are moved into the overflow pages without letting
  47888. ** the cell size drop below the min embedded payload fraction.
  47889. **
  47890. ** The min leaf payload fraction is like the min embedded payload fraction
  47891. ** except that it applies to leaf nodes in a LEAFDATA tree. The maximum
  47892. ** payload fraction for a LEAFDATA tree is always 100% (or 255) and it
  47893. ** not specified in the header.
  47894. **
  47895. ** Each btree pages is divided into three sections: The header, the
  47896. ** cell pointer array, and the cell content area. Page 1 also has a 100-byte
  47897. ** file header that occurs before the page header.
  47898. **
  47899. ** |----------------|
  47900. ** | file header | 100 bytes. Page 1 only.
  47901. ** |----------------|
  47902. ** | page header | 8 bytes for leaves. 12 bytes for interior nodes
  47903. ** |----------------|
  47904. ** | cell pointer | | 2 bytes per cell. Sorted order.
  47905. ** | array | | Grows downward
  47906. ** | | v
  47907. ** |----------------|
  47908. ** | unallocated |
  47909. ** | space |
  47910. ** |----------------| ^ Grows upwards
  47911. ** | cell content | | Arbitrary order interspersed with freeblocks.
  47912. ** | area | | and free space fragments.
  47913. ** |----------------|
  47914. **
  47915. ** The page headers looks like this:
  47916. **
  47917. ** OFFSET SIZE DESCRIPTION
  47918. ** 0 1 Flags. 1: intkey, 2: zerodata, 4: leafdata, 8: leaf
  47919. ** 1 2 byte offset to the first freeblock
  47920. ** 3 2 number of cells on this page
  47921. ** 5 2 first byte of the cell content area
  47922. ** 7 1 number of fragmented free bytes
  47923. ** 8 4 Right child (the Ptr(N) value). Omitted on leaves.
  47924. **
  47925. ** The flags define the format of this btree page. The leaf flag means that
  47926. ** this page has no children. The zerodata flag means that this page carries
  47927. ** only keys and no data. The intkey flag means that the key is an integer
  47928. ** which is stored in the key size entry of the cell header rather than in
  47929. ** the payload area.
  47930. **
  47931. ** The cell pointer array begins on the first byte after the page header.
  47932. ** The cell pointer array contains zero or more 2-byte numbers which are
  47933. ** offsets from the beginning of the page to the cell content in the cell
  47934. ** content area. The cell pointers occur in sorted order. The system strives
  47935. ** to keep free space after the last cell pointer so that new cells can
  47936. ** be easily added without having to defragment the page.
  47937. **
  47938. ** Cell content is stored at the very end of the page and grows toward the
  47939. ** beginning of the page.
  47940. **
  47941. ** Unused space within the cell content area is collected into a linked list of
  47942. ** freeblocks. Each freeblock is at least 4 bytes in size. The byte offset
  47943. ** to the first freeblock is given in the header. Freeblocks occur in
  47944. ** increasing order. Because a freeblock must be at least 4 bytes in size,
  47945. ** any group of 3 or fewer unused bytes in the cell content area cannot
  47946. ** exist on the freeblock chain. A group of 3 or fewer free bytes is called
  47947. ** a fragment. The total number of bytes in all fragments is recorded.
  47948. ** in the page header at offset 7.
  47949. **
  47950. ** SIZE DESCRIPTION
  47951. ** 2 Byte offset of the next freeblock
  47952. ** 2 Bytes in this freeblock
  47953. **
  47954. ** Cells are of variable length. Cells are stored in the cell content area at
  47955. ** the end of the page. Pointers to the cells are in the cell pointer array
  47956. ** that immediately follows the page header. Cells is not necessarily
  47957. ** contiguous or in order, but cell pointers are contiguous and in order.
  47958. **
  47959. ** Cell content makes use of variable length integers. A variable
  47960. ** length integer is 1 to 9 bytes where the lower 7 bits of each
  47961. ** byte are used. The integer consists of all bytes that have bit 8 set and
  47962. ** the first byte with bit 8 clear. The most significant byte of the integer
  47963. ** appears first. A variable-length integer may not be more than 9 bytes long.
  47964. ** As a special case, all 8 bytes of the 9th byte are used as data. This
  47965. ** allows a 64-bit integer to be encoded in 9 bytes.
  47966. **
  47967. ** 0x00 becomes 0x00000000
  47968. ** 0x7f becomes 0x0000007f
  47969. ** 0x81 0x00 becomes 0x00000080
  47970. ** 0x82 0x00 becomes 0x00000100
  47971. ** 0x80 0x7f becomes 0x0000007f
  47972. ** 0x8a 0x91 0xd1 0xac 0x78 becomes 0x12345678
  47973. ** 0x81 0x81 0x81 0x81 0x01 becomes 0x10204081
  47974. **
  47975. ** Variable length integers are used for rowids and to hold the number of
  47976. ** bytes of key and data in a btree cell.
  47977. **
  47978. ** The content of a cell looks like this:
  47979. **
  47980. ** SIZE DESCRIPTION
  47981. ** 4 Page number of the left child. Omitted if leaf flag is set.
  47982. ** var Number of bytes of data. Omitted if the zerodata flag is set.
  47983. ** var Number of bytes of key. Or the key itself if intkey flag is set.
  47984. ** * Payload
  47985. ** 4 First page of the overflow chain. Omitted if no overflow
  47986. **
  47987. ** Overflow pages form a linked list. Each page except the last is completely
  47988. ** filled with data (pagesize - 4 bytes). The last page can have as little
  47989. ** as 1 byte of data.
  47990. **
  47991. ** SIZE DESCRIPTION
  47992. ** 4 Page number of next overflow page
  47993. ** * Data
  47994. **
  47995. ** Freelist pages come in two subtypes: trunk pages and leaf pages. The
  47996. ** file header points to the first in a linked list of trunk page. Each trunk
  47997. ** page points to multiple leaf pages. The content of a leaf page is
  47998. ** unspecified. A trunk page looks like this:
  47999. **
  48000. ** SIZE DESCRIPTION
  48001. ** 4 Page number of next trunk page
  48002. ** 4 Number of leaf pointers on this page
  48003. ** * zero or more pages numbers of leaves
  48004. */
  48005. /* The following value is the maximum cell size assuming a maximum page
  48006. ** size give above.
  48007. */
  48008. #define MX_CELL_SIZE(pBt) ((int)(pBt->pageSize-8))
  48009. /* The maximum number of cells on a single page of the database. This
  48010. ** assumes a minimum cell size of 6 bytes (4 bytes for the cell itself
  48011. ** plus 2 bytes for the index to the cell in the page header). Such
  48012. ** small cells will be rare, but they are possible.
  48013. */
  48014. #define MX_CELL(pBt) ((pBt->pageSize-8)/6)
  48015. /* Forward declarations */
  48016. typedef struct MemPage MemPage;
  48017. typedef struct BtLock BtLock;
  48018. /*
  48019. ** This is a magic string that appears at the beginning of every
  48020. ** SQLite database in order to identify the file as a real database.
  48021. **
  48022. ** You can change this value at compile-time by specifying a
  48023. ** -DSQLITE_FILE_HEADER="..." on the compiler command-line. The
  48024. ** header must be exactly 16 bytes including the zero-terminator so
  48025. ** the string itself should be 15 characters long. If you change
  48026. ** the header, then your custom library will not be able to read
  48027. ** databases generated by the standard tools and the standard tools
  48028. ** will not be able to read databases created by your custom library.
  48029. */
  48030. #ifndef SQLITE_FILE_HEADER /* 123456789 123456 */
  48031. # define SQLITE_FILE_HEADER "SQLite format 3"
  48032. #endif
  48033. /*
  48034. ** Page type flags. An ORed combination of these flags appear as the
  48035. ** first byte of on-disk image of every BTree page.
  48036. */
  48037. #define PTF_INTKEY 0x01
  48038. #define PTF_ZERODATA 0x02
  48039. #define PTF_LEAFDATA 0x04
  48040. #define PTF_LEAF 0x08
  48041. /*
  48042. ** As each page of the file is loaded into memory, an instance of the following
  48043. ** structure is appended and initialized to zero. This structure stores
  48044. ** information about the page that is decoded from the raw file page.
  48045. **
  48046. ** The pParent field points back to the parent page. This allows us to
  48047. ** walk up the BTree from any leaf to the root. Care must be taken to
  48048. ** unref() the parent page pointer when this page is no longer referenced.
  48049. ** The pageDestructor() routine handles that chore.
  48050. **
  48051. ** Access to all fields of this structure is controlled by the mutex
  48052. ** stored in MemPage.pBt->mutex.
  48053. */
  48054. struct MemPage {
  48055. u8 isInit; /* True if previously initialized. MUST BE FIRST! */
  48056. u8 nOverflow; /* Number of overflow cell bodies in aCell[] */
  48057. u8 intKey; /* True if table b-trees. False for index b-trees */
  48058. u8 intKeyLeaf; /* True if the leaf of an intKey table */
  48059. u8 noPayload; /* True if internal intKey page (thus w/o data) */
  48060. u8 leaf; /* True if a leaf page */
  48061. u8 hdrOffset; /* 100 for page 1. 0 otherwise */
  48062. u8 childPtrSize; /* 0 if leaf==1. 4 if leaf==0 */
  48063. u8 max1bytePayload; /* min(maxLocal,127) */
  48064. u16 maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
  48065. u16 minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
  48066. u16 cellOffset; /* Index in aData of first cell pointer */
  48067. u16 nFree; /* Number of free bytes on the page */
  48068. u16 nCell; /* Number of cells on this page, local and ovfl */
  48069. u16 maskPage; /* Mask for page offset */
  48070. u16 aiOvfl[5]; /* Insert the i-th overflow cell before the aiOvfl-th
  48071. ** non-overflow cell */
  48072. u8 *apOvfl[5]; /* Pointers to the body of overflow cells */
  48073. BtShared *pBt; /* Pointer to BtShared that this page is part of */
  48074. u8 *aData; /* Pointer to disk image of the page data */
  48075. u8 *aDataEnd; /* One byte past the end of usable data */
  48076. u8 *aCellIdx; /* The cell index area */
  48077. DbPage *pDbPage; /* Pager page handle */
  48078. Pgno pgno; /* Page number for this page */
  48079. };
  48080. /*
  48081. ** The in-memory image of a disk page has the auxiliary information appended
  48082. ** to the end. EXTRA_SIZE is the number of bytes of space needed to hold
  48083. ** that extra information.
  48084. */
  48085. #define EXTRA_SIZE sizeof(MemPage)
  48086. /*
  48087. ** A linked list of the following structures is stored at BtShared.pLock.
  48088. ** Locks are added (or upgraded from READ_LOCK to WRITE_LOCK) when a cursor
  48089. ** is opened on the table with root page BtShared.iTable. Locks are removed
  48090. ** from this list when a transaction is committed or rolled back, or when
  48091. ** a btree handle is closed.
  48092. */
  48093. struct BtLock {
  48094. Btree *pBtree; /* Btree handle holding this lock */
  48095. Pgno iTable; /* Root page of table */
  48096. u8 eLock; /* READ_LOCK or WRITE_LOCK */
  48097. BtLock *pNext; /* Next in BtShared.pLock list */
  48098. };
  48099. /* Candidate values for BtLock.eLock */
  48100. #define READ_LOCK 1
  48101. #define WRITE_LOCK 2
  48102. /* A Btree handle
  48103. **
  48104. ** A database connection contains a pointer to an instance of
  48105. ** this object for every database file that it has open. This structure
  48106. ** is opaque to the database connection. The database connection cannot
  48107. ** see the internals of this structure and only deals with pointers to
  48108. ** this structure.
  48109. **
  48110. ** For some database files, the same underlying database cache might be
  48111. ** shared between multiple connections. In that case, each connection
  48112. ** has it own instance of this object. But each instance of this object
  48113. ** points to the same BtShared object. The database cache and the
  48114. ** schema associated with the database file are all contained within
  48115. ** the BtShared object.
  48116. **
  48117. ** All fields in this structure are accessed under sqlite3.mutex.
  48118. ** The pBt pointer itself may not be changed while there exists cursors
  48119. ** in the referenced BtShared that point back to this Btree since those
  48120. ** cursors have to go through this Btree to find their BtShared and
  48121. ** they often do so without holding sqlite3.mutex.
  48122. */
  48123. struct Btree {
  48124. sqlite3 *db; /* The database connection holding this btree */
  48125. BtShared *pBt; /* Sharable content of this btree */
  48126. u8 inTrans; /* TRANS_NONE, TRANS_READ or TRANS_WRITE */
  48127. u8 sharable; /* True if we can share pBt with another db */
  48128. u8 locked; /* True if db currently has pBt locked */
  48129. int wantToLock; /* Number of nested calls to sqlite3BtreeEnter() */
  48130. int nBackup; /* Number of backup operations reading this btree */
  48131. Btree *pNext; /* List of other sharable Btrees from the same db */
  48132. Btree *pPrev; /* Back pointer of the same list */
  48133. #ifndef SQLITE_OMIT_SHARED_CACHE
  48134. BtLock lock; /* Object used to lock page 1 */
  48135. #endif
  48136. };
  48137. /*
  48138. ** Btree.inTrans may take one of the following values.
  48139. **
  48140. ** If the shared-data extension is enabled, there may be multiple users
  48141. ** of the Btree structure. At most one of these may open a write transaction,
  48142. ** but any number may have active read transactions.
  48143. */
  48144. #define TRANS_NONE 0
  48145. #define TRANS_READ 1
  48146. #define TRANS_WRITE 2
  48147. /*
  48148. ** An instance of this object represents a single database file.
  48149. **
  48150. ** A single database file can be in use at the same time by two
  48151. ** or more database connections. When two or more connections are
  48152. ** sharing the same database file, each connection has it own
  48153. ** private Btree object for the file and each of those Btrees points
  48154. ** to this one BtShared object. BtShared.nRef is the number of
  48155. ** connections currently sharing this database file.
  48156. **
  48157. ** Fields in this structure are accessed under the BtShared.mutex
  48158. ** mutex, except for nRef and pNext which are accessed under the
  48159. ** global SQLITE_MUTEX_STATIC_MASTER mutex. The pPager field
  48160. ** may not be modified once it is initially set as long as nRef>0.
  48161. ** The pSchema field may be set once under BtShared.mutex and
  48162. ** thereafter is unchanged as long as nRef>0.
  48163. **
  48164. ** isPending:
  48165. **
  48166. ** If a BtShared client fails to obtain a write-lock on a database
  48167. ** table (because there exists one or more read-locks on the table),
  48168. ** the shared-cache enters 'pending-lock' state and isPending is
  48169. ** set to true.
  48170. **
  48171. ** The shared-cache leaves the 'pending lock' state when either of
  48172. ** the following occur:
  48173. **
  48174. ** 1) The current writer (BtShared.pWriter) concludes its transaction, OR
  48175. ** 2) The number of locks held by other connections drops to zero.
  48176. **
  48177. ** while in the 'pending-lock' state, no connection may start a new
  48178. ** transaction.
  48179. **
  48180. ** This feature is included to help prevent writer-starvation.
  48181. */
  48182. struct BtShared {
  48183. Pager *pPager; /* The page cache */
  48184. sqlite3 *db; /* Database connection currently using this Btree */
  48185. BtCursor *pCursor; /* A list of all open cursors */
  48186. MemPage *pPage1; /* First page of the database */
  48187. u8 openFlags; /* Flags to sqlite3BtreeOpen() */
  48188. #ifndef SQLITE_OMIT_AUTOVACUUM
  48189. u8 autoVacuum; /* True if auto-vacuum is enabled */
  48190. u8 incrVacuum; /* True if incr-vacuum is enabled */
  48191. u8 bDoTruncate; /* True to truncate db on commit */
  48192. #endif
  48193. u8 inTransaction; /* Transaction state */
  48194. u8 max1bytePayload; /* Maximum first byte of cell for a 1-byte payload */
  48195. u16 btsFlags; /* Boolean parameters. See BTS_* macros below */
  48196. u16 maxLocal; /* Maximum local payload in non-LEAFDATA tables */
  48197. u16 minLocal; /* Minimum local payload in non-LEAFDATA tables */
  48198. u16 maxLeaf; /* Maximum local payload in a LEAFDATA table */
  48199. u16 minLeaf; /* Minimum local payload in a LEAFDATA table */
  48200. u32 pageSize; /* Total number of bytes on a page */
  48201. u32 usableSize; /* Number of usable bytes on each page */
  48202. int nTransaction; /* Number of open transactions (read + write) */
  48203. u32 nPage; /* Number of pages in the database */
  48204. void *pSchema; /* Pointer to space allocated by sqlite3BtreeSchema() */
  48205. void (*xFreeSchema)(void*); /* Destructor for BtShared.pSchema */
  48206. sqlite3_mutex *mutex; /* Non-recursive mutex required to access this object */
  48207. Bitvec *pHasContent; /* Set of pages moved to free-list this transaction */
  48208. #ifndef SQLITE_OMIT_SHARED_CACHE
  48209. int nRef; /* Number of references to this structure */
  48210. BtShared *pNext; /* Next on a list of sharable BtShared structs */
  48211. BtLock *pLock; /* List of locks held on this shared-btree struct */
  48212. Btree *pWriter; /* Btree with currently open write transaction */
  48213. #endif
  48214. u8 *pTmpSpace; /* Temp space sufficient to hold a single cell */
  48215. };
  48216. /*
  48217. ** Allowed values for BtShared.btsFlags
  48218. */
  48219. #define BTS_READ_ONLY 0x0001 /* Underlying file is readonly */
  48220. #define BTS_PAGESIZE_FIXED 0x0002 /* Page size can no longer be changed */
  48221. #define BTS_SECURE_DELETE 0x0004 /* PRAGMA secure_delete is enabled */
  48222. #define BTS_INITIALLY_EMPTY 0x0008 /* Database was empty at trans start */
  48223. #define BTS_NO_WAL 0x0010 /* Do not open write-ahead-log files */
  48224. #define BTS_EXCLUSIVE 0x0020 /* pWriter has an exclusive lock */
  48225. #define BTS_PENDING 0x0040 /* Waiting for read-locks to clear */
  48226. /*
  48227. ** An instance of the following structure is used to hold information
  48228. ** about a cell. The parseCellPtr() function fills in this structure
  48229. ** based on information extract from the raw disk page.
  48230. */
  48231. typedef struct CellInfo CellInfo;
  48232. struct CellInfo {
  48233. i64 nKey; /* The key for INTKEY tables, or nPayload otherwise */
  48234. u8 *pPayload; /* Pointer to the start of payload */
  48235. u32 nPayload; /* Bytes of payload */
  48236. u16 nLocal; /* Amount of payload held locally, not on overflow */
  48237. u16 iOverflow; /* Offset to overflow page number. Zero if no overflow */
  48238. u16 nSize; /* Size of the cell content on the main b-tree page */
  48239. };
  48240. /*
  48241. ** Maximum depth of an SQLite B-Tree structure. Any B-Tree deeper than
  48242. ** this will be declared corrupt. This value is calculated based on a
  48243. ** maximum database size of 2^31 pages a minimum fanout of 2 for a
  48244. ** root-node and 3 for all other internal nodes.
  48245. **
  48246. ** If a tree that appears to be taller than this is encountered, it is
  48247. ** assumed that the database is corrupt.
  48248. */
  48249. #define BTCURSOR_MAX_DEPTH 20
  48250. /*
  48251. ** A cursor is a pointer to a particular entry within a particular
  48252. ** b-tree within a database file.
  48253. **
  48254. ** The entry is identified by its MemPage and the index in
  48255. ** MemPage.aCell[] of the entry.
  48256. **
  48257. ** A single database file can be shared by two more database connections,
  48258. ** but cursors cannot be shared. Each cursor is associated with a
  48259. ** particular database connection identified BtCursor.pBtree.db.
  48260. **
  48261. ** Fields in this structure are accessed under the BtShared.mutex
  48262. ** found at self->pBt->mutex.
  48263. **
  48264. ** skipNext meaning:
  48265. ** eState==SKIPNEXT && skipNext>0: Next sqlite3BtreeNext() is no-op.
  48266. ** eState==SKIPNEXT && skipNext<0: Next sqlite3BtreePrevious() is no-op.
  48267. ** eState==FAULT: Cursor fault with skipNext as error code.
  48268. */
  48269. struct BtCursor {
  48270. Btree *pBtree; /* The Btree to which this cursor belongs */
  48271. BtShared *pBt; /* The BtShared this cursor points to */
  48272. BtCursor *pNext, *pPrev; /* Forms a linked list of all cursors */
  48273. struct KeyInfo *pKeyInfo; /* Argument passed to comparison function */
  48274. Pgno *aOverflow; /* Cache of overflow page locations */
  48275. CellInfo info; /* A parse of the cell we are pointing at */
  48276. i64 nKey; /* Size of pKey, or last integer key */
  48277. void *pKey; /* Saved key that was cursor last known position */
  48278. Pgno pgnoRoot; /* The root page of this tree */
  48279. int nOvflAlloc; /* Allocated size of aOverflow[] array */
  48280. int skipNext; /* Prev() is noop if negative. Next() is noop if positive.
  48281. ** Error code if eState==CURSOR_FAULT */
  48282. u8 curFlags; /* zero or more BTCF_* flags defined below */
  48283. u8 eState; /* One of the CURSOR_XXX constants (see below) */
  48284. u8 hints; /* As configured by CursorSetHints() */
  48285. i16 iPage; /* Index of current page in apPage */
  48286. u16 aiIdx[BTCURSOR_MAX_DEPTH]; /* Current index in apPage[i] */
  48287. MemPage *apPage[BTCURSOR_MAX_DEPTH]; /* Pages from root to current page */
  48288. };
  48289. /*
  48290. ** Legal values for BtCursor.curFlags
  48291. */
  48292. #define BTCF_WriteFlag 0x01 /* True if a write cursor */
  48293. #define BTCF_ValidNKey 0x02 /* True if info.nKey is valid */
  48294. #define BTCF_ValidOvfl 0x04 /* True if aOverflow is valid */
  48295. #define BTCF_AtLast 0x08 /* Cursor is pointing ot the last entry */
  48296. #define BTCF_Incrblob 0x10 /* True if an incremental I/O handle */
  48297. /*
  48298. ** Potential values for BtCursor.eState.
  48299. **
  48300. ** CURSOR_INVALID:
  48301. ** Cursor does not point to a valid entry. This can happen (for example)
  48302. ** because the table is empty or because BtreeCursorFirst() has not been
  48303. ** called.
  48304. **
  48305. ** CURSOR_VALID:
  48306. ** Cursor points to a valid entry. getPayload() etc. may be called.
  48307. **
  48308. ** CURSOR_SKIPNEXT:
  48309. ** Cursor is valid except that the Cursor.skipNext field is non-zero
  48310. ** indicating that the next sqlite3BtreeNext() or sqlite3BtreePrevious()
  48311. ** operation should be a no-op.
  48312. **
  48313. ** CURSOR_REQUIRESEEK:
  48314. ** The table that this cursor was opened on still exists, but has been
  48315. ** modified since the cursor was last used. The cursor position is saved
  48316. ** in variables BtCursor.pKey and BtCursor.nKey. When a cursor is in
  48317. ** this state, restoreCursorPosition() can be called to attempt to
  48318. ** seek the cursor to the saved position.
  48319. **
  48320. ** CURSOR_FAULT:
  48321. ** An unrecoverable error (an I/O error or a malloc failure) has occurred
  48322. ** on a different connection that shares the BtShared cache with this
  48323. ** cursor. The error has left the cache in an inconsistent state.
  48324. ** Do nothing else with this cursor. Any attempt to use the cursor
  48325. ** should return the error code stored in BtCursor.skipNext
  48326. */
  48327. #define CURSOR_INVALID 0
  48328. #define CURSOR_VALID 1
  48329. #define CURSOR_SKIPNEXT 2
  48330. #define CURSOR_REQUIRESEEK 3
  48331. #define CURSOR_FAULT 4
  48332. /*
  48333. ** The database page the PENDING_BYTE occupies. This page is never used.
  48334. */
  48335. # define PENDING_BYTE_PAGE(pBt) PAGER_MJ_PGNO(pBt)
  48336. /*
  48337. ** These macros define the location of the pointer-map entry for a
  48338. ** database page. The first argument to each is the number of usable
  48339. ** bytes on each page of the database (often 1024). The second is the
  48340. ** page number to look up in the pointer map.
  48341. **
  48342. ** PTRMAP_PAGENO returns the database page number of the pointer-map
  48343. ** page that stores the required pointer. PTRMAP_PTROFFSET returns
  48344. ** the offset of the requested map entry.
  48345. **
  48346. ** If the pgno argument passed to PTRMAP_PAGENO is a pointer-map page,
  48347. ** then pgno is returned. So (pgno==PTRMAP_PAGENO(pgsz, pgno)) can be
  48348. ** used to test if pgno is a pointer-map page. PTRMAP_ISPAGE implements
  48349. ** this test.
  48350. */
  48351. #define PTRMAP_PAGENO(pBt, pgno) ptrmapPageno(pBt, pgno)
  48352. #define PTRMAP_PTROFFSET(pgptrmap, pgno) (5*(pgno-pgptrmap-1))
  48353. #define PTRMAP_ISPAGE(pBt, pgno) (PTRMAP_PAGENO((pBt),(pgno))==(pgno))
  48354. /*
  48355. ** The pointer map is a lookup table that identifies the parent page for
  48356. ** each child page in the database file. The parent page is the page that
  48357. ** contains a pointer to the child. Every page in the database contains
  48358. ** 0 or 1 parent pages. (In this context 'database page' refers
  48359. ** to any page that is not part of the pointer map itself.) Each pointer map
  48360. ** entry consists of a single byte 'type' and a 4 byte parent page number.
  48361. ** The PTRMAP_XXX identifiers below are the valid types.
  48362. **
  48363. ** The purpose of the pointer map is to facility moving pages from one
  48364. ** position in the file to another as part of autovacuum. When a page
  48365. ** is moved, the pointer in its parent must be updated to point to the
  48366. ** new location. The pointer map is used to locate the parent page quickly.
  48367. **
  48368. ** PTRMAP_ROOTPAGE: The database page is a root-page. The page-number is not
  48369. ** used in this case.
  48370. **
  48371. ** PTRMAP_FREEPAGE: The database page is an unused (free) page. The page-number
  48372. ** is not used in this case.
  48373. **
  48374. ** PTRMAP_OVERFLOW1: The database page is the first page in a list of
  48375. ** overflow pages. The page number identifies the page that
  48376. ** contains the cell with a pointer to this overflow page.
  48377. **
  48378. ** PTRMAP_OVERFLOW2: The database page is the second or later page in a list of
  48379. ** overflow pages. The page-number identifies the previous
  48380. ** page in the overflow page list.
  48381. **
  48382. ** PTRMAP_BTREE: The database page is a non-root btree page. The page number
  48383. ** identifies the parent page in the btree.
  48384. */
  48385. #define PTRMAP_ROOTPAGE 1
  48386. #define PTRMAP_FREEPAGE 2
  48387. #define PTRMAP_OVERFLOW1 3
  48388. #define PTRMAP_OVERFLOW2 4
  48389. #define PTRMAP_BTREE 5
  48390. /* A bunch of assert() statements to check the transaction state variables
  48391. ** of handle p (type Btree*) are internally consistent.
  48392. */
  48393. #define btreeIntegrity(p) \
  48394. assert( p->pBt->inTransaction!=TRANS_NONE || p->pBt->nTransaction==0 ); \
  48395. assert( p->pBt->inTransaction>=p->inTrans );
  48396. /*
  48397. ** The ISAUTOVACUUM macro is used within balance_nonroot() to determine
  48398. ** if the database supports auto-vacuum or not. Because it is used
  48399. ** within an expression that is an argument to another macro
  48400. ** (sqliteMallocRaw), it is not possible to use conditional compilation.
  48401. ** So, this macro is defined instead.
  48402. */
  48403. #ifndef SQLITE_OMIT_AUTOVACUUM
  48404. #define ISAUTOVACUUM (pBt->autoVacuum)
  48405. #else
  48406. #define ISAUTOVACUUM 0
  48407. #endif
  48408. /*
  48409. ** This structure is passed around through all the sanity checking routines
  48410. ** in order to keep track of some global state information.
  48411. **
  48412. ** The aRef[] array is allocated so that there is 1 bit for each page in
  48413. ** the database. As the integrity-check proceeds, for each page used in
  48414. ** the database the corresponding bit is set. This allows integrity-check to
  48415. ** detect pages that are used twice and orphaned pages (both of which
  48416. ** indicate corruption).
  48417. */
  48418. typedef struct IntegrityCk IntegrityCk;
  48419. struct IntegrityCk {
  48420. BtShared *pBt; /* The tree being checked out */
  48421. Pager *pPager; /* The associated pager. Also accessible by pBt->pPager */
  48422. u8 *aPgRef; /* 1 bit per page in the db (see above) */
  48423. Pgno nPage; /* Number of pages in the database */
  48424. int mxErr; /* Stop accumulating errors when this reaches zero */
  48425. int nErr; /* Number of messages written to zErrMsg so far */
  48426. int mallocFailed; /* A memory allocation error has occurred */
  48427. const char *zPfx; /* Error message prefix */
  48428. int v1, v2; /* Values for up to two %d fields in zPfx */
  48429. StrAccum errMsg; /* Accumulate the error message text here */
  48430. };
  48431. /*
  48432. ** Routines to read or write a two- and four-byte big-endian integer values.
  48433. */
  48434. #define get2byte(x) ((x)[0]<<8 | (x)[1])
  48435. #define put2byte(p,v) ((p)[0] = (u8)((v)>>8), (p)[1] = (u8)(v))
  48436. #define get4byte sqlite3Get4byte
  48437. #define put4byte sqlite3Put4byte
  48438. /************** End of btreeInt.h ********************************************/
  48439. /************** Continuing where we left off in btmutex.c ********************/
  48440. #ifndef SQLITE_OMIT_SHARED_CACHE
  48441. #if SQLITE_THREADSAFE
  48442. /*
  48443. ** Obtain the BtShared mutex associated with B-Tree handle p. Also,
  48444. ** set BtShared.db to the database handle associated with p and the
  48445. ** p->locked boolean to true.
  48446. */
  48447. static void lockBtreeMutex(Btree *p){
  48448. assert( p->locked==0 );
  48449. assert( sqlite3_mutex_notheld(p->pBt->mutex) );
  48450. assert( sqlite3_mutex_held(p->db->mutex) );
  48451. sqlite3_mutex_enter(p->pBt->mutex);
  48452. p->pBt->db = p->db;
  48453. p->locked = 1;
  48454. }
  48455. /*
  48456. ** Release the BtShared mutex associated with B-Tree handle p and
  48457. ** clear the p->locked boolean.
  48458. */
  48459. static void SQLITE_NOINLINE unlockBtreeMutex(Btree *p){
  48460. BtShared *pBt = p->pBt;
  48461. assert( p->locked==1 );
  48462. assert( sqlite3_mutex_held(pBt->mutex) );
  48463. assert( sqlite3_mutex_held(p->db->mutex) );
  48464. assert( p->db==pBt->db );
  48465. sqlite3_mutex_leave(pBt->mutex);
  48466. p->locked = 0;
  48467. }
  48468. /* Forward reference */
  48469. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p);
  48470. /*
  48471. ** Enter a mutex on the given BTree object.
  48472. **
  48473. ** If the object is not sharable, then no mutex is ever required
  48474. ** and this routine is a no-op. The underlying mutex is non-recursive.
  48475. ** But we keep a reference count in Btree.wantToLock so the behavior
  48476. ** of this interface is recursive.
  48477. **
  48478. ** To avoid deadlocks, multiple Btrees are locked in the same order
  48479. ** by all database connections. The p->pNext is a list of other
  48480. ** Btrees belonging to the same database connection as the p Btree
  48481. ** which need to be locked after p. If we cannot get a lock on
  48482. ** p, then first unlock all of the others on p->pNext, then wait
  48483. ** for the lock to become available on p, then relock all of the
  48484. ** subsequent Btrees that desire a lock.
  48485. */
  48486. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  48487. /* Some basic sanity checking on the Btree. The list of Btrees
  48488. ** connected by pNext and pPrev should be in sorted order by
  48489. ** Btree.pBt value. All elements of the list should belong to
  48490. ** the same connection. Only shared Btrees are on the list. */
  48491. assert( p->pNext==0 || p->pNext->pBt>p->pBt );
  48492. assert( p->pPrev==0 || p->pPrev->pBt<p->pBt );
  48493. assert( p->pNext==0 || p->pNext->db==p->db );
  48494. assert( p->pPrev==0 || p->pPrev->db==p->db );
  48495. assert( p->sharable || (p->pNext==0 && p->pPrev==0) );
  48496. /* Check for locking consistency */
  48497. assert( !p->locked || p->wantToLock>0 );
  48498. assert( p->sharable || p->wantToLock==0 );
  48499. /* We should already hold a lock on the database connection */
  48500. assert( sqlite3_mutex_held(p->db->mutex) );
  48501. /* Unless the database is sharable and unlocked, then BtShared.db
  48502. ** should already be set correctly. */
  48503. assert( (p->locked==0 && p->sharable) || p->pBt->db==p->db );
  48504. if( !p->sharable ) return;
  48505. p->wantToLock++;
  48506. if( p->locked ) return;
  48507. btreeLockCarefully(p);
  48508. }
  48509. /* This is a helper function for sqlite3BtreeLock(). By moving
  48510. ** complex, but seldom used logic, out of sqlite3BtreeLock() and
  48511. ** into this routine, we avoid unnecessary stack pointer changes
  48512. ** and thus help the sqlite3BtreeLock() routine to run much faster
  48513. ** in the common case.
  48514. */
  48515. static void SQLITE_NOINLINE btreeLockCarefully(Btree *p){
  48516. Btree *pLater;
  48517. /* In most cases, we should be able to acquire the lock we
  48518. ** want without having to go through the ascending lock
  48519. ** procedure that follows. Just be sure not to block.
  48520. */
  48521. if( sqlite3_mutex_try(p->pBt->mutex)==SQLITE_OK ){
  48522. p->pBt->db = p->db;
  48523. p->locked = 1;
  48524. return;
  48525. }
  48526. /* To avoid deadlock, first release all locks with a larger
  48527. ** BtShared address. Then acquire our lock. Then reacquire
  48528. ** the other BtShared locks that we used to hold in ascending
  48529. ** order.
  48530. */
  48531. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  48532. assert( pLater->sharable );
  48533. assert( pLater->pNext==0 || pLater->pNext->pBt>pLater->pBt );
  48534. assert( !pLater->locked || pLater->wantToLock>0 );
  48535. if( pLater->locked ){
  48536. unlockBtreeMutex(pLater);
  48537. }
  48538. }
  48539. lockBtreeMutex(p);
  48540. for(pLater=p->pNext; pLater; pLater=pLater->pNext){
  48541. if( pLater->wantToLock ){
  48542. lockBtreeMutex(pLater);
  48543. }
  48544. }
  48545. }
  48546. /*
  48547. ** Exit the recursive mutex on a Btree.
  48548. */
  48549. SQLITE_PRIVATE void sqlite3BtreeLeave(Btree *p){
  48550. if( p->sharable ){
  48551. assert( p->wantToLock>0 );
  48552. p->wantToLock--;
  48553. if( p->wantToLock==0 ){
  48554. unlockBtreeMutex(p);
  48555. }
  48556. }
  48557. }
  48558. #ifndef NDEBUG
  48559. /*
  48560. ** Return true if the BtShared mutex is held on the btree, or if the
  48561. ** B-Tree is not marked as sharable.
  48562. **
  48563. ** This routine is used only from within assert() statements.
  48564. */
  48565. SQLITE_PRIVATE int sqlite3BtreeHoldsMutex(Btree *p){
  48566. assert( p->sharable==0 || p->locked==0 || p->wantToLock>0 );
  48567. assert( p->sharable==0 || p->locked==0 || p->db==p->pBt->db );
  48568. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->pBt->mutex) );
  48569. assert( p->sharable==0 || p->locked==0 || sqlite3_mutex_held(p->db->mutex) );
  48570. return (p->sharable==0 || p->locked);
  48571. }
  48572. #endif
  48573. #ifndef SQLITE_OMIT_INCRBLOB
  48574. /*
  48575. ** Enter and leave a mutex on a Btree given a cursor owned by that
  48576. ** Btree. These entry points are used by incremental I/O and can be
  48577. ** omitted if that module is not used.
  48578. */
  48579. SQLITE_PRIVATE void sqlite3BtreeEnterCursor(BtCursor *pCur){
  48580. sqlite3BtreeEnter(pCur->pBtree);
  48581. }
  48582. SQLITE_PRIVATE void sqlite3BtreeLeaveCursor(BtCursor *pCur){
  48583. sqlite3BtreeLeave(pCur->pBtree);
  48584. }
  48585. #endif /* SQLITE_OMIT_INCRBLOB */
  48586. /*
  48587. ** Enter the mutex on every Btree associated with a database
  48588. ** connection. This is needed (for example) prior to parsing
  48589. ** a statement since we will be comparing table and column names
  48590. ** against all schemas and we do not want those schemas being
  48591. ** reset out from under us.
  48592. **
  48593. ** There is a corresponding leave-all procedures.
  48594. **
  48595. ** Enter the mutexes in accending order by BtShared pointer address
  48596. ** to avoid the possibility of deadlock when two threads with
  48597. ** two or more btrees in common both try to lock all their btrees
  48598. ** at the same instant.
  48599. */
  48600. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  48601. int i;
  48602. Btree *p;
  48603. assert( sqlite3_mutex_held(db->mutex) );
  48604. for(i=0; i<db->nDb; i++){
  48605. p = db->aDb[i].pBt;
  48606. if( p ) sqlite3BtreeEnter(p);
  48607. }
  48608. }
  48609. SQLITE_PRIVATE void sqlite3BtreeLeaveAll(sqlite3 *db){
  48610. int i;
  48611. Btree *p;
  48612. assert( sqlite3_mutex_held(db->mutex) );
  48613. for(i=0; i<db->nDb; i++){
  48614. p = db->aDb[i].pBt;
  48615. if( p ) sqlite3BtreeLeave(p);
  48616. }
  48617. }
  48618. /*
  48619. ** Return true if a particular Btree requires a lock. Return FALSE if
  48620. ** no lock is ever required since it is not sharable.
  48621. */
  48622. SQLITE_PRIVATE int sqlite3BtreeSharable(Btree *p){
  48623. return p->sharable;
  48624. }
  48625. #ifndef NDEBUG
  48626. /*
  48627. ** Return true if the current thread holds the database connection
  48628. ** mutex and all required BtShared mutexes.
  48629. **
  48630. ** This routine is used inside assert() statements only.
  48631. */
  48632. SQLITE_PRIVATE int sqlite3BtreeHoldsAllMutexes(sqlite3 *db){
  48633. int i;
  48634. if( !sqlite3_mutex_held(db->mutex) ){
  48635. return 0;
  48636. }
  48637. for(i=0; i<db->nDb; i++){
  48638. Btree *p;
  48639. p = db->aDb[i].pBt;
  48640. if( p && p->sharable &&
  48641. (p->wantToLock==0 || !sqlite3_mutex_held(p->pBt->mutex)) ){
  48642. return 0;
  48643. }
  48644. }
  48645. return 1;
  48646. }
  48647. #endif /* NDEBUG */
  48648. #ifndef NDEBUG
  48649. /*
  48650. ** Return true if the correct mutexes are held for accessing the
  48651. ** db->aDb[iDb].pSchema structure. The mutexes required for schema
  48652. ** access are:
  48653. **
  48654. ** (1) The mutex on db
  48655. ** (2) if iDb!=1, then the mutex on db->aDb[iDb].pBt.
  48656. **
  48657. ** If pSchema is not NULL, then iDb is computed from pSchema and
  48658. ** db using sqlite3SchemaToIndex().
  48659. */
  48660. SQLITE_PRIVATE int sqlite3SchemaMutexHeld(sqlite3 *db, int iDb, Schema *pSchema){
  48661. Btree *p;
  48662. assert( db!=0 );
  48663. if( pSchema ) iDb = sqlite3SchemaToIndex(db, pSchema);
  48664. assert( iDb>=0 && iDb<db->nDb );
  48665. if( !sqlite3_mutex_held(db->mutex) ) return 0;
  48666. if( iDb==1 ) return 1;
  48667. p = db->aDb[iDb].pBt;
  48668. assert( p!=0 );
  48669. return p->sharable==0 || p->locked==1;
  48670. }
  48671. #endif /* NDEBUG */
  48672. #else /* SQLITE_THREADSAFE>0 above. SQLITE_THREADSAFE==0 below */
  48673. /*
  48674. ** The following are special cases for mutex enter routines for use
  48675. ** in single threaded applications that use shared cache. Except for
  48676. ** these two routines, all mutex operations are no-ops in that case and
  48677. ** are null #defines in btree.h.
  48678. **
  48679. ** If shared cache is disabled, then all btree mutex routines, including
  48680. ** the ones below, are no-ops and are null #defines in btree.h.
  48681. */
  48682. SQLITE_PRIVATE void sqlite3BtreeEnter(Btree *p){
  48683. p->pBt->db = p->db;
  48684. }
  48685. SQLITE_PRIVATE void sqlite3BtreeEnterAll(sqlite3 *db){
  48686. int i;
  48687. for(i=0; i<db->nDb; i++){
  48688. Btree *p = db->aDb[i].pBt;
  48689. if( p ){
  48690. p->pBt->db = p->db;
  48691. }
  48692. }
  48693. }
  48694. #endif /* if SQLITE_THREADSAFE */
  48695. #endif /* ifndef SQLITE_OMIT_SHARED_CACHE */
  48696. /************** End of btmutex.c *********************************************/
  48697. /************** Begin file btree.c *******************************************/
  48698. /*
  48699. ** 2004 April 6
  48700. **
  48701. ** The author disclaims copyright to this source code. In place of
  48702. ** a legal notice, here is a blessing:
  48703. **
  48704. ** May you do good and not evil.
  48705. ** May you find forgiveness for yourself and forgive others.
  48706. ** May you share freely, never taking more than you give.
  48707. **
  48708. *************************************************************************
  48709. ** This file implements an external (disk-based) database using BTrees.
  48710. ** See the header comment on "btreeInt.h" for additional information.
  48711. ** Including a description of file format and an overview of operation.
  48712. */
  48713. /*
  48714. ** The header string that appears at the beginning of every
  48715. ** SQLite database.
  48716. */
  48717. static const char zMagicHeader[] = SQLITE_FILE_HEADER;
  48718. /*
  48719. ** Set this global variable to 1 to enable tracing using the TRACE
  48720. ** macro.
  48721. */
  48722. #if 0
  48723. int sqlite3BtreeTrace=1; /* True to enable tracing */
  48724. # define TRACE(X) if(sqlite3BtreeTrace){printf X;fflush(stdout);}
  48725. #else
  48726. # define TRACE(X)
  48727. #endif
  48728. /*
  48729. ** Extract a 2-byte big-endian integer from an array of unsigned bytes.
  48730. ** But if the value is zero, make it 65536.
  48731. **
  48732. ** This routine is used to extract the "offset to cell content area" value
  48733. ** from the header of a btree page. If the page size is 65536 and the page
  48734. ** is empty, the offset should be 65536, but the 2-byte value stores zero.
  48735. ** This routine makes the necessary adjustment to 65536.
  48736. */
  48737. #define get2byteNotZero(X) (((((int)get2byte(X))-1)&0xffff)+1)
  48738. /*
  48739. ** Values passed as the 5th argument to allocateBtreePage()
  48740. */
  48741. #define BTALLOC_ANY 0 /* Allocate any page */
  48742. #define BTALLOC_EXACT 1 /* Allocate exact page if possible */
  48743. #define BTALLOC_LE 2 /* Allocate any page <= the parameter */
  48744. /*
  48745. ** Macro IfNotOmitAV(x) returns (x) if SQLITE_OMIT_AUTOVACUUM is not
  48746. ** defined, or 0 if it is. For example:
  48747. **
  48748. ** bIncrVacuum = IfNotOmitAV(pBtShared->incrVacuum);
  48749. */
  48750. #ifndef SQLITE_OMIT_AUTOVACUUM
  48751. #define IfNotOmitAV(expr) (expr)
  48752. #else
  48753. #define IfNotOmitAV(expr) 0
  48754. #endif
  48755. #ifndef SQLITE_OMIT_SHARED_CACHE
  48756. /*
  48757. ** A list of BtShared objects that are eligible for participation
  48758. ** in shared cache. This variable has file scope during normal builds,
  48759. ** but the test harness needs to access it so we make it global for
  48760. ** test builds.
  48761. **
  48762. ** Access to this variable is protected by SQLITE_MUTEX_STATIC_MASTER.
  48763. */
  48764. #ifdef SQLITE_TEST
  48765. SQLITE_PRIVATE BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  48766. #else
  48767. static BtShared *SQLITE_WSD sqlite3SharedCacheList = 0;
  48768. #endif
  48769. #endif /* SQLITE_OMIT_SHARED_CACHE */
  48770. #ifndef SQLITE_OMIT_SHARED_CACHE
  48771. /*
  48772. ** Enable or disable the shared pager and schema features.
  48773. **
  48774. ** This routine has no effect on existing database connections.
  48775. ** The shared cache setting effects only future calls to
  48776. ** sqlite3_open(), sqlite3_open16(), or sqlite3_open_v2().
  48777. */
  48778. SQLITE_API int sqlite3_enable_shared_cache(int enable){
  48779. sqlite3GlobalConfig.sharedCacheEnabled = enable;
  48780. return SQLITE_OK;
  48781. }
  48782. #endif
  48783. #ifdef SQLITE_OMIT_SHARED_CACHE
  48784. /*
  48785. ** The functions querySharedCacheTableLock(), setSharedCacheTableLock(),
  48786. ** and clearAllSharedCacheTableLocks()
  48787. ** manipulate entries in the BtShared.pLock linked list used to store
  48788. ** shared-cache table level locks. If the library is compiled with the
  48789. ** shared-cache feature disabled, then there is only ever one user
  48790. ** of each BtShared structure and so this locking is not necessary.
  48791. ** So define the lock related functions as no-ops.
  48792. */
  48793. #define querySharedCacheTableLock(a,b,c) SQLITE_OK
  48794. #define setSharedCacheTableLock(a,b,c) SQLITE_OK
  48795. #define clearAllSharedCacheTableLocks(a)
  48796. #define downgradeAllSharedCacheTableLocks(a)
  48797. #define hasSharedCacheTableLock(a,b,c,d) 1
  48798. #define hasReadConflicts(a, b) 0
  48799. #endif
  48800. #ifndef SQLITE_OMIT_SHARED_CACHE
  48801. #ifdef SQLITE_DEBUG
  48802. /*
  48803. **** This function is only used as part of an assert() statement. ***
  48804. **
  48805. ** Check to see if pBtree holds the required locks to read or write to the
  48806. ** table with root page iRoot. Return 1 if it does and 0 if not.
  48807. **
  48808. ** For example, when writing to a table with root-page iRoot via
  48809. ** Btree connection pBtree:
  48810. **
  48811. ** assert( hasSharedCacheTableLock(pBtree, iRoot, 0, WRITE_LOCK) );
  48812. **
  48813. ** When writing to an index that resides in a sharable database, the
  48814. ** caller should have first obtained a lock specifying the root page of
  48815. ** the corresponding table. This makes things a bit more complicated,
  48816. ** as this module treats each table as a separate structure. To determine
  48817. ** the table corresponding to the index being written, this
  48818. ** function has to search through the database schema.
  48819. **
  48820. ** Instead of a lock on the table/index rooted at page iRoot, the caller may
  48821. ** hold a write-lock on the schema table (root page 1). This is also
  48822. ** acceptable.
  48823. */
  48824. static int hasSharedCacheTableLock(
  48825. Btree *pBtree, /* Handle that must hold lock */
  48826. Pgno iRoot, /* Root page of b-tree */
  48827. int isIndex, /* True if iRoot is the root of an index b-tree */
  48828. int eLockType /* Required lock type (READ_LOCK or WRITE_LOCK) */
  48829. ){
  48830. Schema *pSchema = (Schema *)pBtree->pBt->pSchema;
  48831. Pgno iTab = 0;
  48832. BtLock *pLock;
  48833. /* If this database is not shareable, or if the client is reading
  48834. ** and has the read-uncommitted flag set, then no lock is required.
  48835. ** Return true immediately.
  48836. */
  48837. if( (pBtree->sharable==0)
  48838. || (eLockType==READ_LOCK && (pBtree->db->flags & SQLITE_ReadUncommitted))
  48839. ){
  48840. return 1;
  48841. }
  48842. /* If the client is reading or writing an index and the schema is
  48843. ** not loaded, then it is too difficult to actually check to see if
  48844. ** the correct locks are held. So do not bother - just return true.
  48845. ** This case does not come up very often anyhow.
  48846. */
  48847. if( isIndex && (!pSchema || (pSchema->schemaFlags&DB_SchemaLoaded)==0) ){
  48848. return 1;
  48849. }
  48850. /* Figure out the root-page that the lock should be held on. For table
  48851. ** b-trees, this is just the root page of the b-tree being read or
  48852. ** written. For index b-trees, it is the root page of the associated
  48853. ** table. */
  48854. if( isIndex ){
  48855. HashElem *p;
  48856. for(p=sqliteHashFirst(&pSchema->idxHash); p; p=sqliteHashNext(p)){
  48857. Index *pIdx = (Index *)sqliteHashData(p);
  48858. if( pIdx->tnum==(int)iRoot ){
  48859. iTab = pIdx->pTable->tnum;
  48860. }
  48861. }
  48862. }else{
  48863. iTab = iRoot;
  48864. }
  48865. /* Search for the required lock. Either a write-lock on root-page iTab, a
  48866. ** write-lock on the schema table, or (if the client is reading) a
  48867. ** read-lock on iTab will suffice. Return 1 if any of these are found. */
  48868. for(pLock=pBtree->pBt->pLock; pLock; pLock=pLock->pNext){
  48869. if( pLock->pBtree==pBtree
  48870. && (pLock->iTable==iTab || (pLock->eLock==WRITE_LOCK && pLock->iTable==1))
  48871. && pLock->eLock>=eLockType
  48872. ){
  48873. return 1;
  48874. }
  48875. }
  48876. /* Failed to find the required lock. */
  48877. return 0;
  48878. }
  48879. #endif /* SQLITE_DEBUG */
  48880. #ifdef SQLITE_DEBUG
  48881. /*
  48882. **** This function may be used as part of assert() statements only. ****
  48883. **
  48884. ** Return true if it would be illegal for pBtree to write into the
  48885. ** table or index rooted at iRoot because other shared connections are
  48886. ** simultaneously reading that same table or index.
  48887. **
  48888. ** It is illegal for pBtree to write if some other Btree object that
  48889. ** shares the same BtShared object is currently reading or writing
  48890. ** the iRoot table. Except, if the other Btree object has the
  48891. ** read-uncommitted flag set, then it is OK for the other object to
  48892. ** have a read cursor.
  48893. **
  48894. ** For example, before writing to any part of the table or index
  48895. ** rooted at page iRoot, one should call:
  48896. **
  48897. ** assert( !hasReadConflicts(pBtree, iRoot) );
  48898. */
  48899. static int hasReadConflicts(Btree *pBtree, Pgno iRoot){
  48900. BtCursor *p;
  48901. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  48902. if( p->pgnoRoot==iRoot
  48903. && p->pBtree!=pBtree
  48904. && 0==(p->pBtree->db->flags & SQLITE_ReadUncommitted)
  48905. ){
  48906. return 1;
  48907. }
  48908. }
  48909. return 0;
  48910. }
  48911. #endif /* #ifdef SQLITE_DEBUG */
  48912. /*
  48913. ** Query to see if Btree handle p may obtain a lock of type eLock
  48914. ** (READ_LOCK or WRITE_LOCK) on the table with root-page iTab. Return
  48915. ** SQLITE_OK if the lock may be obtained (by calling
  48916. ** setSharedCacheTableLock()), or SQLITE_LOCKED if not.
  48917. */
  48918. static int querySharedCacheTableLock(Btree *p, Pgno iTab, u8 eLock){
  48919. BtShared *pBt = p->pBt;
  48920. BtLock *pIter;
  48921. assert( sqlite3BtreeHoldsMutex(p) );
  48922. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  48923. assert( p->db!=0 );
  48924. assert( !(p->db->flags&SQLITE_ReadUncommitted)||eLock==WRITE_LOCK||iTab==1 );
  48925. /* If requesting a write-lock, then the Btree must have an open write
  48926. ** transaction on this file. And, obviously, for this to be so there
  48927. ** must be an open write transaction on the file itself.
  48928. */
  48929. assert( eLock==READ_LOCK || (p==pBt->pWriter && p->inTrans==TRANS_WRITE) );
  48930. assert( eLock==READ_LOCK || pBt->inTransaction==TRANS_WRITE );
  48931. /* This routine is a no-op if the shared-cache is not enabled */
  48932. if( !p->sharable ){
  48933. return SQLITE_OK;
  48934. }
  48935. /* If some other connection is holding an exclusive lock, the
  48936. ** requested lock may not be obtained.
  48937. */
  48938. if( pBt->pWriter!=p && (pBt->btsFlags & BTS_EXCLUSIVE)!=0 ){
  48939. sqlite3ConnectionBlocked(p->db, pBt->pWriter->db);
  48940. return SQLITE_LOCKED_SHAREDCACHE;
  48941. }
  48942. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  48943. /* The condition (pIter->eLock!=eLock) in the following if(...)
  48944. ** statement is a simplification of:
  48945. **
  48946. ** (eLock==WRITE_LOCK || pIter->eLock==WRITE_LOCK)
  48947. **
  48948. ** since we know that if eLock==WRITE_LOCK, then no other connection
  48949. ** may hold a WRITE_LOCK on any table in this file (since there can
  48950. ** only be a single writer).
  48951. */
  48952. assert( pIter->eLock==READ_LOCK || pIter->eLock==WRITE_LOCK );
  48953. assert( eLock==READ_LOCK || pIter->pBtree==p || pIter->eLock==READ_LOCK);
  48954. if( pIter->pBtree!=p && pIter->iTable==iTab && pIter->eLock!=eLock ){
  48955. sqlite3ConnectionBlocked(p->db, pIter->pBtree->db);
  48956. if( eLock==WRITE_LOCK ){
  48957. assert( p==pBt->pWriter );
  48958. pBt->btsFlags |= BTS_PENDING;
  48959. }
  48960. return SQLITE_LOCKED_SHAREDCACHE;
  48961. }
  48962. }
  48963. return SQLITE_OK;
  48964. }
  48965. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  48966. #ifndef SQLITE_OMIT_SHARED_CACHE
  48967. /*
  48968. ** Add a lock on the table with root-page iTable to the shared-btree used
  48969. ** by Btree handle p. Parameter eLock must be either READ_LOCK or
  48970. ** WRITE_LOCK.
  48971. **
  48972. ** This function assumes the following:
  48973. **
  48974. ** (a) The specified Btree object p is connected to a sharable
  48975. ** database (one with the BtShared.sharable flag set), and
  48976. **
  48977. ** (b) No other Btree objects hold a lock that conflicts
  48978. ** with the requested lock (i.e. querySharedCacheTableLock() has
  48979. ** already been called and returned SQLITE_OK).
  48980. **
  48981. ** SQLITE_OK is returned if the lock is added successfully. SQLITE_NOMEM
  48982. ** is returned if a malloc attempt fails.
  48983. */
  48984. static int setSharedCacheTableLock(Btree *p, Pgno iTable, u8 eLock){
  48985. BtShared *pBt = p->pBt;
  48986. BtLock *pLock = 0;
  48987. BtLock *pIter;
  48988. assert( sqlite3BtreeHoldsMutex(p) );
  48989. assert( eLock==READ_LOCK || eLock==WRITE_LOCK );
  48990. assert( p->db!=0 );
  48991. /* A connection with the read-uncommitted flag set will never try to
  48992. ** obtain a read-lock using this function. The only read-lock obtained
  48993. ** by a connection in read-uncommitted mode is on the sqlite_master
  48994. ** table, and that lock is obtained in BtreeBeginTrans(). */
  48995. assert( 0==(p->db->flags&SQLITE_ReadUncommitted) || eLock==WRITE_LOCK );
  48996. /* This function should only be called on a sharable b-tree after it
  48997. ** has been determined that no other b-tree holds a conflicting lock. */
  48998. assert( p->sharable );
  48999. assert( SQLITE_OK==querySharedCacheTableLock(p, iTable, eLock) );
  49000. /* First search the list for an existing lock on this table. */
  49001. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  49002. if( pIter->iTable==iTable && pIter->pBtree==p ){
  49003. pLock = pIter;
  49004. break;
  49005. }
  49006. }
  49007. /* If the above search did not find a BtLock struct associating Btree p
  49008. ** with table iTable, allocate one and link it into the list.
  49009. */
  49010. if( !pLock ){
  49011. pLock = (BtLock *)sqlite3MallocZero(sizeof(BtLock));
  49012. if( !pLock ){
  49013. return SQLITE_NOMEM;
  49014. }
  49015. pLock->iTable = iTable;
  49016. pLock->pBtree = p;
  49017. pLock->pNext = pBt->pLock;
  49018. pBt->pLock = pLock;
  49019. }
  49020. /* Set the BtLock.eLock variable to the maximum of the current lock
  49021. ** and the requested lock. This means if a write-lock was already held
  49022. ** and a read-lock requested, we don't incorrectly downgrade the lock.
  49023. */
  49024. assert( WRITE_LOCK>READ_LOCK );
  49025. if( eLock>pLock->eLock ){
  49026. pLock->eLock = eLock;
  49027. }
  49028. return SQLITE_OK;
  49029. }
  49030. #endif /* !SQLITE_OMIT_SHARED_CACHE */
  49031. #ifndef SQLITE_OMIT_SHARED_CACHE
  49032. /*
  49033. ** Release all the table locks (locks obtained via calls to
  49034. ** the setSharedCacheTableLock() procedure) held by Btree object p.
  49035. **
  49036. ** This function assumes that Btree p has an open read or write
  49037. ** transaction. If it does not, then the BTS_PENDING flag
  49038. ** may be incorrectly cleared.
  49039. */
  49040. static void clearAllSharedCacheTableLocks(Btree *p){
  49041. BtShared *pBt = p->pBt;
  49042. BtLock **ppIter = &pBt->pLock;
  49043. assert( sqlite3BtreeHoldsMutex(p) );
  49044. assert( p->sharable || 0==*ppIter );
  49045. assert( p->inTrans>0 );
  49046. while( *ppIter ){
  49047. BtLock *pLock = *ppIter;
  49048. assert( (pBt->btsFlags & BTS_EXCLUSIVE)==0 || pBt->pWriter==pLock->pBtree );
  49049. assert( pLock->pBtree->inTrans>=pLock->eLock );
  49050. if( pLock->pBtree==p ){
  49051. *ppIter = pLock->pNext;
  49052. assert( pLock->iTable!=1 || pLock==&p->lock );
  49053. if( pLock->iTable!=1 ){
  49054. sqlite3_free(pLock);
  49055. }
  49056. }else{
  49057. ppIter = &pLock->pNext;
  49058. }
  49059. }
  49060. assert( (pBt->btsFlags & BTS_PENDING)==0 || pBt->pWriter );
  49061. if( pBt->pWriter==p ){
  49062. pBt->pWriter = 0;
  49063. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49064. }else if( pBt->nTransaction==2 ){
  49065. /* This function is called when Btree p is concluding its
  49066. ** transaction. If there currently exists a writer, and p is not
  49067. ** that writer, then the number of locks held by connections other
  49068. ** than the writer must be about to drop to zero. In this case
  49069. ** set the BTS_PENDING flag to 0.
  49070. **
  49071. ** If there is not currently a writer, then BTS_PENDING must
  49072. ** be zero already. So this next line is harmless in that case.
  49073. */
  49074. pBt->btsFlags &= ~BTS_PENDING;
  49075. }
  49076. }
  49077. /*
  49078. ** This function changes all write-locks held by Btree p into read-locks.
  49079. */
  49080. static void downgradeAllSharedCacheTableLocks(Btree *p){
  49081. BtShared *pBt = p->pBt;
  49082. if( pBt->pWriter==p ){
  49083. BtLock *pLock;
  49084. pBt->pWriter = 0;
  49085. pBt->btsFlags &= ~(BTS_EXCLUSIVE|BTS_PENDING);
  49086. for(pLock=pBt->pLock; pLock; pLock=pLock->pNext){
  49087. assert( pLock->eLock==READ_LOCK || pLock->pBtree==p );
  49088. pLock->eLock = READ_LOCK;
  49089. }
  49090. }
  49091. }
  49092. #endif /* SQLITE_OMIT_SHARED_CACHE */
  49093. static void releasePage(MemPage *pPage); /* Forward reference */
  49094. /*
  49095. ***** This routine is used inside of assert() only ****
  49096. **
  49097. ** Verify that the cursor holds the mutex on its BtShared
  49098. */
  49099. #ifdef SQLITE_DEBUG
  49100. static int cursorHoldsMutex(BtCursor *p){
  49101. return sqlite3_mutex_held(p->pBt->mutex);
  49102. }
  49103. #endif
  49104. /*
  49105. ** Invalidate the overflow cache of the cursor passed as the first argument.
  49106. ** on the shared btree structure pBt.
  49107. */
  49108. #define invalidateOverflowCache(pCur) (pCur->curFlags &= ~BTCF_ValidOvfl)
  49109. /*
  49110. ** Invalidate the overflow page-list cache for all cursors opened
  49111. ** on the shared btree structure pBt.
  49112. */
  49113. static void invalidateAllOverflowCache(BtShared *pBt){
  49114. BtCursor *p;
  49115. assert( sqlite3_mutex_held(pBt->mutex) );
  49116. for(p=pBt->pCursor; p; p=p->pNext){
  49117. invalidateOverflowCache(p);
  49118. }
  49119. }
  49120. #ifndef SQLITE_OMIT_INCRBLOB
  49121. /*
  49122. ** This function is called before modifying the contents of a table
  49123. ** to invalidate any incrblob cursors that are open on the
  49124. ** row or one of the rows being modified.
  49125. **
  49126. ** If argument isClearTable is true, then the entire contents of the
  49127. ** table is about to be deleted. In this case invalidate all incrblob
  49128. ** cursors open on any row within the table with root-page pgnoRoot.
  49129. **
  49130. ** Otherwise, if argument isClearTable is false, then the row with
  49131. ** rowid iRow is being replaced or deleted. In this case invalidate
  49132. ** only those incrblob cursors open on that specific row.
  49133. */
  49134. static void invalidateIncrblobCursors(
  49135. Btree *pBtree, /* The database file to check */
  49136. i64 iRow, /* The rowid that might be changing */
  49137. int isClearTable /* True if all rows are being deleted */
  49138. ){
  49139. BtCursor *p;
  49140. BtShared *pBt = pBtree->pBt;
  49141. assert( sqlite3BtreeHoldsMutex(pBtree) );
  49142. for(p=pBt->pCursor; p; p=p->pNext){
  49143. if( (p->curFlags & BTCF_Incrblob)!=0
  49144. && (isClearTable || p->info.nKey==iRow)
  49145. ){
  49146. p->eState = CURSOR_INVALID;
  49147. }
  49148. }
  49149. }
  49150. #else
  49151. /* Stub function when INCRBLOB is omitted */
  49152. #define invalidateIncrblobCursors(x,y,z)
  49153. #endif /* SQLITE_OMIT_INCRBLOB */
  49154. /*
  49155. ** Set bit pgno of the BtShared.pHasContent bitvec. This is called
  49156. ** when a page that previously contained data becomes a free-list leaf
  49157. ** page.
  49158. **
  49159. ** The BtShared.pHasContent bitvec exists to work around an obscure
  49160. ** bug caused by the interaction of two useful IO optimizations surrounding
  49161. ** free-list leaf pages:
  49162. **
  49163. ** 1) When all data is deleted from a page and the page becomes
  49164. ** a free-list leaf page, the page is not written to the database
  49165. ** (as free-list leaf pages contain no meaningful data). Sometimes
  49166. ** such a page is not even journalled (as it will not be modified,
  49167. ** why bother journalling it?).
  49168. **
  49169. ** 2) When a free-list leaf page is reused, its content is not read
  49170. ** from the database or written to the journal file (why should it
  49171. ** be, if it is not at all meaningful?).
  49172. **
  49173. ** By themselves, these optimizations work fine and provide a handy
  49174. ** performance boost to bulk delete or insert operations. However, if
  49175. ** a page is moved to the free-list and then reused within the same
  49176. ** transaction, a problem comes up. If the page is not journalled when
  49177. ** it is moved to the free-list and it is also not journalled when it
  49178. ** is extracted from the free-list and reused, then the original data
  49179. ** may be lost. In the event of a rollback, it may not be possible
  49180. ** to restore the database to its original configuration.
  49181. **
  49182. ** The solution is the BtShared.pHasContent bitvec. Whenever a page is
  49183. ** moved to become a free-list leaf page, the corresponding bit is
  49184. ** set in the bitvec. Whenever a leaf page is extracted from the free-list,
  49185. ** optimization 2 above is omitted if the corresponding bit is already
  49186. ** set in BtShared.pHasContent. The contents of the bitvec are cleared
  49187. ** at the end of every transaction.
  49188. */
  49189. static int btreeSetHasContent(BtShared *pBt, Pgno pgno){
  49190. int rc = SQLITE_OK;
  49191. if( !pBt->pHasContent ){
  49192. assert( pgno<=pBt->nPage );
  49193. pBt->pHasContent = sqlite3BitvecCreate(pBt->nPage);
  49194. if( !pBt->pHasContent ){
  49195. rc = SQLITE_NOMEM;
  49196. }
  49197. }
  49198. if( rc==SQLITE_OK && pgno<=sqlite3BitvecSize(pBt->pHasContent) ){
  49199. rc = sqlite3BitvecSet(pBt->pHasContent, pgno);
  49200. }
  49201. return rc;
  49202. }
  49203. /*
  49204. ** Query the BtShared.pHasContent vector.
  49205. **
  49206. ** This function is called when a free-list leaf page is removed from the
  49207. ** free-list for reuse. It returns false if it is safe to retrieve the
  49208. ** page from the pager layer with the 'no-content' flag set. True otherwise.
  49209. */
  49210. static int btreeGetHasContent(BtShared *pBt, Pgno pgno){
  49211. Bitvec *p = pBt->pHasContent;
  49212. return (p && (pgno>sqlite3BitvecSize(p) || sqlite3BitvecTest(p, pgno)));
  49213. }
  49214. /*
  49215. ** Clear (destroy) the BtShared.pHasContent bitvec. This should be
  49216. ** invoked at the conclusion of each write-transaction.
  49217. */
  49218. static void btreeClearHasContent(BtShared *pBt){
  49219. sqlite3BitvecDestroy(pBt->pHasContent);
  49220. pBt->pHasContent = 0;
  49221. }
  49222. /*
  49223. ** Release all of the apPage[] pages for a cursor.
  49224. */
  49225. static void btreeReleaseAllCursorPages(BtCursor *pCur){
  49226. int i;
  49227. for(i=0; i<=pCur->iPage; i++){
  49228. releasePage(pCur->apPage[i]);
  49229. pCur->apPage[i] = 0;
  49230. }
  49231. pCur->iPage = -1;
  49232. }
  49233. /*
  49234. ** Save the current cursor position in the variables BtCursor.nKey
  49235. ** and BtCursor.pKey. The cursor's state is set to CURSOR_REQUIRESEEK.
  49236. **
  49237. ** The caller must ensure that the cursor is valid (has eState==CURSOR_VALID)
  49238. ** prior to calling this routine.
  49239. */
  49240. static int saveCursorPosition(BtCursor *pCur){
  49241. int rc;
  49242. assert( CURSOR_VALID==pCur->eState );
  49243. assert( 0==pCur->pKey );
  49244. assert( cursorHoldsMutex(pCur) );
  49245. rc = sqlite3BtreeKeySize(pCur, &pCur->nKey);
  49246. assert( rc==SQLITE_OK ); /* KeySize() cannot fail */
  49247. /* If this is an intKey table, then the above call to BtreeKeySize()
  49248. ** stores the integer key in pCur->nKey. In this case this value is
  49249. ** all that is required. Otherwise, if pCur is not open on an intKey
  49250. ** table, then malloc space for and store the pCur->nKey bytes of key
  49251. ** data.
  49252. */
  49253. if( 0==pCur->apPage[0]->intKey ){
  49254. void *pKey = sqlite3Malloc( pCur->nKey );
  49255. if( pKey ){
  49256. rc = sqlite3BtreeKey(pCur, 0, (int)pCur->nKey, pKey);
  49257. if( rc==SQLITE_OK ){
  49258. pCur->pKey = pKey;
  49259. }else{
  49260. sqlite3_free(pKey);
  49261. }
  49262. }else{
  49263. rc = SQLITE_NOMEM;
  49264. }
  49265. }
  49266. assert( !pCur->apPage[0]->intKey || !pCur->pKey );
  49267. if( rc==SQLITE_OK ){
  49268. btreeReleaseAllCursorPages(pCur);
  49269. pCur->eState = CURSOR_REQUIRESEEK;
  49270. }
  49271. invalidateOverflowCache(pCur);
  49272. return rc;
  49273. }
  49274. /* Forward reference */
  49275. static int SQLITE_NOINLINE saveCursorsOnList(BtCursor*,Pgno,BtCursor*);
  49276. /*
  49277. ** Save the positions of all cursors (except pExcept) that are open on
  49278. ** the table with root-page iRoot. "Saving the cursor position" means that
  49279. ** the location in the btree is remembered in such a way that it can be
  49280. ** moved back to the same spot after the btree has been modified. This
  49281. ** routine is called just before cursor pExcept is used to modify the
  49282. ** table, for example in BtreeDelete() or BtreeInsert().
  49283. **
  49284. ** Implementation note: This routine merely checks to see if any cursors
  49285. ** need to be saved. It calls out to saveCursorsOnList() in the (unusual)
  49286. ** event that cursors are in need to being saved.
  49287. */
  49288. static int saveAllCursors(BtShared *pBt, Pgno iRoot, BtCursor *pExcept){
  49289. BtCursor *p;
  49290. assert( sqlite3_mutex_held(pBt->mutex) );
  49291. assert( pExcept==0 || pExcept->pBt==pBt );
  49292. for(p=pBt->pCursor; p; p=p->pNext){
  49293. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ) break;
  49294. }
  49295. return p ? saveCursorsOnList(p, iRoot, pExcept) : SQLITE_OK;
  49296. }
  49297. /* This helper routine to saveAllCursors does the actual work of saving
  49298. ** the cursors if and when a cursor is found that actually requires saving.
  49299. ** The common case is that no cursors need to be saved, so this routine is
  49300. ** broken out from its caller to avoid unnecessary stack pointer movement.
  49301. */
  49302. static int SQLITE_NOINLINE saveCursorsOnList(
  49303. BtCursor *p, /* The first cursor that needs saving */
  49304. Pgno iRoot, /* Only save cursor with this iRoot. Save all if zero */
  49305. BtCursor *pExcept /* Do not save this cursor */
  49306. ){
  49307. do{
  49308. if( p!=pExcept && (0==iRoot || p->pgnoRoot==iRoot) ){
  49309. if( p->eState==CURSOR_VALID ){
  49310. int rc = saveCursorPosition(p);
  49311. if( SQLITE_OK!=rc ){
  49312. return rc;
  49313. }
  49314. }else{
  49315. testcase( p->iPage>0 );
  49316. btreeReleaseAllCursorPages(p);
  49317. }
  49318. }
  49319. p = p->pNext;
  49320. }while( p );
  49321. return SQLITE_OK;
  49322. }
  49323. /*
  49324. ** Clear the current cursor position.
  49325. */
  49326. SQLITE_PRIVATE void sqlite3BtreeClearCursor(BtCursor *pCur){
  49327. assert( cursorHoldsMutex(pCur) );
  49328. sqlite3_free(pCur->pKey);
  49329. pCur->pKey = 0;
  49330. pCur->eState = CURSOR_INVALID;
  49331. }
  49332. /*
  49333. ** In this version of BtreeMoveto, pKey is a packed index record
  49334. ** such as is generated by the OP_MakeRecord opcode. Unpack the
  49335. ** record and then call BtreeMovetoUnpacked() to do the work.
  49336. */
  49337. static int btreeMoveto(
  49338. BtCursor *pCur, /* Cursor open on the btree to be searched */
  49339. const void *pKey, /* Packed key if the btree is an index */
  49340. i64 nKey, /* Integer key for tables. Size of pKey for indices */
  49341. int bias, /* Bias search to the high end */
  49342. int *pRes /* Write search results here */
  49343. ){
  49344. int rc; /* Status code */
  49345. UnpackedRecord *pIdxKey; /* Unpacked index key */
  49346. char aSpace[200]; /* Temp space for pIdxKey - to avoid a malloc */
  49347. char *pFree = 0;
  49348. if( pKey ){
  49349. assert( nKey==(i64)(int)nKey );
  49350. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  49351. pCur->pKeyInfo, aSpace, sizeof(aSpace), &pFree
  49352. );
  49353. if( pIdxKey==0 ) return SQLITE_NOMEM;
  49354. sqlite3VdbeRecordUnpack(pCur->pKeyInfo, (int)nKey, pKey, pIdxKey);
  49355. if( pIdxKey->nField==0 ){
  49356. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  49357. return SQLITE_CORRUPT_BKPT;
  49358. }
  49359. }else{
  49360. pIdxKey = 0;
  49361. }
  49362. rc = sqlite3BtreeMovetoUnpacked(pCur, pIdxKey, nKey, bias, pRes);
  49363. if( pFree ){
  49364. sqlite3DbFree(pCur->pKeyInfo->db, pFree);
  49365. }
  49366. return rc;
  49367. }
  49368. /*
  49369. ** Restore the cursor to the position it was in (or as close to as possible)
  49370. ** when saveCursorPosition() was called. Note that this call deletes the
  49371. ** saved position info stored by saveCursorPosition(), so there can be
  49372. ** at most one effective restoreCursorPosition() call after each
  49373. ** saveCursorPosition().
  49374. */
  49375. static int btreeRestoreCursorPosition(BtCursor *pCur){
  49376. int rc;
  49377. assert( cursorHoldsMutex(pCur) );
  49378. assert( pCur->eState>=CURSOR_REQUIRESEEK );
  49379. if( pCur->eState==CURSOR_FAULT ){
  49380. return pCur->skipNext;
  49381. }
  49382. pCur->eState = CURSOR_INVALID;
  49383. rc = btreeMoveto(pCur, pCur->pKey, pCur->nKey, 0, &pCur->skipNext);
  49384. if( rc==SQLITE_OK ){
  49385. sqlite3_free(pCur->pKey);
  49386. pCur->pKey = 0;
  49387. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_INVALID );
  49388. if( pCur->skipNext && pCur->eState==CURSOR_VALID ){
  49389. pCur->eState = CURSOR_SKIPNEXT;
  49390. }
  49391. }
  49392. return rc;
  49393. }
  49394. #define restoreCursorPosition(p) \
  49395. (p->eState>=CURSOR_REQUIRESEEK ? \
  49396. btreeRestoreCursorPosition(p) : \
  49397. SQLITE_OK)
  49398. /*
  49399. ** Determine whether or not a cursor has moved from the position where
  49400. ** it was last placed, or has been invalidated for any other reason.
  49401. ** Cursors can move when the row they are pointing at is deleted out
  49402. ** from under them, for example. Cursor might also move if a btree
  49403. ** is rebalanced.
  49404. **
  49405. ** Calling this routine with a NULL cursor pointer returns false.
  49406. **
  49407. ** Use the separate sqlite3BtreeCursorRestore() routine to restore a cursor
  49408. ** back to where it ought to be if this routine returns true.
  49409. */
  49410. SQLITE_PRIVATE int sqlite3BtreeCursorHasMoved(BtCursor *pCur){
  49411. return pCur->eState!=CURSOR_VALID;
  49412. }
  49413. /*
  49414. ** This routine restores a cursor back to its original position after it
  49415. ** has been moved by some outside activity (such as a btree rebalance or
  49416. ** a row having been deleted out from under the cursor).
  49417. **
  49418. ** On success, the *pDifferentRow parameter is false if the cursor is left
  49419. ** pointing at exactly the same row. *pDifferntRow is the row the cursor
  49420. ** was pointing to has been deleted, forcing the cursor to point to some
  49421. ** nearby row.
  49422. **
  49423. ** This routine should only be called for a cursor that just returned
  49424. ** TRUE from sqlite3BtreeCursorHasMoved().
  49425. */
  49426. SQLITE_PRIVATE int sqlite3BtreeCursorRestore(BtCursor *pCur, int *pDifferentRow){
  49427. int rc;
  49428. assert( pCur!=0 );
  49429. assert( pCur->eState!=CURSOR_VALID );
  49430. rc = restoreCursorPosition(pCur);
  49431. if( rc ){
  49432. *pDifferentRow = 1;
  49433. return rc;
  49434. }
  49435. if( pCur->eState!=CURSOR_VALID || NEVER(pCur->skipNext!=0) ){
  49436. *pDifferentRow = 1;
  49437. }else{
  49438. *pDifferentRow = 0;
  49439. }
  49440. return SQLITE_OK;
  49441. }
  49442. #ifndef SQLITE_OMIT_AUTOVACUUM
  49443. /*
  49444. ** Given a page number of a regular database page, return the page
  49445. ** number for the pointer-map page that contains the entry for the
  49446. ** input page number.
  49447. **
  49448. ** Return 0 (not a valid page) for pgno==1 since there is
  49449. ** no pointer map associated with page 1. The integrity_check logic
  49450. ** requires that ptrmapPageno(*,1)!=1.
  49451. */
  49452. static Pgno ptrmapPageno(BtShared *pBt, Pgno pgno){
  49453. int nPagesPerMapPage;
  49454. Pgno iPtrMap, ret;
  49455. assert( sqlite3_mutex_held(pBt->mutex) );
  49456. if( pgno<2 ) return 0;
  49457. nPagesPerMapPage = (pBt->usableSize/5)+1;
  49458. iPtrMap = (pgno-2)/nPagesPerMapPage;
  49459. ret = (iPtrMap*nPagesPerMapPage) + 2;
  49460. if( ret==PENDING_BYTE_PAGE(pBt) ){
  49461. ret++;
  49462. }
  49463. return ret;
  49464. }
  49465. /*
  49466. ** Write an entry into the pointer map.
  49467. **
  49468. ** This routine updates the pointer map entry for page number 'key'
  49469. ** so that it maps to type 'eType' and parent page number 'pgno'.
  49470. **
  49471. ** If *pRC is initially non-zero (non-SQLITE_OK) then this routine is
  49472. ** a no-op. If an error occurs, the appropriate error code is written
  49473. ** into *pRC.
  49474. */
  49475. static void ptrmapPut(BtShared *pBt, Pgno key, u8 eType, Pgno parent, int *pRC){
  49476. DbPage *pDbPage; /* The pointer map page */
  49477. u8 *pPtrmap; /* The pointer map data */
  49478. Pgno iPtrmap; /* The pointer map page number */
  49479. int offset; /* Offset in pointer map page */
  49480. int rc; /* Return code from subfunctions */
  49481. if( *pRC ) return;
  49482. assert( sqlite3_mutex_held(pBt->mutex) );
  49483. /* The master-journal page number must never be used as a pointer map page */
  49484. assert( 0==PTRMAP_ISPAGE(pBt, PENDING_BYTE_PAGE(pBt)) );
  49485. assert( pBt->autoVacuum );
  49486. if( key==0 ){
  49487. *pRC = SQLITE_CORRUPT_BKPT;
  49488. return;
  49489. }
  49490. iPtrmap = PTRMAP_PAGENO(pBt, key);
  49491. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  49492. if( rc!=SQLITE_OK ){
  49493. *pRC = rc;
  49494. return;
  49495. }
  49496. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  49497. if( offset<0 ){
  49498. *pRC = SQLITE_CORRUPT_BKPT;
  49499. goto ptrmap_exit;
  49500. }
  49501. assert( offset <= (int)pBt->usableSize-5 );
  49502. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  49503. if( eType!=pPtrmap[offset] || get4byte(&pPtrmap[offset+1])!=parent ){
  49504. TRACE(("PTRMAP_UPDATE: %d->(%d,%d)\n", key, eType, parent));
  49505. *pRC= rc = sqlite3PagerWrite(pDbPage);
  49506. if( rc==SQLITE_OK ){
  49507. pPtrmap[offset] = eType;
  49508. put4byte(&pPtrmap[offset+1], parent);
  49509. }
  49510. }
  49511. ptrmap_exit:
  49512. sqlite3PagerUnref(pDbPage);
  49513. }
  49514. /*
  49515. ** Read an entry from the pointer map.
  49516. **
  49517. ** This routine retrieves the pointer map entry for page 'key', writing
  49518. ** the type and parent page number to *pEType and *pPgno respectively.
  49519. ** An error code is returned if something goes wrong, otherwise SQLITE_OK.
  49520. */
  49521. static int ptrmapGet(BtShared *pBt, Pgno key, u8 *pEType, Pgno *pPgno){
  49522. DbPage *pDbPage; /* The pointer map page */
  49523. int iPtrmap; /* Pointer map page index */
  49524. u8 *pPtrmap; /* Pointer map page data */
  49525. int offset; /* Offset of entry in pointer map */
  49526. int rc;
  49527. assert( sqlite3_mutex_held(pBt->mutex) );
  49528. iPtrmap = PTRMAP_PAGENO(pBt, key);
  49529. rc = sqlite3PagerGet(pBt->pPager, iPtrmap, &pDbPage);
  49530. if( rc!=0 ){
  49531. return rc;
  49532. }
  49533. pPtrmap = (u8 *)sqlite3PagerGetData(pDbPage);
  49534. offset = PTRMAP_PTROFFSET(iPtrmap, key);
  49535. if( offset<0 ){
  49536. sqlite3PagerUnref(pDbPage);
  49537. return SQLITE_CORRUPT_BKPT;
  49538. }
  49539. assert( offset <= (int)pBt->usableSize-5 );
  49540. assert( pEType!=0 );
  49541. *pEType = pPtrmap[offset];
  49542. if( pPgno ) *pPgno = get4byte(&pPtrmap[offset+1]);
  49543. sqlite3PagerUnref(pDbPage);
  49544. if( *pEType<1 || *pEType>5 ) return SQLITE_CORRUPT_BKPT;
  49545. return SQLITE_OK;
  49546. }
  49547. #else /* if defined SQLITE_OMIT_AUTOVACUUM */
  49548. #define ptrmapPut(w,x,y,z,rc)
  49549. #define ptrmapGet(w,x,y,z) SQLITE_OK
  49550. #define ptrmapPutOvflPtr(x, y, rc)
  49551. #endif
  49552. /*
  49553. ** Given a btree page and a cell index (0 means the first cell on
  49554. ** the page, 1 means the second cell, and so forth) return a pointer
  49555. ** to the cell content.
  49556. **
  49557. ** This routine works only for pages that do not contain overflow cells.
  49558. */
  49559. #define findCell(P,I) \
  49560. ((P)->aData + ((P)->maskPage & get2byte(&(P)->aCellIdx[2*(I)])))
  49561. #define findCellv2(D,M,O,I) (D+(M&get2byte(D+(O+2*(I)))))
  49562. /*
  49563. ** This a more complex version of findCell() that works for
  49564. ** pages that do contain overflow cells.
  49565. */
  49566. static u8 *findOverflowCell(MemPage *pPage, int iCell){
  49567. int i;
  49568. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49569. for(i=pPage->nOverflow-1; i>=0; i--){
  49570. int k;
  49571. k = pPage->aiOvfl[i];
  49572. if( k<=iCell ){
  49573. if( k==iCell ){
  49574. return pPage->apOvfl[i];
  49575. }
  49576. iCell--;
  49577. }
  49578. }
  49579. return findCell(pPage, iCell);
  49580. }
  49581. /*
  49582. ** Parse a cell content block and fill in the CellInfo structure. There
  49583. ** are two versions of this function. btreeParseCell() takes a
  49584. ** cell index as the second argument and btreeParseCellPtr()
  49585. ** takes a pointer to the body of the cell as its second argument.
  49586. */
  49587. static void btreeParseCellPtr(
  49588. MemPage *pPage, /* Page containing the cell */
  49589. u8 *pCell, /* Pointer to the cell text. */
  49590. CellInfo *pInfo /* Fill in this structure */
  49591. ){
  49592. u8 *pIter; /* For scanning through pCell */
  49593. u32 nPayload; /* Number of bytes of cell payload */
  49594. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49595. assert( pPage->leaf==0 || pPage->leaf==1 );
  49596. if( pPage->intKeyLeaf ){
  49597. assert( pPage->childPtrSize==0 );
  49598. pIter = pCell + getVarint32(pCell, nPayload);
  49599. pIter += getVarint(pIter, (u64*)&pInfo->nKey);
  49600. }else if( pPage->noPayload ){
  49601. assert( pPage->childPtrSize==4 );
  49602. pInfo->nSize = 4 + getVarint(&pCell[4], (u64*)&pInfo->nKey);
  49603. pInfo->nPayload = 0;
  49604. pInfo->nLocal = 0;
  49605. pInfo->iOverflow = 0;
  49606. pInfo->pPayload = 0;
  49607. return;
  49608. }else{
  49609. pIter = pCell + pPage->childPtrSize;
  49610. pIter += getVarint32(pIter, nPayload);
  49611. pInfo->nKey = nPayload;
  49612. }
  49613. pInfo->nPayload = nPayload;
  49614. pInfo->pPayload = pIter;
  49615. testcase( nPayload==pPage->maxLocal );
  49616. testcase( nPayload==pPage->maxLocal+1 );
  49617. if( nPayload<=pPage->maxLocal ){
  49618. /* This is the (easy) common case where the entire payload fits
  49619. ** on the local page. No overflow is required.
  49620. */
  49621. pInfo->nSize = nPayload + (u16)(pIter - pCell);
  49622. if( pInfo->nSize<4 ) pInfo->nSize = 4;
  49623. pInfo->nLocal = (u16)nPayload;
  49624. pInfo->iOverflow = 0;
  49625. }else{
  49626. /* If the payload will not fit completely on the local page, we have
  49627. ** to decide how much to store locally and how much to spill onto
  49628. ** overflow pages. The strategy is to minimize the amount of unused
  49629. ** space on overflow pages while keeping the amount of local storage
  49630. ** in between minLocal and maxLocal.
  49631. **
  49632. ** Warning: changing the way overflow payload is distributed in any
  49633. ** way will result in an incompatible file format.
  49634. */
  49635. int minLocal; /* Minimum amount of payload held locally */
  49636. int maxLocal; /* Maximum amount of payload held locally */
  49637. int surplus; /* Overflow payload available for local storage */
  49638. minLocal = pPage->minLocal;
  49639. maxLocal = pPage->maxLocal;
  49640. surplus = minLocal + (nPayload - minLocal)%(pPage->pBt->usableSize - 4);
  49641. testcase( surplus==maxLocal );
  49642. testcase( surplus==maxLocal+1 );
  49643. if( surplus <= maxLocal ){
  49644. pInfo->nLocal = (u16)surplus;
  49645. }else{
  49646. pInfo->nLocal = (u16)minLocal;
  49647. }
  49648. pInfo->iOverflow = (u16)(&pInfo->pPayload[pInfo->nLocal] - pCell);
  49649. pInfo->nSize = pInfo->iOverflow + 4;
  49650. }
  49651. }
  49652. static void btreeParseCell(
  49653. MemPage *pPage, /* Page containing the cell */
  49654. int iCell, /* The cell index. First cell is 0 */
  49655. CellInfo *pInfo /* Fill in this structure */
  49656. ){
  49657. btreeParseCellPtr(pPage, findCell(pPage, iCell), pInfo);
  49658. }
  49659. /*
  49660. ** Compute the total number of bytes that a Cell needs in the cell
  49661. ** data area of the btree-page. The return number includes the cell
  49662. ** data header and the local payload, but not any overflow page or
  49663. ** the space used by the cell pointer.
  49664. */
  49665. static u16 cellSizePtr(MemPage *pPage, u8 *pCell){
  49666. u8 *pIter = pCell + pPage->childPtrSize; /* For looping over bytes of pCell */
  49667. u8 *pEnd; /* End mark for a varint */
  49668. u32 nSize; /* Size value to return */
  49669. #ifdef SQLITE_DEBUG
  49670. /* The value returned by this function should always be the same as
  49671. ** the (CellInfo.nSize) value found by doing a full parse of the
  49672. ** cell. If SQLITE_DEBUG is defined, an assert() at the bottom of
  49673. ** this function verifies that this invariant is not violated. */
  49674. CellInfo debuginfo;
  49675. btreeParseCellPtr(pPage, pCell, &debuginfo);
  49676. #endif
  49677. if( pPage->noPayload ){
  49678. pEnd = &pIter[9];
  49679. while( (*pIter++)&0x80 && pIter<pEnd );
  49680. assert( pPage->childPtrSize==4 );
  49681. return (u16)(pIter - pCell);
  49682. }
  49683. nSize = *pIter;
  49684. if( nSize>=0x80 ){
  49685. pEnd = &pIter[9];
  49686. nSize &= 0x7f;
  49687. do{
  49688. nSize = (nSize<<7) | (*++pIter & 0x7f);
  49689. }while( *(pIter)>=0x80 && pIter<pEnd );
  49690. }
  49691. pIter++;
  49692. if( pPage->intKey ){
  49693. /* pIter now points at the 64-bit integer key value, a variable length
  49694. ** integer. The following block moves pIter to point at the first byte
  49695. ** past the end of the key value. */
  49696. pEnd = &pIter[9];
  49697. while( (*pIter++)&0x80 && pIter<pEnd );
  49698. }
  49699. testcase( nSize==pPage->maxLocal );
  49700. testcase( nSize==pPage->maxLocal+1 );
  49701. if( nSize<=pPage->maxLocal ){
  49702. nSize += (u32)(pIter - pCell);
  49703. if( nSize<4 ) nSize = 4;
  49704. }else{
  49705. int minLocal = pPage->minLocal;
  49706. nSize = minLocal + (nSize - minLocal) % (pPage->pBt->usableSize - 4);
  49707. testcase( nSize==pPage->maxLocal );
  49708. testcase( nSize==pPage->maxLocal+1 );
  49709. if( nSize>pPage->maxLocal ){
  49710. nSize = minLocal;
  49711. }
  49712. nSize += 4 + (u16)(pIter - pCell);
  49713. }
  49714. assert( nSize==debuginfo.nSize || CORRUPT_DB );
  49715. return (u16)nSize;
  49716. }
  49717. #ifdef SQLITE_DEBUG
  49718. /* This variation on cellSizePtr() is used inside of assert() statements
  49719. ** only. */
  49720. static u16 cellSize(MemPage *pPage, int iCell){
  49721. return cellSizePtr(pPage, findCell(pPage, iCell));
  49722. }
  49723. #endif
  49724. #ifndef SQLITE_OMIT_AUTOVACUUM
  49725. /*
  49726. ** If the cell pCell, part of page pPage contains a pointer
  49727. ** to an overflow page, insert an entry into the pointer-map
  49728. ** for the overflow page.
  49729. */
  49730. static void ptrmapPutOvflPtr(MemPage *pPage, u8 *pCell, int *pRC){
  49731. CellInfo info;
  49732. if( *pRC ) return;
  49733. assert( pCell!=0 );
  49734. btreeParseCellPtr(pPage, pCell, &info);
  49735. if( info.iOverflow ){
  49736. Pgno ovfl = get4byte(&pCell[info.iOverflow]);
  49737. ptrmapPut(pPage->pBt, ovfl, PTRMAP_OVERFLOW1, pPage->pgno, pRC);
  49738. }
  49739. }
  49740. #endif
  49741. /*
  49742. ** Defragment the page given. All Cells are moved to the
  49743. ** end of the page and all free space is collected into one
  49744. ** big FreeBlk that occurs in between the header and cell
  49745. ** pointer array and the cell content area.
  49746. */
  49747. static int defragmentPage(MemPage *pPage){
  49748. int i; /* Loop counter */
  49749. int pc; /* Address of the i-th cell */
  49750. int hdr; /* Offset to the page header */
  49751. int size; /* Size of a cell */
  49752. int usableSize; /* Number of usable bytes on a page */
  49753. int cellOffset; /* Offset to the cell pointer array */
  49754. int cbrk; /* Offset to the cell content area */
  49755. int nCell; /* Number of cells on the page */
  49756. unsigned char *data; /* The page data */
  49757. unsigned char *temp; /* Temp area for cell content */
  49758. int iCellFirst; /* First allowable cell index */
  49759. int iCellLast; /* Last possible cell index */
  49760. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  49761. assert( pPage->pBt!=0 );
  49762. assert( pPage->pBt->usableSize <= SQLITE_MAX_PAGE_SIZE );
  49763. assert( pPage->nOverflow==0 );
  49764. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49765. temp = sqlite3PagerTempSpace(pPage->pBt->pPager);
  49766. data = pPage->aData;
  49767. hdr = pPage->hdrOffset;
  49768. cellOffset = pPage->cellOffset;
  49769. nCell = pPage->nCell;
  49770. assert( nCell==get2byte(&data[hdr+3]) );
  49771. usableSize = pPage->pBt->usableSize;
  49772. cbrk = get2byte(&data[hdr+5]);
  49773. memcpy(&temp[cbrk], &data[cbrk], usableSize - cbrk);
  49774. cbrk = usableSize;
  49775. iCellFirst = cellOffset + 2*nCell;
  49776. iCellLast = usableSize - 4;
  49777. for(i=0; i<nCell; i++){
  49778. u8 *pAddr; /* The i-th cell pointer */
  49779. pAddr = &data[cellOffset + i*2];
  49780. pc = get2byte(pAddr);
  49781. testcase( pc==iCellFirst );
  49782. testcase( pc==iCellLast );
  49783. #if !defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  49784. /* These conditions have already been verified in btreeInitPage()
  49785. ** if SQLITE_ENABLE_OVERSIZE_CELL_CHECK is defined
  49786. */
  49787. if( pc<iCellFirst || pc>iCellLast ){
  49788. return SQLITE_CORRUPT_BKPT;
  49789. }
  49790. #endif
  49791. assert( pc>=iCellFirst && pc<=iCellLast );
  49792. size = cellSizePtr(pPage, &temp[pc]);
  49793. cbrk -= size;
  49794. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  49795. if( cbrk<iCellFirst ){
  49796. return SQLITE_CORRUPT_BKPT;
  49797. }
  49798. #else
  49799. if( cbrk<iCellFirst || pc+size>usableSize ){
  49800. return SQLITE_CORRUPT_BKPT;
  49801. }
  49802. #endif
  49803. assert( cbrk+size<=usableSize && cbrk>=iCellFirst );
  49804. testcase( cbrk+size==usableSize );
  49805. testcase( pc+size==usableSize );
  49806. memcpy(&data[cbrk], &temp[pc], size);
  49807. put2byte(pAddr, cbrk);
  49808. }
  49809. assert( cbrk>=iCellFirst );
  49810. put2byte(&data[hdr+5], cbrk);
  49811. data[hdr+1] = 0;
  49812. data[hdr+2] = 0;
  49813. data[hdr+7] = 0;
  49814. memset(&data[iCellFirst], 0, cbrk-iCellFirst);
  49815. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  49816. if( cbrk-iCellFirst!=pPage->nFree ){
  49817. return SQLITE_CORRUPT_BKPT;
  49818. }
  49819. return SQLITE_OK;
  49820. }
  49821. /*
  49822. ** Allocate nByte bytes of space from within the B-Tree page passed
  49823. ** as the first argument. Write into *pIdx the index into pPage->aData[]
  49824. ** of the first byte of allocated space. Return either SQLITE_OK or
  49825. ** an error code (usually SQLITE_CORRUPT).
  49826. **
  49827. ** The caller guarantees that there is sufficient space to make the
  49828. ** allocation. This routine might need to defragment in order to bring
  49829. ** all the space together, however. This routine will avoid using
  49830. ** the first two bytes past the cell pointer area since presumably this
  49831. ** allocation is being made in order to insert a new cell, so we will
  49832. ** also end up needing a new cell pointer.
  49833. */
  49834. static int allocateSpace(MemPage *pPage, int nByte, int *pIdx){
  49835. const int hdr = pPage->hdrOffset; /* Local cache of pPage->hdrOffset */
  49836. u8 * const data = pPage->aData; /* Local cache of pPage->aData */
  49837. int top; /* First byte of cell content area */
  49838. int gap; /* First byte of gap between cell pointers and cell content */
  49839. int rc; /* Integer return code */
  49840. int usableSize; /* Usable size of the page */
  49841. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  49842. assert( pPage->pBt );
  49843. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49844. assert( nByte>=0 ); /* Minimum cell size is 4 */
  49845. assert( pPage->nFree>=nByte );
  49846. assert( pPage->nOverflow==0 );
  49847. usableSize = pPage->pBt->usableSize;
  49848. assert( nByte < usableSize-8 );
  49849. assert( pPage->cellOffset == hdr + 12 - 4*pPage->leaf );
  49850. gap = pPage->cellOffset + 2*pPage->nCell;
  49851. assert( gap<=65536 );
  49852. top = get2byte(&data[hdr+5]);
  49853. if( gap>top ){
  49854. if( top==0 ){
  49855. top = 65536;
  49856. }else{
  49857. return SQLITE_CORRUPT_BKPT;
  49858. }
  49859. }
  49860. /* If there is enough space between gap and top for one more cell pointer
  49861. ** array entry offset, and if the freelist is not empty, then search the
  49862. ** freelist looking for a free slot big enough to satisfy the request.
  49863. */
  49864. testcase( gap+2==top );
  49865. testcase( gap+1==top );
  49866. testcase( gap==top );
  49867. if( gap+2<=top && (data[hdr+1] || data[hdr+2]) ){
  49868. int pc, addr;
  49869. for(addr=hdr+1; (pc = get2byte(&data[addr]))>0; addr=pc){
  49870. int size; /* Size of the free slot */
  49871. if( pc>usableSize-4 || pc<addr+4 ){
  49872. return SQLITE_CORRUPT_BKPT;
  49873. }
  49874. size = get2byte(&data[pc+2]);
  49875. if( size>=nByte ){
  49876. int x = size - nByte;
  49877. testcase( x==4 );
  49878. testcase( x==3 );
  49879. if( x<4 ){
  49880. if( data[hdr+7]>=60 ) goto defragment_page;
  49881. /* Remove the slot from the free-list. Update the number of
  49882. ** fragmented bytes within the page. */
  49883. memcpy(&data[addr], &data[pc], 2);
  49884. data[hdr+7] += (u8)x;
  49885. }else if( size+pc > usableSize ){
  49886. return SQLITE_CORRUPT_BKPT;
  49887. }else{
  49888. /* The slot remains on the free-list. Reduce its size to account
  49889. ** for the portion used by the new allocation. */
  49890. put2byte(&data[pc+2], x);
  49891. }
  49892. *pIdx = pc + x;
  49893. return SQLITE_OK;
  49894. }
  49895. }
  49896. }
  49897. /* The request could not be fulfilled using a freelist slot. Check
  49898. ** to see if defragmentation is necessary.
  49899. */
  49900. testcase( gap+2+nByte==top );
  49901. if( gap+2+nByte>top ){
  49902. defragment_page:
  49903. testcase( pPage->nCell==0 );
  49904. rc = defragmentPage(pPage);
  49905. if( rc ) return rc;
  49906. top = get2byteNotZero(&data[hdr+5]);
  49907. assert( gap+nByte<=top );
  49908. }
  49909. /* Allocate memory from the gap in between the cell pointer array
  49910. ** and the cell content area. The btreeInitPage() call has already
  49911. ** validated the freelist. Given that the freelist is valid, there
  49912. ** is no way that the allocation can extend off the end of the page.
  49913. ** The assert() below verifies the previous sentence.
  49914. */
  49915. top -= nByte;
  49916. put2byte(&data[hdr+5], top);
  49917. assert( top+nByte <= (int)pPage->pBt->usableSize );
  49918. *pIdx = top;
  49919. return SQLITE_OK;
  49920. }
  49921. /*
  49922. ** Return a section of the pPage->aData to the freelist.
  49923. ** The first byte of the new free block is pPage->aData[iStart]
  49924. ** and the size of the block is iSize bytes.
  49925. **
  49926. ** Adjacent freeblocks are coalesced.
  49927. **
  49928. ** Note that even though the freeblock list was checked by btreeInitPage(),
  49929. ** that routine will not detect overlap between cells or freeblocks. Nor
  49930. ** does it detect cells or freeblocks that encrouch into the reserved bytes
  49931. ** at the end of the page. So do additional corruption checks inside this
  49932. ** routine and return SQLITE_CORRUPT if any problems are found.
  49933. */
  49934. static int freeSpace(MemPage *pPage, u16 iStart, u16 iSize){
  49935. u16 iPtr; /* Address of ptr to next freeblock */
  49936. u16 iFreeBlk; /* Address of the next freeblock */
  49937. u8 hdr; /* Page header size. 0 or 100 */
  49938. u8 nFrag = 0; /* Reduction in fragmentation */
  49939. u16 iOrigSize = iSize; /* Original value of iSize */
  49940. u32 iLast = pPage->pBt->usableSize-4; /* Largest possible freeblock offset */
  49941. u32 iEnd = iStart + iSize; /* First byte past the iStart buffer */
  49942. unsigned char *data = pPage->aData; /* Page content */
  49943. assert( pPage->pBt!=0 );
  49944. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  49945. assert( iStart>=pPage->hdrOffset+6+pPage->childPtrSize );
  49946. assert( iEnd <= pPage->pBt->usableSize );
  49947. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  49948. assert( iSize>=4 ); /* Minimum cell size is 4 */
  49949. assert( iStart<=iLast );
  49950. /* Overwrite deleted information with zeros when the secure_delete
  49951. ** option is enabled */
  49952. if( pPage->pBt->btsFlags & BTS_SECURE_DELETE ){
  49953. memset(&data[iStart], 0, iSize);
  49954. }
  49955. /* The list of freeblocks must be in ascending order. Find the
  49956. ** spot on the list where iStart should be inserted.
  49957. */
  49958. hdr = pPage->hdrOffset;
  49959. iPtr = hdr + 1;
  49960. if( data[iPtr+1]==0 && data[iPtr]==0 ){
  49961. iFreeBlk = 0; /* Shortcut for the case when the freelist is empty */
  49962. }else{
  49963. while( (iFreeBlk = get2byte(&data[iPtr]))>0 && iFreeBlk<iStart ){
  49964. if( iFreeBlk<iPtr+4 ) return SQLITE_CORRUPT_BKPT;
  49965. iPtr = iFreeBlk;
  49966. }
  49967. if( iFreeBlk>iLast ) return SQLITE_CORRUPT_BKPT;
  49968. assert( iFreeBlk>iPtr || iFreeBlk==0 );
  49969. /* At this point:
  49970. ** iFreeBlk: First freeblock after iStart, or zero if none
  49971. ** iPtr: The address of a pointer iFreeBlk
  49972. **
  49973. ** Check to see if iFreeBlk should be coalesced onto the end of iStart.
  49974. */
  49975. if( iFreeBlk && iEnd+3>=iFreeBlk ){
  49976. nFrag = iFreeBlk - iEnd;
  49977. if( iEnd>iFreeBlk ) return SQLITE_CORRUPT_BKPT;
  49978. iEnd = iFreeBlk + get2byte(&data[iFreeBlk+2]);
  49979. iSize = iEnd - iStart;
  49980. iFreeBlk = get2byte(&data[iFreeBlk]);
  49981. }
  49982. /* If iPtr is another freeblock (that is, if iPtr is not the freelist
  49983. ** pointer in the page header) then check to see if iStart should be
  49984. ** coalesced onto the end of iPtr.
  49985. */
  49986. if( iPtr>hdr+1 ){
  49987. int iPtrEnd = iPtr + get2byte(&data[iPtr+2]);
  49988. if( iPtrEnd+3>=iStart ){
  49989. if( iPtrEnd>iStart ) return SQLITE_CORRUPT_BKPT;
  49990. nFrag += iStart - iPtrEnd;
  49991. iSize = iEnd - iPtr;
  49992. iStart = iPtr;
  49993. }
  49994. }
  49995. if( nFrag>data[hdr+7] ) return SQLITE_CORRUPT_BKPT;
  49996. data[hdr+7] -= nFrag;
  49997. }
  49998. if( iStart==get2byte(&data[hdr+5]) ){
  49999. /* The new freeblock is at the beginning of the cell content area,
  50000. ** so just extend the cell content area rather than create another
  50001. ** freelist entry */
  50002. if( iPtr!=hdr+1 ) return SQLITE_CORRUPT_BKPT;
  50003. put2byte(&data[hdr+1], iFreeBlk);
  50004. put2byte(&data[hdr+5], iEnd);
  50005. }else{
  50006. /* Insert the new freeblock into the freelist */
  50007. put2byte(&data[iPtr], iStart);
  50008. put2byte(&data[iStart], iFreeBlk);
  50009. put2byte(&data[iStart+2], iSize);
  50010. }
  50011. pPage->nFree += iOrigSize;
  50012. return SQLITE_OK;
  50013. }
  50014. /*
  50015. ** Decode the flags byte (the first byte of the header) for a page
  50016. ** and initialize fields of the MemPage structure accordingly.
  50017. **
  50018. ** Only the following combinations are supported. Anything different
  50019. ** indicates a corrupt database files:
  50020. **
  50021. ** PTF_ZERODATA
  50022. ** PTF_ZERODATA | PTF_LEAF
  50023. ** PTF_LEAFDATA | PTF_INTKEY
  50024. ** PTF_LEAFDATA | PTF_INTKEY | PTF_LEAF
  50025. */
  50026. static int decodeFlags(MemPage *pPage, int flagByte){
  50027. BtShared *pBt; /* A copy of pPage->pBt */
  50028. assert( pPage->hdrOffset==(pPage->pgno==1 ? 100 : 0) );
  50029. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50030. pPage->leaf = (u8)(flagByte>>3); assert( PTF_LEAF == 1<<3 );
  50031. flagByte &= ~PTF_LEAF;
  50032. pPage->childPtrSize = 4-4*pPage->leaf;
  50033. pBt = pPage->pBt;
  50034. if( flagByte==(PTF_LEAFDATA | PTF_INTKEY) ){
  50035. pPage->intKey = 1;
  50036. pPage->intKeyLeaf = pPage->leaf;
  50037. pPage->noPayload = !pPage->leaf;
  50038. pPage->maxLocal = pBt->maxLeaf;
  50039. pPage->minLocal = pBt->minLeaf;
  50040. }else if( flagByte==PTF_ZERODATA ){
  50041. pPage->intKey = 0;
  50042. pPage->intKeyLeaf = 0;
  50043. pPage->noPayload = 0;
  50044. pPage->maxLocal = pBt->maxLocal;
  50045. pPage->minLocal = pBt->minLocal;
  50046. }else{
  50047. return SQLITE_CORRUPT_BKPT;
  50048. }
  50049. pPage->max1bytePayload = pBt->max1bytePayload;
  50050. return SQLITE_OK;
  50051. }
  50052. /*
  50053. ** Initialize the auxiliary information for a disk block.
  50054. **
  50055. ** Return SQLITE_OK on success. If we see that the page does
  50056. ** not contain a well-formed database page, then return
  50057. ** SQLITE_CORRUPT. Note that a return of SQLITE_OK does not
  50058. ** guarantee that the page is well-formed. It only shows that
  50059. ** we failed to detect any corruption.
  50060. */
  50061. static int btreeInitPage(MemPage *pPage){
  50062. assert( pPage->pBt!=0 );
  50063. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50064. assert( pPage->pgno==sqlite3PagerPagenumber(pPage->pDbPage) );
  50065. assert( pPage == sqlite3PagerGetExtra(pPage->pDbPage) );
  50066. assert( pPage->aData == sqlite3PagerGetData(pPage->pDbPage) );
  50067. if( !pPage->isInit ){
  50068. u16 pc; /* Address of a freeblock within pPage->aData[] */
  50069. u8 hdr; /* Offset to beginning of page header */
  50070. u8 *data; /* Equal to pPage->aData */
  50071. BtShared *pBt; /* The main btree structure */
  50072. int usableSize; /* Amount of usable space on each page */
  50073. u16 cellOffset; /* Offset from start of page to first cell pointer */
  50074. int nFree; /* Number of unused bytes on the page */
  50075. int top; /* First byte of the cell content area */
  50076. int iCellFirst; /* First allowable cell or freeblock offset */
  50077. int iCellLast; /* Last possible cell or freeblock offset */
  50078. pBt = pPage->pBt;
  50079. hdr = pPage->hdrOffset;
  50080. data = pPage->aData;
  50081. if( decodeFlags(pPage, data[hdr]) ) return SQLITE_CORRUPT_BKPT;
  50082. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  50083. pPage->maskPage = (u16)(pBt->pageSize - 1);
  50084. pPage->nOverflow = 0;
  50085. usableSize = pBt->usableSize;
  50086. pPage->cellOffset = cellOffset = hdr + 12 - 4*pPage->leaf;
  50087. pPage->aDataEnd = &data[usableSize];
  50088. pPage->aCellIdx = &data[cellOffset];
  50089. top = get2byteNotZero(&data[hdr+5]);
  50090. pPage->nCell = get2byte(&data[hdr+3]);
  50091. if( pPage->nCell>MX_CELL(pBt) ){
  50092. /* To many cells for a single page. The page must be corrupt */
  50093. return SQLITE_CORRUPT_BKPT;
  50094. }
  50095. testcase( pPage->nCell==MX_CELL(pBt) );
  50096. /* A malformed database page might cause us to read past the end
  50097. ** of page when parsing a cell.
  50098. **
  50099. ** The following block of code checks early to see if a cell extends
  50100. ** past the end of a page boundary and causes SQLITE_CORRUPT to be
  50101. ** returned if it does.
  50102. */
  50103. iCellFirst = cellOffset + 2*pPage->nCell;
  50104. iCellLast = usableSize - 4;
  50105. #if defined(SQLITE_ENABLE_OVERSIZE_CELL_CHECK)
  50106. {
  50107. int i; /* Index into the cell pointer array */
  50108. int sz; /* Size of a cell */
  50109. if( !pPage->leaf ) iCellLast--;
  50110. for(i=0; i<pPage->nCell; i++){
  50111. pc = get2byte(&data[cellOffset+i*2]);
  50112. testcase( pc==iCellFirst );
  50113. testcase( pc==iCellLast );
  50114. if( pc<iCellFirst || pc>iCellLast ){
  50115. return SQLITE_CORRUPT_BKPT;
  50116. }
  50117. sz = cellSizePtr(pPage, &data[pc]);
  50118. testcase( pc+sz==usableSize );
  50119. if( pc+sz>usableSize ){
  50120. return SQLITE_CORRUPT_BKPT;
  50121. }
  50122. }
  50123. if( !pPage->leaf ) iCellLast++;
  50124. }
  50125. #endif
  50126. /* Compute the total free space on the page */
  50127. pc = get2byte(&data[hdr+1]);
  50128. nFree = data[hdr+7] + top;
  50129. while( pc>0 ){
  50130. u16 next, size;
  50131. if( pc<iCellFirst || pc>iCellLast ){
  50132. /* Start of free block is off the page */
  50133. return SQLITE_CORRUPT_BKPT;
  50134. }
  50135. next = get2byte(&data[pc]);
  50136. size = get2byte(&data[pc+2]);
  50137. if( (next>0 && next<=pc+size+3) || pc+size>usableSize ){
  50138. /* Free blocks must be in ascending order. And the last byte of
  50139. ** the free-block must lie on the database page. */
  50140. return SQLITE_CORRUPT_BKPT;
  50141. }
  50142. nFree = nFree + size;
  50143. pc = next;
  50144. }
  50145. /* At this point, nFree contains the sum of the offset to the start
  50146. ** of the cell-content area plus the number of free bytes within
  50147. ** the cell-content area. If this is greater than the usable-size
  50148. ** of the page, then the page must be corrupted. This check also
  50149. ** serves to verify that the offset to the start of the cell-content
  50150. ** area, according to the page header, lies within the page.
  50151. */
  50152. if( nFree>usableSize ){
  50153. return SQLITE_CORRUPT_BKPT;
  50154. }
  50155. pPage->nFree = (u16)(nFree - iCellFirst);
  50156. pPage->isInit = 1;
  50157. }
  50158. return SQLITE_OK;
  50159. }
  50160. /*
  50161. ** Set up a raw page so that it looks like a database page holding
  50162. ** no entries.
  50163. */
  50164. static void zeroPage(MemPage *pPage, int flags){
  50165. unsigned char *data = pPage->aData;
  50166. BtShared *pBt = pPage->pBt;
  50167. u8 hdr = pPage->hdrOffset;
  50168. u16 first;
  50169. assert( sqlite3PagerPagenumber(pPage->pDbPage)==pPage->pgno );
  50170. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  50171. assert( sqlite3PagerGetData(pPage->pDbPage) == data );
  50172. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  50173. assert( sqlite3_mutex_held(pBt->mutex) );
  50174. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  50175. memset(&data[hdr], 0, pBt->usableSize - hdr);
  50176. }
  50177. data[hdr] = (char)flags;
  50178. first = hdr + ((flags&PTF_LEAF)==0 ? 12 : 8);
  50179. memset(&data[hdr+1], 0, 4);
  50180. data[hdr+7] = 0;
  50181. put2byte(&data[hdr+5], pBt->usableSize);
  50182. pPage->nFree = (u16)(pBt->usableSize - first);
  50183. decodeFlags(pPage, flags);
  50184. pPage->cellOffset = first;
  50185. pPage->aDataEnd = &data[pBt->usableSize];
  50186. pPage->aCellIdx = &data[first];
  50187. pPage->nOverflow = 0;
  50188. assert( pBt->pageSize>=512 && pBt->pageSize<=65536 );
  50189. pPage->maskPage = (u16)(pBt->pageSize - 1);
  50190. pPage->nCell = 0;
  50191. pPage->isInit = 1;
  50192. }
  50193. /*
  50194. ** Convert a DbPage obtained from the pager into a MemPage used by
  50195. ** the btree layer.
  50196. */
  50197. static MemPage *btreePageFromDbPage(DbPage *pDbPage, Pgno pgno, BtShared *pBt){
  50198. MemPage *pPage = (MemPage*)sqlite3PagerGetExtra(pDbPage);
  50199. pPage->aData = sqlite3PagerGetData(pDbPage);
  50200. pPage->pDbPage = pDbPage;
  50201. pPage->pBt = pBt;
  50202. pPage->pgno = pgno;
  50203. pPage->hdrOffset = pPage->pgno==1 ? 100 : 0;
  50204. return pPage;
  50205. }
  50206. /*
  50207. ** Get a page from the pager. Initialize the MemPage.pBt and
  50208. ** MemPage.aData elements if needed.
  50209. **
  50210. ** If the noContent flag is set, it means that we do not care about
  50211. ** the content of the page at this time. So do not go to the disk
  50212. ** to fetch the content. Just fill in the content with zeros for now.
  50213. ** If in the future we call sqlite3PagerWrite() on this page, that
  50214. ** means we have started to be concerned about content and the disk
  50215. ** read should occur at that point.
  50216. */
  50217. static int btreeGetPage(
  50218. BtShared *pBt, /* The btree */
  50219. Pgno pgno, /* Number of the page to fetch */
  50220. MemPage **ppPage, /* Return the page in this parameter */
  50221. int flags /* PAGER_GET_NOCONTENT or PAGER_GET_READONLY */
  50222. ){
  50223. int rc;
  50224. DbPage *pDbPage;
  50225. assert( flags==0 || flags==PAGER_GET_NOCONTENT || flags==PAGER_GET_READONLY );
  50226. assert( sqlite3_mutex_held(pBt->mutex) );
  50227. rc = sqlite3PagerAcquire(pBt->pPager, pgno, (DbPage**)&pDbPage, flags);
  50228. if( rc ) return rc;
  50229. *ppPage = btreePageFromDbPage(pDbPage, pgno, pBt);
  50230. return SQLITE_OK;
  50231. }
  50232. /*
  50233. ** Retrieve a page from the pager cache. If the requested page is not
  50234. ** already in the pager cache return NULL. Initialize the MemPage.pBt and
  50235. ** MemPage.aData elements if needed.
  50236. */
  50237. static MemPage *btreePageLookup(BtShared *pBt, Pgno pgno){
  50238. DbPage *pDbPage;
  50239. assert( sqlite3_mutex_held(pBt->mutex) );
  50240. pDbPage = sqlite3PagerLookup(pBt->pPager, pgno);
  50241. if( pDbPage ){
  50242. return btreePageFromDbPage(pDbPage, pgno, pBt);
  50243. }
  50244. return 0;
  50245. }
  50246. /*
  50247. ** Return the size of the database file in pages. If there is any kind of
  50248. ** error, return ((unsigned int)-1).
  50249. */
  50250. static Pgno btreePagecount(BtShared *pBt){
  50251. return pBt->nPage;
  50252. }
  50253. SQLITE_PRIVATE u32 sqlite3BtreeLastPage(Btree *p){
  50254. assert( sqlite3BtreeHoldsMutex(p) );
  50255. assert( ((p->pBt->nPage)&0x8000000)==0 );
  50256. return btreePagecount(p->pBt);
  50257. }
  50258. /*
  50259. ** Get a page from the pager and initialize it. This routine is just a
  50260. ** convenience wrapper around separate calls to btreeGetPage() and
  50261. ** btreeInitPage().
  50262. **
  50263. ** If an error occurs, then the value *ppPage is set to is undefined. It
  50264. ** may remain unchanged, or it may be set to an invalid value.
  50265. */
  50266. static int getAndInitPage(
  50267. BtShared *pBt, /* The database file */
  50268. Pgno pgno, /* Number of the page to get */
  50269. MemPage **ppPage, /* Write the page pointer here */
  50270. int bReadonly /* PAGER_GET_READONLY or 0 */
  50271. ){
  50272. int rc;
  50273. assert( sqlite3_mutex_held(pBt->mutex) );
  50274. assert( bReadonly==PAGER_GET_READONLY || bReadonly==0 );
  50275. if( pgno>btreePagecount(pBt) ){
  50276. rc = SQLITE_CORRUPT_BKPT;
  50277. }else{
  50278. rc = btreeGetPage(pBt, pgno, ppPage, bReadonly);
  50279. if( rc==SQLITE_OK && (*ppPage)->isInit==0 ){
  50280. rc = btreeInitPage(*ppPage);
  50281. if( rc!=SQLITE_OK ){
  50282. releasePage(*ppPage);
  50283. }
  50284. }
  50285. }
  50286. testcase( pgno==0 );
  50287. assert( pgno!=0 || rc==SQLITE_CORRUPT );
  50288. return rc;
  50289. }
  50290. /*
  50291. ** Release a MemPage. This should be called once for each prior
  50292. ** call to btreeGetPage.
  50293. */
  50294. static void releasePage(MemPage *pPage){
  50295. if( pPage ){
  50296. assert( pPage->aData );
  50297. assert( pPage->pBt );
  50298. assert( pPage->pDbPage!=0 );
  50299. assert( sqlite3PagerGetExtra(pPage->pDbPage) == (void*)pPage );
  50300. assert( sqlite3PagerGetData(pPage->pDbPage)==pPage->aData );
  50301. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50302. sqlite3PagerUnrefNotNull(pPage->pDbPage);
  50303. }
  50304. }
  50305. /*
  50306. ** During a rollback, when the pager reloads information into the cache
  50307. ** so that the cache is restored to its original state at the start of
  50308. ** the transaction, for each page restored this routine is called.
  50309. **
  50310. ** This routine needs to reset the extra data section at the end of the
  50311. ** page to agree with the restored data.
  50312. */
  50313. static void pageReinit(DbPage *pData){
  50314. MemPage *pPage;
  50315. pPage = (MemPage *)sqlite3PagerGetExtra(pData);
  50316. assert( sqlite3PagerPageRefcount(pData)>0 );
  50317. if( pPage->isInit ){
  50318. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  50319. pPage->isInit = 0;
  50320. if( sqlite3PagerPageRefcount(pData)>1 ){
  50321. /* pPage might not be a btree page; it might be an overflow page
  50322. ** or ptrmap page or a free page. In those cases, the following
  50323. ** call to btreeInitPage() will likely return SQLITE_CORRUPT.
  50324. ** But no harm is done by this. And it is very important that
  50325. ** btreeInitPage() be called on every btree page so we make
  50326. ** the call for every page that comes in for re-initing. */
  50327. btreeInitPage(pPage);
  50328. }
  50329. }
  50330. }
  50331. /*
  50332. ** Invoke the busy handler for a btree.
  50333. */
  50334. static int btreeInvokeBusyHandler(void *pArg){
  50335. BtShared *pBt = (BtShared*)pArg;
  50336. assert( pBt->db );
  50337. assert( sqlite3_mutex_held(pBt->db->mutex) );
  50338. return sqlite3InvokeBusyHandler(&pBt->db->busyHandler);
  50339. }
  50340. /*
  50341. ** Open a database file.
  50342. **
  50343. ** zFilename is the name of the database file. If zFilename is NULL
  50344. ** then an ephemeral database is created. The ephemeral database might
  50345. ** be exclusively in memory, or it might use a disk-based memory cache.
  50346. ** Either way, the ephemeral database will be automatically deleted
  50347. ** when sqlite3BtreeClose() is called.
  50348. **
  50349. ** If zFilename is ":memory:" then an in-memory database is created
  50350. ** that is automatically destroyed when it is closed.
  50351. **
  50352. ** The "flags" parameter is a bitmask that might contain bits like
  50353. ** BTREE_OMIT_JOURNAL and/or BTREE_MEMORY.
  50354. **
  50355. ** If the database is already opened in the same database connection
  50356. ** and we are in shared cache mode, then the open will fail with an
  50357. ** SQLITE_CONSTRAINT error. We cannot allow two or more BtShared
  50358. ** objects in the same database connection since doing so will lead
  50359. ** to problems with locking.
  50360. */
  50361. SQLITE_PRIVATE int sqlite3BtreeOpen(
  50362. sqlite3_vfs *pVfs, /* VFS to use for this b-tree */
  50363. const char *zFilename, /* Name of the file containing the BTree database */
  50364. sqlite3 *db, /* Associated database handle */
  50365. Btree **ppBtree, /* Pointer to new Btree object written here */
  50366. int flags, /* Options */
  50367. int vfsFlags /* Flags passed through to sqlite3_vfs.xOpen() */
  50368. ){
  50369. BtShared *pBt = 0; /* Shared part of btree structure */
  50370. Btree *p; /* Handle to return */
  50371. sqlite3_mutex *mutexOpen = 0; /* Prevents a race condition. Ticket #3537 */
  50372. int rc = SQLITE_OK; /* Result code from this function */
  50373. u8 nReserve; /* Byte of unused space on each page */
  50374. unsigned char zDbHeader[100]; /* Database header content */
  50375. /* True if opening an ephemeral, temporary database */
  50376. const int isTempDb = zFilename==0 || zFilename[0]==0;
  50377. /* Set the variable isMemdb to true for an in-memory database, or
  50378. ** false for a file-based database.
  50379. */
  50380. #ifdef SQLITE_OMIT_MEMORYDB
  50381. const int isMemdb = 0;
  50382. #else
  50383. const int isMemdb = (zFilename && strcmp(zFilename, ":memory:")==0)
  50384. || (isTempDb && sqlite3TempInMemory(db))
  50385. || (vfsFlags & SQLITE_OPEN_MEMORY)!=0;
  50386. #endif
  50387. assert( db!=0 );
  50388. assert( pVfs!=0 );
  50389. assert( sqlite3_mutex_held(db->mutex) );
  50390. assert( (flags&0xff)==flags ); /* flags fit in 8 bits */
  50391. /* Only a BTREE_SINGLE database can be BTREE_UNORDERED */
  50392. assert( (flags & BTREE_UNORDERED)==0 || (flags & BTREE_SINGLE)!=0 );
  50393. /* A BTREE_SINGLE database is always a temporary and/or ephemeral */
  50394. assert( (flags & BTREE_SINGLE)==0 || isTempDb );
  50395. if( isMemdb ){
  50396. flags |= BTREE_MEMORY;
  50397. }
  50398. if( (vfsFlags & SQLITE_OPEN_MAIN_DB)!=0 && (isMemdb || isTempDb) ){
  50399. vfsFlags = (vfsFlags & ~SQLITE_OPEN_MAIN_DB) | SQLITE_OPEN_TEMP_DB;
  50400. }
  50401. p = sqlite3MallocZero(sizeof(Btree));
  50402. if( !p ){
  50403. return SQLITE_NOMEM;
  50404. }
  50405. p->inTrans = TRANS_NONE;
  50406. p->db = db;
  50407. #ifndef SQLITE_OMIT_SHARED_CACHE
  50408. p->lock.pBtree = p;
  50409. p->lock.iTable = 1;
  50410. #endif
  50411. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  50412. /*
  50413. ** If this Btree is a candidate for shared cache, try to find an
  50414. ** existing BtShared object that we can share with
  50415. */
  50416. if( isTempDb==0 && (isMemdb==0 || (vfsFlags&SQLITE_OPEN_URI)!=0) ){
  50417. if( vfsFlags & SQLITE_OPEN_SHAREDCACHE ){
  50418. int nFullPathname = pVfs->mxPathname+1;
  50419. char *zFullPathname = sqlite3Malloc(nFullPathname);
  50420. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  50421. p->sharable = 1;
  50422. if( !zFullPathname ){
  50423. sqlite3_free(p);
  50424. return SQLITE_NOMEM;
  50425. }
  50426. if( isMemdb ){
  50427. memcpy(zFullPathname, zFilename, sqlite3Strlen30(zFilename)+1);
  50428. }else{
  50429. rc = sqlite3OsFullPathname(pVfs, zFilename,
  50430. nFullPathname, zFullPathname);
  50431. if( rc ){
  50432. sqlite3_free(zFullPathname);
  50433. sqlite3_free(p);
  50434. return rc;
  50435. }
  50436. }
  50437. #if SQLITE_THREADSAFE
  50438. mutexOpen = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_OPEN);
  50439. sqlite3_mutex_enter(mutexOpen);
  50440. mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  50441. sqlite3_mutex_enter(mutexShared);
  50442. #endif
  50443. for(pBt=GLOBAL(BtShared*,sqlite3SharedCacheList); pBt; pBt=pBt->pNext){
  50444. assert( pBt->nRef>0 );
  50445. if( 0==strcmp(zFullPathname, sqlite3PagerFilename(pBt->pPager, 0))
  50446. && sqlite3PagerVfs(pBt->pPager)==pVfs ){
  50447. int iDb;
  50448. for(iDb=db->nDb-1; iDb>=0; iDb--){
  50449. Btree *pExisting = db->aDb[iDb].pBt;
  50450. if( pExisting && pExisting->pBt==pBt ){
  50451. sqlite3_mutex_leave(mutexShared);
  50452. sqlite3_mutex_leave(mutexOpen);
  50453. sqlite3_free(zFullPathname);
  50454. sqlite3_free(p);
  50455. return SQLITE_CONSTRAINT;
  50456. }
  50457. }
  50458. p->pBt = pBt;
  50459. pBt->nRef++;
  50460. break;
  50461. }
  50462. }
  50463. sqlite3_mutex_leave(mutexShared);
  50464. sqlite3_free(zFullPathname);
  50465. }
  50466. #ifdef SQLITE_DEBUG
  50467. else{
  50468. /* In debug mode, we mark all persistent databases as sharable
  50469. ** even when they are not. This exercises the locking code and
  50470. ** gives more opportunity for asserts(sqlite3_mutex_held())
  50471. ** statements to find locking problems.
  50472. */
  50473. p->sharable = 1;
  50474. }
  50475. #endif
  50476. }
  50477. #endif
  50478. if( pBt==0 ){
  50479. /*
  50480. ** The following asserts make sure that structures used by the btree are
  50481. ** the right size. This is to guard against size changes that result
  50482. ** when compiling on a different architecture.
  50483. */
  50484. assert( sizeof(i64)==8 || sizeof(i64)==4 );
  50485. assert( sizeof(u64)==8 || sizeof(u64)==4 );
  50486. assert( sizeof(u32)==4 );
  50487. assert( sizeof(u16)==2 );
  50488. assert( sizeof(Pgno)==4 );
  50489. pBt = sqlite3MallocZero( sizeof(*pBt) );
  50490. if( pBt==0 ){
  50491. rc = SQLITE_NOMEM;
  50492. goto btree_open_out;
  50493. }
  50494. rc = sqlite3PagerOpen(pVfs, &pBt->pPager, zFilename,
  50495. EXTRA_SIZE, flags, vfsFlags, pageReinit);
  50496. if( rc==SQLITE_OK ){
  50497. sqlite3PagerSetMmapLimit(pBt->pPager, db->szMmap);
  50498. rc = sqlite3PagerReadFileheader(pBt->pPager,sizeof(zDbHeader),zDbHeader);
  50499. }
  50500. if( rc!=SQLITE_OK ){
  50501. goto btree_open_out;
  50502. }
  50503. pBt->openFlags = (u8)flags;
  50504. pBt->db = db;
  50505. sqlite3PagerSetBusyhandler(pBt->pPager, btreeInvokeBusyHandler, pBt);
  50506. p->pBt = pBt;
  50507. pBt->pCursor = 0;
  50508. pBt->pPage1 = 0;
  50509. if( sqlite3PagerIsreadonly(pBt->pPager) ) pBt->btsFlags |= BTS_READ_ONLY;
  50510. #ifdef SQLITE_SECURE_DELETE
  50511. pBt->btsFlags |= BTS_SECURE_DELETE;
  50512. #endif
  50513. pBt->pageSize = (zDbHeader[16]<<8) | (zDbHeader[17]<<16);
  50514. if( pBt->pageSize<512 || pBt->pageSize>SQLITE_MAX_PAGE_SIZE
  50515. || ((pBt->pageSize-1)&pBt->pageSize)!=0 ){
  50516. pBt->pageSize = 0;
  50517. #ifndef SQLITE_OMIT_AUTOVACUUM
  50518. /* If the magic name ":memory:" will create an in-memory database, then
  50519. ** leave the autoVacuum mode at 0 (do not auto-vacuum), even if
  50520. ** SQLITE_DEFAULT_AUTOVACUUM is true. On the other hand, if
  50521. ** SQLITE_OMIT_MEMORYDB has been defined, then ":memory:" is just a
  50522. ** regular file-name. In this case the auto-vacuum applies as per normal.
  50523. */
  50524. if( zFilename && !isMemdb ){
  50525. pBt->autoVacuum = (SQLITE_DEFAULT_AUTOVACUUM ? 1 : 0);
  50526. pBt->incrVacuum = (SQLITE_DEFAULT_AUTOVACUUM==2 ? 1 : 0);
  50527. }
  50528. #endif
  50529. nReserve = 0;
  50530. }else{
  50531. nReserve = zDbHeader[20];
  50532. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  50533. #ifndef SQLITE_OMIT_AUTOVACUUM
  50534. pBt->autoVacuum = (get4byte(&zDbHeader[36 + 4*4])?1:0);
  50535. pBt->incrVacuum = (get4byte(&zDbHeader[36 + 7*4])?1:0);
  50536. #endif
  50537. }
  50538. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  50539. if( rc ) goto btree_open_out;
  50540. pBt->usableSize = pBt->pageSize - nReserve;
  50541. assert( (pBt->pageSize & 7)==0 ); /* 8-byte alignment of pageSize */
  50542. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  50543. /* Add the new BtShared object to the linked list sharable BtShareds.
  50544. */
  50545. if( p->sharable ){
  50546. MUTEX_LOGIC( sqlite3_mutex *mutexShared; )
  50547. pBt->nRef = 1;
  50548. MUTEX_LOGIC( mutexShared = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);)
  50549. if( SQLITE_THREADSAFE && sqlite3GlobalConfig.bCoreMutex ){
  50550. pBt->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_FAST);
  50551. if( pBt->mutex==0 ){
  50552. rc = SQLITE_NOMEM;
  50553. db->mallocFailed = 0;
  50554. goto btree_open_out;
  50555. }
  50556. }
  50557. sqlite3_mutex_enter(mutexShared);
  50558. pBt->pNext = GLOBAL(BtShared*,sqlite3SharedCacheList);
  50559. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt;
  50560. sqlite3_mutex_leave(mutexShared);
  50561. }
  50562. #endif
  50563. }
  50564. #if !defined(SQLITE_OMIT_SHARED_CACHE) && !defined(SQLITE_OMIT_DISKIO)
  50565. /* If the new Btree uses a sharable pBtShared, then link the new
  50566. ** Btree into the list of all sharable Btrees for the same connection.
  50567. ** The list is kept in ascending order by pBt address.
  50568. */
  50569. if( p->sharable ){
  50570. int i;
  50571. Btree *pSib;
  50572. for(i=0; i<db->nDb; i++){
  50573. if( (pSib = db->aDb[i].pBt)!=0 && pSib->sharable ){
  50574. while( pSib->pPrev ){ pSib = pSib->pPrev; }
  50575. if( p->pBt<pSib->pBt ){
  50576. p->pNext = pSib;
  50577. p->pPrev = 0;
  50578. pSib->pPrev = p;
  50579. }else{
  50580. while( pSib->pNext && pSib->pNext->pBt<p->pBt ){
  50581. pSib = pSib->pNext;
  50582. }
  50583. p->pNext = pSib->pNext;
  50584. p->pPrev = pSib;
  50585. if( p->pNext ){
  50586. p->pNext->pPrev = p;
  50587. }
  50588. pSib->pNext = p;
  50589. }
  50590. break;
  50591. }
  50592. }
  50593. }
  50594. #endif
  50595. *ppBtree = p;
  50596. btree_open_out:
  50597. if( rc!=SQLITE_OK ){
  50598. if( pBt && pBt->pPager ){
  50599. sqlite3PagerClose(pBt->pPager);
  50600. }
  50601. sqlite3_free(pBt);
  50602. sqlite3_free(p);
  50603. *ppBtree = 0;
  50604. }else{
  50605. /* If the B-Tree was successfully opened, set the pager-cache size to the
  50606. ** default value. Except, when opening on an existing shared pager-cache,
  50607. ** do not change the pager-cache size.
  50608. */
  50609. if( sqlite3BtreeSchema(p, 0, 0)==0 ){
  50610. sqlite3PagerSetCachesize(p->pBt->pPager, SQLITE_DEFAULT_CACHE_SIZE);
  50611. }
  50612. }
  50613. if( mutexOpen ){
  50614. assert( sqlite3_mutex_held(mutexOpen) );
  50615. sqlite3_mutex_leave(mutexOpen);
  50616. }
  50617. return rc;
  50618. }
  50619. /*
  50620. ** Decrement the BtShared.nRef counter. When it reaches zero,
  50621. ** remove the BtShared structure from the sharing list. Return
  50622. ** true if the BtShared.nRef counter reaches zero and return
  50623. ** false if it is still positive.
  50624. */
  50625. static int removeFromSharingList(BtShared *pBt){
  50626. #ifndef SQLITE_OMIT_SHARED_CACHE
  50627. MUTEX_LOGIC( sqlite3_mutex *pMaster; )
  50628. BtShared *pList;
  50629. int removed = 0;
  50630. assert( sqlite3_mutex_notheld(pBt->mutex) );
  50631. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  50632. sqlite3_mutex_enter(pMaster);
  50633. pBt->nRef--;
  50634. if( pBt->nRef<=0 ){
  50635. if( GLOBAL(BtShared*,sqlite3SharedCacheList)==pBt ){
  50636. GLOBAL(BtShared*,sqlite3SharedCacheList) = pBt->pNext;
  50637. }else{
  50638. pList = GLOBAL(BtShared*,sqlite3SharedCacheList);
  50639. while( ALWAYS(pList) && pList->pNext!=pBt ){
  50640. pList=pList->pNext;
  50641. }
  50642. if( ALWAYS(pList) ){
  50643. pList->pNext = pBt->pNext;
  50644. }
  50645. }
  50646. if( SQLITE_THREADSAFE ){
  50647. sqlite3_mutex_free(pBt->mutex);
  50648. }
  50649. removed = 1;
  50650. }
  50651. sqlite3_mutex_leave(pMaster);
  50652. return removed;
  50653. #else
  50654. return 1;
  50655. #endif
  50656. }
  50657. /*
  50658. ** Make sure pBt->pTmpSpace points to an allocation of
  50659. ** MX_CELL_SIZE(pBt) bytes with a 4-byte prefix for a left-child
  50660. ** pointer.
  50661. */
  50662. static void allocateTempSpace(BtShared *pBt){
  50663. if( !pBt->pTmpSpace ){
  50664. pBt->pTmpSpace = sqlite3PageMalloc( pBt->pageSize );
  50665. /* One of the uses of pBt->pTmpSpace is to format cells before
  50666. ** inserting them into a leaf page (function fillInCell()). If
  50667. ** a cell is less than 4 bytes in size, it is rounded up to 4 bytes
  50668. ** by the various routines that manipulate binary cells. Which
  50669. ** can mean that fillInCell() only initializes the first 2 or 3
  50670. ** bytes of pTmpSpace, but that the first 4 bytes are copied from
  50671. ** it into a database page. This is not actually a problem, but it
  50672. ** does cause a valgrind error when the 1 or 2 bytes of unitialized
  50673. ** data is passed to system call write(). So to avoid this error,
  50674. ** zero the first 4 bytes of temp space here.
  50675. **
  50676. ** Also: Provide four bytes of initialized space before the
  50677. ** beginning of pTmpSpace as an area available to prepend the
  50678. ** left-child pointer to the beginning of a cell.
  50679. */
  50680. if( pBt->pTmpSpace ){
  50681. memset(pBt->pTmpSpace, 0, 8);
  50682. pBt->pTmpSpace += 4;
  50683. }
  50684. }
  50685. }
  50686. /*
  50687. ** Free the pBt->pTmpSpace allocation
  50688. */
  50689. static void freeTempSpace(BtShared *pBt){
  50690. if( pBt->pTmpSpace ){
  50691. pBt->pTmpSpace -= 4;
  50692. sqlite3PageFree(pBt->pTmpSpace);
  50693. pBt->pTmpSpace = 0;
  50694. }
  50695. }
  50696. /*
  50697. ** Close an open database and invalidate all cursors.
  50698. */
  50699. SQLITE_PRIVATE int sqlite3BtreeClose(Btree *p){
  50700. BtShared *pBt = p->pBt;
  50701. BtCursor *pCur;
  50702. /* Close all cursors opened via this handle. */
  50703. assert( sqlite3_mutex_held(p->db->mutex) );
  50704. sqlite3BtreeEnter(p);
  50705. pCur = pBt->pCursor;
  50706. while( pCur ){
  50707. BtCursor *pTmp = pCur;
  50708. pCur = pCur->pNext;
  50709. if( pTmp->pBtree==p ){
  50710. sqlite3BtreeCloseCursor(pTmp);
  50711. }
  50712. }
  50713. /* Rollback any active transaction and free the handle structure.
  50714. ** The call to sqlite3BtreeRollback() drops any table-locks held by
  50715. ** this handle.
  50716. */
  50717. sqlite3BtreeRollback(p, SQLITE_OK, 0);
  50718. sqlite3BtreeLeave(p);
  50719. /* If there are still other outstanding references to the shared-btree
  50720. ** structure, return now. The remainder of this procedure cleans
  50721. ** up the shared-btree.
  50722. */
  50723. assert( p->wantToLock==0 && p->locked==0 );
  50724. if( !p->sharable || removeFromSharingList(pBt) ){
  50725. /* The pBt is no longer on the sharing list, so we can access
  50726. ** it without having to hold the mutex.
  50727. **
  50728. ** Clean out and delete the BtShared object.
  50729. */
  50730. assert( !pBt->pCursor );
  50731. sqlite3PagerClose(pBt->pPager);
  50732. if( pBt->xFreeSchema && pBt->pSchema ){
  50733. pBt->xFreeSchema(pBt->pSchema);
  50734. }
  50735. sqlite3DbFree(0, pBt->pSchema);
  50736. freeTempSpace(pBt);
  50737. sqlite3_free(pBt);
  50738. }
  50739. #ifndef SQLITE_OMIT_SHARED_CACHE
  50740. assert( p->wantToLock==0 );
  50741. assert( p->locked==0 );
  50742. if( p->pPrev ) p->pPrev->pNext = p->pNext;
  50743. if( p->pNext ) p->pNext->pPrev = p->pPrev;
  50744. #endif
  50745. sqlite3_free(p);
  50746. return SQLITE_OK;
  50747. }
  50748. /*
  50749. ** Change the limit on the number of pages allowed in the cache.
  50750. **
  50751. ** The maximum number of cache pages is set to the absolute
  50752. ** value of mxPage. If mxPage is negative, the pager will
  50753. ** operate asynchronously - it will not stop to do fsync()s
  50754. ** to insure data is written to the disk surface before
  50755. ** continuing. Transactions still work if synchronous is off,
  50756. ** and the database cannot be corrupted if this program
  50757. ** crashes. But if the operating system crashes or there is
  50758. ** an abrupt power failure when synchronous is off, the database
  50759. ** could be left in an inconsistent and unrecoverable state.
  50760. ** Synchronous is on by default so database corruption is not
  50761. ** normally a worry.
  50762. */
  50763. SQLITE_PRIVATE int sqlite3BtreeSetCacheSize(Btree *p, int mxPage){
  50764. BtShared *pBt = p->pBt;
  50765. assert( sqlite3_mutex_held(p->db->mutex) );
  50766. sqlite3BtreeEnter(p);
  50767. sqlite3PagerSetCachesize(pBt->pPager, mxPage);
  50768. sqlite3BtreeLeave(p);
  50769. return SQLITE_OK;
  50770. }
  50771. #if SQLITE_MAX_MMAP_SIZE>0
  50772. /*
  50773. ** Change the limit on the amount of the database file that may be
  50774. ** memory mapped.
  50775. */
  50776. SQLITE_PRIVATE int sqlite3BtreeSetMmapLimit(Btree *p, sqlite3_int64 szMmap){
  50777. BtShared *pBt = p->pBt;
  50778. assert( sqlite3_mutex_held(p->db->mutex) );
  50779. sqlite3BtreeEnter(p);
  50780. sqlite3PagerSetMmapLimit(pBt->pPager, szMmap);
  50781. sqlite3BtreeLeave(p);
  50782. return SQLITE_OK;
  50783. }
  50784. #endif /* SQLITE_MAX_MMAP_SIZE>0 */
  50785. /*
  50786. ** Change the way data is synced to disk in order to increase or decrease
  50787. ** how well the database resists damage due to OS crashes and power
  50788. ** failures. Level 1 is the same as asynchronous (no syncs() occur and
  50789. ** there is a high probability of damage) Level 2 is the default. There
  50790. ** is a very low but non-zero probability of damage. Level 3 reduces the
  50791. ** probability of damage to near zero but with a write performance reduction.
  50792. */
  50793. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  50794. SQLITE_PRIVATE int sqlite3BtreeSetPagerFlags(
  50795. Btree *p, /* The btree to set the safety level on */
  50796. unsigned pgFlags /* Various PAGER_* flags */
  50797. ){
  50798. BtShared *pBt = p->pBt;
  50799. assert( sqlite3_mutex_held(p->db->mutex) );
  50800. sqlite3BtreeEnter(p);
  50801. sqlite3PagerSetFlags(pBt->pPager, pgFlags);
  50802. sqlite3BtreeLeave(p);
  50803. return SQLITE_OK;
  50804. }
  50805. #endif
  50806. /*
  50807. ** Return TRUE if the given btree is set to safety level 1. In other
  50808. ** words, return TRUE if no sync() occurs on the disk files.
  50809. */
  50810. SQLITE_PRIVATE int sqlite3BtreeSyncDisabled(Btree *p){
  50811. BtShared *pBt = p->pBt;
  50812. int rc;
  50813. assert( sqlite3_mutex_held(p->db->mutex) );
  50814. sqlite3BtreeEnter(p);
  50815. assert( pBt && pBt->pPager );
  50816. rc = sqlite3PagerNosync(pBt->pPager);
  50817. sqlite3BtreeLeave(p);
  50818. return rc;
  50819. }
  50820. /*
  50821. ** Change the default pages size and the number of reserved bytes per page.
  50822. ** Or, if the page size has already been fixed, return SQLITE_READONLY
  50823. ** without changing anything.
  50824. **
  50825. ** The page size must be a power of 2 between 512 and 65536. If the page
  50826. ** size supplied does not meet this constraint then the page size is not
  50827. ** changed.
  50828. **
  50829. ** Page sizes are constrained to be a power of two so that the region
  50830. ** of the database file used for locking (beginning at PENDING_BYTE,
  50831. ** the first byte past the 1GB boundary, 0x40000000) needs to occur
  50832. ** at the beginning of a page.
  50833. **
  50834. ** If parameter nReserve is less than zero, then the number of reserved
  50835. ** bytes per page is left unchanged.
  50836. **
  50837. ** If the iFix!=0 then the BTS_PAGESIZE_FIXED flag is set so that the page size
  50838. ** and autovacuum mode can no longer be changed.
  50839. */
  50840. SQLITE_PRIVATE int sqlite3BtreeSetPageSize(Btree *p, int pageSize, int nReserve, int iFix){
  50841. int rc = SQLITE_OK;
  50842. BtShared *pBt = p->pBt;
  50843. assert( nReserve>=-1 && nReserve<=255 );
  50844. sqlite3BtreeEnter(p);
  50845. if( pBt->btsFlags & BTS_PAGESIZE_FIXED ){
  50846. sqlite3BtreeLeave(p);
  50847. return SQLITE_READONLY;
  50848. }
  50849. if( nReserve<0 ){
  50850. nReserve = pBt->pageSize - pBt->usableSize;
  50851. }
  50852. assert( nReserve>=0 && nReserve<=255 );
  50853. if( pageSize>=512 && pageSize<=SQLITE_MAX_PAGE_SIZE &&
  50854. ((pageSize-1)&pageSize)==0 ){
  50855. assert( (pageSize & 7)==0 );
  50856. assert( !pBt->pPage1 && !pBt->pCursor );
  50857. pBt->pageSize = (u32)pageSize;
  50858. freeTempSpace(pBt);
  50859. }
  50860. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize, nReserve);
  50861. pBt->usableSize = pBt->pageSize - (u16)nReserve;
  50862. if( iFix ) pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  50863. sqlite3BtreeLeave(p);
  50864. return rc;
  50865. }
  50866. /*
  50867. ** Return the currently defined page size
  50868. */
  50869. SQLITE_PRIVATE int sqlite3BtreeGetPageSize(Btree *p){
  50870. return p->pBt->pageSize;
  50871. }
  50872. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_DEBUG)
  50873. /*
  50874. ** This function is similar to sqlite3BtreeGetReserve(), except that it
  50875. ** may only be called if it is guaranteed that the b-tree mutex is already
  50876. ** held.
  50877. **
  50878. ** This is useful in one special case in the backup API code where it is
  50879. ** known that the shared b-tree mutex is held, but the mutex on the
  50880. ** database handle that owns *p is not. In this case if sqlite3BtreeEnter()
  50881. ** were to be called, it might collide with some other operation on the
  50882. ** database handle that owns *p, causing undefined behavior.
  50883. */
  50884. SQLITE_PRIVATE int sqlite3BtreeGetReserveNoMutex(Btree *p){
  50885. assert( sqlite3_mutex_held(p->pBt->mutex) );
  50886. return p->pBt->pageSize - p->pBt->usableSize;
  50887. }
  50888. #endif /* SQLITE_HAS_CODEC || SQLITE_DEBUG */
  50889. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM)
  50890. /*
  50891. ** Return the number of bytes of space at the end of every page that
  50892. ** are intentually left unused. This is the "reserved" space that is
  50893. ** sometimes used by extensions.
  50894. */
  50895. SQLITE_PRIVATE int sqlite3BtreeGetReserve(Btree *p){
  50896. int n;
  50897. sqlite3BtreeEnter(p);
  50898. n = p->pBt->pageSize - p->pBt->usableSize;
  50899. sqlite3BtreeLeave(p);
  50900. return n;
  50901. }
  50902. /*
  50903. ** Set the maximum page count for a database if mxPage is positive.
  50904. ** No changes are made if mxPage is 0 or negative.
  50905. ** Regardless of the value of mxPage, return the maximum page count.
  50906. */
  50907. SQLITE_PRIVATE int sqlite3BtreeMaxPageCount(Btree *p, int mxPage){
  50908. int n;
  50909. sqlite3BtreeEnter(p);
  50910. n = sqlite3PagerMaxPageCount(p->pBt->pPager, mxPage);
  50911. sqlite3BtreeLeave(p);
  50912. return n;
  50913. }
  50914. /*
  50915. ** Set the BTS_SECURE_DELETE flag if newFlag is 0 or 1. If newFlag is -1,
  50916. ** then make no changes. Always return the value of the BTS_SECURE_DELETE
  50917. ** setting after the change.
  50918. */
  50919. SQLITE_PRIVATE int sqlite3BtreeSecureDelete(Btree *p, int newFlag){
  50920. int b;
  50921. if( p==0 ) return 0;
  50922. sqlite3BtreeEnter(p);
  50923. if( newFlag>=0 ){
  50924. p->pBt->btsFlags &= ~BTS_SECURE_DELETE;
  50925. if( newFlag ) p->pBt->btsFlags |= BTS_SECURE_DELETE;
  50926. }
  50927. b = (p->pBt->btsFlags & BTS_SECURE_DELETE)!=0;
  50928. sqlite3BtreeLeave(p);
  50929. return b;
  50930. }
  50931. #endif /* !defined(SQLITE_OMIT_PAGER_PRAGMAS) || !defined(SQLITE_OMIT_VACUUM) */
  50932. /*
  50933. ** Change the 'auto-vacuum' property of the database. If the 'autoVacuum'
  50934. ** parameter is non-zero, then auto-vacuum mode is enabled. If zero, it
  50935. ** is disabled. The default value for the auto-vacuum property is
  50936. ** determined by the SQLITE_DEFAULT_AUTOVACUUM macro.
  50937. */
  50938. SQLITE_PRIVATE int sqlite3BtreeSetAutoVacuum(Btree *p, int autoVacuum){
  50939. #ifdef SQLITE_OMIT_AUTOVACUUM
  50940. return SQLITE_READONLY;
  50941. #else
  50942. BtShared *pBt = p->pBt;
  50943. int rc = SQLITE_OK;
  50944. u8 av = (u8)autoVacuum;
  50945. sqlite3BtreeEnter(p);
  50946. if( (pBt->btsFlags & BTS_PAGESIZE_FIXED)!=0 && (av ?1:0)!=pBt->autoVacuum ){
  50947. rc = SQLITE_READONLY;
  50948. }else{
  50949. pBt->autoVacuum = av ?1:0;
  50950. pBt->incrVacuum = av==2 ?1:0;
  50951. }
  50952. sqlite3BtreeLeave(p);
  50953. return rc;
  50954. #endif
  50955. }
  50956. /*
  50957. ** Return the value of the 'auto-vacuum' property. If auto-vacuum is
  50958. ** enabled 1 is returned. Otherwise 0.
  50959. */
  50960. SQLITE_PRIVATE int sqlite3BtreeGetAutoVacuum(Btree *p){
  50961. #ifdef SQLITE_OMIT_AUTOVACUUM
  50962. return BTREE_AUTOVACUUM_NONE;
  50963. #else
  50964. int rc;
  50965. sqlite3BtreeEnter(p);
  50966. rc = (
  50967. (!p->pBt->autoVacuum)?BTREE_AUTOVACUUM_NONE:
  50968. (!p->pBt->incrVacuum)?BTREE_AUTOVACUUM_FULL:
  50969. BTREE_AUTOVACUUM_INCR
  50970. );
  50971. sqlite3BtreeLeave(p);
  50972. return rc;
  50973. #endif
  50974. }
  50975. /*
  50976. ** Get a reference to pPage1 of the database file. This will
  50977. ** also acquire a readlock on that file.
  50978. **
  50979. ** SQLITE_OK is returned on success. If the file is not a
  50980. ** well-formed database file, then SQLITE_CORRUPT is returned.
  50981. ** SQLITE_BUSY is returned if the database is locked. SQLITE_NOMEM
  50982. ** is returned if we run out of memory.
  50983. */
  50984. static int lockBtree(BtShared *pBt){
  50985. int rc; /* Result code from subfunctions */
  50986. MemPage *pPage1; /* Page 1 of the database file */
  50987. int nPage; /* Number of pages in the database */
  50988. int nPageFile = 0; /* Number of pages in the database file */
  50989. int nPageHeader; /* Number of pages in the database according to hdr */
  50990. assert( sqlite3_mutex_held(pBt->mutex) );
  50991. assert( pBt->pPage1==0 );
  50992. rc = sqlite3PagerSharedLock(pBt->pPager);
  50993. if( rc!=SQLITE_OK ) return rc;
  50994. rc = btreeGetPage(pBt, 1, &pPage1, 0);
  50995. if( rc!=SQLITE_OK ) return rc;
  50996. /* Do some checking to help insure the file we opened really is
  50997. ** a valid database file.
  50998. */
  50999. nPage = nPageHeader = get4byte(28+(u8*)pPage1->aData);
  51000. sqlite3PagerPagecount(pBt->pPager, &nPageFile);
  51001. if( nPage==0 || memcmp(24+(u8*)pPage1->aData, 92+(u8*)pPage1->aData,4)!=0 ){
  51002. nPage = nPageFile;
  51003. }
  51004. if( nPage>0 ){
  51005. u32 pageSize;
  51006. u32 usableSize;
  51007. u8 *page1 = pPage1->aData;
  51008. rc = SQLITE_NOTADB;
  51009. if( memcmp(page1, zMagicHeader, 16)!=0 ){
  51010. goto page1_init_failed;
  51011. }
  51012. #ifdef SQLITE_OMIT_WAL
  51013. if( page1[18]>1 ){
  51014. pBt->btsFlags |= BTS_READ_ONLY;
  51015. }
  51016. if( page1[19]>1 ){
  51017. goto page1_init_failed;
  51018. }
  51019. #else
  51020. if( page1[18]>2 ){
  51021. pBt->btsFlags |= BTS_READ_ONLY;
  51022. }
  51023. if( page1[19]>2 ){
  51024. goto page1_init_failed;
  51025. }
  51026. /* If the write version is set to 2, this database should be accessed
  51027. ** in WAL mode. If the log is not already open, open it now. Then
  51028. ** return SQLITE_OK and return without populating BtShared.pPage1.
  51029. ** The caller detects this and calls this function again. This is
  51030. ** required as the version of page 1 currently in the page1 buffer
  51031. ** may not be the latest version - there may be a newer one in the log
  51032. ** file.
  51033. */
  51034. if( page1[19]==2 && (pBt->btsFlags & BTS_NO_WAL)==0 ){
  51035. int isOpen = 0;
  51036. rc = sqlite3PagerOpenWal(pBt->pPager, &isOpen);
  51037. if( rc!=SQLITE_OK ){
  51038. goto page1_init_failed;
  51039. }else if( isOpen==0 ){
  51040. releasePage(pPage1);
  51041. return SQLITE_OK;
  51042. }
  51043. rc = SQLITE_NOTADB;
  51044. }
  51045. #endif
  51046. /* The maximum embedded fraction must be exactly 25%. And the minimum
  51047. ** embedded fraction must be 12.5% for both leaf-data and non-leaf-data.
  51048. ** The original design allowed these amounts to vary, but as of
  51049. ** version 3.6.0, we require them to be fixed.
  51050. */
  51051. if( memcmp(&page1[21], "\100\040\040",3)!=0 ){
  51052. goto page1_init_failed;
  51053. }
  51054. pageSize = (page1[16]<<8) | (page1[17]<<16);
  51055. if( ((pageSize-1)&pageSize)!=0
  51056. || pageSize>SQLITE_MAX_PAGE_SIZE
  51057. || pageSize<=256
  51058. ){
  51059. goto page1_init_failed;
  51060. }
  51061. assert( (pageSize & 7)==0 );
  51062. usableSize = pageSize - page1[20];
  51063. if( (u32)pageSize!=pBt->pageSize ){
  51064. /* After reading the first page of the database assuming a page size
  51065. ** of BtShared.pageSize, we have discovered that the page-size is
  51066. ** actually pageSize. Unlock the database, leave pBt->pPage1 at
  51067. ** zero and return SQLITE_OK. The caller will call this function
  51068. ** again with the correct page-size.
  51069. */
  51070. releasePage(pPage1);
  51071. pBt->usableSize = usableSize;
  51072. pBt->pageSize = pageSize;
  51073. freeTempSpace(pBt);
  51074. rc = sqlite3PagerSetPagesize(pBt->pPager, &pBt->pageSize,
  51075. pageSize-usableSize);
  51076. return rc;
  51077. }
  51078. if( (pBt->db->flags & SQLITE_RecoveryMode)==0 && nPage>nPageFile ){
  51079. rc = SQLITE_CORRUPT_BKPT;
  51080. goto page1_init_failed;
  51081. }
  51082. if( usableSize<480 ){
  51083. goto page1_init_failed;
  51084. }
  51085. pBt->pageSize = pageSize;
  51086. pBt->usableSize = usableSize;
  51087. #ifndef SQLITE_OMIT_AUTOVACUUM
  51088. pBt->autoVacuum = (get4byte(&page1[36 + 4*4])?1:0);
  51089. pBt->incrVacuum = (get4byte(&page1[36 + 7*4])?1:0);
  51090. #endif
  51091. }
  51092. /* maxLocal is the maximum amount of payload to store locally for
  51093. ** a cell. Make sure it is small enough so that at least minFanout
  51094. ** cells can will fit on one page. We assume a 10-byte page header.
  51095. ** Besides the payload, the cell must store:
  51096. ** 2-byte pointer to the cell
  51097. ** 4-byte child pointer
  51098. ** 9-byte nKey value
  51099. ** 4-byte nData value
  51100. ** 4-byte overflow page pointer
  51101. ** So a cell consists of a 2-byte pointer, a header which is as much as
  51102. ** 17 bytes long, 0 to N bytes of payload, and an optional 4 byte overflow
  51103. ** page pointer.
  51104. */
  51105. pBt->maxLocal = (u16)((pBt->usableSize-12)*64/255 - 23);
  51106. pBt->minLocal = (u16)((pBt->usableSize-12)*32/255 - 23);
  51107. pBt->maxLeaf = (u16)(pBt->usableSize - 35);
  51108. pBt->minLeaf = (u16)((pBt->usableSize-12)*32/255 - 23);
  51109. if( pBt->maxLocal>127 ){
  51110. pBt->max1bytePayload = 127;
  51111. }else{
  51112. pBt->max1bytePayload = (u8)pBt->maxLocal;
  51113. }
  51114. assert( pBt->maxLeaf + 23 <= MX_CELL_SIZE(pBt) );
  51115. pBt->pPage1 = pPage1;
  51116. pBt->nPage = nPage;
  51117. return SQLITE_OK;
  51118. page1_init_failed:
  51119. releasePage(pPage1);
  51120. pBt->pPage1 = 0;
  51121. return rc;
  51122. }
  51123. #ifndef NDEBUG
  51124. /*
  51125. ** Return the number of cursors open on pBt. This is for use
  51126. ** in assert() expressions, so it is only compiled if NDEBUG is not
  51127. ** defined.
  51128. **
  51129. ** Only write cursors are counted if wrOnly is true. If wrOnly is
  51130. ** false then all cursors are counted.
  51131. **
  51132. ** For the purposes of this routine, a cursor is any cursor that
  51133. ** is capable of reading or writing to the database. Cursors that
  51134. ** have been tripped into the CURSOR_FAULT state are not counted.
  51135. */
  51136. static int countValidCursors(BtShared *pBt, int wrOnly){
  51137. BtCursor *pCur;
  51138. int r = 0;
  51139. for(pCur=pBt->pCursor; pCur; pCur=pCur->pNext){
  51140. if( (wrOnly==0 || (pCur->curFlags & BTCF_WriteFlag)!=0)
  51141. && pCur->eState!=CURSOR_FAULT ) r++;
  51142. }
  51143. return r;
  51144. }
  51145. #endif
  51146. /*
  51147. ** If there are no outstanding cursors and we are not in the middle
  51148. ** of a transaction but there is a read lock on the database, then
  51149. ** this routine unrefs the first page of the database file which
  51150. ** has the effect of releasing the read lock.
  51151. **
  51152. ** If there is a transaction in progress, this routine is a no-op.
  51153. */
  51154. static void unlockBtreeIfUnused(BtShared *pBt){
  51155. assert( sqlite3_mutex_held(pBt->mutex) );
  51156. assert( countValidCursors(pBt,0)==0 || pBt->inTransaction>TRANS_NONE );
  51157. if( pBt->inTransaction==TRANS_NONE && pBt->pPage1!=0 ){
  51158. MemPage *pPage1 = pBt->pPage1;
  51159. assert( pPage1->aData );
  51160. assert( sqlite3PagerRefcount(pBt->pPager)==1 );
  51161. pBt->pPage1 = 0;
  51162. releasePage(pPage1);
  51163. }
  51164. }
  51165. /*
  51166. ** If pBt points to an empty file then convert that empty file
  51167. ** into a new empty database by initializing the first page of
  51168. ** the database.
  51169. */
  51170. static int newDatabase(BtShared *pBt){
  51171. MemPage *pP1;
  51172. unsigned char *data;
  51173. int rc;
  51174. assert( sqlite3_mutex_held(pBt->mutex) );
  51175. if( pBt->nPage>0 ){
  51176. return SQLITE_OK;
  51177. }
  51178. pP1 = pBt->pPage1;
  51179. assert( pP1!=0 );
  51180. data = pP1->aData;
  51181. rc = sqlite3PagerWrite(pP1->pDbPage);
  51182. if( rc ) return rc;
  51183. memcpy(data, zMagicHeader, sizeof(zMagicHeader));
  51184. assert( sizeof(zMagicHeader)==16 );
  51185. data[16] = (u8)((pBt->pageSize>>8)&0xff);
  51186. data[17] = (u8)((pBt->pageSize>>16)&0xff);
  51187. data[18] = 1;
  51188. data[19] = 1;
  51189. assert( pBt->usableSize<=pBt->pageSize && pBt->usableSize+255>=pBt->pageSize);
  51190. data[20] = (u8)(pBt->pageSize - pBt->usableSize);
  51191. data[21] = 64;
  51192. data[22] = 32;
  51193. data[23] = 32;
  51194. memset(&data[24], 0, 100-24);
  51195. zeroPage(pP1, PTF_INTKEY|PTF_LEAF|PTF_LEAFDATA );
  51196. pBt->btsFlags |= BTS_PAGESIZE_FIXED;
  51197. #ifndef SQLITE_OMIT_AUTOVACUUM
  51198. assert( pBt->autoVacuum==1 || pBt->autoVacuum==0 );
  51199. assert( pBt->incrVacuum==1 || pBt->incrVacuum==0 );
  51200. put4byte(&data[36 + 4*4], pBt->autoVacuum);
  51201. put4byte(&data[36 + 7*4], pBt->incrVacuum);
  51202. #endif
  51203. pBt->nPage = 1;
  51204. data[31] = 1;
  51205. return SQLITE_OK;
  51206. }
  51207. /*
  51208. ** Initialize the first page of the database file (creating a database
  51209. ** consisting of a single page and no schema objects). Return SQLITE_OK
  51210. ** if successful, or an SQLite error code otherwise.
  51211. */
  51212. SQLITE_PRIVATE int sqlite3BtreeNewDb(Btree *p){
  51213. int rc;
  51214. sqlite3BtreeEnter(p);
  51215. p->pBt->nPage = 0;
  51216. rc = newDatabase(p->pBt);
  51217. sqlite3BtreeLeave(p);
  51218. return rc;
  51219. }
  51220. /*
  51221. ** Attempt to start a new transaction. A write-transaction
  51222. ** is started if the second argument is nonzero, otherwise a read-
  51223. ** transaction. If the second argument is 2 or more and exclusive
  51224. ** transaction is started, meaning that no other process is allowed
  51225. ** to access the database. A preexisting transaction may not be
  51226. ** upgraded to exclusive by calling this routine a second time - the
  51227. ** exclusivity flag only works for a new transaction.
  51228. **
  51229. ** A write-transaction must be started before attempting any
  51230. ** changes to the database. None of the following routines
  51231. ** will work unless a transaction is started first:
  51232. **
  51233. ** sqlite3BtreeCreateTable()
  51234. ** sqlite3BtreeCreateIndex()
  51235. ** sqlite3BtreeClearTable()
  51236. ** sqlite3BtreeDropTable()
  51237. ** sqlite3BtreeInsert()
  51238. ** sqlite3BtreeDelete()
  51239. ** sqlite3BtreeUpdateMeta()
  51240. **
  51241. ** If an initial attempt to acquire the lock fails because of lock contention
  51242. ** and the database was previously unlocked, then invoke the busy handler
  51243. ** if there is one. But if there was previously a read-lock, do not
  51244. ** invoke the busy handler - just return SQLITE_BUSY. SQLITE_BUSY is
  51245. ** returned when there is already a read-lock in order to avoid a deadlock.
  51246. **
  51247. ** Suppose there are two processes A and B. A has a read lock and B has
  51248. ** a reserved lock. B tries to promote to exclusive but is blocked because
  51249. ** of A's read lock. A tries to promote to reserved but is blocked by B.
  51250. ** One or the other of the two processes must give way or there can be
  51251. ** no progress. By returning SQLITE_BUSY and not invoking the busy callback
  51252. ** when A already has a read lock, we encourage A to give up and let B
  51253. ** proceed.
  51254. */
  51255. SQLITE_PRIVATE int sqlite3BtreeBeginTrans(Btree *p, int wrflag){
  51256. sqlite3 *pBlock = 0;
  51257. BtShared *pBt = p->pBt;
  51258. int rc = SQLITE_OK;
  51259. sqlite3BtreeEnter(p);
  51260. btreeIntegrity(p);
  51261. /* If the btree is already in a write-transaction, or it
  51262. ** is already in a read-transaction and a read-transaction
  51263. ** is requested, this is a no-op.
  51264. */
  51265. if( p->inTrans==TRANS_WRITE || (p->inTrans==TRANS_READ && !wrflag) ){
  51266. goto trans_begun;
  51267. }
  51268. assert( pBt->inTransaction==TRANS_WRITE || IfNotOmitAV(pBt->bDoTruncate)==0 );
  51269. /* Write transactions are not possible on a read-only database */
  51270. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 && wrflag ){
  51271. rc = SQLITE_READONLY;
  51272. goto trans_begun;
  51273. }
  51274. #ifndef SQLITE_OMIT_SHARED_CACHE
  51275. /* If another database handle has already opened a write transaction
  51276. ** on this shared-btree structure and a second write transaction is
  51277. ** requested, return SQLITE_LOCKED.
  51278. */
  51279. if( (wrflag && pBt->inTransaction==TRANS_WRITE)
  51280. || (pBt->btsFlags & BTS_PENDING)!=0
  51281. ){
  51282. pBlock = pBt->pWriter->db;
  51283. }else if( wrflag>1 ){
  51284. BtLock *pIter;
  51285. for(pIter=pBt->pLock; pIter; pIter=pIter->pNext){
  51286. if( pIter->pBtree!=p ){
  51287. pBlock = pIter->pBtree->db;
  51288. break;
  51289. }
  51290. }
  51291. }
  51292. if( pBlock ){
  51293. sqlite3ConnectionBlocked(p->db, pBlock);
  51294. rc = SQLITE_LOCKED_SHAREDCACHE;
  51295. goto trans_begun;
  51296. }
  51297. #endif
  51298. /* Any read-only or read-write transaction implies a read-lock on
  51299. ** page 1. So if some other shared-cache client already has a write-lock
  51300. ** on page 1, the transaction cannot be opened. */
  51301. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  51302. if( SQLITE_OK!=rc ) goto trans_begun;
  51303. pBt->btsFlags &= ~BTS_INITIALLY_EMPTY;
  51304. if( pBt->nPage==0 ) pBt->btsFlags |= BTS_INITIALLY_EMPTY;
  51305. do {
  51306. /* Call lockBtree() until either pBt->pPage1 is populated or
  51307. ** lockBtree() returns something other than SQLITE_OK. lockBtree()
  51308. ** may return SQLITE_OK but leave pBt->pPage1 set to 0 if after
  51309. ** reading page 1 it discovers that the page-size of the database
  51310. ** file is not pBt->pageSize. In this case lockBtree() will update
  51311. ** pBt->pageSize to the page-size of the file on disk.
  51312. */
  51313. while( pBt->pPage1==0 && SQLITE_OK==(rc = lockBtree(pBt)) );
  51314. if( rc==SQLITE_OK && wrflag ){
  51315. if( (pBt->btsFlags & BTS_READ_ONLY)!=0 ){
  51316. rc = SQLITE_READONLY;
  51317. }else{
  51318. rc = sqlite3PagerBegin(pBt->pPager,wrflag>1,sqlite3TempInMemory(p->db));
  51319. if( rc==SQLITE_OK ){
  51320. rc = newDatabase(pBt);
  51321. }
  51322. }
  51323. }
  51324. if( rc!=SQLITE_OK ){
  51325. unlockBtreeIfUnused(pBt);
  51326. }
  51327. }while( (rc&0xFF)==SQLITE_BUSY && pBt->inTransaction==TRANS_NONE &&
  51328. btreeInvokeBusyHandler(pBt) );
  51329. if( rc==SQLITE_OK ){
  51330. if( p->inTrans==TRANS_NONE ){
  51331. pBt->nTransaction++;
  51332. #ifndef SQLITE_OMIT_SHARED_CACHE
  51333. if( p->sharable ){
  51334. assert( p->lock.pBtree==p && p->lock.iTable==1 );
  51335. p->lock.eLock = READ_LOCK;
  51336. p->lock.pNext = pBt->pLock;
  51337. pBt->pLock = &p->lock;
  51338. }
  51339. #endif
  51340. }
  51341. p->inTrans = (wrflag?TRANS_WRITE:TRANS_READ);
  51342. if( p->inTrans>pBt->inTransaction ){
  51343. pBt->inTransaction = p->inTrans;
  51344. }
  51345. if( wrflag ){
  51346. MemPage *pPage1 = pBt->pPage1;
  51347. #ifndef SQLITE_OMIT_SHARED_CACHE
  51348. assert( !pBt->pWriter );
  51349. pBt->pWriter = p;
  51350. pBt->btsFlags &= ~BTS_EXCLUSIVE;
  51351. if( wrflag>1 ) pBt->btsFlags |= BTS_EXCLUSIVE;
  51352. #endif
  51353. /* If the db-size header field is incorrect (as it may be if an old
  51354. ** client has been writing the database file), update it now. Doing
  51355. ** this sooner rather than later means the database size can safely
  51356. ** re-read the database size from page 1 if a savepoint or transaction
  51357. ** rollback occurs within the transaction.
  51358. */
  51359. if( pBt->nPage!=get4byte(&pPage1->aData[28]) ){
  51360. rc = sqlite3PagerWrite(pPage1->pDbPage);
  51361. if( rc==SQLITE_OK ){
  51362. put4byte(&pPage1->aData[28], pBt->nPage);
  51363. }
  51364. }
  51365. }
  51366. }
  51367. trans_begun:
  51368. if( rc==SQLITE_OK && wrflag ){
  51369. /* This call makes sure that the pager has the correct number of
  51370. ** open savepoints. If the second parameter is greater than 0 and
  51371. ** the sub-journal is not already open, then it will be opened here.
  51372. */
  51373. rc = sqlite3PagerOpenSavepoint(pBt->pPager, p->db->nSavepoint);
  51374. }
  51375. btreeIntegrity(p);
  51376. sqlite3BtreeLeave(p);
  51377. return rc;
  51378. }
  51379. #ifndef SQLITE_OMIT_AUTOVACUUM
  51380. /*
  51381. ** Set the pointer-map entries for all children of page pPage. Also, if
  51382. ** pPage contains cells that point to overflow pages, set the pointer
  51383. ** map entries for the overflow pages as well.
  51384. */
  51385. static int setChildPtrmaps(MemPage *pPage){
  51386. int i; /* Counter variable */
  51387. int nCell; /* Number of cells in page pPage */
  51388. int rc; /* Return code */
  51389. BtShared *pBt = pPage->pBt;
  51390. u8 isInitOrig = pPage->isInit;
  51391. Pgno pgno = pPage->pgno;
  51392. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51393. rc = btreeInitPage(pPage);
  51394. if( rc!=SQLITE_OK ){
  51395. goto set_child_ptrmaps_out;
  51396. }
  51397. nCell = pPage->nCell;
  51398. for(i=0; i<nCell; i++){
  51399. u8 *pCell = findCell(pPage, i);
  51400. ptrmapPutOvflPtr(pPage, pCell, &rc);
  51401. if( !pPage->leaf ){
  51402. Pgno childPgno = get4byte(pCell);
  51403. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  51404. }
  51405. }
  51406. if( !pPage->leaf ){
  51407. Pgno childPgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  51408. ptrmapPut(pBt, childPgno, PTRMAP_BTREE, pgno, &rc);
  51409. }
  51410. set_child_ptrmaps_out:
  51411. pPage->isInit = isInitOrig;
  51412. return rc;
  51413. }
  51414. /*
  51415. ** Somewhere on pPage is a pointer to page iFrom. Modify this pointer so
  51416. ** that it points to iTo. Parameter eType describes the type of pointer to
  51417. ** be modified, as follows:
  51418. **
  51419. ** PTRMAP_BTREE: pPage is a btree-page. The pointer points at a child
  51420. ** page of pPage.
  51421. **
  51422. ** PTRMAP_OVERFLOW1: pPage is a btree-page. The pointer points at an overflow
  51423. ** page pointed to by one of the cells on pPage.
  51424. **
  51425. ** PTRMAP_OVERFLOW2: pPage is an overflow-page. The pointer points at the next
  51426. ** overflow page in the list.
  51427. */
  51428. static int modifyPagePointer(MemPage *pPage, Pgno iFrom, Pgno iTo, u8 eType){
  51429. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  51430. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  51431. if( eType==PTRMAP_OVERFLOW2 ){
  51432. /* The pointer is always the first 4 bytes of the page in this case. */
  51433. if( get4byte(pPage->aData)!=iFrom ){
  51434. return SQLITE_CORRUPT_BKPT;
  51435. }
  51436. put4byte(pPage->aData, iTo);
  51437. }else{
  51438. u8 isInitOrig = pPage->isInit;
  51439. int i;
  51440. int nCell;
  51441. btreeInitPage(pPage);
  51442. nCell = pPage->nCell;
  51443. for(i=0; i<nCell; i++){
  51444. u8 *pCell = findCell(pPage, i);
  51445. if( eType==PTRMAP_OVERFLOW1 ){
  51446. CellInfo info;
  51447. btreeParseCellPtr(pPage, pCell, &info);
  51448. if( info.iOverflow
  51449. && pCell+info.iOverflow+3<=pPage->aData+pPage->maskPage
  51450. && iFrom==get4byte(&pCell[info.iOverflow])
  51451. ){
  51452. put4byte(&pCell[info.iOverflow], iTo);
  51453. break;
  51454. }
  51455. }else{
  51456. if( get4byte(pCell)==iFrom ){
  51457. put4byte(pCell, iTo);
  51458. break;
  51459. }
  51460. }
  51461. }
  51462. if( i==nCell ){
  51463. if( eType!=PTRMAP_BTREE ||
  51464. get4byte(&pPage->aData[pPage->hdrOffset+8])!=iFrom ){
  51465. return SQLITE_CORRUPT_BKPT;
  51466. }
  51467. put4byte(&pPage->aData[pPage->hdrOffset+8], iTo);
  51468. }
  51469. pPage->isInit = isInitOrig;
  51470. }
  51471. return SQLITE_OK;
  51472. }
  51473. /*
  51474. ** Move the open database page pDbPage to location iFreePage in the
  51475. ** database. The pDbPage reference remains valid.
  51476. **
  51477. ** The isCommit flag indicates that there is no need to remember that
  51478. ** the journal needs to be sync()ed before database page pDbPage->pgno
  51479. ** can be written to. The caller has already promised not to write to that
  51480. ** page.
  51481. */
  51482. static int relocatePage(
  51483. BtShared *pBt, /* Btree */
  51484. MemPage *pDbPage, /* Open page to move */
  51485. u8 eType, /* Pointer map 'type' entry for pDbPage */
  51486. Pgno iPtrPage, /* Pointer map 'page-no' entry for pDbPage */
  51487. Pgno iFreePage, /* The location to move pDbPage to */
  51488. int isCommit /* isCommit flag passed to sqlite3PagerMovepage */
  51489. ){
  51490. MemPage *pPtrPage; /* The page that contains a pointer to pDbPage */
  51491. Pgno iDbPage = pDbPage->pgno;
  51492. Pager *pPager = pBt->pPager;
  51493. int rc;
  51494. assert( eType==PTRMAP_OVERFLOW2 || eType==PTRMAP_OVERFLOW1 ||
  51495. eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE );
  51496. assert( sqlite3_mutex_held(pBt->mutex) );
  51497. assert( pDbPage->pBt==pBt );
  51498. /* Move page iDbPage from its current location to page number iFreePage */
  51499. TRACE(("AUTOVACUUM: Moving %d to free page %d (ptr page %d type %d)\n",
  51500. iDbPage, iFreePage, iPtrPage, eType));
  51501. rc = sqlite3PagerMovepage(pPager, pDbPage->pDbPage, iFreePage, isCommit);
  51502. if( rc!=SQLITE_OK ){
  51503. return rc;
  51504. }
  51505. pDbPage->pgno = iFreePage;
  51506. /* If pDbPage was a btree-page, then it may have child pages and/or cells
  51507. ** that point to overflow pages. The pointer map entries for all these
  51508. ** pages need to be changed.
  51509. **
  51510. ** If pDbPage is an overflow page, then the first 4 bytes may store a
  51511. ** pointer to a subsequent overflow page. If this is the case, then
  51512. ** the pointer map needs to be updated for the subsequent overflow page.
  51513. */
  51514. if( eType==PTRMAP_BTREE || eType==PTRMAP_ROOTPAGE ){
  51515. rc = setChildPtrmaps(pDbPage);
  51516. if( rc!=SQLITE_OK ){
  51517. return rc;
  51518. }
  51519. }else{
  51520. Pgno nextOvfl = get4byte(pDbPage->aData);
  51521. if( nextOvfl!=0 ){
  51522. ptrmapPut(pBt, nextOvfl, PTRMAP_OVERFLOW2, iFreePage, &rc);
  51523. if( rc!=SQLITE_OK ){
  51524. return rc;
  51525. }
  51526. }
  51527. }
  51528. /* Fix the database pointer on page iPtrPage that pointed at iDbPage so
  51529. ** that it points at iFreePage. Also fix the pointer map entry for
  51530. ** iPtrPage.
  51531. */
  51532. if( eType!=PTRMAP_ROOTPAGE ){
  51533. rc = btreeGetPage(pBt, iPtrPage, &pPtrPage, 0);
  51534. if( rc!=SQLITE_OK ){
  51535. return rc;
  51536. }
  51537. rc = sqlite3PagerWrite(pPtrPage->pDbPage);
  51538. if( rc!=SQLITE_OK ){
  51539. releasePage(pPtrPage);
  51540. return rc;
  51541. }
  51542. rc = modifyPagePointer(pPtrPage, iDbPage, iFreePage, eType);
  51543. releasePage(pPtrPage);
  51544. if( rc==SQLITE_OK ){
  51545. ptrmapPut(pBt, iFreePage, eType, iPtrPage, &rc);
  51546. }
  51547. }
  51548. return rc;
  51549. }
  51550. /* Forward declaration required by incrVacuumStep(). */
  51551. static int allocateBtreePage(BtShared *, MemPage **, Pgno *, Pgno, u8);
  51552. /*
  51553. ** Perform a single step of an incremental-vacuum. If successful, return
  51554. ** SQLITE_OK. If there is no work to do (and therefore no point in
  51555. ** calling this function again), return SQLITE_DONE. Or, if an error
  51556. ** occurs, return some other error code.
  51557. **
  51558. ** More specifically, this function attempts to re-organize the database so
  51559. ** that the last page of the file currently in use is no longer in use.
  51560. **
  51561. ** Parameter nFin is the number of pages that this database would contain
  51562. ** were this function called until it returns SQLITE_DONE.
  51563. **
  51564. ** If the bCommit parameter is non-zero, this function assumes that the
  51565. ** caller will keep calling incrVacuumStep() until it returns SQLITE_DONE
  51566. ** or an error. bCommit is passed true for an auto-vacuum-on-commit
  51567. ** operation, or false for an incremental vacuum.
  51568. */
  51569. static int incrVacuumStep(BtShared *pBt, Pgno nFin, Pgno iLastPg, int bCommit){
  51570. Pgno nFreeList; /* Number of pages still on the free-list */
  51571. int rc;
  51572. assert( sqlite3_mutex_held(pBt->mutex) );
  51573. assert( iLastPg>nFin );
  51574. if( !PTRMAP_ISPAGE(pBt, iLastPg) && iLastPg!=PENDING_BYTE_PAGE(pBt) ){
  51575. u8 eType;
  51576. Pgno iPtrPage;
  51577. nFreeList = get4byte(&pBt->pPage1->aData[36]);
  51578. if( nFreeList==0 ){
  51579. return SQLITE_DONE;
  51580. }
  51581. rc = ptrmapGet(pBt, iLastPg, &eType, &iPtrPage);
  51582. if( rc!=SQLITE_OK ){
  51583. return rc;
  51584. }
  51585. if( eType==PTRMAP_ROOTPAGE ){
  51586. return SQLITE_CORRUPT_BKPT;
  51587. }
  51588. if( eType==PTRMAP_FREEPAGE ){
  51589. if( bCommit==0 ){
  51590. /* Remove the page from the files free-list. This is not required
  51591. ** if bCommit is non-zero. In that case, the free-list will be
  51592. ** truncated to zero after this function returns, so it doesn't
  51593. ** matter if it still contains some garbage entries.
  51594. */
  51595. Pgno iFreePg;
  51596. MemPage *pFreePg;
  51597. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iLastPg, BTALLOC_EXACT);
  51598. if( rc!=SQLITE_OK ){
  51599. return rc;
  51600. }
  51601. assert( iFreePg==iLastPg );
  51602. releasePage(pFreePg);
  51603. }
  51604. } else {
  51605. Pgno iFreePg; /* Index of free page to move pLastPg to */
  51606. MemPage *pLastPg;
  51607. u8 eMode = BTALLOC_ANY; /* Mode parameter for allocateBtreePage() */
  51608. Pgno iNear = 0; /* nearby parameter for allocateBtreePage() */
  51609. rc = btreeGetPage(pBt, iLastPg, &pLastPg, 0);
  51610. if( rc!=SQLITE_OK ){
  51611. return rc;
  51612. }
  51613. /* If bCommit is zero, this loop runs exactly once and page pLastPg
  51614. ** is swapped with the first free page pulled off the free list.
  51615. **
  51616. ** On the other hand, if bCommit is greater than zero, then keep
  51617. ** looping until a free-page located within the first nFin pages
  51618. ** of the file is found.
  51619. */
  51620. if( bCommit==0 ){
  51621. eMode = BTALLOC_LE;
  51622. iNear = nFin;
  51623. }
  51624. do {
  51625. MemPage *pFreePg;
  51626. rc = allocateBtreePage(pBt, &pFreePg, &iFreePg, iNear, eMode);
  51627. if( rc!=SQLITE_OK ){
  51628. releasePage(pLastPg);
  51629. return rc;
  51630. }
  51631. releasePage(pFreePg);
  51632. }while( bCommit && iFreePg>nFin );
  51633. assert( iFreePg<iLastPg );
  51634. rc = relocatePage(pBt, pLastPg, eType, iPtrPage, iFreePg, bCommit);
  51635. releasePage(pLastPg);
  51636. if( rc!=SQLITE_OK ){
  51637. return rc;
  51638. }
  51639. }
  51640. }
  51641. if( bCommit==0 ){
  51642. do {
  51643. iLastPg--;
  51644. }while( iLastPg==PENDING_BYTE_PAGE(pBt) || PTRMAP_ISPAGE(pBt, iLastPg) );
  51645. pBt->bDoTruncate = 1;
  51646. pBt->nPage = iLastPg;
  51647. }
  51648. return SQLITE_OK;
  51649. }
  51650. /*
  51651. ** The database opened by the first argument is an auto-vacuum database
  51652. ** nOrig pages in size containing nFree free pages. Return the expected
  51653. ** size of the database in pages following an auto-vacuum operation.
  51654. */
  51655. static Pgno finalDbSize(BtShared *pBt, Pgno nOrig, Pgno nFree){
  51656. int nEntry; /* Number of entries on one ptrmap page */
  51657. Pgno nPtrmap; /* Number of PtrMap pages to be freed */
  51658. Pgno nFin; /* Return value */
  51659. nEntry = pBt->usableSize/5;
  51660. nPtrmap = (nFree-nOrig+PTRMAP_PAGENO(pBt, nOrig)+nEntry)/nEntry;
  51661. nFin = nOrig - nFree - nPtrmap;
  51662. if( nOrig>PENDING_BYTE_PAGE(pBt) && nFin<PENDING_BYTE_PAGE(pBt) ){
  51663. nFin--;
  51664. }
  51665. while( PTRMAP_ISPAGE(pBt, nFin) || nFin==PENDING_BYTE_PAGE(pBt) ){
  51666. nFin--;
  51667. }
  51668. return nFin;
  51669. }
  51670. /*
  51671. ** A write-transaction must be opened before calling this function.
  51672. ** It performs a single unit of work towards an incremental vacuum.
  51673. **
  51674. ** If the incremental vacuum is finished after this function has run,
  51675. ** SQLITE_DONE is returned. If it is not finished, but no error occurred,
  51676. ** SQLITE_OK is returned. Otherwise an SQLite error code.
  51677. */
  51678. SQLITE_PRIVATE int sqlite3BtreeIncrVacuum(Btree *p){
  51679. int rc;
  51680. BtShared *pBt = p->pBt;
  51681. sqlite3BtreeEnter(p);
  51682. assert( pBt->inTransaction==TRANS_WRITE && p->inTrans==TRANS_WRITE );
  51683. if( !pBt->autoVacuum ){
  51684. rc = SQLITE_DONE;
  51685. }else{
  51686. Pgno nOrig = btreePagecount(pBt);
  51687. Pgno nFree = get4byte(&pBt->pPage1->aData[36]);
  51688. Pgno nFin = finalDbSize(pBt, nOrig, nFree);
  51689. if( nOrig<nFin ){
  51690. rc = SQLITE_CORRUPT_BKPT;
  51691. }else if( nFree>0 ){
  51692. rc = saveAllCursors(pBt, 0, 0);
  51693. if( rc==SQLITE_OK ){
  51694. invalidateAllOverflowCache(pBt);
  51695. rc = incrVacuumStep(pBt, nFin, nOrig, 0);
  51696. }
  51697. if( rc==SQLITE_OK ){
  51698. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  51699. put4byte(&pBt->pPage1->aData[28], pBt->nPage);
  51700. }
  51701. }else{
  51702. rc = SQLITE_DONE;
  51703. }
  51704. }
  51705. sqlite3BtreeLeave(p);
  51706. return rc;
  51707. }
  51708. /*
  51709. ** This routine is called prior to sqlite3PagerCommit when a transaction
  51710. ** is committed for an auto-vacuum database.
  51711. **
  51712. ** If SQLITE_OK is returned, then *pnTrunc is set to the number of pages
  51713. ** the database file should be truncated to during the commit process.
  51714. ** i.e. the database has been reorganized so that only the first *pnTrunc
  51715. ** pages are in use.
  51716. */
  51717. static int autoVacuumCommit(BtShared *pBt){
  51718. int rc = SQLITE_OK;
  51719. Pager *pPager = pBt->pPager;
  51720. VVA_ONLY( int nRef = sqlite3PagerRefcount(pPager) );
  51721. assert( sqlite3_mutex_held(pBt->mutex) );
  51722. invalidateAllOverflowCache(pBt);
  51723. assert(pBt->autoVacuum);
  51724. if( !pBt->incrVacuum ){
  51725. Pgno nFin; /* Number of pages in database after autovacuuming */
  51726. Pgno nFree; /* Number of pages on the freelist initially */
  51727. Pgno iFree; /* The next page to be freed */
  51728. Pgno nOrig; /* Database size before freeing */
  51729. nOrig = btreePagecount(pBt);
  51730. if( PTRMAP_ISPAGE(pBt, nOrig) || nOrig==PENDING_BYTE_PAGE(pBt) ){
  51731. /* It is not possible to create a database for which the final page
  51732. ** is either a pointer-map page or the pending-byte page. If one
  51733. ** is encountered, this indicates corruption.
  51734. */
  51735. return SQLITE_CORRUPT_BKPT;
  51736. }
  51737. nFree = get4byte(&pBt->pPage1->aData[36]);
  51738. nFin = finalDbSize(pBt, nOrig, nFree);
  51739. if( nFin>nOrig ) return SQLITE_CORRUPT_BKPT;
  51740. if( nFin<nOrig ){
  51741. rc = saveAllCursors(pBt, 0, 0);
  51742. }
  51743. for(iFree=nOrig; iFree>nFin && rc==SQLITE_OK; iFree--){
  51744. rc = incrVacuumStep(pBt, nFin, iFree, 1);
  51745. }
  51746. if( (rc==SQLITE_DONE || rc==SQLITE_OK) && nFree>0 ){
  51747. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  51748. put4byte(&pBt->pPage1->aData[32], 0);
  51749. put4byte(&pBt->pPage1->aData[36], 0);
  51750. put4byte(&pBt->pPage1->aData[28], nFin);
  51751. pBt->bDoTruncate = 1;
  51752. pBt->nPage = nFin;
  51753. }
  51754. if( rc!=SQLITE_OK ){
  51755. sqlite3PagerRollback(pPager);
  51756. }
  51757. }
  51758. assert( nRef>=sqlite3PagerRefcount(pPager) );
  51759. return rc;
  51760. }
  51761. #else /* ifndef SQLITE_OMIT_AUTOVACUUM */
  51762. # define setChildPtrmaps(x) SQLITE_OK
  51763. #endif
  51764. /*
  51765. ** This routine does the first phase of a two-phase commit. This routine
  51766. ** causes a rollback journal to be created (if it does not already exist)
  51767. ** and populated with enough information so that if a power loss occurs
  51768. ** the database can be restored to its original state by playing back
  51769. ** the journal. Then the contents of the journal are flushed out to
  51770. ** the disk. After the journal is safely on oxide, the changes to the
  51771. ** database are written into the database file and flushed to oxide.
  51772. ** At the end of this call, the rollback journal still exists on the
  51773. ** disk and we are still holding all locks, so the transaction has not
  51774. ** committed. See sqlite3BtreeCommitPhaseTwo() for the second phase of the
  51775. ** commit process.
  51776. **
  51777. ** This call is a no-op if no write-transaction is currently active on pBt.
  51778. **
  51779. ** Otherwise, sync the database file for the btree pBt. zMaster points to
  51780. ** the name of a master journal file that should be written into the
  51781. ** individual journal file, or is NULL, indicating no master journal file
  51782. ** (single database transaction).
  51783. **
  51784. ** When this is called, the master journal should already have been
  51785. ** created, populated with this journal pointer and synced to disk.
  51786. **
  51787. ** Once this is routine has returned, the only thing required to commit
  51788. ** the write-transaction for this database file is to delete the journal.
  51789. */
  51790. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseOne(Btree *p, const char *zMaster){
  51791. int rc = SQLITE_OK;
  51792. if( p->inTrans==TRANS_WRITE ){
  51793. BtShared *pBt = p->pBt;
  51794. sqlite3BtreeEnter(p);
  51795. #ifndef SQLITE_OMIT_AUTOVACUUM
  51796. if( pBt->autoVacuum ){
  51797. rc = autoVacuumCommit(pBt);
  51798. if( rc!=SQLITE_OK ){
  51799. sqlite3BtreeLeave(p);
  51800. return rc;
  51801. }
  51802. }
  51803. if( pBt->bDoTruncate ){
  51804. sqlite3PagerTruncateImage(pBt->pPager, pBt->nPage);
  51805. }
  51806. #endif
  51807. rc = sqlite3PagerCommitPhaseOne(pBt->pPager, zMaster, 0);
  51808. sqlite3BtreeLeave(p);
  51809. }
  51810. return rc;
  51811. }
  51812. /*
  51813. ** This function is called from both BtreeCommitPhaseTwo() and BtreeRollback()
  51814. ** at the conclusion of a transaction.
  51815. */
  51816. static void btreeEndTransaction(Btree *p){
  51817. BtShared *pBt = p->pBt;
  51818. sqlite3 *db = p->db;
  51819. assert( sqlite3BtreeHoldsMutex(p) );
  51820. #ifndef SQLITE_OMIT_AUTOVACUUM
  51821. pBt->bDoTruncate = 0;
  51822. #endif
  51823. if( p->inTrans>TRANS_NONE && db->nVdbeRead>1 ){
  51824. /* If there are other active statements that belong to this database
  51825. ** handle, downgrade to a read-only transaction. The other statements
  51826. ** may still be reading from the database. */
  51827. downgradeAllSharedCacheTableLocks(p);
  51828. p->inTrans = TRANS_READ;
  51829. }else{
  51830. /* If the handle had any kind of transaction open, decrement the
  51831. ** transaction count of the shared btree. If the transaction count
  51832. ** reaches 0, set the shared state to TRANS_NONE. The unlockBtreeIfUnused()
  51833. ** call below will unlock the pager. */
  51834. if( p->inTrans!=TRANS_NONE ){
  51835. clearAllSharedCacheTableLocks(p);
  51836. pBt->nTransaction--;
  51837. if( 0==pBt->nTransaction ){
  51838. pBt->inTransaction = TRANS_NONE;
  51839. }
  51840. }
  51841. /* Set the current transaction state to TRANS_NONE and unlock the
  51842. ** pager if this call closed the only read or write transaction. */
  51843. p->inTrans = TRANS_NONE;
  51844. unlockBtreeIfUnused(pBt);
  51845. }
  51846. btreeIntegrity(p);
  51847. }
  51848. /*
  51849. ** Commit the transaction currently in progress.
  51850. **
  51851. ** This routine implements the second phase of a 2-phase commit. The
  51852. ** sqlite3BtreeCommitPhaseOne() routine does the first phase and should
  51853. ** be invoked prior to calling this routine. The sqlite3BtreeCommitPhaseOne()
  51854. ** routine did all the work of writing information out to disk and flushing the
  51855. ** contents so that they are written onto the disk platter. All this
  51856. ** routine has to do is delete or truncate or zero the header in the
  51857. ** the rollback journal (which causes the transaction to commit) and
  51858. ** drop locks.
  51859. **
  51860. ** Normally, if an error occurs while the pager layer is attempting to
  51861. ** finalize the underlying journal file, this function returns an error and
  51862. ** the upper layer will attempt a rollback. However, if the second argument
  51863. ** is non-zero then this b-tree transaction is part of a multi-file
  51864. ** transaction. In this case, the transaction has already been committed
  51865. ** (by deleting a master journal file) and the caller will ignore this
  51866. ** functions return code. So, even if an error occurs in the pager layer,
  51867. ** reset the b-tree objects internal state to indicate that the write
  51868. ** transaction has been closed. This is quite safe, as the pager will have
  51869. ** transitioned to the error state.
  51870. **
  51871. ** This will release the write lock on the database file. If there
  51872. ** are no active cursors, it also releases the read lock.
  51873. */
  51874. SQLITE_PRIVATE int sqlite3BtreeCommitPhaseTwo(Btree *p, int bCleanup){
  51875. if( p->inTrans==TRANS_NONE ) return SQLITE_OK;
  51876. sqlite3BtreeEnter(p);
  51877. btreeIntegrity(p);
  51878. /* If the handle has a write-transaction open, commit the shared-btrees
  51879. ** transaction and set the shared state to TRANS_READ.
  51880. */
  51881. if( p->inTrans==TRANS_WRITE ){
  51882. int rc;
  51883. BtShared *pBt = p->pBt;
  51884. assert( pBt->inTransaction==TRANS_WRITE );
  51885. assert( pBt->nTransaction>0 );
  51886. rc = sqlite3PagerCommitPhaseTwo(pBt->pPager);
  51887. if( rc!=SQLITE_OK && bCleanup==0 ){
  51888. sqlite3BtreeLeave(p);
  51889. return rc;
  51890. }
  51891. pBt->inTransaction = TRANS_READ;
  51892. btreeClearHasContent(pBt);
  51893. }
  51894. btreeEndTransaction(p);
  51895. sqlite3BtreeLeave(p);
  51896. return SQLITE_OK;
  51897. }
  51898. /*
  51899. ** Do both phases of a commit.
  51900. */
  51901. SQLITE_PRIVATE int sqlite3BtreeCommit(Btree *p){
  51902. int rc;
  51903. sqlite3BtreeEnter(p);
  51904. rc = sqlite3BtreeCommitPhaseOne(p, 0);
  51905. if( rc==SQLITE_OK ){
  51906. rc = sqlite3BtreeCommitPhaseTwo(p, 0);
  51907. }
  51908. sqlite3BtreeLeave(p);
  51909. return rc;
  51910. }
  51911. /*
  51912. ** This routine sets the state to CURSOR_FAULT and the error
  51913. ** code to errCode for every cursor on any BtShared that pBtree
  51914. ** references. Or if the writeOnly flag is set to 1, then only
  51915. ** trip write cursors and leave read cursors unchanged.
  51916. **
  51917. ** Every cursor is a candidate to be tripped, including cursors
  51918. ** that belong to other database connections that happen to be
  51919. ** sharing the cache with pBtree.
  51920. **
  51921. ** This routine gets called when a rollback occurs. If the writeOnly
  51922. ** flag is true, then only write-cursors need be tripped - read-only
  51923. ** cursors save their current positions so that they may continue
  51924. ** following the rollback. Or, if writeOnly is false, all cursors are
  51925. ** tripped. In general, writeOnly is false if the transaction being
  51926. ** rolled back modified the database schema. In this case b-tree root
  51927. ** pages may be moved or deleted from the database altogether, making
  51928. ** it unsafe for read cursors to continue.
  51929. **
  51930. ** If the writeOnly flag is true and an error is encountered while
  51931. ** saving the current position of a read-only cursor, all cursors,
  51932. ** including all read-cursors are tripped.
  51933. **
  51934. ** SQLITE_OK is returned if successful, or if an error occurs while
  51935. ** saving a cursor position, an SQLite error code.
  51936. */
  51937. SQLITE_PRIVATE int sqlite3BtreeTripAllCursors(Btree *pBtree, int errCode, int writeOnly){
  51938. BtCursor *p;
  51939. int rc = SQLITE_OK;
  51940. assert( (writeOnly==0 || writeOnly==1) && BTCF_WriteFlag==1 );
  51941. if( pBtree ){
  51942. sqlite3BtreeEnter(pBtree);
  51943. for(p=pBtree->pBt->pCursor; p; p=p->pNext){
  51944. int i;
  51945. if( writeOnly && (p->curFlags & BTCF_WriteFlag)==0 ){
  51946. if( p->eState==CURSOR_VALID ){
  51947. rc = saveCursorPosition(p);
  51948. if( rc!=SQLITE_OK ){
  51949. (void)sqlite3BtreeTripAllCursors(pBtree, rc, 0);
  51950. break;
  51951. }
  51952. }
  51953. }else{
  51954. sqlite3BtreeClearCursor(p);
  51955. p->eState = CURSOR_FAULT;
  51956. p->skipNext = errCode;
  51957. }
  51958. for(i=0; i<=p->iPage; i++){
  51959. releasePage(p->apPage[i]);
  51960. p->apPage[i] = 0;
  51961. }
  51962. }
  51963. sqlite3BtreeLeave(pBtree);
  51964. }
  51965. return rc;
  51966. }
  51967. /*
  51968. ** Rollback the transaction in progress.
  51969. **
  51970. ** If tripCode is not SQLITE_OK then cursors will be invalidated (tripped).
  51971. ** Only write cursors are tripped if writeOnly is true but all cursors are
  51972. ** tripped if writeOnly is false. Any attempt to use
  51973. ** a tripped cursor will result in an error.
  51974. **
  51975. ** This will release the write lock on the database file. If there
  51976. ** are no active cursors, it also releases the read lock.
  51977. */
  51978. SQLITE_PRIVATE int sqlite3BtreeRollback(Btree *p, int tripCode, int writeOnly){
  51979. int rc;
  51980. BtShared *pBt = p->pBt;
  51981. MemPage *pPage1;
  51982. assert( writeOnly==1 || writeOnly==0 );
  51983. assert( tripCode==SQLITE_ABORT_ROLLBACK || tripCode==SQLITE_OK );
  51984. sqlite3BtreeEnter(p);
  51985. if( tripCode==SQLITE_OK ){
  51986. rc = tripCode = saveAllCursors(pBt, 0, 0);
  51987. if( rc ) writeOnly = 0;
  51988. }else{
  51989. rc = SQLITE_OK;
  51990. }
  51991. if( tripCode ){
  51992. int rc2 = sqlite3BtreeTripAllCursors(p, tripCode, writeOnly);
  51993. assert( rc==SQLITE_OK || (writeOnly==0 && rc2==SQLITE_OK) );
  51994. if( rc2!=SQLITE_OK ) rc = rc2;
  51995. }
  51996. btreeIntegrity(p);
  51997. if( p->inTrans==TRANS_WRITE ){
  51998. int rc2;
  51999. assert( TRANS_WRITE==pBt->inTransaction );
  52000. rc2 = sqlite3PagerRollback(pBt->pPager);
  52001. if( rc2!=SQLITE_OK ){
  52002. rc = rc2;
  52003. }
  52004. /* The rollback may have destroyed the pPage1->aData value. So
  52005. ** call btreeGetPage() on page 1 again to make
  52006. ** sure pPage1->aData is set correctly. */
  52007. if( btreeGetPage(pBt, 1, &pPage1, 0)==SQLITE_OK ){
  52008. int nPage = get4byte(28+(u8*)pPage1->aData);
  52009. testcase( nPage==0 );
  52010. if( nPage==0 ) sqlite3PagerPagecount(pBt->pPager, &nPage);
  52011. testcase( pBt->nPage!=nPage );
  52012. pBt->nPage = nPage;
  52013. releasePage(pPage1);
  52014. }
  52015. assert( countValidCursors(pBt, 1)==0 );
  52016. pBt->inTransaction = TRANS_READ;
  52017. btreeClearHasContent(pBt);
  52018. }
  52019. btreeEndTransaction(p);
  52020. sqlite3BtreeLeave(p);
  52021. return rc;
  52022. }
  52023. /*
  52024. ** Start a statement subtransaction. The subtransaction can be rolled
  52025. ** back independently of the main transaction. You must start a transaction
  52026. ** before starting a subtransaction. The subtransaction is ended automatically
  52027. ** if the main transaction commits or rolls back.
  52028. **
  52029. ** Statement subtransactions are used around individual SQL statements
  52030. ** that are contained within a BEGIN...COMMIT block. If a constraint
  52031. ** error occurs within the statement, the effect of that one statement
  52032. ** can be rolled back without having to rollback the entire transaction.
  52033. **
  52034. ** A statement sub-transaction is implemented as an anonymous savepoint. The
  52035. ** value passed as the second parameter is the total number of savepoints,
  52036. ** including the new anonymous savepoint, open on the B-Tree. i.e. if there
  52037. ** are no active savepoints and no other statement-transactions open,
  52038. ** iStatement is 1. This anonymous savepoint can be released or rolled back
  52039. ** using the sqlite3BtreeSavepoint() function.
  52040. */
  52041. SQLITE_PRIVATE int sqlite3BtreeBeginStmt(Btree *p, int iStatement){
  52042. int rc;
  52043. BtShared *pBt = p->pBt;
  52044. sqlite3BtreeEnter(p);
  52045. assert( p->inTrans==TRANS_WRITE );
  52046. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  52047. assert( iStatement>0 );
  52048. assert( iStatement>p->db->nSavepoint );
  52049. assert( pBt->inTransaction==TRANS_WRITE );
  52050. /* At the pager level, a statement transaction is a savepoint with
  52051. ** an index greater than all savepoints created explicitly using
  52052. ** SQL statements. It is illegal to open, release or rollback any
  52053. ** such savepoints while the statement transaction savepoint is active.
  52054. */
  52055. rc = sqlite3PagerOpenSavepoint(pBt->pPager, iStatement);
  52056. sqlite3BtreeLeave(p);
  52057. return rc;
  52058. }
  52059. /*
  52060. ** The second argument to this function, op, is always SAVEPOINT_ROLLBACK
  52061. ** or SAVEPOINT_RELEASE. This function either releases or rolls back the
  52062. ** savepoint identified by parameter iSavepoint, depending on the value
  52063. ** of op.
  52064. **
  52065. ** Normally, iSavepoint is greater than or equal to zero. However, if op is
  52066. ** SAVEPOINT_ROLLBACK, then iSavepoint may also be -1. In this case the
  52067. ** contents of the entire transaction are rolled back. This is different
  52068. ** from a normal transaction rollback, as no locks are released and the
  52069. ** transaction remains open.
  52070. */
  52071. SQLITE_PRIVATE int sqlite3BtreeSavepoint(Btree *p, int op, int iSavepoint){
  52072. int rc = SQLITE_OK;
  52073. if( p && p->inTrans==TRANS_WRITE ){
  52074. BtShared *pBt = p->pBt;
  52075. assert( op==SAVEPOINT_RELEASE || op==SAVEPOINT_ROLLBACK );
  52076. assert( iSavepoint>=0 || (iSavepoint==-1 && op==SAVEPOINT_ROLLBACK) );
  52077. sqlite3BtreeEnter(p);
  52078. rc = sqlite3PagerSavepoint(pBt->pPager, op, iSavepoint);
  52079. if( rc==SQLITE_OK ){
  52080. if( iSavepoint<0 && (pBt->btsFlags & BTS_INITIALLY_EMPTY)!=0 ){
  52081. pBt->nPage = 0;
  52082. }
  52083. rc = newDatabase(pBt);
  52084. pBt->nPage = get4byte(28 + pBt->pPage1->aData);
  52085. /* The database size was written into the offset 28 of the header
  52086. ** when the transaction started, so we know that the value at offset
  52087. ** 28 is nonzero. */
  52088. assert( pBt->nPage>0 );
  52089. }
  52090. sqlite3BtreeLeave(p);
  52091. }
  52092. return rc;
  52093. }
  52094. /*
  52095. ** Create a new cursor for the BTree whose root is on the page
  52096. ** iTable. If a read-only cursor is requested, it is assumed that
  52097. ** the caller already has at least a read-only transaction open
  52098. ** on the database already. If a write-cursor is requested, then
  52099. ** the caller is assumed to have an open write transaction.
  52100. **
  52101. ** If wrFlag==0, then the cursor can only be used for reading.
  52102. ** If wrFlag==1, then the cursor can be used for reading or for
  52103. ** writing if other conditions for writing are also met. These
  52104. ** are the conditions that must be met in order for writing to
  52105. ** be allowed:
  52106. **
  52107. ** 1: The cursor must have been opened with wrFlag==1
  52108. **
  52109. ** 2: Other database connections that share the same pager cache
  52110. ** but which are not in the READ_UNCOMMITTED state may not have
  52111. ** cursors open with wrFlag==0 on the same table. Otherwise
  52112. ** the changes made by this write cursor would be visible to
  52113. ** the read cursors in the other database connection.
  52114. **
  52115. ** 3: The database must be writable (not on read-only media)
  52116. **
  52117. ** 4: There must be an active transaction.
  52118. **
  52119. ** No checking is done to make sure that page iTable really is the
  52120. ** root page of a b-tree. If it is not, then the cursor acquired
  52121. ** will not work correctly.
  52122. **
  52123. ** It is assumed that the sqlite3BtreeCursorZero() has been called
  52124. ** on pCur to initialize the memory space prior to invoking this routine.
  52125. */
  52126. static int btreeCursor(
  52127. Btree *p, /* The btree */
  52128. int iTable, /* Root page of table to open */
  52129. int wrFlag, /* 1 to write. 0 read-only */
  52130. struct KeyInfo *pKeyInfo, /* First arg to comparison function */
  52131. BtCursor *pCur /* Space for new cursor */
  52132. ){
  52133. BtShared *pBt = p->pBt; /* Shared b-tree handle */
  52134. assert( sqlite3BtreeHoldsMutex(p) );
  52135. assert( wrFlag==0 || wrFlag==1 );
  52136. /* The following assert statements verify that if this is a sharable
  52137. ** b-tree database, the connection is holding the required table locks,
  52138. ** and that no other connection has any open cursor that conflicts with
  52139. ** this lock. */
  52140. assert( hasSharedCacheTableLock(p, iTable, pKeyInfo!=0, wrFlag+1) );
  52141. assert( wrFlag==0 || !hasReadConflicts(p, iTable) );
  52142. /* Assert that the caller has opened the required transaction. */
  52143. assert( p->inTrans>TRANS_NONE );
  52144. assert( wrFlag==0 || p->inTrans==TRANS_WRITE );
  52145. assert( pBt->pPage1 && pBt->pPage1->aData );
  52146. if( NEVER(wrFlag && (pBt->btsFlags & BTS_READ_ONLY)!=0) ){
  52147. return SQLITE_READONLY;
  52148. }
  52149. if( wrFlag ){
  52150. allocateTempSpace(pBt);
  52151. if( pBt->pTmpSpace==0 ) return SQLITE_NOMEM;
  52152. }
  52153. if( iTable==1 && btreePagecount(pBt)==0 ){
  52154. assert( wrFlag==0 );
  52155. iTable = 0;
  52156. }
  52157. /* Now that no other errors can occur, finish filling in the BtCursor
  52158. ** variables and link the cursor into the BtShared list. */
  52159. pCur->pgnoRoot = (Pgno)iTable;
  52160. pCur->iPage = -1;
  52161. pCur->pKeyInfo = pKeyInfo;
  52162. pCur->pBtree = p;
  52163. pCur->pBt = pBt;
  52164. assert( wrFlag==0 || wrFlag==BTCF_WriteFlag );
  52165. pCur->curFlags = wrFlag;
  52166. pCur->pNext = pBt->pCursor;
  52167. if( pCur->pNext ){
  52168. pCur->pNext->pPrev = pCur;
  52169. }
  52170. pBt->pCursor = pCur;
  52171. pCur->eState = CURSOR_INVALID;
  52172. return SQLITE_OK;
  52173. }
  52174. SQLITE_PRIVATE int sqlite3BtreeCursor(
  52175. Btree *p, /* The btree */
  52176. int iTable, /* Root page of table to open */
  52177. int wrFlag, /* 1 to write. 0 read-only */
  52178. struct KeyInfo *pKeyInfo, /* First arg to xCompare() */
  52179. BtCursor *pCur /* Write new cursor here */
  52180. ){
  52181. int rc;
  52182. sqlite3BtreeEnter(p);
  52183. rc = btreeCursor(p, iTable, wrFlag, pKeyInfo, pCur);
  52184. sqlite3BtreeLeave(p);
  52185. return rc;
  52186. }
  52187. /*
  52188. ** Return the size of a BtCursor object in bytes.
  52189. **
  52190. ** This interfaces is needed so that users of cursors can preallocate
  52191. ** sufficient storage to hold a cursor. The BtCursor object is opaque
  52192. ** to users so they cannot do the sizeof() themselves - they must call
  52193. ** this routine.
  52194. */
  52195. SQLITE_PRIVATE int sqlite3BtreeCursorSize(void){
  52196. return ROUND8(sizeof(BtCursor));
  52197. }
  52198. /*
  52199. ** Initialize memory that will be converted into a BtCursor object.
  52200. **
  52201. ** The simple approach here would be to memset() the entire object
  52202. ** to zero. But it turns out that the apPage[] and aiIdx[] arrays
  52203. ** do not need to be zeroed and they are large, so we can save a lot
  52204. ** of run-time by skipping the initialization of those elements.
  52205. */
  52206. SQLITE_PRIVATE void sqlite3BtreeCursorZero(BtCursor *p){
  52207. memset(p, 0, offsetof(BtCursor, iPage));
  52208. }
  52209. /*
  52210. ** Close a cursor. The read lock on the database file is released
  52211. ** when the last cursor is closed.
  52212. */
  52213. SQLITE_PRIVATE int sqlite3BtreeCloseCursor(BtCursor *pCur){
  52214. Btree *pBtree = pCur->pBtree;
  52215. if( pBtree ){
  52216. int i;
  52217. BtShared *pBt = pCur->pBt;
  52218. sqlite3BtreeEnter(pBtree);
  52219. sqlite3BtreeClearCursor(pCur);
  52220. if( pCur->pPrev ){
  52221. pCur->pPrev->pNext = pCur->pNext;
  52222. }else{
  52223. pBt->pCursor = pCur->pNext;
  52224. }
  52225. if( pCur->pNext ){
  52226. pCur->pNext->pPrev = pCur->pPrev;
  52227. }
  52228. for(i=0; i<=pCur->iPage; i++){
  52229. releasePage(pCur->apPage[i]);
  52230. }
  52231. unlockBtreeIfUnused(pBt);
  52232. sqlite3DbFree(pBtree->db, pCur->aOverflow);
  52233. /* sqlite3_free(pCur); */
  52234. sqlite3BtreeLeave(pBtree);
  52235. }
  52236. return SQLITE_OK;
  52237. }
  52238. /*
  52239. ** Make sure the BtCursor* given in the argument has a valid
  52240. ** BtCursor.info structure. If it is not already valid, call
  52241. ** btreeParseCell() to fill it in.
  52242. **
  52243. ** BtCursor.info is a cache of the information in the current cell.
  52244. ** Using this cache reduces the number of calls to btreeParseCell().
  52245. **
  52246. ** 2007-06-25: There is a bug in some versions of MSVC that cause the
  52247. ** compiler to crash when getCellInfo() is implemented as a macro.
  52248. ** But there is a measureable speed advantage to using the macro on gcc
  52249. ** (when less compiler optimizations like -Os or -O0 are used and the
  52250. ** compiler is not doing aggressive inlining.) So we use a real function
  52251. ** for MSVC and a macro for everything else. Ticket #2457.
  52252. */
  52253. #ifndef NDEBUG
  52254. static void assertCellInfo(BtCursor *pCur){
  52255. CellInfo info;
  52256. int iPage = pCur->iPage;
  52257. memset(&info, 0, sizeof(info));
  52258. btreeParseCell(pCur->apPage[iPage], pCur->aiIdx[iPage], &info);
  52259. assert( CORRUPT_DB || memcmp(&info, &pCur->info, sizeof(info))==0 );
  52260. }
  52261. #else
  52262. #define assertCellInfo(x)
  52263. #endif
  52264. #ifdef _MSC_VER
  52265. /* Use a real function in MSVC to work around bugs in that compiler. */
  52266. static void getCellInfo(BtCursor *pCur){
  52267. if( pCur->info.nSize==0 ){
  52268. int iPage = pCur->iPage;
  52269. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info);
  52270. pCur->curFlags |= BTCF_ValidNKey;
  52271. }else{
  52272. assertCellInfo(pCur);
  52273. }
  52274. }
  52275. #else /* if not _MSC_VER */
  52276. /* Use a macro in all other compilers so that the function is inlined */
  52277. #define getCellInfo(pCur) \
  52278. if( pCur->info.nSize==0 ){ \
  52279. int iPage = pCur->iPage; \
  52280. btreeParseCell(pCur->apPage[iPage],pCur->aiIdx[iPage],&pCur->info); \
  52281. pCur->curFlags |= BTCF_ValidNKey; \
  52282. }else{ \
  52283. assertCellInfo(pCur); \
  52284. }
  52285. #endif /* _MSC_VER */
  52286. #ifndef NDEBUG /* The next routine used only within assert() statements */
  52287. /*
  52288. ** Return true if the given BtCursor is valid. A valid cursor is one
  52289. ** that is currently pointing to a row in a (non-empty) table.
  52290. ** This is a verification routine is used only within assert() statements.
  52291. */
  52292. SQLITE_PRIVATE int sqlite3BtreeCursorIsValid(BtCursor *pCur){
  52293. return pCur && pCur->eState==CURSOR_VALID;
  52294. }
  52295. #endif /* NDEBUG */
  52296. /*
  52297. ** Set *pSize to the size of the buffer needed to hold the value of
  52298. ** the key for the current entry. If the cursor is not pointing
  52299. ** to a valid entry, *pSize is set to 0.
  52300. **
  52301. ** For a table with the INTKEY flag set, this routine returns the key
  52302. ** itself, not the number of bytes in the key.
  52303. **
  52304. ** The caller must position the cursor prior to invoking this routine.
  52305. **
  52306. ** This routine cannot fail. It always returns SQLITE_OK.
  52307. */
  52308. SQLITE_PRIVATE int sqlite3BtreeKeySize(BtCursor *pCur, i64 *pSize){
  52309. assert( cursorHoldsMutex(pCur) );
  52310. assert( pCur->eState==CURSOR_VALID );
  52311. getCellInfo(pCur);
  52312. *pSize = pCur->info.nKey;
  52313. return SQLITE_OK;
  52314. }
  52315. /*
  52316. ** Set *pSize to the number of bytes of data in the entry the
  52317. ** cursor currently points to.
  52318. **
  52319. ** The caller must guarantee that the cursor is pointing to a non-NULL
  52320. ** valid entry. In other words, the calling procedure must guarantee
  52321. ** that the cursor has Cursor.eState==CURSOR_VALID.
  52322. **
  52323. ** Failure is not possible. This function always returns SQLITE_OK.
  52324. ** It might just as well be a procedure (returning void) but we continue
  52325. ** to return an integer result code for historical reasons.
  52326. */
  52327. SQLITE_PRIVATE int sqlite3BtreeDataSize(BtCursor *pCur, u32 *pSize){
  52328. assert( cursorHoldsMutex(pCur) );
  52329. assert( pCur->eState==CURSOR_VALID );
  52330. assert( pCur->apPage[pCur->iPage]->intKeyLeaf==1 );
  52331. getCellInfo(pCur);
  52332. *pSize = pCur->info.nPayload;
  52333. return SQLITE_OK;
  52334. }
  52335. /*
  52336. ** Given the page number of an overflow page in the database (parameter
  52337. ** ovfl), this function finds the page number of the next page in the
  52338. ** linked list of overflow pages. If possible, it uses the auto-vacuum
  52339. ** pointer-map data instead of reading the content of page ovfl to do so.
  52340. **
  52341. ** If an error occurs an SQLite error code is returned. Otherwise:
  52342. **
  52343. ** The page number of the next overflow page in the linked list is
  52344. ** written to *pPgnoNext. If page ovfl is the last page in its linked
  52345. ** list, *pPgnoNext is set to zero.
  52346. **
  52347. ** If ppPage is not NULL, and a reference to the MemPage object corresponding
  52348. ** to page number pOvfl was obtained, then *ppPage is set to point to that
  52349. ** reference. It is the responsibility of the caller to call releasePage()
  52350. ** on *ppPage to free the reference. In no reference was obtained (because
  52351. ** the pointer-map was used to obtain the value for *pPgnoNext), then
  52352. ** *ppPage is set to zero.
  52353. */
  52354. static int getOverflowPage(
  52355. BtShared *pBt, /* The database file */
  52356. Pgno ovfl, /* Current overflow page number */
  52357. MemPage **ppPage, /* OUT: MemPage handle (may be NULL) */
  52358. Pgno *pPgnoNext /* OUT: Next overflow page number */
  52359. ){
  52360. Pgno next = 0;
  52361. MemPage *pPage = 0;
  52362. int rc = SQLITE_OK;
  52363. assert( sqlite3_mutex_held(pBt->mutex) );
  52364. assert(pPgnoNext);
  52365. #ifndef SQLITE_OMIT_AUTOVACUUM
  52366. /* Try to find the next page in the overflow list using the
  52367. ** autovacuum pointer-map pages. Guess that the next page in
  52368. ** the overflow list is page number (ovfl+1). If that guess turns
  52369. ** out to be wrong, fall back to loading the data of page
  52370. ** number ovfl to determine the next page number.
  52371. */
  52372. if( pBt->autoVacuum ){
  52373. Pgno pgno;
  52374. Pgno iGuess = ovfl+1;
  52375. u8 eType;
  52376. while( PTRMAP_ISPAGE(pBt, iGuess) || iGuess==PENDING_BYTE_PAGE(pBt) ){
  52377. iGuess++;
  52378. }
  52379. if( iGuess<=btreePagecount(pBt) ){
  52380. rc = ptrmapGet(pBt, iGuess, &eType, &pgno);
  52381. if( rc==SQLITE_OK && eType==PTRMAP_OVERFLOW2 && pgno==ovfl ){
  52382. next = iGuess;
  52383. rc = SQLITE_DONE;
  52384. }
  52385. }
  52386. }
  52387. #endif
  52388. assert( next==0 || rc==SQLITE_DONE );
  52389. if( rc==SQLITE_OK ){
  52390. rc = btreeGetPage(pBt, ovfl, &pPage, (ppPage==0) ? PAGER_GET_READONLY : 0);
  52391. assert( rc==SQLITE_OK || pPage==0 );
  52392. if( rc==SQLITE_OK ){
  52393. next = get4byte(pPage->aData);
  52394. }
  52395. }
  52396. *pPgnoNext = next;
  52397. if( ppPage ){
  52398. *ppPage = pPage;
  52399. }else{
  52400. releasePage(pPage);
  52401. }
  52402. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  52403. }
  52404. /*
  52405. ** Copy data from a buffer to a page, or from a page to a buffer.
  52406. **
  52407. ** pPayload is a pointer to data stored on database page pDbPage.
  52408. ** If argument eOp is false, then nByte bytes of data are copied
  52409. ** from pPayload to the buffer pointed at by pBuf. If eOp is true,
  52410. ** then sqlite3PagerWrite() is called on pDbPage and nByte bytes
  52411. ** of data are copied from the buffer pBuf to pPayload.
  52412. **
  52413. ** SQLITE_OK is returned on success, otherwise an error code.
  52414. */
  52415. static int copyPayload(
  52416. void *pPayload, /* Pointer to page data */
  52417. void *pBuf, /* Pointer to buffer */
  52418. int nByte, /* Number of bytes to copy */
  52419. int eOp, /* 0 -> copy from page, 1 -> copy to page */
  52420. DbPage *pDbPage /* Page containing pPayload */
  52421. ){
  52422. if( eOp ){
  52423. /* Copy data from buffer to page (a write operation) */
  52424. int rc = sqlite3PagerWrite(pDbPage);
  52425. if( rc!=SQLITE_OK ){
  52426. return rc;
  52427. }
  52428. memcpy(pPayload, pBuf, nByte);
  52429. }else{
  52430. /* Copy data from page to buffer (a read operation) */
  52431. memcpy(pBuf, pPayload, nByte);
  52432. }
  52433. return SQLITE_OK;
  52434. }
  52435. /*
  52436. ** This function is used to read or overwrite payload information
  52437. ** for the entry that the pCur cursor is pointing to. The eOp
  52438. ** argument is interpreted as follows:
  52439. **
  52440. ** 0: The operation is a read. Populate the overflow cache.
  52441. ** 1: The operation is a write. Populate the overflow cache.
  52442. ** 2: The operation is a read. Do not populate the overflow cache.
  52443. **
  52444. ** A total of "amt" bytes are read or written beginning at "offset".
  52445. ** Data is read to or from the buffer pBuf.
  52446. **
  52447. ** The content being read or written might appear on the main page
  52448. ** or be scattered out on multiple overflow pages.
  52449. **
  52450. ** If the current cursor entry uses one or more overflow pages and the
  52451. ** eOp argument is not 2, this function may allocate space for and lazily
  52452. ** populates the overflow page-list cache array (BtCursor.aOverflow).
  52453. ** Subsequent calls use this cache to make seeking to the supplied offset
  52454. ** more efficient.
  52455. **
  52456. ** Once an overflow page-list cache has been allocated, it may be
  52457. ** invalidated if some other cursor writes to the same table, or if
  52458. ** the cursor is moved to a different row. Additionally, in auto-vacuum
  52459. ** mode, the following events may invalidate an overflow page-list cache.
  52460. **
  52461. ** * An incremental vacuum,
  52462. ** * A commit in auto_vacuum="full" mode,
  52463. ** * Creating a table (may require moving an overflow page).
  52464. */
  52465. static int accessPayload(
  52466. BtCursor *pCur, /* Cursor pointing to entry to read from */
  52467. u32 offset, /* Begin reading this far into payload */
  52468. u32 amt, /* Read this many bytes */
  52469. unsigned char *pBuf, /* Write the bytes into this buffer */
  52470. int eOp /* zero to read. non-zero to write. */
  52471. ){
  52472. unsigned char *aPayload;
  52473. int rc = SQLITE_OK;
  52474. int iIdx = 0;
  52475. MemPage *pPage = pCur->apPage[pCur->iPage]; /* Btree page of current entry */
  52476. BtShared *pBt = pCur->pBt; /* Btree this cursor belongs to */
  52477. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  52478. unsigned char * const pBufStart = pBuf;
  52479. int bEnd; /* True if reading to end of data */
  52480. #endif
  52481. assert( pPage );
  52482. assert( pCur->eState==CURSOR_VALID );
  52483. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  52484. assert( cursorHoldsMutex(pCur) );
  52485. assert( eOp!=2 || offset==0 ); /* Always start from beginning for eOp==2 */
  52486. getCellInfo(pCur);
  52487. aPayload = pCur->info.pPayload;
  52488. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  52489. bEnd = offset+amt==pCur->info.nPayload;
  52490. #endif
  52491. assert( offset+amt <= pCur->info.nPayload );
  52492. if( &aPayload[pCur->info.nLocal] > &pPage->aData[pBt->usableSize] ){
  52493. /* Trying to read or write past the end of the data is an error */
  52494. return SQLITE_CORRUPT_BKPT;
  52495. }
  52496. /* Check if data must be read/written to/from the btree page itself. */
  52497. if( offset<pCur->info.nLocal ){
  52498. int a = amt;
  52499. if( a+offset>pCur->info.nLocal ){
  52500. a = pCur->info.nLocal - offset;
  52501. }
  52502. rc = copyPayload(&aPayload[offset], pBuf, a, (eOp & 0x01), pPage->pDbPage);
  52503. offset = 0;
  52504. pBuf += a;
  52505. amt -= a;
  52506. }else{
  52507. offset -= pCur->info.nLocal;
  52508. }
  52509. if( rc==SQLITE_OK && amt>0 ){
  52510. const u32 ovflSize = pBt->usableSize - 4; /* Bytes content per ovfl page */
  52511. Pgno nextPage;
  52512. nextPage = get4byte(&aPayload[pCur->info.nLocal]);
  52513. /* If the BtCursor.aOverflow[] has not been allocated, allocate it now.
  52514. ** Except, do not allocate aOverflow[] for eOp==2.
  52515. **
  52516. ** The aOverflow[] array is sized at one entry for each overflow page
  52517. ** in the overflow chain. The page number of the first overflow page is
  52518. ** stored in aOverflow[0], etc. A value of 0 in the aOverflow[] array
  52519. ** means "not yet known" (the cache is lazily populated).
  52520. */
  52521. if( eOp!=2 && (pCur->curFlags & BTCF_ValidOvfl)==0 ){
  52522. int nOvfl = (pCur->info.nPayload-pCur->info.nLocal+ovflSize-1)/ovflSize;
  52523. if( nOvfl>pCur->nOvflAlloc ){
  52524. Pgno *aNew = (Pgno*)sqlite3DbRealloc(
  52525. pCur->pBtree->db, pCur->aOverflow, nOvfl*2*sizeof(Pgno)
  52526. );
  52527. if( aNew==0 ){
  52528. rc = SQLITE_NOMEM;
  52529. }else{
  52530. pCur->nOvflAlloc = nOvfl*2;
  52531. pCur->aOverflow = aNew;
  52532. }
  52533. }
  52534. if( rc==SQLITE_OK ){
  52535. memset(pCur->aOverflow, 0, nOvfl*sizeof(Pgno));
  52536. pCur->curFlags |= BTCF_ValidOvfl;
  52537. }
  52538. }
  52539. /* If the overflow page-list cache has been allocated and the
  52540. ** entry for the first required overflow page is valid, skip
  52541. ** directly to it.
  52542. */
  52543. if( (pCur->curFlags & BTCF_ValidOvfl)!=0
  52544. && pCur->aOverflow[offset/ovflSize]
  52545. ){
  52546. iIdx = (offset/ovflSize);
  52547. nextPage = pCur->aOverflow[iIdx];
  52548. offset = (offset%ovflSize);
  52549. }
  52550. for( ; rc==SQLITE_OK && amt>0 && nextPage; iIdx++){
  52551. /* If required, populate the overflow page-list cache. */
  52552. if( (pCur->curFlags & BTCF_ValidOvfl)!=0 ){
  52553. assert(!pCur->aOverflow[iIdx] || pCur->aOverflow[iIdx]==nextPage);
  52554. pCur->aOverflow[iIdx] = nextPage;
  52555. }
  52556. if( offset>=ovflSize ){
  52557. /* The only reason to read this page is to obtain the page
  52558. ** number for the next page in the overflow chain. The page
  52559. ** data is not required. So first try to lookup the overflow
  52560. ** page-list cache, if any, then fall back to the getOverflowPage()
  52561. ** function.
  52562. **
  52563. ** Note that the aOverflow[] array must be allocated because eOp!=2
  52564. ** here. If eOp==2, then offset==0 and this branch is never taken.
  52565. */
  52566. assert( eOp!=2 );
  52567. assert( pCur->curFlags & BTCF_ValidOvfl );
  52568. if( pCur->aOverflow[iIdx+1] ){
  52569. nextPage = pCur->aOverflow[iIdx+1];
  52570. }else{
  52571. rc = getOverflowPage(pBt, nextPage, 0, &nextPage);
  52572. }
  52573. offset -= ovflSize;
  52574. }else{
  52575. /* Need to read this page properly. It contains some of the
  52576. ** range of data that is being read (eOp==0) or written (eOp!=0).
  52577. */
  52578. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  52579. sqlite3_file *fd;
  52580. #endif
  52581. int a = amt;
  52582. if( a + offset > ovflSize ){
  52583. a = ovflSize - offset;
  52584. }
  52585. #ifdef SQLITE_DIRECT_OVERFLOW_READ
  52586. /* If all the following are true:
  52587. **
  52588. ** 1) this is a read operation, and
  52589. ** 2) data is required from the start of this overflow page, and
  52590. ** 3) the database is file-backed, and
  52591. ** 4) there is no open write-transaction, and
  52592. ** 5) the database is not a WAL database,
  52593. ** 6) all data from the page is being read.
  52594. ** 7) at least 4 bytes have already been read into the output buffer
  52595. **
  52596. ** then data can be read directly from the database file into the
  52597. ** output buffer, bypassing the page-cache altogether. This speeds
  52598. ** up loading large records that span many overflow pages.
  52599. */
  52600. if( (eOp&0x01)==0 /* (1) */
  52601. && offset==0 /* (2) */
  52602. && (bEnd || a==ovflSize) /* (6) */
  52603. && pBt->inTransaction==TRANS_READ /* (4) */
  52604. && (fd = sqlite3PagerFile(pBt->pPager))->pMethods /* (3) */
  52605. && pBt->pPage1->aData[19]==0x01 /* (5) */
  52606. && &pBuf[-4]>=pBufStart /* (7) */
  52607. ){
  52608. u8 aSave[4];
  52609. u8 *aWrite = &pBuf[-4];
  52610. assert( aWrite>=pBufStart ); /* hence (7) */
  52611. memcpy(aSave, aWrite, 4);
  52612. rc = sqlite3OsRead(fd, aWrite, a+4, (i64)pBt->pageSize*(nextPage-1));
  52613. nextPage = get4byte(aWrite);
  52614. memcpy(aWrite, aSave, 4);
  52615. }else
  52616. #endif
  52617. {
  52618. DbPage *pDbPage;
  52619. rc = sqlite3PagerAcquire(pBt->pPager, nextPage, &pDbPage,
  52620. ((eOp&0x01)==0 ? PAGER_GET_READONLY : 0)
  52621. );
  52622. if( rc==SQLITE_OK ){
  52623. aPayload = sqlite3PagerGetData(pDbPage);
  52624. nextPage = get4byte(aPayload);
  52625. rc = copyPayload(&aPayload[offset+4], pBuf, a, (eOp&0x01), pDbPage);
  52626. sqlite3PagerUnref(pDbPage);
  52627. offset = 0;
  52628. }
  52629. }
  52630. amt -= a;
  52631. pBuf += a;
  52632. }
  52633. }
  52634. }
  52635. if( rc==SQLITE_OK && amt>0 ){
  52636. return SQLITE_CORRUPT_BKPT;
  52637. }
  52638. return rc;
  52639. }
  52640. /*
  52641. ** Read part of the key associated with cursor pCur. Exactly
  52642. ** "amt" bytes will be transferred into pBuf[]. The transfer
  52643. ** begins at "offset".
  52644. **
  52645. ** The caller must ensure that pCur is pointing to a valid row
  52646. ** in the table.
  52647. **
  52648. ** Return SQLITE_OK on success or an error code if anything goes
  52649. ** wrong. An error is returned if "offset+amt" is larger than
  52650. ** the available payload.
  52651. */
  52652. SQLITE_PRIVATE int sqlite3BtreeKey(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  52653. assert( cursorHoldsMutex(pCur) );
  52654. assert( pCur->eState==CURSOR_VALID );
  52655. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  52656. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  52657. return accessPayload(pCur, offset, amt, (unsigned char*)pBuf, 0);
  52658. }
  52659. /*
  52660. ** Read part of the data associated with cursor pCur. Exactly
  52661. ** "amt" bytes will be transfered into pBuf[]. The transfer
  52662. ** begins at "offset".
  52663. **
  52664. ** Return SQLITE_OK on success or an error code if anything goes
  52665. ** wrong. An error is returned if "offset+amt" is larger than
  52666. ** the available payload.
  52667. */
  52668. SQLITE_PRIVATE int sqlite3BtreeData(BtCursor *pCur, u32 offset, u32 amt, void *pBuf){
  52669. int rc;
  52670. #ifndef SQLITE_OMIT_INCRBLOB
  52671. if ( pCur->eState==CURSOR_INVALID ){
  52672. return SQLITE_ABORT;
  52673. }
  52674. #endif
  52675. assert( cursorHoldsMutex(pCur) );
  52676. rc = restoreCursorPosition(pCur);
  52677. if( rc==SQLITE_OK ){
  52678. assert( pCur->eState==CURSOR_VALID );
  52679. assert( pCur->iPage>=0 && pCur->apPage[pCur->iPage] );
  52680. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  52681. rc = accessPayload(pCur, offset, amt, pBuf, 0);
  52682. }
  52683. return rc;
  52684. }
  52685. /*
  52686. ** Return a pointer to payload information from the entry that the
  52687. ** pCur cursor is pointing to. The pointer is to the beginning of
  52688. ** the key if index btrees (pPage->intKey==0) and is the data for
  52689. ** table btrees (pPage->intKey==1). The number of bytes of available
  52690. ** key/data is written into *pAmt. If *pAmt==0, then the value
  52691. ** returned will not be a valid pointer.
  52692. **
  52693. ** This routine is an optimization. It is common for the entire key
  52694. ** and data to fit on the local page and for there to be no overflow
  52695. ** pages. When that is so, this routine can be used to access the
  52696. ** key and data without making a copy. If the key and/or data spills
  52697. ** onto overflow pages, then accessPayload() must be used to reassemble
  52698. ** the key/data and copy it into a preallocated buffer.
  52699. **
  52700. ** The pointer returned by this routine looks directly into the cached
  52701. ** page of the database. The data might change or move the next time
  52702. ** any btree routine is called.
  52703. */
  52704. static const void *fetchPayload(
  52705. BtCursor *pCur, /* Cursor pointing to entry to read from */
  52706. u32 *pAmt /* Write the number of available bytes here */
  52707. ){
  52708. assert( pCur!=0 && pCur->iPage>=0 && pCur->apPage[pCur->iPage]);
  52709. assert( pCur->eState==CURSOR_VALID );
  52710. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  52711. assert( cursorHoldsMutex(pCur) );
  52712. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  52713. assert( pCur->info.nSize>0 );
  52714. *pAmt = pCur->info.nLocal;
  52715. return (void*)pCur->info.pPayload;
  52716. }
  52717. /*
  52718. ** For the entry that cursor pCur is point to, return as
  52719. ** many bytes of the key or data as are available on the local
  52720. ** b-tree page. Write the number of available bytes into *pAmt.
  52721. **
  52722. ** The pointer returned is ephemeral. The key/data may move
  52723. ** or be destroyed on the next call to any Btree routine,
  52724. ** including calls from other threads against the same cache.
  52725. ** Hence, a mutex on the BtShared should be held prior to calling
  52726. ** this routine.
  52727. **
  52728. ** These routines is used to get quick access to key and data
  52729. ** in the common case where no overflow pages are used.
  52730. */
  52731. SQLITE_PRIVATE const void *sqlite3BtreeKeyFetch(BtCursor *pCur, u32 *pAmt){
  52732. return fetchPayload(pCur, pAmt);
  52733. }
  52734. SQLITE_PRIVATE const void *sqlite3BtreeDataFetch(BtCursor *pCur, u32 *pAmt){
  52735. return fetchPayload(pCur, pAmt);
  52736. }
  52737. /*
  52738. ** Move the cursor down to a new child page. The newPgno argument is the
  52739. ** page number of the child page to move to.
  52740. **
  52741. ** This function returns SQLITE_CORRUPT if the page-header flags field of
  52742. ** the new child page does not match the flags field of the parent (i.e.
  52743. ** if an intkey page appears to be the parent of a non-intkey page, or
  52744. ** vice-versa).
  52745. */
  52746. static int moveToChild(BtCursor *pCur, u32 newPgno){
  52747. int rc;
  52748. int i = pCur->iPage;
  52749. MemPage *pNewPage;
  52750. BtShared *pBt = pCur->pBt;
  52751. assert( cursorHoldsMutex(pCur) );
  52752. assert( pCur->eState==CURSOR_VALID );
  52753. assert( pCur->iPage<BTCURSOR_MAX_DEPTH );
  52754. assert( pCur->iPage>=0 );
  52755. if( pCur->iPage>=(BTCURSOR_MAX_DEPTH-1) ){
  52756. return SQLITE_CORRUPT_BKPT;
  52757. }
  52758. rc = getAndInitPage(pBt, newPgno, &pNewPage,
  52759. (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
  52760. if( rc ) return rc;
  52761. pCur->apPage[i+1] = pNewPage;
  52762. pCur->aiIdx[i+1] = 0;
  52763. pCur->iPage++;
  52764. pCur->info.nSize = 0;
  52765. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  52766. if( pNewPage->nCell<1 || pNewPage->intKey!=pCur->apPage[i]->intKey ){
  52767. return SQLITE_CORRUPT_BKPT;
  52768. }
  52769. return SQLITE_OK;
  52770. }
  52771. #if 0
  52772. /*
  52773. ** Page pParent is an internal (non-leaf) tree page. This function
  52774. ** asserts that page number iChild is the left-child if the iIdx'th
  52775. ** cell in page pParent. Or, if iIdx is equal to the total number of
  52776. ** cells in pParent, that page number iChild is the right-child of
  52777. ** the page.
  52778. */
  52779. static void assertParentIndex(MemPage *pParent, int iIdx, Pgno iChild){
  52780. assert( iIdx<=pParent->nCell );
  52781. if( iIdx==pParent->nCell ){
  52782. assert( get4byte(&pParent->aData[pParent->hdrOffset+8])==iChild );
  52783. }else{
  52784. assert( get4byte(findCell(pParent, iIdx))==iChild );
  52785. }
  52786. }
  52787. #else
  52788. # define assertParentIndex(x,y,z)
  52789. #endif
  52790. /*
  52791. ** Move the cursor up to the parent page.
  52792. **
  52793. ** pCur->idx is set to the cell index that contains the pointer
  52794. ** to the page we are coming from. If we are coming from the
  52795. ** right-most child page then pCur->idx is set to one more than
  52796. ** the largest cell index.
  52797. */
  52798. static void moveToParent(BtCursor *pCur){
  52799. assert( cursorHoldsMutex(pCur) );
  52800. assert( pCur->eState==CURSOR_VALID );
  52801. assert( pCur->iPage>0 );
  52802. assert( pCur->apPage[pCur->iPage] );
  52803. /* UPDATE: It is actually possible for the condition tested by the assert
  52804. ** below to be untrue if the database file is corrupt. This can occur if
  52805. ** one cursor has modified page pParent while a reference to it is held
  52806. ** by a second cursor. Which can only happen if a single page is linked
  52807. ** into more than one b-tree structure in a corrupt database. */
  52808. #if 0
  52809. assertParentIndex(
  52810. pCur->apPage[pCur->iPage-1],
  52811. pCur->aiIdx[pCur->iPage-1],
  52812. pCur->apPage[pCur->iPage]->pgno
  52813. );
  52814. #endif
  52815. testcase( pCur->aiIdx[pCur->iPage-1] > pCur->apPage[pCur->iPage-1]->nCell );
  52816. releasePage(pCur->apPage[pCur->iPage]);
  52817. pCur->iPage--;
  52818. pCur->info.nSize = 0;
  52819. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  52820. }
  52821. /*
  52822. ** Move the cursor to point to the root page of its b-tree structure.
  52823. **
  52824. ** If the table has a virtual root page, then the cursor is moved to point
  52825. ** to the virtual root page instead of the actual root page. A table has a
  52826. ** virtual root page when the actual root page contains no cells and a
  52827. ** single child page. This can only happen with the table rooted at page 1.
  52828. **
  52829. ** If the b-tree structure is empty, the cursor state is set to
  52830. ** CURSOR_INVALID. Otherwise, the cursor is set to point to the first
  52831. ** cell located on the root (or virtual root) page and the cursor state
  52832. ** is set to CURSOR_VALID.
  52833. **
  52834. ** If this function returns successfully, it may be assumed that the
  52835. ** page-header flags indicate that the [virtual] root-page is the expected
  52836. ** kind of b-tree page (i.e. if when opening the cursor the caller did not
  52837. ** specify a KeyInfo structure the flags byte is set to 0x05 or 0x0D,
  52838. ** indicating a table b-tree, or if the caller did specify a KeyInfo
  52839. ** structure the flags byte is set to 0x02 or 0x0A, indicating an index
  52840. ** b-tree).
  52841. */
  52842. static int moveToRoot(BtCursor *pCur){
  52843. MemPage *pRoot;
  52844. int rc = SQLITE_OK;
  52845. assert( cursorHoldsMutex(pCur) );
  52846. assert( CURSOR_INVALID < CURSOR_REQUIRESEEK );
  52847. assert( CURSOR_VALID < CURSOR_REQUIRESEEK );
  52848. assert( CURSOR_FAULT > CURSOR_REQUIRESEEK );
  52849. if( pCur->eState>=CURSOR_REQUIRESEEK ){
  52850. if( pCur->eState==CURSOR_FAULT ){
  52851. assert( pCur->skipNext!=SQLITE_OK );
  52852. return pCur->skipNext;
  52853. }
  52854. sqlite3BtreeClearCursor(pCur);
  52855. }
  52856. if( pCur->iPage>=0 ){
  52857. while( pCur->iPage ) releasePage(pCur->apPage[pCur->iPage--]);
  52858. }else if( pCur->pgnoRoot==0 ){
  52859. pCur->eState = CURSOR_INVALID;
  52860. return SQLITE_OK;
  52861. }else{
  52862. rc = getAndInitPage(pCur->pBtree->pBt, pCur->pgnoRoot, &pCur->apPage[0],
  52863. (pCur->curFlags & BTCF_WriteFlag)==0 ? PAGER_GET_READONLY : 0);
  52864. if( rc!=SQLITE_OK ){
  52865. pCur->eState = CURSOR_INVALID;
  52866. return rc;
  52867. }
  52868. pCur->iPage = 0;
  52869. }
  52870. pRoot = pCur->apPage[0];
  52871. assert( pRoot->pgno==pCur->pgnoRoot );
  52872. /* If pCur->pKeyInfo is not NULL, then the caller that opened this cursor
  52873. ** expected to open it on an index b-tree. Otherwise, if pKeyInfo is
  52874. ** NULL, the caller expects a table b-tree. If this is not the case,
  52875. ** return an SQLITE_CORRUPT error.
  52876. **
  52877. ** Earlier versions of SQLite assumed that this test could not fail
  52878. ** if the root page was already loaded when this function was called (i.e.
  52879. ** if pCur->iPage>=0). But this is not so if the database is corrupted
  52880. ** in such a way that page pRoot is linked into a second b-tree table
  52881. ** (or the freelist). */
  52882. assert( pRoot->intKey==1 || pRoot->intKey==0 );
  52883. if( pRoot->isInit==0 || (pCur->pKeyInfo==0)!=pRoot->intKey ){
  52884. return SQLITE_CORRUPT_BKPT;
  52885. }
  52886. pCur->aiIdx[0] = 0;
  52887. pCur->info.nSize = 0;
  52888. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidNKey|BTCF_ValidOvfl);
  52889. if( pRoot->nCell>0 ){
  52890. pCur->eState = CURSOR_VALID;
  52891. }else if( !pRoot->leaf ){
  52892. Pgno subpage;
  52893. if( pRoot->pgno!=1 ) return SQLITE_CORRUPT_BKPT;
  52894. subpage = get4byte(&pRoot->aData[pRoot->hdrOffset+8]);
  52895. pCur->eState = CURSOR_VALID;
  52896. rc = moveToChild(pCur, subpage);
  52897. }else{
  52898. pCur->eState = CURSOR_INVALID;
  52899. }
  52900. return rc;
  52901. }
  52902. /*
  52903. ** Move the cursor down to the left-most leaf entry beneath the
  52904. ** entry to which it is currently pointing.
  52905. **
  52906. ** The left-most leaf is the one with the smallest key - the first
  52907. ** in ascending order.
  52908. */
  52909. static int moveToLeftmost(BtCursor *pCur){
  52910. Pgno pgno;
  52911. int rc = SQLITE_OK;
  52912. MemPage *pPage;
  52913. assert( cursorHoldsMutex(pCur) );
  52914. assert( pCur->eState==CURSOR_VALID );
  52915. while( rc==SQLITE_OK && !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  52916. assert( pCur->aiIdx[pCur->iPage]<pPage->nCell );
  52917. pgno = get4byte(findCell(pPage, pCur->aiIdx[pCur->iPage]));
  52918. rc = moveToChild(pCur, pgno);
  52919. }
  52920. return rc;
  52921. }
  52922. /*
  52923. ** Move the cursor down to the right-most leaf entry beneath the
  52924. ** page to which it is currently pointing. Notice the difference
  52925. ** between moveToLeftmost() and moveToRightmost(). moveToLeftmost()
  52926. ** finds the left-most entry beneath the *entry* whereas moveToRightmost()
  52927. ** finds the right-most entry beneath the *page*.
  52928. **
  52929. ** The right-most entry is the one with the largest key - the last
  52930. ** key in ascending order.
  52931. */
  52932. static int moveToRightmost(BtCursor *pCur){
  52933. Pgno pgno;
  52934. int rc = SQLITE_OK;
  52935. MemPage *pPage = 0;
  52936. assert( cursorHoldsMutex(pCur) );
  52937. assert( pCur->eState==CURSOR_VALID );
  52938. while( !(pPage = pCur->apPage[pCur->iPage])->leaf ){
  52939. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  52940. pCur->aiIdx[pCur->iPage] = pPage->nCell;
  52941. rc = moveToChild(pCur, pgno);
  52942. if( rc ) return rc;
  52943. }
  52944. pCur->aiIdx[pCur->iPage] = pPage->nCell-1;
  52945. assert( pCur->info.nSize==0 );
  52946. assert( (pCur->curFlags & BTCF_ValidNKey)==0 );
  52947. return SQLITE_OK;
  52948. }
  52949. /* Move the cursor to the first entry in the table. Return SQLITE_OK
  52950. ** on success. Set *pRes to 0 if the cursor actually points to something
  52951. ** or set *pRes to 1 if the table is empty.
  52952. */
  52953. SQLITE_PRIVATE int sqlite3BtreeFirst(BtCursor *pCur, int *pRes){
  52954. int rc;
  52955. assert( cursorHoldsMutex(pCur) );
  52956. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  52957. rc = moveToRoot(pCur);
  52958. if( rc==SQLITE_OK ){
  52959. if( pCur->eState==CURSOR_INVALID ){
  52960. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  52961. *pRes = 1;
  52962. }else{
  52963. assert( pCur->apPage[pCur->iPage]->nCell>0 );
  52964. *pRes = 0;
  52965. rc = moveToLeftmost(pCur);
  52966. }
  52967. }
  52968. return rc;
  52969. }
  52970. /* Move the cursor to the last entry in the table. Return SQLITE_OK
  52971. ** on success. Set *pRes to 0 if the cursor actually points to something
  52972. ** or set *pRes to 1 if the table is empty.
  52973. */
  52974. SQLITE_PRIVATE int sqlite3BtreeLast(BtCursor *pCur, int *pRes){
  52975. int rc;
  52976. assert( cursorHoldsMutex(pCur) );
  52977. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  52978. /* If the cursor already points to the last entry, this is a no-op. */
  52979. if( CURSOR_VALID==pCur->eState && (pCur->curFlags & BTCF_AtLast)!=0 ){
  52980. #ifdef SQLITE_DEBUG
  52981. /* This block serves to assert() that the cursor really does point
  52982. ** to the last entry in the b-tree. */
  52983. int ii;
  52984. for(ii=0; ii<pCur->iPage; ii++){
  52985. assert( pCur->aiIdx[ii]==pCur->apPage[ii]->nCell );
  52986. }
  52987. assert( pCur->aiIdx[pCur->iPage]==pCur->apPage[pCur->iPage]->nCell-1 );
  52988. assert( pCur->apPage[pCur->iPage]->leaf );
  52989. #endif
  52990. return SQLITE_OK;
  52991. }
  52992. rc = moveToRoot(pCur);
  52993. if( rc==SQLITE_OK ){
  52994. if( CURSOR_INVALID==pCur->eState ){
  52995. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  52996. *pRes = 1;
  52997. }else{
  52998. assert( pCur->eState==CURSOR_VALID );
  52999. *pRes = 0;
  53000. rc = moveToRightmost(pCur);
  53001. if( rc==SQLITE_OK ){
  53002. pCur->curFlags |= BTCF_AtLast;
  53003. }else{
  53004. pCur->curFlags &= ~BTCF_AtLast;
  53005. }
  53006. }
  53007. }
  53008. return rc;
  53009. }
  53010. /* Move the cursor so that it points to an entry near the key
  53011. ** specified by pIdxKey or intKey. Return a success code.
  53012. **
  53013. ** For INTKEY tables, the intKey parameter is used. pIdxKey
  53014. ** must be NULL. For index tables, pIdxKey is used and intKey
  53015. ** is ignored.
  53016. **
  53017. ** If an exact match is not found, then the cursor is always
  53018. ** left pointing at a leaf page which would hold the entry if it
  53019. ** were present. The cursor might point to an entry that comes
  53020. ** before or after the key.
  53021. **
  53022. ** An integer is written into *pRes which is the result of
  53023. ** comparing the key with the entry to which the cursor is
  53024. ** pointing. The meaning of the integer written into
  53025. ** *pRes is as follows:
  53026. **
  53027. ** *pRes<0 The cursor is left pointing at an entry that
  53028. ** is smaller than intKey/pIdxKey or if the table is empty
  53029. ** and the cursor is therefore left point to nothing.
  53030. **
  53031. ** *pRes==0 The cursor is left pointing at an entry that
  53032. ** exactly matches intKey/pIdxKey.
  53033. **
  53034. ** *pRes>0 The cursor is left pointing at an entry that
  53035. ** is larger than intKey/pIdxKey.
  53036. **
  53037. */
  53038. SQLITE_PRIVATE int sqlite3BtreeMovetoUnpacked(
  53039. BtCursor *pCur, /* The cursor to be moved */
  53040. UnpackedRecord *pIdxKey, /* Unpacked index key */
  53041. i64 intKey, /* The table key */
  53042. int biasRight, /* If true, bias the search to the high end */
  53043. int *pRes /* Write search results here */
  53044. ){
  53045. int rc;
  53046. RecordCompare xRecordCompare;
  53047. assert( cursorHoldsMutex(pCur) );
  53048. assert( sqlite3_mutex_held(pCur->pBtree->db->mutex) );
  53049. assert( pRes );
  53050. assert( (pIdxKey==0)==(pCur->pKeyInfo==0) );
  53051. /* If the cursor is already positioned at the point we are trying
  53052. ** to move to, then just return without doing any work */
  53053. if( pCur->eState==CURSOR_VALID && (pCur->curFlags & BTCF_ValidNKey)!=0
  53054. && pCur->apPage[0]->intKey
  53055. ){
  53056. if( pCur->info.nKey==intKey ){
  53057. *pRes = 0;
  53058. return SQLITE_OK;
  53059. }
  53060. if( (pCur->curFlags & BTCF_AtLast)!=0 && pCur->info.nKey<intKey ){
  53061. *pRes = -1;
  53062. return SQLITE_OK;
  53063. }
  53064. }
  53065. if( pIdxKey ){
  53066. xRecordCompare = sqlite3VdbeFindCompare(pIdxKey);
  53067. pIdxKey->errCode = 0;
  53068. assert( pIdxKey->default_rc==1
  53069. || pIdxKey->default_rc==0
  53070. || pIdxKey->default_rc==-1
  53071. );
  53072. }else{
  53073. xRecordCompare = 0; /* All keys are integers */
  53074. }
  53075. rc = moveToRoot(pCur);
  53076. if( rc ){
  53077. return rc;
  53078. }
  53079. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage] );
  53080. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->isInit );
  53081. assert( pCur->eState==CURSOR_INVALID || pCur->apPage[pCur->iPage]->nCell>0 );
  53082. if( pCur->eState==CURSOR_INVALID ){
  53083. *pRes = -1;
  53084. assert( pCur->pgnoRoot==0 || pCur->apPage[pCur->iPage]->nCell==0 );
  53085. return SQLITE_OK;
  53086. }
  53087. assert( pCur->apPage[0]->intKey || pIdxKey );
  53088. for(;;){
  53089. int lwr, upr, idx, c;
  53090. Pgno chldPg;
  53091. MemPage *pPage = pCur->apPage[pCur->iPage];
  53092. u8 *pCell; /* Pointer to current cell in pPage */
  53093. /* pPage->nCell must be greater than zero. If this is the root-page
  53094. ** the cursor would have been INVALID above and this for(;;) loop
  53095. ** not run. If this is not the root-page, then the moveToChild() routine
  53096. ** would have already detected db corruption. Similarly, pPage must
  53097. ** be the right kind (index or table) of b-tree page. Otherwise
  53098. ** a moveToChild() or moveToRoot() call would have detected corruption. */
  53099. assert( pPage->nCell>0 );
  53100. assert( pPage->intKey==(pIdxKey==0) );
  53101. lwr = 0;
  53102. upr = pPage->nCell-1;
  53103. assert( biasRight==0 || biasRight==1 );
  53104. idx = upr>>(1-biasRight); /* idx = biasRight ? upr : (lwr+upr)/2; */
  53105. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53106. if( xRecordCompare==0 ){
  53107. for(;;){
  53108. i64 nCellKey;
  53109. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  53110. if( pPage->intKeyLeaf ){
  53111. while( 0x80 <= *(pCell++) ){
  53112. if( pCell>=pPage->aDataEnd ) return SQLITE_CORRUPT_BKPT;
  53113. }
  53114. }
  53115. getVarint(pCell, (u64*)&nCellKey);
  53116. if( nCellKey<intKey ){
  53117. lwr = idx+1;
  53118. if( lwr>upr ){ c = -1; break; }
  53119. }else if( nCellKey>intKey ){
  53120. upr = idx-1;
  53121. if( lwr>upr ){ c = +1; break; }
  53122. }else{
  53123. assert( nCellKey==intKey );
  53124. pCur->curFlags |= BTCF_ValidNKey;
  53125. pCur->info.nKey = nCellKey;
  53126. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53127. if( !pPage->leaf ){
  53128. lwr = idx;
  53129. goto moveto_next_layer;
  53130. }else{
  53131. *pRes = 0;
  53132. rc = SQLITE_OK;
  53133. goto moveto_finish;
  53134. }
  53135. }
  53136. assert( lwr+upr>=0 );
  53137. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2; */
  53138. }
  53139. }else{
  53140. for(;;){
  53141. int nCell;
  53142. pCell = findCell(pPage, idx) + pPage->childPtrSize;
  53143. /* The maximum supported page-size is 65536 bytes. This means that
  53144. ** the maximum number of record bytes stored on an index B-Tree
  53145. ** page is less than 16384 bytes and may be stored as a 2-byte
  53146. ** varint. This information is used to attempt to avoid parsing
  53147. ** the entire cell by checking for the cases where the record is
  53148. ** stored entirely within the b-tree page by inspecting the first
  53149. ** 2 bytes of the cell.
  53150. */
  53151. nCell = pCell[0];
  53152. if( nCell<=pPage->max1bytePayload ){
  53153. /* This branch runs if the record-size field of the cell is a
  53154. ** single byte varint and the record fits entirely on the main
  53155. ** b-tree page. */
  53156. testcase( pCell+nCell+1==pPage->aDataEnd );
  53157. c = xRecordCompare(nCell, (void*)&pCell[1], pIdxKey);
  53158. }else if( !(pCell[1] & 0x80)
  53159. && (nCell = ((nCell&0x7f)<<7) + pCell[1])<=pPage->maxLocal
  53160. ){
  53161. /* The record-size field is a 2 byte varint and the record
  53162. ** fits entirely on the main b-tree page. */
  53163. testcase( pCell+nCell+2==pPage->aDataEnd );
  53164. c = xRecordCompare(nCell, (void*)&pCell[2], pIdxKey);
  53165. }else{
  53166. /* The record flows over onto one or more overflow pages. In
  53167. ** this case the whole cell needs to be parsed, a buffer allocated
  53168. ** and accessPayload() used to retrieve the record into the
  53169. ** buffer before VdbeRecordCompare() can be called. */
  53170. void *pCellKey;
  53171. u8 * const pCellBody = pCell - pPage->childPtrSize;
  53172. btreeParseCellPtr(pPage, pCellBody, &pCur->info);
  53173. nCell = (int)pCur->info.nKey;
  53174. pCellKey = sqlite3Malloc( nCell );
  53175. if( pCellKey==0 ){
  53176. rc = SQLITE_NOMEM;
  53177. goto moveto_finish;
  53178. }
  53179. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53180. rc = accessPayload(pCur, 0, nCell, (unsigned char*)pCellKey, 2);
  53181. if( rc ){
  53182. sqlite3_free(pCellKey);
  53183. goto moveto_finish;
  53184. }
  53185. c = xRecordCompare(nCell, pCellKey, pIdxKey);
  53186. sqlite3_free(pCellKey);
  53187. }
  53188. assert(
  53189. (pIdxKey->errCode!=SQLITE_CORRUPT || c==0)
  53190. && (pIdxKey->errCode!=SQLITE_NOMEM || pCur->pBtree->db->mallocFailed)
  53191. );
  53192. if( c<0 ){
  53193. lwr = idx+1;
  53194. }else if( c>0 ){
  53195. upr = idx-1;
  53196. }else{
  53197. assert( c==0 );
  53198. *pRes = 0;
  53199. rc = SQLITE_OK;
  53200. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53201. if( pIdxKey->errCode ) rc = SQLITE_CORRUPT;
  53202. goto moveto_finish;
  53203. }
  53204. if( lwr>upr ) break;
  53205. assert( lwr+upr>=0 );
  53206. idx = (lwr+upr)>>1; /* idx = (lwr+upr)/2 */
  53207. }
  53208. }
  53209. assert( lwr==upr+1 || (pPage->intKey && !pPage->leaf) );
  53210. assert( pPage->isInit );
  53211. if( pPage->leaf ){
  53212. assert( pCur->aiIdx[pCur->iPage]<pCur->apPage[pCur->iPage]->nCell );
  53213. pCur->aiIdx[pCur->iPage] = (u16)idx;
  53214. *pRes = c;
  53215. rc = SQLITE_OK;
  53216. goto moveto_finish;
  53217. }
  53218. moveto_next_layer:
  53219. if( lwr>=pPage->nCell ){
  53220. chldPg = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  53221. }else{
  53222. chldPg = get4byte(findCell(pPage, lwr));
  53223. }
  53224. pCur->aiIdx[pCur->iPage] = (u16)lwr;
  53225. rc = moveToChild(pCur, chldPg);
  53226. if( rc ) break;
  53227. }
  53228. moveto_finish:
  53229. pCur->info.nSize = 0;
  53230. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  53231. return rc;
  53232. }
  53233. /*
  53234. ** Return TRUE if the cursor is not pointing at an entry of the table.
  53235. **
  53236. ** TRUE will be returned after a call to sqlite3BtreeNext() moves
  53237. ** past the last entry in the table or sqlite3BtreePrev() moves past
  53238. ** the first entry. TRUE is also returned if the table is empty.
  53239. */
  53240. SQLITE_PRIVATE int sqlite3BtreeEof(BtCursor *pCur){
  53241. /* TODO: What if the cursor is in CURSOR_REQUIRESEEK but all table entries
  53242. ** have been deleted? This API will need to change to return an error code
  53243. ** as well as the boolean result value.
  53244. */
  53245. return (CURSOR_VALID!=pCur->eState);
  53246. }
  53247. /*
  53248. ** Advance the cursor to the next entry in the database. If
  53249. ** successful then set *pRes=0. If the cursor
  53250. ** was already pointing to the last entry in the database before
  53251. ** this routine was called, then set *pRes=1.
  53252. **
  53253. ** The main entry point is sqlite3BtreeNext(). That routine is optimized
  53254. ** for the common case of merely incrementing the cell counter BtCursor.aiIdx
  53255. ** to the next cell on the current page. The (slower) btreeNext() helper
  53256. ** routine is called when it is necessary to move to a different page or
  53257. ** to restore the cursor.
  53258. **
  53259. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  53260. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  53261. ** if this routine could have been skipped if that SQL index had been
  53262. ** a unique index. Otherwise the caller will have set *pRes to zero.
  53263. ** Zero is the common case. The btree implementation is free to use the
  53264. ** initial *pRes value as a hint to improve performance, but the current
  53265. ** SQLite btree implementation does not. (Note that the comdb2 btree
  53266. ** implementation does use this hint, however.)
  53267. */
  53268. static SQLITE_NOINLINE int btreeNext(BtCursor *pCur, int *pRes){
  53269. int rc;
  53270. int idx;
  53271. MemPage *pPage;
  53272. assert( cursorHoldsMutex(pCur) );
  53273. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  53274. assert( *pRes==0 );
  53275. if( pCur->eState!=CURSOR_VALID ){
  53276. assert( (pCur->curFlags & BTCF_ValidOvfl)==0 );
  53277. rc = restoreCursorPosition(pCur);
  53278. if( rc!=SQLITE_OK ){
  53279. return rc;
  53280. }
  53281. if( CURSOR_INVALID==pCur->eState ){
  53282. *pRes = 1;
  53283. return SQLITE_OK;
  53284. }
  53285. if( pCur->skipNext ){
  53286. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  53287. pCur->eState = CURSOR_VALID;
  53288. if( pCur->skipNext>0 ){
  53289. pCur->skipNext = 0;
  53290. return SQLITE_OK;
  53291. }
  53292. pCur->skipNext = 0;
  53293. }
  53294. }
  53295. pPage = pCur->apPage[pCur->iPage];
  53296. idx = ++pCur->aiIdx[pCur->iPage];
  53297. assert( pPage->isInit );
  53298. /* If the database file is corrupt, it is possible for the value of idx
  53299. ** to be invalid here. This can only occur if a second cursor modifies
  53300. ** the page while cursor pCur is holding a reference to it. Which can
  53301. ** only happen if the database is corrupt in such a way as to link the
  53302. ** page into more than one b-tree structure. */
  53303. testcase( idx>pPage->nCell );
  53304. if( idx>=pPage->nCell ){
  53305. if( !pPage->leaf ){
  53306. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  53307. if( rc ) return rc;
  53308. return moveToLeftmost(pCur);
  53309. }
  53310. do{
  53311. if( pCur->iPage==0 ){
  53312. *pRes = 1;
  53313. pCur->eState = CURSOR_INVALID;
  53314. return SQLITE_OK;
  53315. }
  53316. moveToParent(pCur);
  53317. pPage = pCur->apPage[pCur->iPage];
  53318. }while( pCur->aiIdx[pCur->iPage]>=pPage->nCell );
  53319. if( pPage->intKey ){
  53320. return sqlite3BtreeNext(pCur, pRes);
  53321. }else{
  53322. return SQLITE_OK;
  53323. }
  53324. }
  53325. if( pPage->leaf ){
  53326. return SQLITE_OK;
  53327. }else{
  53328. return moveToLeftmost(pCur);
  53329. }
  53330. }
  53331. SQLITE_PRIVATE int sqlite3BtreeNext(BtCursor *pCur, int *pRes){
  53332. MemPage *pPage;
  53333. assert( cursorHoldsMutex(pCur) );
  53334. assert( pRes!=0 );
  53335. assert( *pRes==0 || *pRes==1 );
  53336. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  53337. pCur->info.nSize = 0;
  53338. pCur->curFlags &= ~(BTCF_ValidNKey|BTCF_ValidOvfl);
  53339. *pRes = 0;
  53340. if( pCur->eState!=CURSOR_VALID ) return btreeNext(pCur, pRes);
  53341. pPage = pCur->apPage[pCur->iPage];
  53342. if( (++pCur->aiIdx[pCur->iPage])>=pPage->nCell ){
  53343. pCur->aiIdx[pCur->iPage]--;
  53344. return btreeNext(pCur, pRes);
  53345. }
  53346. if( pPage->leaf ){
  53347. return SQLITE_OK;
  53348. }else{
  53349. return moveToLeftmost(pCur);
  53350. }
  53351. }
  53352. /*
  53353. ** Step the cursor to the back to the previous entry in the database. If
  53354. ** successful then set *pRes=0. If the cursor
  53355. ** was already pointing to the first entry in the database before
  53356. ** this routine was called, then set *pRes=1.
  53357. **
  53358. ** The main entry point is sqlite3BtreePrevious(). That routine is optimized
  53359. ** for the common case of merely decrementing the cell counter BtCursor.aiIdx
  53360. ** to the previous cell on the current page. The (slower) btreePrevious()
  53361. ** helper routine is called when it is necessary to move to a different page
  53362. ** or to restore the cursor.
  53363. **
  53364. ** The calling function will set *pRes to 0 or 1. The initial *pRes value
  53365. ** will be 1 if the cursor being stepped corresponds to an SQL index and
  53366. ** if this routine could have been skipped if that SQL index had been
  53367. ** a unique index. Otherwise the caller will have set *pRes to zero.
  53368. ** Zero is the common case. The btree implementation is free to use the
  53369. ** initial *pRes value as a hint to improve performance, but the current
  53370. ** SQLite btree implementation does not. (Note that the comdb2 btree
  53371. ** implementation does use this hint, however.)
  53372. */
  53373. static SQLITE_NOINLINE int btreePrevious(BtCursor *pCur, int *pRes){
  53374. int rc;
  53375. MemPage *pPage;
  53376. assert( cursorHoldsMutex(pCur) );
  53377. assert( pRes!=0 );
  53378. assert( *pRes==0 );
  53379. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  53380. assert( (pCur->curFlags & (BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey))==0 );
  53381. assert( pCur->info.nSize==0 );
  53382. if( pCur->eState!=CURSOR_VALID ){
  53383. rc = restoreCursorPosition(pCur);
  53384. if( rc!=SQLITE_OK ){
  53385. return rc;
  53386. }
  53387. if( CURSOR_INVALID==pCur->eState ){
  53388. *pRes = 1;
  53389. return SQLITE_OK;
  53390. }
  53391. if( pCur->skipNext ){
  53392. assert( pCur->eState==CURSOR_VALID || pCur->eState==CURSOR_SKIPNEXT );
  53393. pCur->eState = CURSOR_VALID;
  53394. if( pCur->skipNext<0 ){
  53395. pCur->skipNext = 0;
  53396. return SQLITE_OK;
  53397. }
  53398. pCur->skipNext = 0;
  53399. }
  53400. }
  53401. pPage = pCur->apPage[pCur->iPage];
  53402. assert( pPage->isInit );
  53403. if( !pPage->leaf ){
  53404. int idx = pCur->aiIdx[pCur->iPage];
  53405. rc = moveToChild(pCur, get4byte(findCell(pPage, idx)));
  53406. if( rc ) return rc;
  53407. rc = moveToRightmost(pCur);
  53408. }else{
  53409. while( pCur->aiIdx[pCur->iPage]==0 ){
  53410. if( pCur->iPage==0 ){
  53411. pCur->eState = CURSOR_INVALID;
  53412. *pRes = 1;
  53413. return SQLITE_OK;
  53414. }
  53415. moveToParent(pCur);
  53416. }
  53417. assert( pCur->info.nSize==0 );
  53418. assert( (pCur->curFlags & (BTCF_ValidNKey|BTCF_ValidOvfl))==0 );
  53419. pCur->aiIdx[pCur->iPage]--;
  53420. pPage = pCur->apPage[pCur->iPage];
  53421. if( pPage->intKey && !pPage->leaf ){
  53422. rc = sqlite3BtreePrevious(pCur, pRes);
  53423. }else{
  53424. rc = SQLITE_OK;
  53425. }
  53426. }
  53427. return rc;
  53428. }
  53429. SQLITE_PRIVATE int sqlite3BtreePrevious(BtCursor *pCur, int *pRes){
  53430. assert( cursorHoldsMutex(pCur) );
  53431. assert( pRes!=0 );
  53432. assert( *pRes==0 || *pRes==1 );
  53433. assert( pCur->skipNext==0 || pCur->eState!=CURSOR_VALID );
  53434. *pRes = 0;
  53435. pCur->curFlags &= ~(BTCF_AtLast|BTCF_ValidOvfl|BTCF_ValidNKey);
  53436. pCur->info.nSize = 0;
  53437. if( pCur->eState!=CURSOR_VALID
  53438. || pCur->aiIdx[pCur->iPage]==0
  53439. || pCur->apPage[pCur->iPage]->leaf==0
  53440. ){
  53441. return btreePrevious(pCur, pRes);
  53442. }
  53443. pCur->aiIdx[pCur->iPage]--;
  53444. return SQLITE_OK;
  53445. }
  53446. /*
  53447. ** Allocate a new page from the database file.
  53448. **
  53449. ** The new page is marked as dirty. (In other words, sqlite3PagerWrite()
  53450. ** has already been called on the new page.) The new page has also
  53451. ** been referenced and the calling routine is responsible for calling
  53452. ** sqlite3PagerUnref() on the new page when it is done.
  53453. **
  53454. ** SQLITE_OK is returned on success. Any other return value indicates
  53455. ** an error. *ppPage and *pPgno are undefined in the event of an error.
  53456. ** Do not invoke sqlite3PagerUnref() on *ppPage if an error is returned.
  53457. **
  53458. ** If the "nearby" parameter is not 0, then an effort is made to
  53459. ** locate a page close to the page number "nearby". This can be used in an
  53460. ** attempt to keep related pages close to each other in the database file,
  53461. ** which in turn can make database access faster.
  53462. **
  53463. ** If the eMode parameter is BTALLOC_EXACT and the nearby page exists
  53464. ** anywhere on the free-list, then it is guaranteed to be returned. If
  53465. ** eMode is BTALLOC_LT then the page returned will be less than or equal
  53466. ** to nearby if any such page exists. If eMode is BTALLOC_ANY then there
  53467. ** are no restrictions on which page is returned.
  53468. */
  53469. static int allocateBtreePage(
  53470. BtShared *pBt, /* The btree */
  53471. MemPage **ppPage, /* Store pointer to the allocated page here */
  53472. Pgno *pPgno, /* Store the page number here */
  53473. Pgno nearby, /* Search for a page near this one */
  53474. u8 eMode /* BTALLOC_EXACT, BTALLOC_LT, or BTALLOC_ANY */
  53475. ){
  53476. MemPage *pPage1;
  53477. int rc;
  53478. u32 n; /* Number of pages on the freelist */
  53479. u32 k; /* Number of leaves on the trunk of the freelist */
  53480. MemPage *pTrunk = 0;
  53481. MemPage *pPrevTrunk = 0;
  53482. Pgno mxPage; /* Total size of the database file */
  53483. assert( sqlite3_mutex_held(pBt->mutex) );
  53484. assert( eMode==BTALLOC_ANY || (nearby>0 && IfNotOmitAV(pBt->autoVacuum)) );
  53485. pPage1 = pBt->pPage1;
  53486. mxPage = btreePagecount(pBt);
  53487. n = get4byte(&pPage1->aData[36]);
  53488. testcase( n==mxPage-1 );
  53489. if( n>=mxPage ){
  53490. return SQLITE_CORRUPT_BKPT;
  53491. }
  53492. if( n>0 ){
  53493. /* There are pages on the freelist. Reuse one of those pages. */
  53494. Pgno iTrunk;
  53495. u8 searchList = 0; /* If the free-list must be searched for 'nearby' */
  53496. /* If eMode==BTALLOC_EXACT and a query of the pointer-map
  53497. ** shows that the page 'nearby' is somewhere on the free-list, then
  53498. ** the entire-list will be searched for that page.
  53499. */
  53500. #ifndef SQLITE_OMIT_AUTOVACUUM
  53501. if( eMode==BTALLOC_EXACT ){
  53502. if( nearby<=mxPage ){
  53503. u8 eType;
  53504. assert( nearby>0 );
  53505. assert( pBt->autoVacuum );
  53506. rc = ptrmapGet(pBt, nearby, &eType, 0);
  53507. if( rc ) return rc;
  53508. if( eType==PTRMAP_FREEPAGE ){
  53509. searchList = 1;
  53510. }
  53511. }
  53512. }else if( eMode==BTALLOC_LE ){
  53513. searchList = 1;
  53514. }
  53515. #endif
  53516. /* Decrement the free-list count by 1. Set iTrunk to the index of the
  53517. ** first free-list trunk page. iPrevTrunk is initially 1.
  53518. */
  53519. rc = sqlite3PagerWrite(pPage1->pDbPage);
  53520. if( rc ) return rc;
  53521. put4byte(&pPage1->aData[36], n-1);
  53522. /* The code within this loop is run only once if the 'searchList' variable
  53523. ** is not true. Otherwise, it runs once for each trunk-page on the
  53524. ** free-list until the page 'nearby' is located (eMode==BTALLOC_EXACT)
  53525. ** or until a page less than 'nearby' is located (eMode==BTALLOC_LT)
  53526. */
  53527. do {
  53528. pPrevTrunk = pTrunk;
  53529. if( pPrevTrunk ){
  53530. iTrunk = get4byte(&pPrevTrunk->aData[0]);
  53531. }else{
  53532. iTrunk = get4byte(&pPage1->aData[32]);
  53533. }
  53534. testcase( iTrunk==mxPage );
  53535. if( iTrunk>mxPage ){
  53536. rc = SQLITE_CORRUPT_BKPT;
  53537. }else{
  53538. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  53539. }
  53540. if( rc ){
  53541. pTrunk = 0;
  53542. goto end_allocate_page;
  53543. }
  53544. assert( pTrunk!=0 );
  53545. assert( pTrunk->aData!=0 );
  53546. k = get4byte(&pTrunk->aData[4]); /* # of leaves on this trunk page */
  53547. if( k==0 && !searchList ){
  53548. /* The trunk has no leaves and the list is not being searched.
  53549. ** So extract the trunk page itself and use it as the newly
  53550. ** allocated page */
  53551. assert( pPrevTrunk==0 );
  53552. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  53553. if( rc ){
  53554. goto end_allocate_page;
  53555. }
  53556. *pPgno = iTrunk;
  53557. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  53558. *ppPage = pTrunk;
  53559. pTrunk = 0;
  53560. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  53561. }else if( k>(u32)(pBt->usableSize/4 - 2) ){
  53562. /* Value of k is out of range. Database corruption */
  53563. rc = SQLITE_CORRUPT_BKPT;
  53564. goto end_allocate_page;
  53565. #ifndef SQLITE_OMIT_AUTOVACUUM
  53566. }else if( searchList
  53567. && (nearby==iTrunk || (iTrunk<nearby && eMode==BTALLOC_LE))
  53568. ){
  53569. /* The list is being searched and this trunk page is the page
  53570. ** to allocate, regardless of whether it has leaves.
  53571. */
  53572. *pPgno = iTrunk;
  53573. *ppPage = pTrunk;
  53574. searchList = 0;
  53575. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  53576. if( rc ){
  53577. goto end_allocate_page;
  53578. }
  53579. if( k==0 ){
  53580. if( !pPrevTrunk ){
  53581. memcpy(&pPage1->aData[32], &pTrunk->aData[0], 4);
  53582. }else{
  53583. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  53584. if( rc!=SQLITE_OK ){
  53585. goto end_allocate_page;
  53586. }
  53587. memcpy(&pPrevTrunk->aData[0], &pTrunk->aData[0], 4);
  53588. }
  53589. }else{
  53590. /* The trunk page is required by the caller but it contains
  53591. ** pointers to free-list leaves. The first leaf becomes a trunk
  53592. ** page in this case.
  53593. */
  53594. MemPage *pNewTrunk;
  53595. Pgno iNewTrunk = get4byte(&pTrunk->aData[8]);
  53596. if( iNewTrunk>mxPage ){
  53597. rc = SQLITE_CORRUPT_BKPT;
  53598. goto end_allocate_page;
  53599. }
  53600. testcase( iNewTrunk==mxPage );
  53601. rc = btreeGetPage(pBt, iNewTrunk, &pNewTrunk, 0);
  53602. if( rc!=SQLITE_OK ){
  53603. goto end_allocate_page;
  53604. }
  53605. rc = sqlite3PagerWrite(pNewTrunk->pDbPage);
  53606. if( rc!=SQLITE_OK ){
  53607. releasePage(pNewTrunk);
  53608. goto end_allocate_page;
  53609. }
  53610. memcpy(&pNewTrunk->aData[0], &pTrunk->aData[0], 4);
  53611. put4byte(&pNewTrunk->aData[4], k-1);
  53612. memcpy(&pNewTrunk->aData[8], &pTrunk->aData[12], (k-1)*4);
  53613. releasePage(pNewTrunk);
  53614. if( !pPrevTrunk ){
  53615. assert( sqlite3PagerIswriteable(pPage1->pDbPage) );
  53616. put4byte(&pPage1->aData[32], iNewTrunk);
  53617. }else{
  53618. rc = sqlite3PagerWrite(pPrevTrunk->pDbPage);
  53619. if( rc ){
  53620. goto end_allocate_page;
  53621. }
  53622. put4byte(&pPrevTrunk->aData[0], iNewTrunk);
  53623. }
  53624. }
  53625. pTrunk = 0;
  53626. TRACE(("ALLOCATE: %d trunk - %d free pages left\n", *pPgno, n-1));
  53627. #endif
  53628. }else if( k>0 ){
  53629. /* Extract a leaf from the trunk */
  53630. u32 closest;
  53631. Pgno iPage;
  53632. unsigned char *aData = pTrunk->aData;
  53633. if( nearby>0 ){
  53634. u32 i;
  53635. closest = 0;
  53636. if( eMode==BTALLOC_LE ){
  53637. for(i=0; i<k; i++){
  53638. iPage = get4byte(&aData[8+i*4]);
  53639. if( iPage<=nearby ){
  53640. closest = i;
  53641. break;
  53642. }
  53643. }
  53644. }else{
  53645. int dist;
  53646. dist = sqlite3AbsInt32(get4byte(&aData[8]) - nearby);
  53647. for(i=1; i<k; i++){
  53648. int d2 = sqlite3AbsInt32(get4byte(&aData[8+i*4]) - nearby);
  53649. if( d2<dist ){
  53650. closest = i;
  53651. dist = d2;
  53652. }
  53653. }
  53654. }
  53655. }else{
  53656. closest = 0;
  53657. }
  53658. iPage = get4byte(&aData[8+closest*4]);
  53659. testcase( iPage==mxPage );
  53660. if( iPage>mxPage ){
  53661. rc = SQLITE_CORRUPT_BKPT;
  53662. goto end_allocate_page;
  53663. }
  53664. testcase( iPage==mxPage );
  53665. if( !searchList
  53666. || (iPage==nearby || (iPage<nearby && eMode==BTALLOC_LE))
  53667. ){
  53668. int noContent;
  53669. *pPgno = iPage;
  53670. TRACE(("ALLOCATE: %d was leaf %d of %d on trunk %d"
  53671. ": %d more free pages\n",
  53672. *pPgno, closest+1, k, pTrunk->pgno, n-1));
  53673. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  53674. if( rc ) goto end_allocate_page;
  53675. if( closest<k-1 ){
  53676. memcpy(&aData[8+closest*4], &aData[4+k*4], 4);
  53677. }
  53678. put4byte(&aData[4], k-1);
  53679. noContent = !btreeGetHasContent(pBt, *pPgno)? PAGER_GET_NOCONTENT : 0;
  53680. rc = btreeGetPage(pBt, *pPgno, ppPage, noContent);
  53681. if( rc==SQLITE_OK ){
  53682. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  53683. if( rc!=SQLITE_OK ){
  53684. releasePage(*ppPage);
  53685. }
  53686. }
  53687. searchList = 0;
  53688. }
  53689. }
  53690. releasePage(pPrevTrunk);
  53691. pPrevTrunk = 0;
  53692. }while( searchList );
  53693. }else{
  53694. /* There are no pages on the freelist, so append a new page to the
  53695. ** database image.
  53696. **
  53697. ** Normally, new pages allocated by this block can be requested from the
  53698. ** pager layer with the 'no-content' flag set. This prevents the pager
  53699. ** from trying to read the pages content from disk. However, if the
  53700. ** current transaction has already run one or more incremental-vacuum
  53701. ** steps, then the page we are about to allocate may contain content
  53702. ** that is required in the event of a rollback. In this case, do
  53703. ** not set the no-content flag. This causes the pager to load and journal
  53704. ** the current page content before overwriting it.
  53705. **
  53706. ** Note that the pager will not actually attempt to load or journal
  53707. ** content for any page that really does lie past the end of the database
  53708. ** file on disk. So the effects of disabling the no-content optimization
  53709. ** here are confined to those pages that lie between the end of the
  53710. ** database image and the end of the database file.
  53711. */
  53712. int bNoContent = (0==IfNotOmitAV(pBt->bDoTruncate))? PAGER_GET_NOCONTENT:0;
  53713. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  53714. if( rc ) return rc;
  53715. pBt->nPage++;
  53716. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ) pBt->nPage++;
  53717. #ifndef SQLITE_OMIT_AUTOVACUUM
  53718. if( pBt->autoVacuum && PTRMAP_ISPAGE(pBt, pBt->nPage) ){
  53719. /* If *pPgno refers to a pointer-map page, allocate two new pages
  53720. ** at the end of the file instead of one. The first allocated page
  53721. ** becomes a new pointer-map page, the second is used by the caller.
  53722. */
  53723. MemPage *pPg = 0;
  53724. TRACE(("ALLOCATE: %d from end of file (pointer-map page)\n", pBt->nPage));
  53725. assert( pBt->nPage!=PENDING_BYTE_PAGE(pBt) );
  53726. rc = btreeGetPage(pBt, pBt->nPage, &pPg, bNoContent);
  53727. if( rc==SQLITE_OK ){
  53728. rc = sqlite3PagerWrite(pPg->pDbPage);
  53729. releasePage(pPg);
  53730. }
  53731. if( rc ) return rc;
  53732. pBt->nPage++;
  53733. if( pBt->nPage==PENDING_BYTE_PAGE(pBt) ){ pBt->nPage++; }
  53734. }
  53735. #endif
  53736. put4byte(28 + (u8*)pBt->pPage1->aData, pBt->nPage);
  53737. *pPgno = pBt->nPage;
  53738. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  53739. rc = btreeGetPage(pBt, *pPgno, ppPage, bNoContent);
  53740. if( rc ) return rc;
  53741. rc = sqlite3PagerWrite((*ppPage)->pDbPage);
  53742. if( rc!=SQLITE_OK ){
  53743. releasePage(*ppPage);
  53744. }
  53745. TRACE(("ALLOCATE: %d from end of file\n", *pPgno));
  53746. }
  53747. assert( *pPgno!=PENDING_BYTE_PAGE(pBt) );
  53748. end_allocate_page:
  53749. releasePage(pTrunk);
  53750. releasePage(pPrevTrunk);
  53751. if( rc==SQLITE_OK ){
  53752. if( sqlite3PagerPageRefcount((*ppPage)->pDbPage)>1 ){
  53753. releasePage(*ppPage);
  53754. *ppPage = 0;
  53755. return SQLITE_CORRUPT_BKPT;
  53756. }
  53757. (*ppPage)->isInit = 0;
  53758. }else{
  53759. *ppPage = 0;
  53760. }
  53761. assert( rc!=SQLITE_OK || sqlite3PagerIswriteable((*ppPage)->pDbPage) );
  53762. return rc;
  53763. }
  53764. /*
  53765. ** This function is used to add page iPage to the database file free-list.
  53766. ** It is assumed that the page is not already a part of the free-list.
  53767. **
  53768. ** The value passed as the second argument to this function is optional.
  53769. ** If the caller happens to have a pointer to the MemPage object
  53770. ** corresponding to page iPage handy, it may pass it as the second value.
  53771. ** Otherwise, it may pass NULL.
  53772. **
  53773. ** If a pointer to a MemPage object is passed as the second argument,
  53774. ** its reference count is not altered by this function.
  53775. */
  53776. static int freePage2(BtShared *pBt, MemPage *pMemPage, Pgno iPage){
  53777. MemPage *pTrunk = 0; /* Free-list trunk page */
  53778. Pgno iTrunk = 0; /* Page number of free-list trunk page */
  53779. MemPage *pPage1 = pBt->pPage1; /* Local reference to page 1 */
  53780. MemPage *pPage; /* Page being freed. May be NULL. */
  53781. int rc; /* Return Code */
  53782. int nFree; /* Initial number of pages on free-list */
  53783. assert( sqlite3_mutex_held(pBt->mutex) );
  53784. assert( iPage>1 );
  53785. assert( !pMemPage || pMemPage->pgno==iPage );
  53786. if( pMemPage ){
  53787. pPage = pMemPage;
  53788. sqlite3PagerRef(pPage->pDbPage);
  53789. }else{
  53790. pPage = btreePageLookup(pBt, iPage);
  53791. }
  53792. /* Increment the free page count on pPage1 */
  53793. rc = sqlite3PagerWrite(pPage1->pDbPage);
  53794. if( rc ) goto freepage_out;
  53795. nFree = get4byte(&pPage1->aData[36]);
  53796. put4byte(&pPage1->aData[36], nFree+1);
  53797. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  53798. /* If the secure_delete option is enabled, then
  53799. ** always fully overwrite deleted information with zeros.
  53800. */
  53801. if( (!pPage && ((rc = btreeGetPage(pBt, iPage, &pPage, 0))!=0) )
  53802. || ((rc = sqlite3PagerWrite(pPage->pDbPage))!=0)
  53803. ){
  53804. goto freepage_out;
  53805. }
  53806. memset(pPage->aData, 0, pPage->pBt->pageSize);
  53807. }
  53808. /* If the database supports auto-vacuum, write an entry in the pointer-map
  53809. ** to indicate that the page is free.
  53810. */
  53811. if( ISAUTOVACUUM ){
  53812. ptrmapPut(pBt, iPage, PTRMAP_FREEPAGE, 0, &rc);
  53813. if( rc ) goto freepage_out;
  53814. }
  53815. /* Now manipulate the actual database free-list structure. There are two
  53816. ** possibilities. If the free-list is currently empty, or if the first
  53817. ** trunk page in the free-list is full, then this page will become a
  53818. ** new free-list trunk page. Otherwise, it will become a leaf of the
  53819. ** first trunk page in the current free-list. This block tests if it
  53820. ** is possible to add the page as a new free-list leaf.
  53821. */
  53822. if( nFree!=0 ){
  53823. u32 nLeaf; /* Initial number of leaf cells on trunk page */
  53824. iTrunk = get4byte(&pPage1->aData[32]);
  53825. rc = btreeGetPage(pBt, iTrunk, &pTrunk, 0);
  53826. if( rc!=SQLITE_OK ){
  53827. goto freepage_out;
  53828. }
  53829. nLeaf = get4byte(&pTrunk->aData[4]);
  53830. assert( pBt->usableSize>32 );
  53831. if( nLeaf > (u32)pBt->usableSize/4 - 2 ){
  53832. rc = SQLITE_CORRUPT_BKPT;
  53833. goto freepage_out;
  53834. }
  53835. if( nLeaf < (u32)pBt->usableSize/4 - 8 ){
  53836. /* In this case there is room on the trunk page to insert the page
  53837. ** being freed as a new leaf.
  53838. **
  53839. ** Note that the trunk page is not really full until it contains
  53840. ** usableSize/4 - 2 entries, not usableSize/4 - 8 entries as we have
  53841. ** coded. But due to a coding error in versions of SQLite prior to
  53842. ** 3.6.0, databases with freelist trunk pages holding more than
  53843. ** usableSize/4 - 8 entries will be reported as corrupt. In order
  53844. ** to maintain backwards compatibility with older versions of SQLite,
  53845. ** we will continue to restrict the number of entries to usableSize/4 - 8
  53846. ** for now. At some point in the future (once everyone has upgraded
  53847. ** to 3.6.0 or later) we should consider fixing the conditional above
  53848. ** to read "usableSize/4-2" instead of "usableSize/4-8".
  53849. */
  53850. rc = sqlite3PagerWrite(pTrunk->pDbPage);
  53851. if( rc==SQLITE_OK ){
  53852. put4byte(&pTrunk->aData[4], nLeaf+1);
  53853. put4byte(&pTrunk->aData[8+nLeaf*4], iPage);
  53854. if( pPage && (pBt->btsFlags & BTS_SECURE_DELETE)==0 ){
  53855. sqlite3PagerDontWrite(pPage->pDbPage);
  53856. }
  53857. rc = btreeSetHasContent(pBt, iPage);
  53858. }
  53859. TRACE(("FREE-PAGE: %d leaf on trunk page %d\n",pPage->pgno,pTrunk->pgno));
  53860. goto freepage_out;
  53861. }
  53862. }
  53863. /* If control flows to this point, then it was not possible to add the
  53864. ** the page being freed as a leaf page of the first trunk in the free-list.
  53865. ** Possibly because the free-list is empty, or possibly because the
  53866. ** first trunk in the free-list is full. Either way, the page being freed
  53867. ** will become the new first trunk page in the free-list.
  53868. */
  53869. if( pPage==0 && SQLITE_OK!=(rc = btreeGetPage(pBt, iPage, &pPage, 0)) ){
  53870. goto freepage_out;
  53871. }
  53872. rc = sqlite3PagerWrite(pPage->pDbPage);
  53873. if( rc!=SQLITE_OK ){
  53874. goto freepage_out;
  53875. }
  53876. put4byte(pPage->aData, iTrunk);
  53877. put4byte(&pPage->aData[4], 0);
  53878. put4byte(&pPage1->aData[32], iPage);
  53879. TRACE(("FREE-PAGE: %d new trunk page replacing %d\n", pPage->pgno, iTrunk));
  53880. freepage_out:
  53881. if( pPage ){
  53882. pPage->isInit = 0;
  53883. }
  53884. releasePage(pPage);
  53885. releasePage(pTrunk);
  53886. return rc;
  53887. }
  53888. static void freePage(MemPage *pPage, int *pRC){
  53889. if( (*pRC)==SQLITE_OK ){
  53890. *pRC = freePage2(pPage->pBt, pPage, pPage->pgno);
  53891. }
  53892. }
  53893. /*
  53894. ** Free any overflow pages associated with the given Cell. Write the
  53895. ** local Cell size (the number of bytes on the original page, omitting
  53896. ** overflow) into *pnSize.
  53897. */
  53898. static int clearCell(
  53899. MemPage *pPage, /* The page that contains the Cell */
  53900. unsigned char *pCell, /* First byte of the Cell */
  53901. u16 *pnSize /* Write the size of the Cell here */
  53902. ){
  53903. BtShared *pBt = pPage->pBt;
  53904. CellInfo info;
  53905. Pgno ovflPgno;
  53906. int rc;
  53907. int nOvfl;
  53908. u32 ovflPageSize;
  53909. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53910. btreeParseCellPtr(pPage, pCell, &info);
  53911. *pnSize = info.nSize;
  53912. if( info.iOverflow==0 ){
  53913. return SQLITE_OK; /* No overflow pages. Return without doing anything */
  53914. }
  53915. if( pCell+info.iOverflow+3 > pPage->aData+pPage->maskPage ){
  53916. return SQLITE_CORRUPT_BKPT; /* Cell extends past end of page */
  53917. }
  53918. ovflPgno = get4byte(&pCell[info.iOverflow]);
  53919. assert( pBt->usableSize > 4 );
  53920. ovflPageSize = pBt->usableSize - 4;
  53921. nOvfl = (info.nPayload - info.nLocal + ovflPageSize - 1)/ovflPageSize;
  53922. assert( ovflPgno==0 || nOvfl>0 );
  53923. while( nOvfl-- ){
  53924. Pgno iNext = 0;
  53925. MemPage *pOvfl = 0;
  53926. if( ovflPgno<2 || ovflPgno>btreePagecount(pBt) ){
  53927. /* 0 is not a legal page number and page 1 cannot be an
  53928. ** overflow page. Therefore if ovflPgno<2 or past the end of the
  53929. ** file the database must be corrupt. */
  53930. return SQLITE_CORRUPT_BKPT;
  53931. }
  53932. if( nOvfl ){
  53933. rc = getOverflowPage(pBt, ovflPgno, &pOvfl, &iNext);
  53934. if( rc ) return rc;
  53935. }
  53936. if( ( pOvfl || ((pOvfl = btreePageLookup(pBt, ovflPgno))!=0) )
  53937. && sqlite3PagerPageRefcount(pOvfl->pDbPage)!=1
  53938. ){
  53939. /* There is no reason any cursor should have an outstanding reference
  53940. ** to an overflow page belonging to a cell that is being deleted/updated.
  53941. ** So if there exists more than one reference to this page, then it
  53942. ** must not really be an overflow page and the database must be corrupt.
  53943. ** It is helpful to detect this before calling freePage2(), as
  53944. ** freePage2() may zero the page contents if secure-delete mode is
  53945. ** enabled. If this 'overflow' page happens to be a page that the
  53946. ** caller is iterating through or using in some other way, this
  53947. ** can be problematic.
  53948. */
  53949. rc = SQLITE_CORRUPT_BKPT;
  53950. }else{
  53951. rc = freePage2(pBt, pOvfl, ovflPgno);
  53952. }
  53953. if( pOvfl ){
  53954. sqlite3PagerUnref(pOvfl->pDbPage);
  53955. }
  53956. if( rc ) return rc;
  53957. ovflPgno = iNext;
  53958. }
  53959. return SQLITE_OK;
  53960. }
  53961. /*
  53962. ** Create the byte sequence used to represent a cell on page pPage
  53963. ** and write that byte sequence into pCell[]. Overflow pages are
  53964. ** allocated and filled in as necessary. The calling procedure
  53965. ** is responsible for making sure sufficient space has been allocated
  53966. ** for pCell[].
  53967. **
  53968. ** Note that pCell does not necessary need to point to the pPage->aData
  53969. ** area. pCell might point to some temporary storage. The cell will
  53970. ** be constructed in this temporary area then copied into pPage->aData
  53971. ** later.
  53972. */
  53973. static int fillInCell(
  53974. MemPage *pPage, /* The page that contains the cell */
  53975. unsigned char *pCell, /* Complete text of the cell */
  53976. const void *pKey, i64 nKey, /* The key */
  53977. const void *pData,int nData, /* The data */
  53978. int nZero, /* Extra zero bytes to append to pData */
  53979. int *pnSize /* Write cell size here */
  53980. ){
  53981. int nPayload;
  53982. const u8 *pSrc;
  53983. int nSrc, n, rc;
  53984. int spaceLeft;
  53985. MemPage *pOvfl = 0;
  53986. MemPage *pToRelease = 0;
  53987. unsigned char *pPrior;
  53988. unsigned char *pPayload;
  53989. BtShared *pBt = pPage->pBt;
  53990. Pgno pgnoOvfl = 0;
  53991. int nHeader;
  53992. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  53993. /* pPage is not necessarily writeable since pCell might be auxiliary
  53994. ** buffer space that is separate from the pPage buffer area */
  53995. assert( pCell<pPage->aData || pCell>=&pPage->aData[pBt->pageSize]
  53996. || sqlite3PagerIswriteable(pPage->pDbPage) );
  53997. /* Fill in the header. */
  53998. nHeader = pPage->childPtrSize;
  53999. nPayload = nData + nZero;
  54000. if( pPage->intKeyLeaf ){
  54001. nHeader += putVarint32(&pCell[nHeader], nPayload);
  54002. }else{
  54003. assert( nData==0 );
  54004. assert( nZero==0 );
  54005. }
  54006. nHeader += putVarint(&pCell[nHeader], *(u64*)&nKey);
  54007. /* Fill in the payload size */
  54008. if( pPage->intKey ){
  54009. pSrc = pData;
  54010. nSrc = nData;
  54011. nData = 0;
  54012. }else{
  54013. if( NEVER(nKey>0x7fffffff || pKey==0) ){
  54014. return SQLITE_CORRUPT_BKPT;
  54015. }
  54016. nPayload = (int)nKey;
  54017. pSrc = pKey;
  54018. nSrc = (int)nKey;
  54019. }
  54020. if( nPayload<=pPage->maxLocal ){
  54021. n = nHeader + nPayload;
  54022. testcase( n==3 );
  54023. testcase( n==4 );
  54024. if( n<4 ) n = 4;
  54025. *pnSize = n;
  54026. spaceLeft = nPayload;
  54027. pPrior = pCell;
  54028. }else{
  54029. int mn = pPage->minLocal;
  54030. n = mn + (nPayload - mn) % (pPage->pBt->usableSize - 4);
  54031. testcase( n==pPage->maxLocal );
  54032. testcase( n==pPage->maxLocal+1 );
  54033. if( n > pPage->maxLocal ) n = mn;
  54034. spaceLeft = n;
  54035. *pnSize = n + nHeader + 4;
  54036. pPrior = &pCell[nHeader+n];
  54037. }
  54038. pPayload = &pCell[nHeader];
  54039. /* At this point variables should be set as follows:
  54040. **
  54041. ** nPayload Total payload size in bytes
  54042. ** pPayload Begin writing payload here
  54043. ** spaceLeft Space available at pPayload. If nPayload>spaceLeft,
  54044. ** that means content must spill into overflow pages.
  54045. ** *pnSize Size of the local cell (not counting overflow pages)
  54046. ** pPrior Where to write the pgno of the first overflow page
  54047. **
  54048. ** Use a call to btreeParseCellPtr() to verify that the values above
  54049. ** were computed correctly.
  54050. */
  54051. #if SQLITE_DEBUG
  54052. {
  54053. CellInfo info;
  54054. btreeParseCellPtr(pPage, pCell, &info);
  54055. assert( nHeader=(int)(info.pPayload - pCell) );
  54056. assert( info.nKey==nKey );
  54057. assert( *pnSize == info.nSize );
  54058. assert( spaceLeft == info.nLocal );
  54059. assert( pPrior == &pCell[info.iOverflow] );
  54060. }
  54061. #endif
  54062. /* Write the payload into the local Cell and any extra into overflow pages */
  54063. while( nPayload>0 ){
  54064. if( spaceLeft==0 ){
  54065. #ifndef SQLITE_OMIT_AUTOVACUUM
  54066. Pgno pgnoPtrmap = pgnoOvfl; /* Overflow page pointer-map entry page */
  54067. if( pBt->autoVacuum ){
  54068. do{
  54069. pgnoOvfl++;
  54070. } while(
  54071. PTRMAP_ISPAGE(pBt, pgnoOvfl) || pgnoOvfl==PENDING_BYTE_PAGE(pBt)
  54072. );
  54073. }
  54074. #endif
  54075. rc = allocateBtreePage(pBt, &pOvfl, &pgnoOvfl, pgnoOvfl, 0);
  54076. #ifndef SQLITE_OMIT_AUTOVACUUM
  54077. /* If the database supports auto-vacuum, and the second or subsequent
  54078. ** overflow page is being allocated, add an entry to the pointer-map
  54079. ** for that page now.
  54080. **
  54081. ** If this is the first overflow page, then write a partial entry
  54082. ** to the pointer-map. If we write nothing to this pointer-map slot,
  54083. ** then the optimistic overflow chain processing in clearCell()
  54084. ** may misinterpret the uninitialized values and delete the
  54085. ** wrong pages from the database.
  54086. */
  54087. if( pBt->autoVacuum && rc==SQLITE_OK ){
  54088. u8 eType = (pgnoPtrmap?PTRMAP_OVERFLOW2:PTRMAP_OVERFLOW1);
  54089. ptrmapPut(pBt, pgnoOvfl, eType, pgnoPtrmap, &rc);
  54090. if( rc ){
  54091. releasePage(pOvfl);
  54092. }
  54093. }
  54094. #endif
  54095. if( rc ){
  54096. releasePage(pToRelease);
  54097. return rc;
  54098. }
  54099. /* If pToRelease is not zero than pPrior points into the data area
  54100. ** of pToRelease. Make sure pToRelease is still writeable. */
  54101. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  54102. /* If pPrior is part of the data area of pPage, then make sure pPage
  54103. ** is still writeable */
  54104. assert( pPrior<pPage->aData || pPrior>=&pPage->aData[pBt->pageSize]
  54105. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54106. put4byte(pPrior, pgnoOvfl);
  54107. releasePage(pToRelease);
  54108. pToRelease = pOvfl;
  54109. pPrior = pOvfl->aData;
  54110. put4byte(pPrior, 0);
  54111. pPayload = &pOvfl->aData[4];
  54112. spaceLeft = pBt->usableSize - 4;
  54113. }
  54114. n = nPayload;
  54115. if( n>spaceLeft ) n = spaceLeft;
  54116. /* If pToRelease is not zero than pPayload points into the data area
  54117. ** of pToRelease. Make sure pToRelease is still writeable. */
  54118. assert( pToRelease==0 || sqlite3PagerIswriteable(pToRelease->pDbPage) );
  54119. /* If pPayload is part of the data area of pPage, then make sure pPage
  54120. ** is still writeable */
  54121. assert( pPayload<pPage->aData || pPayload>=&pPage->aData[pBt->pageSize]
  54122. || sqlite3PagerIswriteable(pPage->pDbPage) );
  54123. if( nSrc>0 ){
  54124. if( n>nSrc ) n = nSrc;
  54125. assert( pSrc );
  54126. memcpy(pPayload, pSrc, n);
  54127. }else{
  54128. memset(pPayload, 0, n);
  54129. }
  54130. nPayload -= n;
  54131. pPayload += n;
  54132. pSrc += n;
  54133. nSrc -= n;
  54134. spaceLeft -= n;
  54135. if( nSrc==0 ){
  54136. nSrc = nData;
  54137. pSrc = pData;
  54138. }
  54139. }
  54140. releasePage(pToRelease);
  54141. return SQLITE_OK;
  54142. }
  54143. /*
  54144. ** Remove the i-th cell from pPage. This routine effects pPage only.
  54145. ** The cell content is not freed or deallocated. It is assumed that
  54146. ** the cell content has been copied someplace else. This routine just
  54147. ** removes the reference to the cell from pPage.
  54148. **
  54149. ** "sz" must be the number of bytes in the cell.
  54150. */
  54151. static void dropCell(MemPage *pPage, int idx, int sz, int *pRC){
  54152. u32 pc; /* Offset to cell content of cell being deleted */
  54153. u8 *data; /* pPage->aData */
  54154. u8 *ptr; /* Used to move bytes around within data[] */
  54155. int rc; /* The return code */
  54156. int hdr; /* Beginning of the header. 0 most pages. 100 page 1 */
  54157. if( *pRC ) return;
  54158. assert( idx>=0 && idx<pPage->nCell );
  54159. assert( sz==cellSize(pPage, idx) );
  54160. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54161. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54162. data = pPage->aData;
  54163. ptr = &pPage->aCellIdx[2*idx];
  54164. pc = get2byte(ptr);
  54165. hdr = pPage->hdrOffset;
  54166. testcase( pc==get2byte(&data[hdr+5]) );
  54167. testcase( pc+sz==pPage->pBt->usableSize );
  54168. if( pc < (u32)get2byte(&data[hdr+5]) || pc+sz > pPage->pBt->usableSize ){
  54169. *pRC = SQLITE_CORRUPT_BKPT;
  54170. return;
  54171. }
  54172. rc = freeSpace(pPage, pc, sz);
  54173. if( rc ){
  54174. *pRC = rc;
  54175. return;
  54176. }
  54177. pPage->nCell--;
  54178. memmove(ptr, ptr+2, 2*(pPage->nCell - idx));
  54179. put2byte(&data[hdr+3], pPage->nCell);
  54180. pPage->nFree += 2;
  54181. }
  54182. /*
  54183. ** Insert a new cell on pPage at cell index "i". pCell points to the
  54184. ** content of the cell.
  54185. **
  54186. ** If the cell content will fit on the page, then put it there. If it
  54187. ** will not fit, then make a copy of the cell content into pTemp if
  54188. ** pTemp is not null. Regardless of pTemp, allocate a new entry
  54189. ** in pPage->apOvfl[] and make it point to the cell content (either
  54190. ** in pTemp or the original pCell) and also record its index.
  54191. ** Allocating a new entry in pPage->aCell[] implies that
  54192. ** pPage->nOverflow is incremented.
  54193. */
  54194. static void insertCell(
  54195. MemPage *pPage, /* Page into which we are copying */
  54196. int i, /* New cell becomes the i-th cell of the page */
  54197. u8 *pCell, /* Content of the new cell */
  54198. int sz, /* Bytes of content in pCell */
  54199. u8 *pTemp, /* Temp storage space for pCell, if needed */
  54200. Pgno iChild, /* If non-zero, replace first 4 bytes with this value */
  54201. int *pRC /* Read and write return code from here */
  54202. ){
  54203. int idx = 0; /* Where to write new cell content in data[] */
  54204. int j; /* Loop counter */
  54205. int end; /* First byte past the last cell pointer in data[] */
  54206. int ins; /* Index in data[] where new cell pointer is inserted */
  54207. int cellOffset; /* Address of first cell pointer in data[] */
  54208. u8 *data; /* The content of the whole page */
  54209. if( *pRC ) return;
  54210. assert( i>=0 && i<=pPage->nCell+pPage->nOverflow );
  54211. assert( MX_CELL(pPage->pBt)<=10921 );
  54212. assert( pPage->nCell<=MX_CELL(pPage->pBt) || CORRUPT_DB );
  54213. assert( pPage->nOverflow<=ArraySize(pPage->apOvfl) );
  54214. assert( ArraySize(pPage->apOvfl)==ArraySize(pPage->aiOvfl) );
  54215. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54216. /* The cell should normally be sized correctly. However, when moving a
  54217. ** malformed cell from a leaf page to an interior page, if the cell size
  54218. ** wanted to be less than 4 but got rounded up to 4 on the leaf, then size
  54219. ** might be less than 8 (leaf-size + pointer) on the interior node. Hence
  54220. ** the term after the || in the following assert(). */
  54221. assert( sz==cellSizePtr(pPage, pCell) || (sz==8 && iChild>0) );
  54222. if( pPage->nOverflow || sz+2>pPage->nFree ){
  54223. if( pTemp ){
  54224. memcpy(pTemp, pCell, sz);
  54225. pCell = pTemp;
  54226. }
  54227. if( iChild ){
  54228. put4byte(pCell, iChild);
  54229. }
  54230. j = pPage->nOverflow++;
  54231. assert( j<(int)(sizeof(pPage->apOvfl)/sizeof(pPage->apOvfl[0])) );
  54232. pPage->apOvfl[j] = pCell;
  54233. pPage->aiOvfl[j] = (u16)i;
  54234. }else{
  54235. int rc = sqlite3PagerWrite(pPage->pDbPage);
  54236. if( rc!=SQLITE_OK ){
  54237. *pRC = rc;
  54238. return;
  54239. }
  54240. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54241. data = pPage->aData;
  54242. cellOffset = pPage->cellOffset;
  54243. end = cellOffset + 2*pPage->nCell;
  54244. ins = cellOffset + 2*i;
  54245. rc = allocateSpace(pPage, sz, &idx);
  54246. if( rc ){ *pRC = rc; return; }
  54247. /* The allocateSpace() routine guarantees the following two properties
  54248. ** if it returns success */
  54249. assert( idx >= end+2 );
  54250. assert( idx+sz <= (int)pPage->pBt->usableSize );
  54251. pPage->nCell++;
  54252. pPage->nFree -= (u16)(2 + sz);
  54253. memcpy(&data[idx], pCell, sz);
  54254. if( iChild ){
  54255. put4byte(&data[idx], iChild);
  54256. }
  54257. memmove(&data[ins+2], &data[ins], end-ins);
  54258. put2byte(&data[ins], idx);
  54259. put2byte(&data[pPage->hdrOffset+3], pPage->nCell);
  54260. #ifndef SQLITE_OMIT_AUTOVACUUM
  54261. if( pPage->pBt->autoVacuum ){
  54262. /* The cell may contain a pointer to an overflow page. If so, write
  54263. ** the entry for the overflow page into the pointer map.
  54264. */
  54265. ptrmapPutOvflPtr(pPage, pCell, pRC);
  54266. }
  54267. #endif
  54268. }
  54269. }
  54270. /*
  54271. ** Add a list of cells to a page. The page should be initially empty.
  54272. ** The cells are guaranteed to fit on the page.
  54273. */
  54274. static void assemblePage(
  54275. MemPage *pPage, /* The page to be assembled */
  54276. int nCell, /* The number of cells to add to this page */
  54277. u8 **apCell, /* Pointers to cell bodies */
  54278. u16 *aSize /* Sizes of the cells */
  54279. ){
  54280. int i; /* Loop counter */
  54281. u8 *pCellptr; /* Address of next cell pointer */
  54282. int cellbody; /* Address of next cell body */
  54283. u8 * const data = pPage->aData; /* Pointer to data for pPage */
  54284. const int hdr = pPage->hdrOffset; /* Offset of header on pPage */
  54285. const int nUsable = pPage->pBt->usableSize; /* Usable size of page */
  54286. assert( pPage->nOverflow==0 );
  54287. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54288. assert( nCell>=0 && nCell<=(int)MX_CELL(pPage->pBt)
  54289. && (int)MX_CELL(pPage->pBt)<=10921);
  54290. assert( sqlite3PagerIswriteable(pPage->pDbPage) );
  54291. /* Check that the page has just been zeroed by zeroPage() */
  54292. assert( pPage->nCell==0 );
  54293. assert( get2byteNotZero(&data[hdr+5])==nUsable );
  54294. pCellptr = &pPage->aCellIdx[nCell*2];
  54295. cellbody = nUsable;
  54296. for(i=nCell-1; i>=0; i--){
  54297. u16 sz = aSize[i];
  54298. pCellptr -= 2;
  54299. cellbody -= sz;
  54300. put2byte(pCellptr, cellbody);
  54301. memcpy(&data[cellbody], apCell[i], sz);
  54302. }
  54303. put2byte(&data[hdr+3], nCell);
  54304. put2byte(&data[hdr+5], cellbody);
  54305. pPage->nFree -= (nCell*2 + nUsable - cellbody);
  54306. pPage->nCell = (u16)nCell;
  54307. }
  54308. /*
  54309. ** The following parameters determine how many adjacent pages get involved
  54310. ** in a balancing operation. NN is the number of neighbors on either side
  54311. ** of the page that participate in the balancing operation. NB is the
  54312. ** total number of pages that participate, including the target page and
  54313. ** NN neighbors on either side.
  54314. **
  54315. ** The minimum value of NN is 1 (of course). Increasing NN above 1
  54316. ** (to 2 or 3) gives a modest improvement in SELECT and DELETE performance
  54317. ** in exchange for a larger degradation in INSERT and UPDATE performance.
  54318. ** The value of NN appears to give the best results overall.
  54319. */
  54320. #define NN 1 /* Number of neighbors on either side of pPage */
  54321. #define NB (NN*2+1) /* Total pages involved in the balance */
  54322. #ifndef SQLITE_OMIT_QUICKBALANCE
  54323. /*
  54324. ** This version of balance() handles the common special case where
  54325. ** a new entry is being inserted on the extreme right-end of the
  54326. ** tree, in other words, when the new entry will become the largest
  54327. ** entry in the tree.
  54328. **
  54329. ** Instead of trying to balance the 3 right-most leaf pages, just add
  54330. ** a new page to the right-hand side and put the one new entry in
  54331. ** that page. This leaves the right side of the tree somewhat
  54332. ** unbalanced. But odds are that we will be inserting new entries
  54333. ** at the end soon afterwards so the nearly empty page will quickly
  54334. ** fill up. On average.
  54335. **
  54336. ** pPage is the leaf page which is the right-most page in the tree.
  54337. ** pParent is its parent. pPage must have a single overflow entry
  54338. ** which is also the right-most entry on the page.
  54339. **
  54340. ** The pSpace buffer is used to store a temporary copy of the divider
  54341. ** cell that will be inserted into pParent. Such a cell consists of a 4
  54342. ** byte page number followed by a variable length integer. In other
  54343. ** words, at most 13 bytes. Hence the pSpace buffer must be at
  54344. ** least 13 bytes in size.
  54345. */
  54346. static int balance_quick(MemPage *pParent, MemPage *pPage, u8 *pSpace){
  54347. BtShared *const pBt = pPage->pBt; /* B-Tree Database */
  54348. MemPage *pNew; /* Newly allocated page */
  54349. int rc; /* Return Code */
  54350. Pgno pgnoNew; /* Page number of pNew */
  54351. assert( sqlite3_mutex_held(pPage->pBt->mutex) );
  54352. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  54353. assert( pPage->nOverflow==1 );
  54354. /* This error condition is now caught prior to reaching this function */
  54355. if( pPage->nCell==0 ) return SQLITE_CORRUPT_BKPT;
  54356. /* Allocate a new page. This page will become the right-sibling of
  54357. ** pPage. Make the parent page writable, so that the new divider cell
  54358. ** may be inserted. If both these operations are successful, proceed.
  54359. */
  54360. rc = allocateBtreePage(pBt, &pNew, &pgnoNew, 0, 0);
  54361. if( rc==SQLITE_OK ){
  54362. u8 *pOut = &pSpace[4];
  54363. u8 *pCell = pPage->apOvfl[0];
  54364. u16 szCell = cellSizePtr(pPage, pCell);
  54365. u8 *pStop;
  54366. assert( sqlite3PagerIswriteable(pNew->pDbPage) );
  54367. assert( pPage->aData[0]==(PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF) );
  54368. zeroPage(pNew, PTF_INTKEY|PTF_LEAFDATA|PTF_LEAF);
  54369. assemblePage(pNew, 1, &pCell, &szCell);
  54370. /* If this is an auto-vacuum database, update the pointer map
  54371. ** with entries for the new page, and any pointer from the
  54372. ** cell on the page to an overflow page. If either of these
  54373. ** operations fails, the return code is set, but the contents
  54374. ** of the parent page are still manipulated by thh code below.
  54375. ** That is Ok, at this point the parent page is guaranteed to
  54376. ** be marked as dirty. Returning an error code will cause a
  54377. ** rollback, undoing any changes made to the parent page.
  54378. */
  54379. if( ISAUTOVACUUM ){
  54380. ptrmapPut(pBt, pgnoNew, PTRMAP_BTREE, pParent->pgno, &rc);
  54381. if( szCell>pNew->minLocal ){
  54382. ptrmapPutOvflPtr(pNew, pCell, &rc);
  54383. }
  54384. }
  54385. /* Create a divider cell to insert into pParent. The divider cell
  54386. ** consists of a 4-byte page number (the page number of pPage) and
  54387. ** a variable length key value (which must be the same value as the
  54388. ** largest key on pPage).
  54389. **
  54390. ** To find the largest key value on pPage, first find the right-most
  54391. ** cell on pPage. The first two fields of this cell are the
  54392. ** record-length (a variable length integer at most 32-bits in size)
  54393. ** and the key value (a variable length integer, may have any value).
  54394. ** The first of the while(...) loops below skips over the record-length
  54395. ** field. The second while(...) loop copies the key value from the
  54396. ** cell on pPage into the pSpace buffer.
  54397. */
  54398. pCell = findCell(pPage, pPage->nCell-1);
  54399. pStop = &pCell[9];
  54400. while( (*(pCell++)&0x80) && pCell<pStop );
  54401. pStop = &pCell[9];
  54402. while( ((*(pOut++) = *(pCell++))&0x80) && pCell<pStop );
  54403. /* Insert the new divider cell into pParent. */
  54404. insertCell(pParent, pParent->nCell, pSpace, (int)(pOut-pSpace),
  54405. 0, pPage->pgno, &rc);
  54406. /* Set the right-child pointer of pParent to point to the new page. */
  54407. put4byte(&pParent->aData[pParent->hdrOffset+8], pgnoNew);
  54408. /* Release the reference to the new page. */
  54409. releasePage(pNew);
  54410. }
  54411. return rc;
  54412. }
  54413. #endif /* SQLITE_OMIT_QUICKBALANCE */
  54414. #if 0
  54415. /*
  54416. ** This function does not contribute anything to the operation of SQLite.
  54417. ** it is sometimes activated temporarily while debugging code responsible
  54418. ** for setting pointer-map entries.
  54419. */
  54420. static int ptrmapCheckPages(MemPage **apPage, int nPage){
  54421. int i, j;
  54422. for(i=0; i<nPage; i++){
  54423. Pgno n;
  54424. u8 e;
  54425. MemPage *pPage = apPage[i];
  54426. BtShared *pBt = pPage->pBt;
  54427. assert( pPage->isInit );
  54428. for(j=0; j<pPage->nCell; j++){
  54429. CellInfo info;
  54430. u8 *z;
  54431. z = findCell(pPage, j);
  54432. btreeParseCellPtr(pPage, z, &info);
  54433. if( info.iOverflow ){
  54434. Pgno ovfl = get4byte(&z[info.iOverflow]);
  54435. ptrmapGet(pBt, ovfl, &e, &n);
  54436. assert( n==pPage->pgno && e==PTRMAP_OVERFLOW1 );
  54437. }
  54438. if( !pPage->leaf ){
  54439. Pgno child = get4byte(z);
  54440. ptrmapGet(pBt, child, &e, &n);
  54441. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  54442. }
  54443. }
  54444. if( !pPage->leaf ){
  54445. Pgno child = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  54446. ptrmapGet(pBt, child, &e, &n);
  54447. assert( n==pPage->pgno && e==PTRMAP_BTREE );
  54448. }
  54449. }
  54450. return 1;
  54451. }
  54452. #endif
  54453. /*
  54454. ** This function is used to copy the contents of the b-tree node stored
  54455. ** on page pFrom to page pTo. If page pFrom was not a leaf page, then
  54456. ** the pointer-map entries for each child page are updated so that the
  54457. ** parent page stored in the pointer map is page pTo. If pFrom contained
  54458. ** any cells with overflow page pointers, then the corresponding pointer
  54459. ** map entries are also updated so that the parent page is page pTo.
  54460. **
  54461. ** If pFrom is currently carrying any overflow cells (entries in the
  54462. ** MemPage.apOvfl[] array), they are not copied to pTo.
  54463. **
  54464. ** Before returning, page pTo is reinitialized using btreeInitPage().
  54465. **
  54466. ** The performance of this function is not critical. It is only used by
  54467. ** the balance_shallower() and balance_deeper() procedures, neither of
  54468. ** which are called often under normal circumstances.
  54469. */
  54470. static void copyNodeContent(MemPage *pFrom, MemPage *pTo, int *pRC){
  54471. if( (*pRC)==SQLITE_OK ){
  54472. BtShared * const pBt = pFrom->pBt;
  54473. u8 * const aFrom = pFrom->aData;
  54474. u8 * const aTo = pTo->aData;
  54475. int const iFromHdr = pFrom->hdrOffset;
  54476. int const iToHdr = ((pTo->pgno==1) ? 100 : 0);
  54477. int rc;
  54478. int iData;
  54479. assert( pFrom->isInit );
  54480. assert( pFrom->nFree>=iToHdr );
  54481. assert( get2byte(&aFrom[iFromHdr+5]) <= (int)pBt->usableSize );
  54482. /* Copy the b-tree node content from page pFrom to page pTo. */
  54483. iData = get2byte(&aFrom[iFromHdr+5]);
  54484. memcpy(&aTo[iData], &aFrom[iData], pBt->usableSize-iData);
  54485. memcpy(&aTo[iToHdr], &aFrom[iFromHdr], pFrom->cellOffset + 2*pFrom->nCell);
  54486. /* Reinitialize page pTo so that the contents of the MemPage structure
  54487. ** match the new data. The initialization of pTo can actually fail under
  54488. ** fairly obscure circumstances, even though it is a copy of initialized
  54489. ** page pFrom.
  54490. */
  54491. pTo->isInit = 0;
  54492. rc = btreeInitPage(pTo);
  54493. if( rc!=SQLITE_OK ){
  54494. *pRC = rc;
  54495. return;
  54496. }
  54497. /* If this is an auto-vacuum database, update the pointer-map entries
  54498. ** for any b-tree or overflow pages that pTo now contains the pointers to.
  54499. */
  54500. if( ISAUTOVACUUM ){
  54501. *pRC = setChildPtrmaps(pTo);
  54502. }
  54503. }
  54504. }
  54505. /*
  54506. ** This routine redistributes cells on the iParentIdx'th child of pParent
  54507. ** (hereafter "the page") and up to 2 siblings so that all pages have about the
  54508. ** same amount of free space. Usually a single sibling on either side of the
  54509. ** page are used in the balancing, though both siblings might come from one
  54510. ** side if the page is the first or last child of its parent. If the page
  54511. ** has fewer than 2 siblings (something which can only happen if the page
  54512. ** is a root page or a child of a root page) then all available siblings
  54513. ** participate in the balancing.
  54514. **
  54515. ** The number of siblings of the page might be increased or decreased by
  54516. ** one or two in an effort to keep pages nearly full but not over full.
  54517. **
  54518. ** Note that when this routine is called, some of the cells on the page
  54519. ** might not actually be stored in MemPage.aData[]. This can happen
  54520. ** if the page is overfull. This routine ensures that all cells allocated
  54521. ** to the page and its siblings fit into MemPage.aData[] before returning.
  54522. **
  54523. ** In the course of balancing the page and its siblings, cells may be
  54524. ** inserted into or removed from the parent page (pParent). Doing so
  54525. ** may cause the parent page to become overfull or underfull. If this
  54526. ** happens, it is the responsibility of the caller to invoke the correct
  54527. ** balancing routine to fix this problem (see the balance() routine).
  54528. **
  54529. ** If this routine fails for any reason, it might leave the database
  54530. ** in a corrupted state. So if this routine fails, the database should
  54531. ** be rolled back.
  54532. **
  54533. ** The third argument to this function, aOvflSpace, is a pointer to a
  54534. ** buffer big enough to hold one page. If while inserting cells into the parent
  54535. ** page (pParent) the parent page becomes overfull, this buffer is
  54536. ** used to store the parent's overflow cells. Because this function inserts
  54537. ** a maximum of four divider cells into the parent page, and the maximum
  54538. ** size of a cell stored within an internal node is always less than 1/4
  54539. ** of the page-size, the aOvflSpace[] buffer is guaranteed to be large
  54540. ** enough for all overflow cells.
  54541. **
  54542. ** If aOvflSpace is set to a null pointer, this function returns
  54543. ** SQLITE_NOMEM.
  54544. */
  54545. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  54546. #pragma optimize("", off)
  54547. #endif
  54548. static int balance_nonroot(
  54549. MemPage *pParent, /* Parent page of siblings being balanced */
  54550. int iParentIdx, /* Index of "the page" in pParent */
  54551. u8 *aOvflSpace, /* page-size bytes of space for parent ovfl */
  54552. int isRoot, /* True if pParent is a root-page */
  54553. int bBulk /* True if this call is part of a bulk load */
  54554. ){
  54555. BtShared *pBt; /* The whole database */
  54556. int nCell = 0; /* Number of cells in apCell[] */
  54557. int nMaxCells = 0; /* Allocated size of apCell, szCell, aFrom. */
  54558. int nNew = 0; /* Number of pages in apNew[] */
  54559. int nOld; /* Number of pages in apOld[] */
  54560. int i, j, k; /* Loop counters */
  54561. int nxDiv; /* Next divider slot in pParent->aCell[] */
  54562. int rc = SQLITE_OK; /* The return code */
  54563. u16 leafCorrection; /* 4 if pPage is a leaf. 0 if not */
  54564. int leafData; /* True if pPage is a leaf of a LEAFDATA tree */
  54565. int usableSpace; /* Bytes in pPage beyond the header */
  54566. int pageFlags; /* Value of pPage->aData[0] */
  54567. int subtotal; /* Subtotal of bytes in cells on one page */
  54568. int iSpace1 = 0; /* First unused byte of aSpace1[] */
  54569. int iOvflSpace = 0; /* First unused byte of aOvflSpace[] */
  54570. int szScratch; /* Size of scratch memory requested */
  54571. MemPage *apOld[NB]; /* pPage and up to two siblings */
  54572. MemPage *apCopy[NB]; /* Private copies of apOld[] pages */
  54573. MemPage *apNew[NB+2]; /* pPage and up to NB siblings after balancing */
  54574. u8 *pRight; /* Location in parent of right-sibling pointer */
  54575. u8 *apDiv[NB-1]; /* Divider cells in pParent */
  54576. int cntNew[NB+2]; /* Index in aCell[] of cell after i-th page */
  54577. int szNew[NB+2]; /* Combined size of cells place on i-th page */
  54578. u8 **apCell = 0; /* All cells begin balanced */
  54579. u16 *szCell; /* Local size of all cells in apCell[] */
  54580. u8 *aSpace1; /* Space for copies of dividers cells */
  54581. Pgno pgno; /* Temp var to store a page number in */
  54582. pBt = pParent->pBt;
  54583. assert( sqlite3_mutex_held(pBt->mutex) );
  54584. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  54585. #if 0
  54586. TRACE(("BALANCE: begin page %d child of %d\n", pPage->pgno, pParent->pgno));
  54587. #endif
  54588. /* At this point pParent may have at most one overflow cell. And if
  54589. ** this overflow cell is present, it must be the cell with
  54590. ** index iParentIdx. This scenario comes about when this function
  54591. ** is called (indirectly) from sqlite3BtreeDelete().
  54592. */
  54593. assert( pParent->nOverflow==0 || pParent->nOverflow==1 );
  54594. assert( pParent->nOverflow==0 || pParent->aiOvfl[0]==iParentIdx );
  54595. if( !aOvflSpace ){
  54596. return SQLITE_NOMEM;
  54597. }
  54598. /* Find the sibling pages to balance. Also locate the cells in pParent
  54599. ** that divide the siblings. An attempt is made to find NN siblings on
  54600. ** either side of pPage. More siblings are taken from one side, however,
  54601. ** if there are fewer than NN siblings on the other side. If pParent
  54602. ** has NB or fewer children then all children of pParent are taken.
  54603. **
  54604. ** This loop also drops the divider cells from the parent page. This
  54605. ** way, the remainder of the function does not have to deal with any
  54606. ** overflow cells in the parent page, since if any existed they will
  54607. ** have already been removed.
  54608. */
  54609. i = pParent->nOverflow + pParent->nCell;
  54610. if( i<2 ){
  54611. nxDiv = 0;
  54612. }else{
  54613. assert( bBulk==0 || bBulk==1 );
  54614. if( iParentIdx==0 ){
  54615. nxDiv = 0;
  54616. }else if( iParentIdx==i ){
  54617. nxDiv = i-2+bBulk;
  54618. }else{
  54619. assert( bBulk==0 );
  54620. nxDiv = iParentIdx-1;
  54621. }
  54622. i = 2-bBulk;
  54623. }
  54624. nOld = i+1;
  54625. if( (i+nxDiv-pParent->nOverflow)==pParent->nCell ){
  54626. pRight = &pParent->aData[pParent->hdrOffset+8];
  54627. }else{
  54628. pRight = findCell(pParent, i+nxDiv-pParent->nOverflow);
  54629. }
  54630. pgno = get4byte(pRight);
  54631. while( 1 ){
  54632. rc = getAndInitPage(pBt, pgno, &apOld[i], 0);
  54633. if( rc ){
  54634. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  54635. goto balance_cleanup;
  54636. }
  54637. nMaxCells += 1+apOld[i]->nCell+apOld[i]->nOverflow;
  54638. if( (i--)==0 ) break;
  54639. if( i+nxDiv==pParent->aiOvfl[0] && pParent->nOverflow ){
  54640. apDiv[i] = pParent->apOvfl[0];
  54641. pgno = get4byte(apDiv[i]);
  54642. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  54643. pParent->nOverflow = 0;
  54644. }else{
  54645. apDiv[i] = findCell(pParent, i+nxDiv-pParent->nOverflow);
  54646. pgno = get4byte(apDiv[i]);
  54647. szNew[i] = cellSizePtr(pParent, apDiv[i]);
  54648. /* Drop the cell from the parent page. apDiv[i] still points to
  54649. ** the cell within the parent, even though it has been dropped.
  54650. ** This is safe because dropping a cell only overwrites the first
  54651. ** four bytes of it, and this function does not need the first
  54652. ** four bytes of the divider cell. So the pointer is safe to use
  54653. ** later on.
  54654. **
  54655. ** But not if we are in secure-delete mode. In secure-delete mode,
  54656. ** the dropCell() routine will overwrite the entire cell with zeroes.
  54657. ** In this case, temporarily copy the cell into the aOvflSpace[]
  54658. ** buffer. It will be copied out again as soon as the aSpace[] buffer
  54659. ** is allocated. */
  54660. if( pBt->btsFlags & BTS_SECURE_DELETE ){
  54661. int iOff;
  54662. iOff = SQLITE_PTR_TO_INT(apDiv[i]) - SQLITE_PTR_TO_INT(pParent->aData);
  54663. if( (iOff+szNew[i])>(int)pBt->usableSize ){
  54664. rc = SQLITE_CORRUPT_BKPT;
  54665. memset(apOld, 0, (i+1)*sizeof(MemPage*));
  54666. goto balance_cleanup;
  54667. }else{
  54668. memcpy(&aOvflSpace[iOff], apDiv[i], szNew[i]);
  54669. apDiv[i] = &aOvflSpace[apDiv[i]-pParent->aData];
  54670. }
  54671. }
  54672. dropCell(pParent, i+nxDiv-pParent->nOverflow, szNew[i], &rc);
  54673. }
  54674. }
  54675. /* Make nMaxCells a multiple of 4 in order to preserve 8-byte
  54676. ** alignment */
  54677. nMaxCells = (nMaxCells + 3)&~3;
  54678. /*
  54679. ** Allocate space for memory structures
  54680. */
  54681. k = pBt->pageSize + ROUND8(sizeof(MemPage));
  54682. szScratch =
  54683. nMaxCells*sizeof(u8*) /* apCell */
  54684. + nMaxCells*sizeof(u16) /* szCell */
  54685. + pBt->pageSize /* aSpace1 */
  54686. + k*nOld; /* Page copies (apCopy) */
  54687. apCell = sqlite3ScratchMalloc( szScratch );
  54688. if( apCell==0 ){
  54689. rc = SQLITE_NOMEM;
  54690. goto balance_cleanup;
  54691. }
  54692. szCell = (u16*)&apCell[nMaxCells];
  54693. aSpace1 = (u8*)&szCell[nMaxCells];
  54694. assert( EIGHT_BYTE_ALIGNMENT(aSpace1) );
  54695. /*
  54696. ** Load pointers to all cells on sibling pages and the divider cells
  54697. ** into the local apCell[] array. Make copies of the divider cells
  54698. ** into space obtained from aSpace1[] and remove the divider cells
  54699. ** from pParent.
  54700. **
  54701. ** If the siblings are on leaf pages, then the child pointers of the
  54702. ** divider cells are stripped from the cells before they are copied
  54703. ** into aSpace1[]. In this way, all cells in apCell[] are without
  54704. ** child pointers. If siblings are not leaves, then all cell in
  54705. ** apCell[] include child pointers. Either way, all cells in apCell[]
  54706. ** are alike.
  54707. **
  54708. ** leafCorrection: 4 if pPage is a leaf. 0 if pPage is not a leaf.
  54709. ** leafData: 1 if pPage holds key+data and pParent holds only keys.
  54710. */
  54711. leafCorrection = apOld[0]->leaf*4;
  54712. leafData = apOld[0]->intKeyLeaf;
  54713. for(i=0; i<nOld; i++){
  54714. int limit;
  54715. /* Before doing anything else, take a copy of the i'th original sibling
  54716. ** The rest of this function will use data from the copies rather
  54717. ** that the original pages since the original pages will be in the
  54718. ** process of being overwritten. */
  54719. MemPage *pOld = apCopy[i] = (MemPage*)&aSpace1[pBt->pageSize + k*i];
  54720. memcpy(pOld, apOld[i], sizeof(MemPage));
  54721. pOld->aData = (void*)&pOld[1];
  54722. memcpy(pOld->aData, apOld[i]->aData, pBt->pageSize);
  54723. limit = pOld->nCell+pOld->nOverflow;
  54724. if( pOld->nOverflow>0 ){
  54725. for(j=0; j<limit; j++){
  54726. assert( nCell<nMaxCells );
  54727. apCell[nCell] = findOverflowCell(pOld, j);
  54728. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  54729. nCell++;
  54730. }
  54731. }else{
  54732. u8 *aData = pOld->aData;
  54733. u16 maskPage = pOld->maskPage;
  54734. u16 cellOffset = pOld->cellOffset;
  54735. for(j=0; j<limit; j++){
  54736. assert( nCell<nMaxCells );
  54737. apCell[nCell] = findCellv2(aData, maskPage, cellOffset, j);
  54738. szCell[nCell] = cellSizePtr(pOld, apCell[nCell]);
  54739. nCell++;
  54740. }
  54741. }
  54742. if( i<nOld-1 && !leafData){
  54743. u16 sz = (u16)szNew[i];
  54744. u8 *pTemp;
  54745. assert( nCell<nMaxCells );
  54746. szCell[nCell] = sz;
  54747. pTemp = &aSpace1[iSpace1];
  54748. iSpace1 += sz;
  54749. assert( sz<=pBt->maxLocal+23 );
  54750. assert( iSpace1 <= (int)pBt->pageSize );
  54751. memcpy(pTemp, apDiv[i], sz);
  54752. apCell[nCell] = pTemp+leafCorrection;
  54753. assert( leafCorrection==0 || leafCorrection==4 );
  54754. szCell[nCell] = szCell[nCell] - leafCorrection;
  54755. if( !pOld->leaf ){
  54756. assert( leafCorrection==0 );
  54757. assert( pOld->hdrOffset==0 );
  54758. /* The right pointer of the child page pOld becomes the left
  54759. ** pointer of the divider cell */
  54760. memcpy(apCell[nCell], &pOld->aData[8], 4);
  54761. }else{
  54762. assert( leafCorrection==4 );
  54763. if( szCell[nCell]<4 ){
  54764. /* Do not allow any cells smaller than 4 bytes. */
  54765. szCell[nCell] = 4;
  54766. }
  54767. }
  54768. nCell++;
  54769. }
  54770. }
  54771. /*
  54772. ** Figure out the number of pages needed to hold all nCell cells.
  54773. ** Store this number in "k". Also compute szNew[] which is the total
  54774. ** size of all cells on the i-th page and cntNew[] which is the index
  54775. ** in apCell[] of the cell that divides page i from page i+1.
  54776. ** cntNew[k] should equal nCell.
  54777. **
  54778. ** Values computed by this block:
  54779. **
  54780. ** k: The total number of sibling pages
  54781. ** szNew[i]: Spaced used on the i-th sibling page.
  54782. ** cntNew[i]: Index in apCell[] and szCell[] for the first cell to
  54783. ** the right of the i-th sibling page.
  54784. ** usableSpace: Number of bytes of space available on each sibling.
  54785. **
  54786. */
  54787. usableSpace = pBt->usableSize - 12 + leafCorrection;
  54788. for(subtotal=k=i=0; i<nCell; i++){
  54789. assert( i<nMaxCells );
  54790. subtotal += szCell[i] + 2;
  54791. if( subtotal > usableSpace ){
  54792. szNew[k] = subtotal - szCell[i];
  54793. cntNew[k] = i;
  54794. if( leafData ){ i--; }
  54795. subtotal = 0;
  54796. k++;
  54797. if( k>NB+1 ){ rc = SQLITE_CORRUPT_BKPT; goto balance_cleanup; }
  54798. }
  54799. }
  54800. szNew[k] = subtotal;
  54801. cntNew[k] = nCell;
  54802. k++;
  54803. /*
  54804. ** The packing computed by the previous block is biased toward the siblings
  54805. ** on the left side. The left siblings are always nearly full, while the
  54806. ** right-most sibling might be nearly empty. This block of code attempts
  54807. ** to adjust the packing of siblings to get a better balance.
  54808. **
  54809. ** This adjustment is more than an optimization. The packing above might
  54810. ** be so out of balance as to be illegal. For example, the right-most
  54811. ** sibling might be completely empty. This adjustment is not optional.
  54812. */
  54813. for(i=k-1; i>0; i--){
  54814. int szRight = szNew[i]; /* Size of sibling on the right */
  54815. int szLeft = szNew[i-1]; /* Size of sibling on the left */
  54816. int r; /* Index of right-most cell in left sibling */
  54817. int d; /* Index of first cell to the left of right sibling */
  54818. r = cntNew[i-1] - 1;
  54819. d = r + 1 - leafData;
  54820. assert( d<nMaxCells );
  54821. assert( r<nMaxCells );
  54822. while( szRight==0
  54823. || (!bBulk && szRight+szCell[d]+2<=szLeft-(szCell[r]+2))
  54824. ){
  54825. szRight += szCell[d] + 2;
  54826. szLeft -= szCell[r] + 2;
  54827. cntNew[i-1]--;
  54828. r = cntNew[i-1] - 1;
  54829. d = r + 1 - leafData;
  54830. }
  54831. szNew[i] = szRight;
  54832. szNew[i-1] = szLeft;
  54833. }
  54834. /* Either we found one or more cells (cntnew[0])>0) or pPage is
  54835. ** a virtual root page. A virtual root page is when the real root
  54836. ** page is page 1 and we are the only child of that page.
  54837. **
  54838. ** UPDATE: The assert() below is not necessarily true if the database
  54839. ** file is corrupt. The corruption will be detected and reported later
  54840. ** in this procedure so there is no need to act upon it now.
  54841. */
  54842. #if 0
  54843. assert( cntNew[0]>0 || (pParent->pgno==1 && pParent->nCell==0) );
  54844. #endif
  54845. TRACE(("BALANCE: old: %d %d %d ",
  54846. apOld[0]->pgno,
  54847. nOld>=2 ? apOld[1]->pgno : 0,
  54848. nOld>=3 ? apOld[2]->pgno : 0
  54849. ));
  54850. /*
  54851. ** Allocate k new pages. Reuse old pages where possible.
  54852. */
  54853. if( apOld[0]->pgno<=1 ){
  54854. rc = SQLITE_CORRUPT_BKPT;
  54855. goto balance_cleanup;
  54856. }
  54857. pageFlags = apOld[0]->aData[0];
  54858. for(i=0; i<k; i++){
  54859. MemPage *pNew;
  54860. if( i<nOld ){
  54861. pNew = apNew[i] = apOld[i];
  54862. apOld[i] = 0;
  54863. rc = sqlite3PagerWrite(pNew->pDbPage);
  54864. nNew++;
  54865. if( rc ) goto balance_cleanup;
  54866. }else{
  54867. assert( i>0 );
  54868. rc = allocateBtreePage(pBt, &pNew, &pgno, (bBulk ? 1 : pgno), 0);
  54869. if( rc ) goto balance_cleanup;
  54870. apNew[i] = pNew;
  54871. nNew++;
  54872. /* Set the pointer-map entry for the new sibling page. */
  54873. if( ISAUTOVACUUM ){
  54874. ptrmapPut(pBt, pNew->pgno, PTRMAP_BTREE, pParent->pgno, &rc);
  54875. if( rc!=SQLITE_OK ){
  54876. goto balance_cleanup;
  54877. }
  54878. }
  54879. }
  54880. }
  54881. /* Free any old pages that were not reused as new pages.
  54882. */
  54883. while( i<nOld ){
  54884. freePage(apOld[i], &rc);
  54885. if( rc ) goto balance_cleanup;
  54886. releasePage(apOld[i]);
  54887. apOld[i] = 0;
  54888. i++;
  54889. }
  54890. /*
  54891. ** Put the new pages in ascending order. This helps to
  54892. ** keep entries in the disk file in order so that a scan
  54893. ** of the table is a linear scan through the file. That
  54894. ** in turn helps the operating system to deliver pages
  54895. ** from the disk more rapidly.
  54896. **
  54897. ** An O(n^2) insertion sort algorithm is used, but since
  54898. ** n is never more than NB (a small constant), that should
  54899. ** not be a problem.
  54900. **
  54901. ** When NB==3, this one optimization makes the database
  54902. ** about 25% faster for large insertions and deletions.
  54903. */
  54904. for(i=0; i<k-1; i++){
  54905. int minV = apNew[i]->pgno;
  54906. int minI = i;
  54907. for(j=i+1; j<k; j++){
  54908. if( apNew[j]->pgno<(unsigned)minV ){
  54909. minI = j;
  54910. minV = apNew[j]->pgno;
  54911. }
  54912. }
  54913. if( minI>i ){
  54914. MemPage *pT;
  54915. pT = apNew[i];
  54916. apNew[i] = apNew[minI];
  54917. apNew[minI] = pT;
  54918. }
  54919. }
  54920. TRACE(("new: %d(%d) %d(%d) %d(%d) %d(%d) %d(%d)\n",
  54921. apNew[0]->pgno, szNew[0],
  54922. nNew>=2 ? apNew[1]->pgno : 0, nNew>=2 ? szNew[1] : 0,
  54923. nNew>=3 ? apNew[2]->pgno : 0, nNew>=3 ? szNew[2] : 0,
  54924. nNew>=4 ? apNew[3]->pgno : 0, nNew>=4 ? szNew[3] : 0,
  54925. nNew>=5 ? apNew[4]->pgno : 0, nNew>=5 ? szNew[4] : 0));
  54926. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  54927. put4byte(pRight, apNew[nNew-1]->pgno);
  54928. /*
  54929. ** Evenly distribute the data in apCell[] across the new pages.
  54930. ** Insert divider cells into pParent as necessary.
  54931. */
  54932. j = 0;
  54933. for(i=0; i<nNew; i++){
  54934. /* Assemble the new sibling page. */
  54935. MemPage *pNew = apNew[i];
  54936. assert( j<nMaxCells );
  54937. zeroPage(pNew, pageFlags);
  54938. assemblePage(pNew, cntNew[i]-j, &apCell[j], &szCell[j]);
  54939. assert( pNew->nCell>0 || (nNew==1 && cntNew[0]==0) );
  54940. assert( pNew->nOverflow==0 );
  54941. j = cntNew[i];
  54942. /* If the sibling page assembled above was not the right-most sibling,
  54943. ** insert a divider cell into the parent page.
  54944. */
  54945. assert( i<nNew-1 || j==nCell );
  54946. if( j<nCell ){
  54947. u8 *pCell;
  54948. u8 *pTemp;
  54949. int sz;
  54950. assert( j<nMaxCells );
  54951. pCell = apCell[j];
  54952. sz = szCell[j] + leafCorrection;
  54953. pTemp = &aOvflSpace[iOvflSpace];
  54954. if( !pNew->leaf ){
  54955. memcpy(&pNew->aData[8], pCell, 4);
  54956. }else if( leafData ){
  54957. /* If the tree is a leaf-data tree, and the siblings are leaves,
  54958. ** then there is no divider cell in apCell[]. Instead, the divider
  54959. ** cell consists of the integer key for the right-most cell of
  54960. ** the sibling-page assembled above only.
  54961. */
  54962. CellInfo info;
  54963. j--;
  54964. btreeParseCellPtr(pNew, apCell[j], &info);
  54965. pCell = pTemp;
  54966. sz = 4 + putVarint(&pCell[4], info.nKey);
  54967. pTemp = 0;
  54968. }else{
  54969. pCell -= 4;
  54970. /* Obscure case for non-leaf-data trees: If the cell at pCell was
  54971. ** previously stored on a leaf node, and its reported size was 4
  54972. ** bytes, then it may actually be smaller than this
  54973. ** (see btreeParseCellPtr(), 4 bytes is the minimum size of
  54974. ** any cell). But it is important to pass the correct size to
  54975. ** insertCell(), so reparse the cell now.
  54976. **
  54977. ** Note that this can never happen in an SQLite data file, as all
  54978. ** cells are at least 4 bytes. It only happens in b-trees used
  54979. ** to evaluate "IN (SELECT ...)" and similar clauses.
  54980. */
  54981. if( szCell[j]==4 ){
  54982. assert(leafCorrection==4);
  54983. sz = cellSizePtr(pParent, pCell);
  54984. }
  54985. }
  54986. iOvflSpace += sz;
  54987. assert( sz<=pBt->maxLocal+23 );
  54988. assert( iOvflSpace <= (int)pBt->pageSize );
  54989. insertCell(pParent, nxDiv, pCell, sz, pTemp, pNew->pgno, &rc);
  54990. if( rc!=SQLITE_OK ) goto balance_cleanup;
  54991. assert( sqlite3PagerIswriteable(pParent->pDbPage) );
  54992. j++;
  54993. nxDiv++;
  54994. }
  54995. }
  54996. assert( j==nCell );
  54997. assert( nOld>0 );
  54998. assert( nNew>0 );
  54999. if( (pageFlags & PTF_LEAF)==0 ){
  55000. u8 *zChild = &apCopy[nOld-1]->aData[8];
  55001. memcpy(&apNew[nNew-1]->aData[8], zChild, 4);
  55002. }
  55003. if( isRoot && pParent->nCell==0 && pParent->hdrOffset<=apNew[0]->nFree ){
  55004. /* The root page of the b-tree now contains no cells. The only sibling
  55005. ** page is the right-child of the parent. Copy the contents of the
  55006. ** child page into the parent, decreasing the overall height of the
  55007. ** b-tree structure by one. This is described as the "balance-shallower"
  55008. ** sub-algorithm in some documentation.
  55009. **
  55010. ** If this is an auto-vacuum database, the call to copyNodeContent()
  55011. ** sets all pointer-map entries corresponding to database image pages
  55012. ** for which the pointer is stored within the content being copied.
  55013. **
  55014. ** The second assert below verifies that the child page is defragmented
  55015. ** (it must be, as it was just reconstructed using assemblePage()). This
  55016. ** is important if the parent page happens to be page 1 of the database
  55017. ** image. */
  55018. assert( nNew==1 );
  55019. assert( apNew[0]->nFree ==
  55020. (get2byte(&apNew[0]->aData[5])-apNew[0]->cellOffset-apNew[0]->nCell*2)
  55021. );
  55022. copyNodeContent(apNew[0], pParent, &rc);
  55023. freePage(apNew[0], &rc);
  55024. }else if( ISAUTOVACUUM ){
  55025. /* Fix the pointer-map entries for all the cells that were shifted around.
  55026. ** There are several different types of pointer-map entries that need to
  55027. ** be dealt with by this routine. Some of these have been set already, but
  55028. ** many have not. The following is a summary:
  55029. **
  55030. ** 1) The entries associated with new sibling pages that were not
  55031. ** siblings when this function was called. These have already
  55032. ** been set. We don't need to worry about old siblings that were
  55033. ** moved to the free-list - the freePage() code has taken care
  55034. ** of those.
  55035. **
  55036. ** 2) The pointer-map entries associated with the first overflow
  55037. ** page in any overflow chains used by new divider cells. These
  55038. ** have also already been taken care of by the insertCell() code.
  55039. **
  55040. ** 3) If the sibling pages are not leaves, then the child pages of
  55041. ** cells stored on the sibling pages may need to be updated.
  55042. **
  55043. ** 4) If the sibling pages are not internal intkey nodes, then any
  55044. ** overflow pages used by these cells may need to be updated
  55045. ** (internal intkey nodes never contain pointers to overflow pages).
  55046. **
  55047. ** 5) If the sibling pages are not leaves, then the pointer-map
  55048. ** entries for the right-child pages of each sibling may need
  55049. ** to be updated.
  55050. **
  55051. ** Cases 1 and 2 are dealt with above by other code. The next
  55052. ** block deals with cases 3 and 4 and the one after that, case 5. Since
  55053. ** setting a pointer map entry is a relatively expensive operation, this
  55054. ** code only sets pointer map entries for child or overflow pages that have
  55055. ** actually moved between pages. */
  55056. MemPage *pNew = apNew[0];
  55057. MemPage *pOld = apCopy[0];
  55058. int nOverflow = pOld->nOverflow;
  55059. int iNextOld = pOld->nCell + nOverflow;
  55060. int iOverflow = (nOverflow ? pOld->aiOvfl[0] : -1);
  55061. j = 0; /* Current 'old' sibling page */
  55062. k = 0; /* Current 'new' sibling page */
  55063. for(i=0; i<nCell; i++){
  55064. int isDivider = 0;
  55065. while( i==iNextOld ){
  55066. /* Cell i is the cell immediately following the last cell on old
  55067. ** sibling page j. If the siblings are not leaf pages of an
  55068. ** intkey b-tree, then cell i was a divider cell. */
  55069. assert( j+1 < ArraySize(apCopy) );
  55070. assert( j+1 < nOld );
  55071. pOld = apCopy[++j];
  55072. iNextOld = i + !leafData + pOld->nCell + pOld->nOverflow;
  55073. if( pOld->nOverflow ){
  55074. nOverflow = pOld->nOverflow;
  55075. iOverflow = i + !leafData + pOld->aiOvfl[0];
  55076. }
  55077. isDivider = !leafData;
  55078. }
  55079. assert(nOverflow>0 || iOverflow<i );
  55080. assert(nOverflow<2 || pOld->aiOvfl[0]==pOld->aiOvfl[1]-1);
  55081. assert(nOverflow<3 || pOld->aiOvfl[1]==pOld->aiOvfl[2]-1);
  55082. if( i==iOverflow ){
  55083. isDivider = 1;
  55084. if( (--nOverflow)>0 ){
  55085. iOverflow++;
  55086. }
  55087. }
  55088. if( i==cntNew[k] ){
  55089. /* Cell i is the cell immediately following the last cell on new
  55090. ** sibling page k. If the siblings are not leaf pages of an
  55091. ** intkey b-tree, then cell i is a divider cell. */
  55092. pNew = apNew[++k];
  55093. if( !leafData ) continue;
  55094. }
  55095. assert( j<nOld );
  55096. assert( k<nNew );
  55097. /* If the cell was originally divider cell (and is not now) or
  55098. ** an overflow cell, or if the cell was located on a different sibling
  55099. ** page before the balancing, then the pointer map entries associated
  55100. ** with any child or overflow pages need to be updated. */
  55101. if( isDivider || pOld->pgno!=pNew->pgno ){
  55102. if( !leafCorrection ){
  55103. ptrmapPut(pBt, get4byte(apCell[i]), PTRMAP_BTREE, pNew->pgno, &rc);
  55104. }
  55105. if( szCell[i]>pNew->minLocal ){
  55106. ptrmapPutOvflPtr(pNew, apCell[i], &rc);
  55107. }
  55108. }
  55109. }
  55110. if( !leafCorrection ){
  55111. for(i=0; i<nNew; i++){
  55112. u32 key = get4byte(&apNew[i]->aData[8]);
  55113. ptrmapPut(pBt, key, PTRMAP_BTREE, apNew[i]->pgno, &rc);
  55114. }
  55115. }
  55116. #if 0
  55117. /* The ptrmapCheckPages() contains assert() statements that verify that
  55118. ** all pointer map pages are set correctly. This is helpful while
  55119. ** debugging. This is usually disabled because a corrupt database may
  55120. ** cause an assert() statement to fail. */
  55121. ptrmapCheckPages(apNew, nNew);
  55122. ptrmapCheckPages(&pParent, 1);
  55123. #endif
  55124. }
  55125. assert( pParent->isInit );
  55126. TRACE(("BALANCE: finished: old=%d new=%d cells=%d\n",
  55127. nOld, nNew, nCell));
  55128. /*
  55129. ** Cleanup before returning.
  55130. */
  55131. balance_cleanup:
  55132. sqlite3ScratchFree(apCell);
  55133. for(i=0; i<nOld; i++){
  55134. releasePage(apOld[i]);
  55135. }
  55136. for(i=0; i<nNew; i++){
  55137. releasePage(apNew[i]);
  55138. }
  55139. return rc;
  55140. }
  55141. #if defined(_MSC_VER) && _MSC_VER >= 1700 && defined(_M_ARM)
  55142. #pragma optimize("", on)
  55143. #endif
  55144. /*
  55145. ** This function is called when the root page of a b-tree structure is
  55146. ** overfull (has one or more overflow pages).
  55147. **
  55148. ** A new child page is allocated and the contents of the current root
  55149. ** page, including overflow cells, are copied into the child. The root
  55150. ** page is then overwritten to make it an empty page with the right-child
  55151. ** pointer pointing to the new page.
  55152. **
  55153. ** Before returning, all pointer-map entries corresponding to pages
  55154. ** that the new child-page now contains pointers to are updated. The
  55155. ** entry corresponding to the new right-child pointer of the root
  55156. ** page is also updated.
  55157. **
  55158. ** If successful, *ppChild is set to contain a reference to the child
  55159. ** page and SQLITE_OK is returned. In this case the caller is required
  55160. ** to call releasePage() on *ppChild exactly once. If an error occurs,
  55161. ** an error code is returned and *ppChild is set to 0.
  55162. */
  55163. static int balance_deeper(MemPage *pRoot, MemPage **ppChild){
  55164. int rc; /* Return value from subprocedures */
  55165. MemPage *pChild = 0; /* Pointer to a new child page */
  55166. Pgno pgnoChild = 0; /* Page number of the new child page */
  55167. BtShared *pBt = pRoot->pBt; /* The BTree */
  55168. assert( pRoot->nOverflow>0 );
  55169. assert( sqlite3_mutex_held(pBt->mutex) );
  55170. /* Make pRoot, the root page of the b-tree, writable. Allocate a new
  55171. ** page that will become the new right-child of pPage. Copy the contents
  55172. ** of the node stored on pRoot into the new child page.
  55173. */
  55174. rc = sqlite3PagerWrite(pRoot->pDbPage);
  55175. if( rc==SQLITE_OK ){
  55176. rc = allocateBtreePage(pBt,&pChild,&pgnoChild,pRoot->pgno,0);
  55177. copyNodeContent(pRoot, pChild, &rc);
  55178. if( ISAUTOVACUUM ){
  55179. ptrmapPut(pBt, pgnoChild, PTRMAP_BTREE, pRoot->pgno, &rc);
  55180. }
  55181. }
  55182. if( rc ){
  55183. *ppChild = 0;
  55184. releasePage(pChild);
  55185. return rc;
  55186. }
  55187. assert( sqlite3PagerIswriteable(pChild->pDbPage) );
  55188. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  55189. assert( pChild->nCell==pRoot->nCell );
  55190. TRACE(("BALANCE: copy root %d into %d\n", pRoot->pgno, pChild->pgno));
  55191. /* Copy the overflow cells from pRoot to pChild */
  55192. memcpy(pChild->aiOvfl, pRoot->aiOvfl,
  55193. pRoot->nOverflow*sizeof(pRoot->aiOvfl[0]));
  55194. memcpy(pChild->apOvfl, pRoot->apOvfl,
  55195. pRoot->nOverflow*sizeof(pRoot->apOvfl[0]));
  55196. pChild->nOverflow = pRoot->nOverflow;
  55197. /* Zero the contents of pRoot. Then install pChild as the right-child. */
  55198. zeroPage(pRoot, pChild->aData[0] & ~PTF_LEAF);
  55199. put4byte(&pRoot->aData[pRoot->hdrOffset+8], pgnoChild);
  55200. *ppChild = pChild;
  55201. return SQLITE_OK;
  55202. }
  55203. /*
  55204. ** The page that pCur currently points to has just been modified in
  55205. ** some way. This function figures out if this modification means the
  55206. ** tree needs to be balanced, and if so calls the appropriate balancing
  55207. ** routine. Balancing routines are:
  55208. **
  55209. ** balance_quick()
  55210. ** balance_deeper()
  55211. ** balance_nonroot()
  55212. */
  55213. static int balance(BtCursor *pCur){
  55214. int rc = SQLITE_OK;
  55215. const int nMin = pCur->pBt->usableSize * 2 / 3;
  55216. u8 aBalanceQuickSpace[13];
  55217. u8 *pFree = 0;
  55218. TESTONLY( int balance_quick_called = 0 );
  55219. TESTONLY( int balance_deeper_called = 0 );
  55220. do {
  55221. int iPage = pCur->iPage;
  55222. MemPage *pPage = pCur->apPage[iPage];
  55223. if( iPage==0 ){
  55224. if( pPage->nOverflow ){
  55225. /* The root page of the b-tree is overfull. In this case call the
  55226. ** balance_deeper() function to create a new child for the root-page
  55227. ** and copy the current contents of the root-page to it. The
  55228. ** next iteration of the do-loop will balance the child page.
  55229. */
  55230. assert( (balance_deeper_called++)==0 );
  55231. rc = balance_deeper(pPage, &pCur->apPage[1]);
  55232. if( rc==SQLITE_OK ){
  55233. pCur->iPage = 1;
  55234. pCur->aiIdx[0] = 0;
  55235. pCur->aiIdx[1] = 0;
  55236. assert( pCur->apPage[1]->nOverflow );
  55237. }
  55238. }else{
  55239. break;
  55240. }
  55241. }else if( pPage->nOverflow==0 && pPage->nFree<=nMin ){
  55242. break;
  55243. }else{
  55244. MemPage * const pParent = pCur->apPage[iPage-1];
  55245. int const iIdx = pCur->aiIdx[iPage-1];
  55246. rc = sqlite3PagerWrite(pParent->pDbPage);
  55247. if( rc==SQLITE_OK ){
  55248. #ifndef SQLITE_OMIT_QUICKBALANCE
  55249. if( pPage->intKeyLeaf
  55250. && pPage->nOverflow==1
  55251. && pPage->aiOvfl[0]==pPage->nCell
  55252. && pParent->pgno!=1
  55253. && pParent->nCell==iIdx
  55254. ){
  55255. /* Call balance_quick() to create a new sibling of pPage on which
  55256. ** to store the overflow cell. balance_quick() inserts a new cell
  55257. ** into pParent, which may cause pParent overflow. If this
  55258. ** happens, the next iteration of the do-loop will balance pParent
  55259. ** use either balance_nonroot() or balance_deeper(). Until this
  55260. ** happens, the overflow cell is stored in the aBalanceQuickSpace[]
  55261. ** buffer.
  55262. **
  55263. ** The purpose of the following assert() is to check that only a
  55264. ** single call to balance_quick() is made for each call to this
  55265. ** function. If this were not verified, a subtle bug involving reuse
  55266. ** of the aBalanceQuickSpace[] might sneak in.
  55267. */
  55268. assert( (balance_quick_called++)==0 );
  55269. rc = balance_quick(pParent, pPage, aBalanceQuickSpace);
  55270. }else
  55271. #endif
  55272. {
  55273. /* In this case, call balance_nonroot() to redistribute cells
  55274. ** between pPage and up to 2 of its sibling pages. This involves
  55275. ** modifying the contents of pParent, which may cause pParent to
  55276. ** become overfull or underfull. The next iteration of the do-loop
  55277. ** will balance the parent page to correct this.
  55278. **
  55279. ** If the parent page becomes overfull, the overflow cell or cells
  55280. ** are stored in the pSpace buffer allocated immediately below.
  55281. ** A subsequent iteration of the do-loop will deal with this by
  55282. ** calling balance_nonroot() (balance_deeper() may be called first,
  55283. ** but it doesn't deal with overflow cells - just moves them to a
  55284. ** different page). Once this subsequent call to balance_nonroot()
  55285. ** has completed, it is safe to release the pSpace buffer used by
  55286. ** the previous call, as the overflow cell data will have been
  55287. ** copied either into the body of a database page or into the new
  55288. ** pSpace buffer passed to the latter call to balance_nonroot().
  55289. */
  55290. u8 *pSpace = sqlite3PageMalloc(pCur->pBt->pageSize);
  55291. rc = balance_nonroot(pParent, iIdx, pSpace, iPage==1, pCur->hints);
  55292. if( pFree ){
  55293. /* If pFree is not NULL, it points to the pSpace buffer used
  55294. ** by a previous call to balance_nonroot(). Its contents are
  55295. ** now stored either on real database pages or within the
  55296. ** new pSpace buffer, so it may be safely freed here. */
  55297. sqlite3PageFree(pFree);
  55298. }
  55299. /* The pSpace buffer will be freed after the next call to
  55300. ** balance_nonroot(), or just before this function returns, whichever
  55301. ** comes first. */
  55302. pFree = pSpace;
  55303. }
  55304. }
  55305. pPage->nOverflow = 0;
  55306. /* The next iteration of the do-loop balances the parent page. */
  55307. releasePage(pPage);
  55308. pCur->iPage--;
  55309. }
  55310. }while( rc==SQLITE_OK );
  55311. if( pFree ){
  55312. sqlite3PageFree(pFree);
  55313. }
  55314. return rc;
  55315. }
  55316. /*
  55317. ** Insert a new record into the BTree. The key is given by (pKey,nKey)
  55318. ** and the data is given by (pData,nData). The cursor is used only to
  55319. ** define what table the record should be inserted into. The cursor
  55320. ** is left pointing at a random location.
  55321. **
  55322. ** For an INTKEY table, only the nKey value of the key is used. pKey is
  55323. ** ignored. For a ZERODATA table, the pData and nData are both ignored.
  55324. **
  55325. ** If the seekResult parameter is non-zero, then a successful call to
  55326. ** MovetoUnpacked() to seek cursor pCur to (pKey, nKey) has already
  55327. ** been performed. seekResult is the search result returned (a negative
  55328. ** number if pCur points at an entry that is smaller than (pKey, nKey), or
  55329. ** a positive value if pCur points at an entry that is larger than
  55330. ** (pKey, nKey)).
  55331. **
  55332. ** If the seekResult parameter is non-zero, then the caller guarantees that
  55333. ** cursor pCur is pointing at the existing copy of a row that is to be
  55334. ** overwritten. If the seekResult parameter is 0, then cursor pCur may
  55335. ** point to any entry or to no entry at all and so this function has to seek
  55336. ** the cursor before the new key can be inserted.
  55337. */
  55338. SQLITE_PRIVATE int sqlite3BtreeInsert(
  55339. BtCursor *pCur, /* Insert data into the table of this cursor */
  55340. const void *pKey, i64 nKey, /* The key of the new record */
  55341. const void *pData, int nData, /* The data of the new record */
  55342. int nZero, /* Number of extra 0 bytes to append to data */
  55343. int appendBias, /* True if this is likely an append */
  55344. int seekResult /* Result of prior MovetoUnpacked() call */
  55345. ){
  55346. int rc;
  55347. int loc = seekResult; /* -1: before desired location +1: after */
  55348. int szNew = 0;
  55349. int idx;
  55350. MemPage *pPage;
  55351. Btree *p = pCur->pBtree;
  55352. BtShared *pBt = p->pBt;
  55353. unsigned char *oldCell;
  55354. unsigned char *newCell = 0;
  55355. if( pCur->eState==CURSOR_FAULT ){
  55356. assert( pCur->skipNext!=SQLITE_OK );
  55357. return pCur->skipNext;
  55358. }
  55359. assert( cursorHoldsMutex(pCur) );
  55360. assert( (pCur->curFlags & BTCF_WriteFlag)!=0
  55361. && pBt->inTransaction==TRANS_WRITE
  55362. && (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55363. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  55364. /* Assert that the caller has been consistent. If this cursor was opened
  55365. ** expecting an index b-tree, then the caller should be inserting blob
  55366. ** keys with no associated data. If the cursor was opened expecting an
  55367. ** intkey table, the caller should be inserting integer keys with a
  55368. ** blob of associated data. */
  55369. assert( (pKey==0)==(pCur->pKeyInfo==0) );
  55370. /* Save the positions of any other cursors open on this table.
  55371. **
  55372. ** In some cases, the call to btreeMoveto() below is a no-op. For
  55373. ** example, when inserting data into a table with auto-generated integer
  55374. ** keys, the VDBE layer invokes sqlite3BtreeLast() to figure out the
  55375. ** integer key to use. It then calls this function to actually insert the
  55376. ** data into the intkey B-Tree. In this case btreeMoveto() recognizes
  55377. ** that the cursor is already where it needs to be and returns without
  55378. ** doing any work. To avoid thwarting these optimizations, it is important
  55379. ** not to clear the cursor here.
  55380. */
  55381. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  55382. if( rc ) return rc;
  55383. if( pCur->pKeyInfo==0 ){
  55384. /* If this is an insert into a table b-tree, invalidate any incrblob
  55385. ** cursors open on the row being replaced */
  55386. invalidateIncrblobCursors(p, nKey, 0);
  55387. /* If the cursor is currently on the last row and we are appending a
  55388. ** new row onto the end, set the "loc" to avoid an unnecessary btreeMoveto()
  55389. ** call */
  55390. if( (pCur->curFlags&BTCF_ValidNKey)!=0 && nKey>0
  55391. && pCur->info.nKey==nKey-1 ){
  55392. loc = -1;
  55393. }
  55394. }
  55395. if( !loc ){
  55396. rc = btreeMoveto(pCur, pKey, nKey, appendBias, &loc);
  55397. if( rc ) return rc;
  55398. }
  55399. assert( pCur->eState==CURSOR_VALID || (pCur->eState==CURSOR_INVALID && loc) );
  55400. pPage = pCur->apPage[pCur->iPage];
  55401. assert( pPage->intKey || nKey>=0 );
  55402. assert( pPage->leaf || !pPage->intKey );
  55403. TRACE(("INSERT: table=%d nkey=%lld ndata=%d page=%d %s\n",
  55404. pCur->pgnoRoot, nKey, nData, pPage->pgno,
  55405. loc==0 ? "overwrite" : "new entry"));
  55406. assert( pPage->isInit );
  55407. newCell = pBt->pTmpSpace;
  55408. assert( newCell!=0 );
  55409. rc = fillInCell(pPage, newCell, pKey, nKey, pData, nData, nZero, &szNew);
  55410. if( rc ) goto end_insert;
  55411. assert( szNew==cellSizePtr(pPage, newCell) );
  55412. assert( szNew <= MX_CELL_SIZE(pBt) );
  55413. idx = pCur->aiIdx[pCur->iPage];
  55414. if( loc==0 ){
  55415. u16 szOld;
  55416. assert( idx<pPage->nCell );
  55417. rc = sqlite3PagerWrite(pPage->pDbPage);
  55418. if( rc ){
  55419. goto end_insert;
  55420. }
  55421. oldCell = findCell(pPage, idx);
  55422. if( !pPage->leaf ){
  55423. memcpy(newCell, oldCell, 4);
  55424. }
  55425. rc = clearCell(pPage, oldCell, &szOld);
  55426. dropCell(pPage, idx, szOld, &rc);
  55427. if( rc ) goto end_insert;
  55428. }else if( loc<0 && pPage->nCell>0 ){
  55429. assert( pPage->leaf );
  55430. idx = ++pCur->aiIdx[pCur->iPage];
  55431. }else{
  55432. assert( pPage->leaf );
  55433. }
  55434. insertCell(pPage, idx, newCell, szNew, 0, 0, &rc);
  55435. assert( rc!=SQLITE_OK || pPage->nCell>0 || pPage->nOverflow>0 );
  55436. /* If no error has occurred and pPage has an overflow cell, call balance()
  55437. ** to redistribute the cells within the tree. Since balance() may move
  55438. ** the cursor, zero the BtCursor.info.nSize and BTCF_ValidNKey
  55439. ** variables.
  55440. **
  55441. ** Previous versions of SQLite called moveToRoot() to move the cursor
  55442. ** back to the root page as balance() used to invalidate the contents
  55443. ** of BtCursor.apPage[] and BtCursor.aiIdx[]. Instead of doing that,
  55444. ** set the cursor state to "invalid". This makes common insert operations
  55445. ** slightly faster.
  55446. **
  55447. ** There is a subtle but important optimization here too. When inserting
  55448. ** multiple records into an intkey b-tree using a single cursor (as can
  55449. ** happen while processing an "INSERT INTO ... SELECT" statement), it
  55450. ** is advantageous to leave the cursor pointing to the last entry in
  55451. ** the b-tree if possible. If the cursor is left pointing to the last
  55452. ** entry in the table, and the next row inserted has an integer key
  55453. ** larger than the largest existing key, it is possible to insert the
  55454. ** row without seeking the cursor. This can be a big performance boost.
  55455. */
  55456. pCur->info.nSize = 0;
  55457. if( rc==SQLITE_OK && pPage->nOverflow ){
  55458. pCur->curFlags &= ~(BTCF_ValidNKey);
  55459. rc = balance(pCur);
  55460. /* Must make sure nOverflow is reset to zero even if the balance()
  55461. ** fails. Internal data structure corruption will result otherwise.
  55462. ** Also, set the cursor state to invalid. This stops saveCursorPosition()
  55463. ** from trying to save the current position of the cursor. */
  55464. pCur->apPage[pCur->iPage]->nOverflow = 0;
  55465. pCur->eState = CURSOR_INVALID;
  55466. }
  55467. assert( pCur->apPage[pCur->iPage]->nOverflow==0 );
  55468. end_insert:
  55469. return rc;
  55470. }
  55471. /*
  55472. ** Delete the entry that the cursor is pointing to. The cursor
  55473. ** is left pointing at an arbitrary location.
  55474. */
  55475. SQLITE_PRIVATE int sqlite3BtreeDelete(BtCursor *pCur){
  55476. Btree *p = pCur->pBtree;
  55477. BtShared *pBt = p->pBt;
  55478. int rc; /* Return code */
  55479. MemPage *pPage; /* Page to delete cell from */
  55480. unsigned char *pCell; /* Pointer to cell to delete */
  55481. int iCellIdx; /* Index of cell to delete */
  55482. int iCellDepth; /* Depth of node containing pCell */
  55483. u16 szCell; /* Size of the cell being deleted */
  55484. assert( cursorHoldsMutex(pCur) );
  55485. assert( pBt->inTransaction==TRANS_WRITE );
  55486. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55487. assert( pCur->curFlags & BTCF_WriteFlag );
  55488. assert( hasSharedCacheTableLock(p, pCur->pgnoRoot, pCur->pKeyInfo!=0, 2) );
  55489. assert( !hasReadConflicts(p, pCur->pgnoRoot) );
  55490. if( NEVER(pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell)
  55491. || NEVER(pCur->eState!=CURSOR_VALID)
  55492. ){
  55493. return SQLITE_ERROR; /* Something has gone awry. */
  55494. }
  55495. iCellDepth = pCur->iPage;
  55496. iCellIdx = pCur->aiIdx[iCellDepth];
  55497. pPage = pCur->apPage[iCellDepth];
  55498. pCell = findCell(pPage, iCellIdx);
  55499. /* If the page containing the entry to delete is not a leaf page, move
  55500. ** the cursor to the largest entry in the tree that is smaller than
  55501. ** the entry being deleted. This cell will replace the cell being deleted
  55502. ** from the internal node. The 'previous' entry is used for this instead
  55503. ** of the 'next' entry, as the previous entry is always a part of the
  55504. ** sub-tree headed by the child page of the cell being deleted. This makes
  55505. ** balancing the tree following the delete operation easier. */
  55506. if( !pPage->leaf ){
  55507. int notUsed = 0;
  55508. rc = sqlite3BtreePrevious(pCur, &notUsed);
  55509. if( rc ) return rc;
  55510. }
  55511. /* Save the positions of any other cursors open on this table before
  55512. ** making any modifications. Make the page containing the entry to be
  55513. ** deleted writable. Then free any overflow pages associated with the
  55514. ** entry and finally remove the cell itself from within the page.
  55515. */
  55516. rc = saveAllCursors(pBt, pCur->pgnoRoot, pCur);
  55517. if( rc ) return rc;
  55518. /* If this is a delete operation to remove a row from a table b-tree,
  55519. ** invalidate any incrblob cursors open on the row being deleted. */
  55520. if( pCur->pKeyInfo==0 ){
  55521. invalidateIncrblobCursors(p, pCur->info.nKey, 0);
  55522. }
  55523. rc = sqlite3PagerWrite(pPage->pDbPage);
  55524. if( rc ) return rc;
  55525. rc = clearCell(pPage, pCell, &szCell);
  55526. dropCell(pPage, iCellIdx, szCell, &rc);
  55527. if( rc ) return rc;
  55528. /* If the cell deleted was not located on a leaf page, then the cursor
  55529. ** is currently pointing to the largest entry in the sub-tree headed
  55530. ** by the child-page of the cell that was just deleted from an internal
  55531. ** node. The cell from the leaf node needs to be moved to the internal
  55532. ** node to replace the deleted cell. */
  55533. if( !pPage->leaf ){
  55534. MemPage *pLeaf = pCur->apPage[pCur->iPage];
  55535. int nCell;
  55536. Pgno n = pCur->apPage[iCellDepth+1]->pgno;
  55537. unsigned char *pTmp;
  55538. pCell = findCell(pLeaf, pLeaf->nCell-1);
  55539. nCell = cellSizePtr(pLeaf, pCell);
  55540. assert( MX_CELL_SIZE(pBt) >= nCell );
  55541. pTmp = pBt->pTmpSpace;
  55542. assert( pTmp!=0 );
  55543. rc = sqlite3PagerWrite(pLeaf->pDbPage);
  55544. insertCell(pPage, iCellIdx, pCell-4, nCell+4, pTmp, n, &rc);
  55545. dropCell(pLeaf, pLeaf->nCell-1, nCell, &rc);
  55546. if( rc ) return rc;
  55547. }
  55548. /* Balance the tree. If the entry deleted was located on a leaf page,
  55549. ** then the cursor still points to that page. In this case the first
  55550. ** call to balance() repairs the tree, and the if(...) condition is
  55551. ** never true.
  55552. **
  55553. ** Otherwise, if the entry deleted was on an internal node page, then
  55554. ** pCur is pointing to the leaf page from which a cell was removed to
  55555. ** replace the cell deleted from the internal node. This is slightly
  55556. ** tricky as the leaf node may be underfull, and the internal node may
  55557. ** be either under or overfull. In this case run the balancing algorithm
  55558. ** on the leaf node first. If the balance proceeds far enough up the
  55559. ** tree that we can be sure that any problem in the internal node has
  55560. ** been corrected, so be it. Otherwise, after balancing the leaf node,
  55561. ** walk the cursor up the tree to the internal node and balance it as
  55562. ** well. */
  55563. rc = balance(pCur);
  55564. if( rc==SQLITE_OK && pCur->iPage>iCellDepth ){
  55565. while( pCur->iPage>iCellDepth ){
  55566. releasePage(pCur->apPage[pCur->iPage--]);
  55567. }
  55568. rc = balance(pCur);
  55569. }
  55570. if( rc==SQLITE_OK ){
  55571. moveToRoot(pCur);
  55572. }
  55573. return rc;
  55574. }
  55575. /*
  55576. ** Create a new BTree table. Write into *piTable the page
  55577. ** number for the root page of the new table.
  55578. **
  55579. ** The type of type is determined by the flags parameter. Only the
  55580. ** following values of flags are currently in use. Other values for
  55581. ** flags might not work:
  55582. **
  55583. ** BTREE_INTKEY|BTREE_LEAFDATA Used for SQL tables with rowid keys
  55584. ** BTREE_ZERODATA Used for SQL indices
  55585. */
  55586. static int btreeCreateTable(Btree *p, int *piTable, int createTabFlags){
  55587. BtShared *pBt = p->pBt;
  55588. MemPage *pRoot;
  55589. Pgno pgnoRoot;
  55590. int rc;
  55591. int ptfFlags; /* Page-type flage for the root page of new table */
  55592. assert( sqlite3BtreeHoldsMutex(p) );
  55593. assert( pBt->inTransaction==TRANS_WRITE );
  55594. assert( (pBt->btsFlags & BTS_READ_ONLY)==0 );
  55595. #ifdef SQLITE_OMIT_AUTOVACUUM
  55596. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  55597. if( rc ){
  55598. return rc;
  55599. }
  55600. #else
  55601. if( pBt->autoVacuum ){
  55602. Pgno pgnoMove; /* Move a page here to make room for the root-page */
  55603. MemPage *pPageMove; /* The page to move to. */
  55604. /* Creating a new table may probably require moving an existing database
  55605. ** to make room for the new tables root page. In case this page turns
  55606. ** out to be an overflow page, delete all overflow page-map caches
  55607. ** held by open cursors.
  55608. */
  55609. invalidateAllOverflowCache(pBt);
  55610. /* Read the value of meta[3] from the database to determine where the
  55611. ** root page of the new table should go. meta[3] is the largest root-page
  55612. ** created so far, so the new root-page is (meta[3]+1).
  55613. */
  55614. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &pgnoRoot);
  55615. pgnoRoot++;
  55616. /* The new root-page may not be allocated on a pointer-map page, or the
  55617. ** PENDING_BYTE page.
  55618. */
  55619. while( pgnoRoot==PTRMAP_PAGENO(pBt, pgnoRoot) ||
  55620. pgnoRoot==PENDING_BYTE_PAGE(pBt) ){
  55621. pgnoRoot++;
  55622. }
  55623. assert( pgnoRoot>=3 );
  55624. /* Allocate a page. The page that currently resides at pgnoRoot will
  55625. ** be moved to the allocated page (unless the allocated page happens
  55626. ** to reside at pgnoRoot).
  55627. */
  55628. rc = allocateBtreePage(pBt, &pPageMove, &pgnoMove, pgnoRoot, BTALLOC_EXACT);
  55629. if( rc!=SQLITE_OK ){
  55630. return rc;
  55631. }
  55632. if( pgnoMove!=pgnoRoot ){
  55633. /* pgnoRoot is the page that will be used for the root-page of
  55634. ** the new table (assuming an error did not occur). But we were
  55635. ** allocated pgnoMove. If required (i.e. if it was not allocated
  55636. ** by extending the file), the current page at position pgnoMove
  55637. ** is already journaled.
  55638. */
  55639. u8 eType = 0;
  55640. Pgno iPtrPage = 0;
  55641. /* Save the positions of any open cursors. This is required in
  55642. ** case they are holding a reference to an xFetch reference
  55643. ** corresponding to page pgnoRoot. */
  55644. rc = saveAllCursors(pBt, 0, 0);
  55645. releasePage(pPageMove);
  55646. if( rc!=SQLITE_OK ){
  55647. return rc;
  55648. }
  55649. /* Move the page currently at pgnoRoot to pgnoMove. */
  55650. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  55651. if( rc!=SQLITE_OK ){
  55652. return rc;
  55653. }
  55654. rc = ptrmapGet(pBt, pgnoRoot, &eType, &iPtrPage);
  55655. if( eType==PTRMAP_ROOTPAGE || eType==PTRMAP_FREEPAGE ){
  55656. rc = SQLITE_CORRUPT_BKPT;
  55657. }
  55658. if( rc!=SQLITE_OK ){
  55659. releasePage(pRoot);
  55660. return rc;
  55661. }
  55662. assert( eType!=PTRMAP_ROOTPAGE );
  55663. assert( eType!=PTRMAP_FREEPAGE );
  55664. rc = relocatePage(pBt, pRoot, eType, iPtrPage, pgnoMove, 0);
  55665. releasePage(pRoot);
  55666. /* Obtain the page at pgnoRoot */
  55667. if( rc!=SQLITE_OK ){
  55668. return rc;
  55669. }
  55670. rc = btreeGetPage(pBt, pgnoRoot, &pRoot, 0);
  55671. if( rc!=SQLITE_OK ){
  55672. return rc;
  55673. }
  55674. rc = sqlite3PagerWrite(pRoot->pDbPage);
  55675. if( rc!=SQLITE_OK ){
  55676. releasePage(pRoot);
  55677. return rc;
  55678. }
  55679. }else{
  55680. pRoot = pPageMove;
  55681. }
  55682. /* Update the pointer-map and meta-data with the new root-page number. */
  55683. ptrmapPut(pBt, pgnoRoot, PTRMAP_ROOTPAGE, 0, &rc);
  55684. if( rc ){
  55685. releasePage(pRoot);
  55686. return rc;
  55687. }
  55688. /* When the new root page was allocated, page 1 was made writable in
  55689. ** order either to increase the database filesize, or to decrement the
  55690. ** freelist count. Hence, the sqlite3BtreeUpdateMeta() call cannot fail.
  55691. */
  55692. assert( sqlite3PagerIswriteable(pBt->pPage1->pDbPage) );
  55693. rc = sqlite3BtreeUpdateMeta(p, 4, pgnoRoot);
  55694. if( NEVER(rc) ){
  55695. releasePage(pRoot);
  55696. return rc;
  55697. }
  55698. }else{
  55699. rc = allocateBtreePage(pBt, &pRoot, &pgnoRoot, 1, 0);
  55700. if( rc ) return rc;
  55701. }
  55702. #endif
  55703. assert( sqlite3PagerIswriteable(pRoot->pDbPage) );
  55704. if( createTabFlags & BTREE_INTKEY ){
  55705. ptfFlags = PTF_INTKEY | PTF_LEAFDATA | PTF_LEAF;
  55706. }else{
  55707. ptfFlags = PTF_ZERODATA | PTF_LEAF;
  55708. }
  55709. zeroPage(pRoot, ptfFlags);
  55710. sqlite3PagerUnref(pRoot->pDbPage);
  55711. assert( (pBt->openFlags & BTREE_SINGLE)==0 || pgnoRoot==2 );
  55712. *piTable = (int)pgnoRoot;
  55713. return SQLITE_OK;
  55714. }
  55715. SQLITE_PRIVATE int sqlite3BtreeCreateTable(Btree *p, int *piTable, int flags){
  55716. int rc;
  55717. sqlite3BtreeEnter(p);
  55718. rc = btreeCreateTable(p, piTable, flags);
  55719. sqlite3BtreeLeave(p);
  55720. return rc;
  55721. }
  55722. /*
  55723. ** Erase the given database page and all its children. Return
  55724. ** the page to the freelist.
  55725. */
  55726. static int clearDatabasePage(
  55727. BtShared *pBt, /* The BTree that contains the table */
  55728. Pgno pgno, /* Page number to clear */
  55729. int freePageFlag, /* Deallocate page if true */
  55730. int *pnChange /* Add number of Cells freed to this counter */
  55731. ){
  55732. MemPage *pPage;
  55733. int rc;
  55734. unsigned char *pCell;
  55735. int i;
  55736. int hdr;
  55737. u16 szCell;
  55738. assert( sqlite3_mutex_held(pBt->mutex) );
  55739. if( pgno>btreePagecount(pBt) ){
  55740. return SQLITE_CORRUPT_BKPT;
  55741. }
  55742. rc = getAndInitPage(pBt, pgno, &pPage, 0);
  55743. if( rc ) return rc;
  55744. hdr = pPage->hdrOffset;
  55745. for(i=0; i<pPage->nCell; i++){
  55746. pCell = findCell(pPage, i);
  55747. if( !pPage->leaf ){
  55748. rc = clearDatabasePage(pBt, get4byte(pCell), 1, pnChange);
  55749. if( rc ) goto cleardatabasepage_out;
  55750. }
  55751. rc = clearCell(pPage, pCell, &szCell);
  55752. if( rc ) goto cleardatabasepage_out;
  55753. }
  55754. if( !pPage->leaf ){
  55755. rc = clearDatabasePage(pBt, get4byte(&pPage->aData[hdr+8]), 1, pnChange);
  55756. if( rc ) goto cleardatabasepage_out;
  55757. }else if( pnChange ){
  55758. assert( pPage->intKey );
  55759. *pnChange += pPage->nCell;
  55760. }
  55761. if( freePageFlag ){
  55762. freePage(pPage, &rc);
  55763. }else if( (rc = sqlite3PagerWrite(pPage->pDbPage))==0 ){
  55764. zeroPage(pPage, pPage->aData[hdr] | PTF_LEAF);
  55765. }
  55766. cleardatabasepage_out:
  55767. releasePage(pPage);
  55768. return rc;
  55769. }
  55770. /*
  55771. ** Delete all information from a single table in the database. iTable is
  55772. ** the page number of the root of the table. After this routine returns,
  55773. ** the root page is empty, but still exists.
  55774. **
  55775. ** This routine will fail with SQLITE_LOCKED if there are any open
  55776. ** read cursors on the table. Open write cursors are moved to the
  55777. ** root of the table.
  55778. **
  55779. ** If pnChange is not NULL, then table iTable must be an intkey table. The
  55780. ** integer value pointed to by pnChange is incremented by the number of
  55781. ** entries in the table.
  55782. */
  55783. SQLITE_PRIVATE int sqlite3BtreeClearTable(Btree *p, int iTable, int *pnChange){
  55784. int rc;
  55785. BtShared *pBt = p->pBt;
  55786. sqlite3BtreeEnter(p);
  55787. assert( p->inTrans==TRANS_WRITE );
  55788. rc = saveAllCursors(pBt, (Pgno)iTable, 0);
  55789. if( SQLITE_OK==rc ){
  55790. /* Invalidate all incrblob cursors open on table iTable (assuming iTable
  55791. ** is the root of a table b-tree - if it is not, the following call is
  55792. ** a no-op). */
  55793. invalidateIncrblobCursors(p, 0, 1);
  55794. rc = clearDatabasePage(pBt, (Pgno)iTable, 0, pnChange);
  55795. }
  55796. sqlite3BtreeLeave(p);
  55797. return rc;
  55798. }
  55799. /*
  55800. ** Delete all information from the single table that pCur is open on.
  55801. **
  55802. ** This routine only work for pCur on an ephemeral table.
  55803. */
  55804. SQLITE_PRIVATE int sqlite3BtreeClearTableOfCursor(BtCursor *pCur){
  55805. return sqlite3BtreeClearTable(pCur->pBtree, pCur->pgnoRoot, 0);
  55806. }
  55807. /*
  55808. ** Erase all information in a table and add the root of the table to
  55809. ** the freelist. Except, the root of the principle table (the one on
  55810. ** page 1) is never added to the freelist.
  55811. **
  55812. ** This routine will fail with SQLITE_LOCKED if there are any open
  55813. ** cursors on the table.
  55814. **
  55815. ** If AUTOVACUUM is enabled and the page at iTable is not the last
  55816. ** root page in the database file, then the last root page
  55817. ** in the database file is moved into the slot formerly occupied by
  55818. ** iTable and that last slot formerly occupied by the last root page
  55819. ** is added to the freelist instead of iTable. In this say, all
  55820. ** root pages are kept at the beginning of the database file, which
  55821. ** is necessary for AUTOVACUUM to work right. *piMoved is set to the
  55822. ** page number that used to be the last root page in the file before
  55823. ** the move. If no page gets moved, *piMoved is set to 0.
  55824. ** The last root page is recorded in meta[3] and the value of
  55825. ** meta[3] is updated by this procedure.
  55826. */
  55827. static int btreeDropTable(Btree *p, Pgno iTable, int *piMoved){
  55828. int rc;
  55829. MemPage *pPage = 0;
  55830. BtShared *pBt = p->pBt;
  55831. assert( sqlite3BtreeHoldsMutex(p) );
  55832. assert( p->inTrans==TRANS_WRITE );
  55833. /* It is illegal to drop a table if any cursors are open on the
  55834. ** database. This is because in auto-vacuum mode the backend may
  55835. ** need to move another root-page to fill a gap left by the deleted
  55836. ** root page. If an open cursor was using this page a problem would
  55837. ** occur.
  55838. **
  55839. ** This error is caught long before control reaches this point.
  55840. */
  55841. if( NEVER(pBt->pCursor) ){
  55842. sqlite3ConnectionBlocked(p->db, pBt->pCursor->pBtree->db);
  55843. return SQLITE_LOCKED_SHAREDCACHE;
  55844. }
  55845. rc = btreeGetPage(pBt, (Pgno)iTable, &pPage, 0);
  55846. if( rc ) return rc;
  55847. rc = sqlite3BtreeClearTable(p, iTable, 0);
  55848. if( rc ){
  55849. releasePage(pPage);
  55850. return rc;
  55851. }
  55852. *piMoved = 0;
  55853. if( iTable>1 ){
  55854. #ifdef SQLITE_OMIT_AUTOVACUUM
  55855. freePage(pPage, &rc);
  55856. releasePage(pPage);
  55857. #else
  55858. if( pBt->autoVacuum ){
  55859. Pgno maxRootPgno;
  55860. sqlite3BtreeGetMeta(p, BTREE_LARGEST_ROOT_PAGE, &maxRootPgno);
  55861. if( iTable==maxRootPgno ){
  55862. /* If the table being dropped is the table with the largest root-page
  55863. ** number in the database, put the root page on the free list.
  55864. */
  55865. freePage(pPage, &rc);
  55866. releasePage(pPage);
  55867. if( rc!=SQLITE_OK ){
  55868. return rc;
  55869. }
  55870. }else{
  55871. /* The table being dropped does not have the largest root-page
  55872. ** number in the database. So move the page that does into the
  55873. ** gap left by the deleted root-page.
  55874. */
  55875. MemPage *pMove;
  55876. releasePage(pPage);
  55877. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  55878. if( rc!=SQLITE_OK ){
  55879. return rc;
  55880. }
  55881. rc = relocatePage(pBt, pMove, PTRMAP_ROOTPAGE, 0, iTable, 0);
  55882. releasePage(pMove);
  55883. if( rc!=SQLITE_OK ){
  55884. return rc;
  55885. }
  55886. pMove = 0;
  55887. rc = btreeGetPage(pBt, maxRootPgno, &pMove, 0);
  55888. freePage(pMove, &rc);
  55889. releasePage(pMove);
  55890. if( rc!=SQLITE_OK ){
  55891. return rc;
  55892. }
  55893. *piMoved = maxRootPgno;
  55894. }
  55895. /* Set the new 'max-root-page' value in the database header. This
  55896. ** is the old value less one, less one more if that happens to
  55897. ** be a root-page number, less one again if that is the
  55898. ** PENDING_BYTE_PAGE.
  55899. */
  55900. maxRootPgno--;
  55901. while( maxRootPgno==PENDING_BYTE_PAGE(pBt)
  55902. || PTRMAP_ISPAGE(pBt, maxRootPgno) ){
  55903. maxRootPgno--;
  55904. }
  55905. assert( maxRootPgno!=PENDING_BYTE_PAGE(pBt) );
  55906. rc = sqlite3BtreeUpdateMeta(p, 4, maxRootPgno);
  55907. }else{
  55908. freePage(pPage, &rc);
  55909. releasePage(pPage);
  55910. }
  55911. #endif
  55912. }else{
  55913. /* If sqlite3BtreeDropTable was called on page 1.
  55914. ** This really never should happen except in a corrupt
  55915. ** database.
  55916. */
  55917. zeroPage(pPage, PTF_INTKEY|PTF_LEAF );
  55918. releasePage(pPage);
  55919. }
  55920. return rc;
  55921. }
  55922. SQLITE_PRIVATE int sqlite3BtreeDropTable(Btree *p, int iTable, int *piMoved){
  55923. int rc;
  55924. sqlite3BtreeEnter(p);
  55925. rc = btreeDropTable(p, iTable, piMoved);
  55926. sqlite3BtreeLeave(p);
  55927. return rc;
  55928. }
  55929. /*
  55930. ** This function may only be called if the b-tree connection already
  55931. ** has a read or write transaction open on the database.
  55932. **
  55933. ** Read the meta-information out of a database file. Meta[0]
  55934. ** is the number of free pages currently in the database. Meta[1]
  55935. ** through meta[15] are available for use by higher layers. Meta[0]
  55936. ** is read-only, the others are read/write.
  55937. **
  55938. ** The schema layer numbers meta values differently. At the schema
  55939. ** layer (and the SetCookie and ReadCookie opcodes) the number of
  55940. ** free pages is not visible. So Cookie[0] is the same as Meta[1].
  55941. */
  55942. SQLITE_PRIVATE void sqlite3BtreeGetMeta(Btree *p, int idx, u32 *pMeta){
  55943. BtShared *pBt = p->pBt;
  55944. sqlite3BtreeEnter(p);
  55945. assert( p->inTrans>TRANS_NONE );
  55946. assert( SQLITE_OK==querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK) );
  55947. assert( pBt->pPage1 );
  55948. assert( idx>=0 && idx<=15 );
  55949. *pMeta = get4byte(&pBt->pPage1->aData[36 + idx*4]);
  55950. /* If auto-vacuum is disabled in this build and this is an auto-vacuum
  55951. ** database, mark the database as read-only. */
  55952. #ifdef SQLITE_OMIT_AUTOVACUUM
  55953. if( idx==BTREE_LARGEST_ROOT_PAGE && *pMeta>0 ){
  55954. pBt->btsFlags |= BTS_READ_ONLY;
  55955. }
  55956. #endif
  55957. sqlite3BtreeLeave(p);
  55958. }
  55959. /*
  55960. ** Write meta-information back into the database. Meta[0] is
  55961. ** read-only and may not be written.
  55962. */
  55963. SQLITE_PRIVATE int sqlite3BtreeUpdateMeta(Btree *p, int idx, u32 iMeta){
  55964. BtShared *pBt = p->pBt;
  55965. unsigned char *pP1;
  55966. int rc;
  55967. assert( idx>=1 && idx<=15 );
  55968. sqlite3BtreeEnter(p);
  55969. assert( p->inTrans==TRANS_WRITE );
  55970. assert( pBt->pPage1!=0 );
  55971. pP1 = pBt->pPage1->aData;
  55972. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  55973. if( rc==SQLITE_OK ){
  55974. put4byte(&pP1[36 + idx*4], iMeta);
  55975. #ifndef SQLITE_OMIT_AUTOVACUUM
  55976. if( idx==BTREE_INCR_VACUUM ){
  55977. assert( pBt->autoVacuum || iMeta==0 );
  55978. assert( iMeta==0 || iMeta==1 );
  55979. pBt->incrVacuum = (u8)iMeta;
  55980. }
  55981. #endif
  55982. }
  55983. sqlite3BtreeLeave(p);
  55984. return rc;
  55985. }
  55986. #ifndef SQLITE_OMIT_BTREECOUNT
  55987. /*
  55988. ** The first argument, pCur, is a cursor opened on some b-tree. Count the
  55989. ** number of entries in the b-tree and write the result to *pnEntry.
  55990. **
  55991. ** SQLITE_OK is returned if the operation is successfully executed.
  55992. ** Otherwise, if an error is encountered (i.e. an IO error or database
  55993. ** corruption) an SQLite error code is returned.
  55994. */
  55995. SQLITE_PRIVATE int sqlite3BtreeCount(BtCursor *pCur, i64 *pnEntry){
  55996. i64 nEntry = 0; /* Value to return in *pnEntry */
  55997. int rc; /* Return code */
  55998. if( pCur->pgnoRoot==0 ){
  55999. *pnEntry = 0;
  56000. return SQLITE_OK;
  56001. }
  56002. rc = moveToRoot(pCur);
  56003. /* Unless an error occurs, the following loop runs one iteration for each
  56004. ** page in the B-Tree structure (not including overflow pages).
  56005. */
  56006. while( rc==SQLITE_OK ){
  56007. int iIdx; /* Index of child node in parent */
  56008. MemPage *pPage; /* Current page of the b-tree */
  56009. /* If this is a leaf page or the tree is not an int-key tree, then
  56010. ** this page contains countable entries. Increment the entry counter
  56011. ** accordingly.
  56012. */
  56013. pPage = pCur->apPage[pCur->iPage];
  56014. if( pPage->leaf || !pPage->intKey ){
  56015. nEntry += pPage->nCell;
  56016. }
  56017. /* pPage is a leaf node. This loop navigates the cursor so that it
  56018. ** points to the first interior cell that it points to the parent of
  56019. ** the next page in the tree that has not yet been visited. The
  56020. ** pCur->aiIdx[pCur->iPage] value is set to the index of the parent cell
  56021. ** of the page, or to the number of cells in the page if the next page
  56022. ** to visit is the right-child of its parent.
  56023. **
  56024. ** If all pages in the tree have been visited, return SQLITE_OK to the
  56025. ** caller.
  56026. */
  56027. if( pPage->leaf ){
  56028. do {
  56029. if( pCur->iPage==0 ){
  56030. /* All pages of the b-tree have been visited. Return successfully. */
  56031. *pnEntry = nEntry;
  56032. return SQLITE_OK;
  56033. }
  56034. moveToParent(pCur);
  56035. }while ( pCur->aiIdx[pCur->iPage]>=pCur->apPage[pCur->iPage]->nCell );
  56036. pCur->aiIdx[pCur->iPage]++;
  56037. pPage = pCur->apPage[pCur->iPage];
  56038. }
  56039. /* Descend to the child node of the cell that the cursor currently
  56040. ** points at. This is the right-child if (iIdx==pPage->nCell).
  56041. */
  56042. iIdx = pCur->aiIdx[pCur->iPage];
  56043. if( iIdx==pPage->nCell ){
  56044. rc = moveToChild(pCur, get4byte(&pPage->aData[pPage->hdrOffset+8]));
  56045. }else{
  56046. rc = moveToChild(pCur, get4byte(findCell(pPage, iIdx)));
  56047. }
  56048. }
  56049. /* An error has occurred. Return an error code. */
  56050. return rc;
  56051. }
  56052. #endif
  56053. /*
  56054. ** Return the pager associated with a BTree. This routine is used for
  56055. ** testing and debugging only.
  56056. */
  56057. SQLITE_PRIVATE Pager *sqlite3BtreePager(Btree *p){
  56058. return p->pBt->pPager;
  56059. }
  56060. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56061. /*
  56062. ** Append a message to the error message string.
  56063. */
  56064. static void checkAppendMsg(
  56065. IntegrityCk *pCheck,
  56066. const char *zFormat,
  56067. ...
  56068. ){
  56069. va_list ap;
  56070. char zBuf[200];
  56071. if( !pCheck->mxErr ) return;
  56072. pCheck->mxErr--;
  56073. pCheck->nErr++;
  56074. va_start(ap, zFormat);
  56075. if( pCheck->errMsg.nChar ){
  56076. sqlite3StrAccumAppend(&pCheck->errMsg, "\n", 1);
  56077. }
  56078. if( pCheck->zPfx ){
  56079. sqlite3_snprintf(sizeof(zBuf), zBuf, pCheck->zPfx, pCheck->v1, pCheck->v2);
  56080. sqlite3StrAccumAppendAll(&pCheck->errMsg, zBuf);
  56081. }
  56082. sqlite3VXPrintf(&pCheck->errMsg, 1, zFormat, ap);
  56083. va_end(ap);
  56084. if( pCheck->errMsg.accError==STRACCUM_NOMEM ){
  56085. pCheck->mallocFailed = 1;
  56086. }
  56087. }
  56088. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56089. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56090. /*
  56091. ** Return non-zero if the bit in the IntegrityCk.aPgRef[] array that
  56092. ** corresponds to page iPg is already set.
  56093. */
  56094. static int getPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  56095. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  56096. return (pCheck->aPgRef[iPg/8] & (1 << (iPg & 0x07)));
  56097. }
  56098. /*
  56099. ** Set the bit in the IntegrityCk.aPgRef[] array that corresponds to page iPg.
  56100. */
  56101. static void setPageReferenced(IntegrityCk *pCheck, Pgno iPg){
  56102. assert( iPg<=pCheck->nPage && sizeof(pCheck->aPgRef[0])==1 );
  56103. pCheck->aPgRef[iPg/8] |= (1 << (iPg & 0x07));
  56104. }
  56105. /*
  56106. ** Add 1 to the reference count for page iPage. If this is the second
  56107. ** reference to the page, add an error message to pCheck->zErrMsg.
  56108. ** Return 1 if there are 2 or more references to the page and 0 if
  56109. ** if this is the first reference to the page.
  56110. **
  56111. ** Also check that the page number is in bounds.
  56112. */
  56113. static int checkRef(IntegrityCk *pCheck, Pgno iPage){
  56114. if( iPage==0 ) return 1;
  56115. if( iPage>pCheck->nPage ){
  56116. checkAppendMsg(pCheck, "invalid page number %d", iPage);
  56117. return 1;
  56118. }
  56119. if( getPageReferenced(pCheck, iPage) ){
  56120. checkAppendMsg(pCheck, "2nd reference to page %d", iPage);
  56121. return 1;
  56122. }
  56123. setPageReferenced(pCheck, iPage);
  56124. return 0;
  56125. }
  56126. #ifndef SQLITE_OMIT_AUTOVACUUM
  56127. /*
  56128. ** Check that the entry in the pointer-map for page iChild maps to
  56129. ** page iParent, pointer type ptrType. If not, append an error message
  56130. ** to pCheck.
  56131. */
  56132. static void checkPtrmap(
  56133. IntegrityCk *pCheck, /* Integrity check context */
  56134. Pgno iChild, /* Child page number */
  56135. u8 eType, /* Expected pointer map type */
  56136. Pgno iParent /* Expected pointer map parent page number */
  56137. ){
  56138. int rc;
  56139. u8 ePtrmapType;
  56140. Pgno iPtrmapParent;
  56141. rc = ptrmapGet(pCheck->pBt, iChild, &ePtrmapType, &iPtrmapParent);
  56142. if( rc!=SQLITE_OK ){
  56143. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ) pCheck->mallocFailed = 1;
  56144. checkAppendMsg(pCheck, "Failed to read ptrmap key=%d", iChild);
  56145. return;
  56146. }
  56147. if( ePtrmapType!=eType || iPtrmapParent!=iParent ){
  56148. checkAppendMsg(pCheck,
  56149. "Bad ptr map entry key=%d expected=(%d,%d) got=(%d,%d)",
  56150. iChild, eType, iParent, ePtrmapType, iPtrmapParent);
  56151. }
  56152. }
  56153. #endif
  56154. /*
  56155. ** Check the integrity of the freelist or of an overflow page list.
  56156. ** Verify that the number of pages on the list is N.
  56157. */
  56158. static void checkList(
  56159. IntegrityCk *pCheck, /* Integrity checking context */
  56160. int isFreeList, /* True for a freelist. False for overflow page list */
  56161. int iPage, /* Page number for first page in the list */
  56162. int N /* Expected number of pages in the list */
  56163. ){
  56164. int i;
  56165. int expected = N;
  56166. int iFirst = iPage;
  56167. while( N-- > 0 && pCheck->mxErr ){
  56168. DbPage *pOvflPage;
  56169. unsigned char *pOvflData;
  56170. if( iPage<1 ){
  56171. checkAppendMsg(pCheck,
  56172. "%d of %d pages missing from overflow list starting at %d",
  56173. N+1, expected, iFirst);
  56174. break;
  56175. }
  56176. if( checkRef(pCheck, iPage) ) break;
  56177. if( sqlite3PagerGet(pCheck->pPager, (Pgno)iPage, &pOvflPage) ){
  56178. checkAppendMsg(pCheck, "failed to get page %d", iPage);
  56179. break;
  56180. }
  56181. pOvflData = (unsigned char *)sqlite3PagerGetData(pOvflPage);
  56182. if( isFreeList ){
  56183. int n = get4byte(&pOvflData[4]);
  56184. #ifndef SQLITE_OMIT_AUTOVACUUM
  56185. if( pCheck->pBt->autoVacuum ){
  56186. checkPtrmap(pCheck, iPage, PTRMAP_FREEPAGE, 0);
  56187. }
  56188. #endif
  56189. if( n>(int)pCheck->pBt->usableSize/4-2 ){
  56190. checkAppendMsg(pCheck,
  56191. "freelist leaf count too big on page %d", iPage);
  56192. N--;
  56193. }else{
  56194. for(i=0; i<n; i++){
  56195. Pgno iFreePage = get4byte(&pOvflData[8+i*4]);
  56196. #ifndef SQLITE_OMIT_AUTOVACUUM
  56197. if( pCheck->pBt->autoVacuum ){
  56198. checkPtrmap(pCheck, iFreePage, PTRMAP_FREEPAGE, 0);
  56199. }
  56200. #endif
  56201. checkRef(pCheck, iFreePage);
  56202. }
  56203. N -= n;
  56204. }
  56205. }
  56206. #ifndef SQLITE_OMIT_AUTOVACUUM
  56207. else{
  56208. /* If this database supports auto-vacuum and iPage is not the last
  56209. ** page in this overflow list, check that the pointer-map entry for
  56210. ** the following page matches iPage.
  56211. */
  56212. if( pCheck->pBt->autoVacuum && N>0 ){
  56213. i = get4byte(pOvflData);
  56214. checkPtrmap(pCheck, i, PTRMAP_OVERFLOW2, iPage);
  56215. }
  56216. }
  56217. #endif
  56218. iPage = get4byte(pOvflData);
  56219. sqlite3PagerUnref(pOvflPage);
  56220. }
  56221. }
  56222. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56223. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56224. /*
  56225. ** Do various sanity checks on a single page of a tree. Return
  56226. ** the tree depth. Root pages return 0. Parents of root pages
  56227. ** return 1, and so forth.
  56228. **
  56229. ** These checks are done:
  56230. **
  56231. ** 1. Make sure that cells and freeblocks do not overlap
  56232. ** but combine to completely cover the page.
  56233. ** NO 2. Make sure cell keys are in order.
  56234. ** NO 3. Make sure no key is less than or equal to zLowerBound.
  56235. ** NO 4. Make sure no key is greater than or equal to zUpperBound.
  56236. ** 5. Check the integrity of overflow pages.
  56237. ** 6. Recursively call checkTreePage on all children.
  56238. ** 7. Verify that the depth of all children is the same.
  56239. ** 8. Make sure this page is at least 33% full or else it is
  56240. ** the root of the tree.
  56241. */
  56242. static int checkTreePage(
  56243. IntegrityCk *pCheck, /* Context for the sanity check */
  56244. int iPage, /* Page number of the page to check */
  56245. i64 *pnParentMinKey,
  56246. i64 *pnParentMaxKey
  56247. ){
  56248. MemPage *pPage;
  56249. int i, rc, depth, d2, pgno, cnt;
  56250. int hdr, cellStart;
  56251. int nCell;
  56252. u8 *data;
  56253. BtShared *pBt;
  56254. int usableSize;
  56255. char *hit = 0;
  56256. i64 nMinKey = 0;
  56257. i64 nMaxKey = 0;
  56258. const char *saved_zPfx = pCheck->zPfx;
  56259. int saved_v1 = pCheck->v1;
  56260. int saved_v2 = pCheck->v2;
  56261. /* Check that the page exists
  56262. */
  56263. pBt = pCheck->pBt;
  56264. usableSize = pBt->usableSize;
  56265. if( iPage==0 ) return 0;
  56266. if( checkRef(pCheck, iPage) ) return 0;
  56267. pCheck->zPfx = "Page %d: ";
  56268. pCheck->v1 = iPage;
  56269. if( (rc = btreeGetPage(pBt, (Pgno)iPage, &pPage, 0))!=0 ){
  56270. checkAppendMsg(pCheck,
  56271. "unable to get the page. error code=%d", rc);
  56272. depth = -1;
  56273. goto end_of_check;
  56274. }
  56275. /* Clear MemPage.isInit to make sure the corruption detection code in
  56276. ** btreeInitPage() is executed. */
  56277. pPage->isInit = 0;
  56278. if( (rc = btreeInitPage(pPage))!=0 ){
  56279. assert( rc==SQLITE_CORRUPT ); /* The only possible error from InitPage */
  56280. checkAppendMsg(pCheck,
  56281. "btreeInitPage() returns error code %d", rc);
  56282. releasePage(pPage);
  56283. depth = -1;
  56284. goto end_of_check;
  56285. }
  56286. /* Check out all the cells.
  56287. */
  56288. depth = 0;
  56289. for(i=0; i<pPage->nCell && pCheck->mxErr; i++){
  56290. u8 *pCell;
  56291. u32 sz;
  56292. CellInfo info;
  56293. /* Check payload overflow pages
  56294. */
  56295. pCheck->zPfx = "On tree page %d cell %d: ";
  56296. pCheck->v1 = iPage;
  56297. pCheck->v2 = i;
  56298. pCell = findCell(pPage,i);
  56299. btreeParseCellPtr(pPage, pCell, &info);
  56300. sz = info.nPayload;
  56301. /* For intKey pages, check that the keys are in order.
  56302. */
  56303. if( pPage->intKey ){
  56304. if( i==0 ){
  56305. nMinKey = nMaxKey = info.nKey;
  56306. }else if( info.nKey <= nMaxKey ){
  56307. checkAppendMsg(pCheck,
  56308. "Rowid %lld out of order (previous was %lld)", info.nKey, nMaxKey);
  56309. }
  56310. nMaxKey = info.nKey;
  56311. }
  56312. if( (sz>info.nLocal)
  56313. && (&pCell[info.iOverflow]<=&pPage->aData[pBt->usableSize])
  56314. ){
  56315. int nPage = (sz - info.nLocal + usableSize - 5)/(usableSize - 4);
  56316. Pgno pgnoOvfl = get4byte(&pCell[info.iOverflow]);
  56317. #ifndef SQLITE_OMIT_AUTOVACUUM
  56318. if( pBt->autoVacuum ){
  56319. checkPtrmap(pCheck, pgnoOvfl, PTRMAP_OVERFLOW1, iPage);
  56320. }
  56321. #endif
  56322. checkList(pCheck, 0, pgnoOvfl, nPage);
  56323. }
  56324. /* Check sanity of left child page.
  56325. */
  56326. if( !pPage->leaf ){
  56327. pgno = get4byte(pCell);
  56328. #ifndef SQLITE_OMIT_AUTOVACUUM
  56329. if( pBt->autoVacuum ){
  56330. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  56331. }
  56332. #endif
  56333. d2 = checkTreePage(pCheck, pgno, &nMinKey, i==0?NULL:&nMaxKey);
  56334. if( i>0 && d2!=depth ){
  56335. checkAppendMsg(pCheck, "Child page depth differs");
  56336. }
  56337. depth = d2;
  56338. }
  56339. }
  56340. if( !pPage->leaf ){
  56341. pgno = get4byte(&pPage->aData[pPage->hdrOffset+8]);
  56342. pCheck->zPfx = "On page %d at right child: ";
  56343. pCheck->v1 = iPage;
  56344. #ifndef SQLITE_OMIT_AUTOVACUUM
  56345. if( pBt->autoVacuum ){
  56346. checkPtrmap(pCheck, pgno, PTRMAP_BTREE, iPage);
  56347. }
  56348. #endif
  56349. checkTreePage(pCheck, pgno, NULL, !pPage->nCell?NULL:&nMaxKey);
  56350. }
  56351. /* For intKey leaf pages, check that the min/max keys are in order
  56352. ** with any left/parent/right pages.
  56353. */
  56354. pCheck->zPfx = "Page %d: ";
  56355. pCheck->v1 = iPage;
  56356. if( pPage->leaf && pPage->intKey ){
  56357. /* if we are a left child page */
  56358. if( pnParentMinKey ){
  56359. /* if we are the left most child page */
  56360. if( !pnParentMaxKey ){
  56361. if( nMaxKey > *pnParentMinKey ){
  56362. checkAppendMsg(pCheck,
  56363. "Rowid %lld out of order (max larger than parent min of %lld)",
  56364. nMaxKey, *pnParentMinKey);
  56365. }
  56366. }else{
  56367. if( nMinKey <= *pnParentMinKey ){
  56368. checkAppendMsg(pCheck,
  56369. "Rowid %lld out of order (min less than parent min of %lld)",
  56370. nMinKey, *pnParentMinKey);
  56371. }
  56372. if( nMaxKey > *pnParentMaxKey ){
  56373. checkAppendMsg(pCheck,
  56374. "Rowid %lld out of order (max larger than parent max of %lld)",
  56375. nMaxKey, *pnParentMaxKey);
  56376. }
  56377. *pnParentMinKey = nMaxKey;
  56378. }
  56379. /* else if we're a right child page */
  56380. } else if( pnParentMaxKey ){
  56381. if( nMinKey <= *pnParentMaxKey ){
  56382. checkAppendMsg(pCheck,
  56383. "Rowid %lld out of order (min less than parent max of %lld)",
  56384. nMinKey, *pnParentMaxKey);
  56385. }
  56386. }
  56387. }
  56388. /* Check for complete coverage of the page
  56389. */
  56390. data = pPage->aData;
  56391. hdr = pPage->hdrOffset;
  56392. hit = sqlite3PageMalloc( pBt->pageSize );
  56393. pCheck->zPfx = 0;
  56394. if( hit==0 ){
  56395. pCheck->mallocFailed = 1;
  56396. }else{
  56397. int contentOffset = get2byteNotZero(&data[hdr+5]);
  56398. assert( contentOffset<=usableSize ); /* Enforced by btreeInitPage() */
  56399. memset(hit+contentOffset, 0, usableSize-contentOffset);
  56400. memset(hit, 1, contentOffset);
  56401. nCell = get2byte(&data[hdr+3]);
  56402. cellStart = hdr + 12 - 4*pPage->leaf;
  56403. for(i=0; i<nCell; i++){
  56404. int pc = get2byte(&data[cellStart+i*2]);
  56405. u32 size = 65536;
  56406. int j;
  56407. if( pc<=usableSize-4 ){
  56408. size = cellSizePtr(pPage, &data[pc]);
  56409. }
  56410. if( (int)(pc+size-1)>=usableSize ){
  56411. pCheck->zPfx = 0;
  56412. checkAppendMsg(pCheck,
  56413. "Corruption detected in cell %d on page %d",i,iPage);
  56414. }else{
  56415. for(j=pc+size-1; j>=pc; j--) hit[j]++;
  56416. }
  56417. }
  56418. i = get2byte(&data[hdr+1]);
  56419. while( i>0 ){
  56420. int size, j;
  56421. assert( i<=usableSize-4 ); /* Enforced by btreeInitPage() */
  56422. size = get2byte(&data[i+2]);
  56423. assert( i+size<=usableSize ); /* Enforced by btreeInitPage() */
  56424. for(j=i+size-1; j>=i; j--) hit[j]++;
  56425. j = get2byte(&data[i]);
  56426. assert( j==0 || j>i+size ); /* Enforced by btreeInitPage() */
  56427. assert( j<=usableSize-4 ); /* Enforced by btreeInitPage() */
  56428. i = j;
  56429. }
  56430. for(i=cnt=0; i<usableSize; i++){
  56431. if( hit[i]==0 ){
  56432. cnt++;
  56433. }else if( hit[i]>1 ){
  56434. checkAppendMsg(pCheck,
  56435. "Multiple uses for byte %d of page %d", i, iPage);
  56436. break;
  56437. }
  56438. }
  56439. if( cnt!=data[hdr+7] ){
  56440. checkAppendMsg(pCheck,
  56441. "Fragmentation of %d bytes reported as %d on page %d",
  56442. cnt, data[hdr+7], iPage);
  56443. }
  56444. }
  56445. sqlite3PageFree(hit);
  56446. releasePage(pPage);
  56447. end_of_check:
  56448. pCheck->zPfx = saved_zPfx;
  56449. pCheck->v1 = saved_v1;
  56450. pCheck->v2 = saved_v2;
  56451. return depth+1;
  56452. }
  56453. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56454. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  56455. /*
  56456. ** This routine does a complete check of the given BTree file. aRoot[] is
  56457. ** an array of pages numbers were each page number is the root page of
  56458. ** a table. nRoot is the number of entries in aRoot.
  56459. **
  56460. ** A read-only or read-write transaction must be opened before calling
  56461. ** this function.
  56462. **
  56463. ** Write the number of error seen in *pnErr. Except for some memory
  56464. ** allocation errors, an error message held in memory obtained from
  56465. ** malloc is returned if *pnErr is non-zero. If *pnErr==0 then NULL is
  56466. ** returned. If a memory allocation error occurs, NULL is returned.
  56467. */
  56468. SQLITE_PRIVATE char *sqlite3BtreeIntegrityCheck(
  56469. Btree *p, /* The btree to be checked */
  56470. int *aRoot, /* An array of root pages numbers for individual trees */
  56471. int nRoot, /* Number of entries in aRoot[] */
  56472. int mxErr, /* Stop reporting errors after this many */
  56473. int *pnErr /* Write number of errors seen to this variable */
  56474. ){
  56475. Pgno i;
  56476. int nRef;
  56477. IntegrityCk sCheck;
  56478. BtShared *pBt = p->pBt;
  56479. char zErr[100];
  56480. sqlite3BtreeEnter(p);
  56481. assert( p->inTrans>TRANS_NONE && pBt->inTransaction>TRANS_NONE );
  56482. nRef = sqlite3PagerRefcount(pBt->pPager);
  56483. sCheck.pBt = pBt;
  56484. sCheck.pPager = pBt->pPager;
  56485. sCheck.nPage = btreePagecount(sCheck.pBt);
  56486. sCheck.mxErr = mxErr;
  56487. sCheck.nErr = 0;
  56488. sCheck.mallocFailed = 0;
  56489. sCheck.zPfx = 0;
  56490. sCheck.v1 = 0;
  56491. sCheck.v2 = 0;
  56492. *pnErr = 0;
  56493. if( sCheck.nPage==0 ){
  56494. sqlite3BtreeLeave(p);
  56495. return 0;
  56496. }
  56497. sCheck.aPgRef = sqlite3MallocZero((sCheck.nPage / 8)+ 1);
  56498. if( !sCheck.aPgRef ){
  56499. *pnErr = 1;
  56500. sqlite3BtreeLeave(p);
  56501. return 0;
  56502. }
  56503. i = PENDING_BYTE_PAGE(pBt);
  56504. if( i<=sCheck.nPage ) setPageReferenced(&sCheck, i);
  56505. sqlite3StrAccumInit(&sCheck.errMsg, zErr, sizeof(zErr), SQLITE_MAX_LENGTH);
  56506. sCheck.errMsg.useMalloc = 2;
  56507. /* Check the integrity of the freelist
  56508. */
  56509. sCheck.zPfx = "Main freelist: ";
  56510. checkList(&sCheck, 1, get4byte(&pBt->pPage1->aData[32]),
  56511. get4byte(&pBt->pPage1->aData[36]));
  56512. sCheck.zPfx = 0;
  56513. /* Check all the tables.
  56514. */
  56515. for(i=0; (int)i<nRoot && sCheck.mxErr; i++){
  56516. if( aRoot[i]==0 ) continue;
  56517. #ifndef SQLITE_OMIT_AUTOVACUUM
  56518. if( pBt->autoVacuum && aRoot[i]>1 ){
  56519. checkPtrmap(&sCheck, aRoot[i], PTRMAP_ROOTPAGE, 0);
  56520. }
  56521. #endif
  56522. sCheck.zPfx = "List of tree roots: ";
  56523. checkTreePage(&sCheck, aRoot[i], NULL, NULL);
  56524. sCheck.zPfx = 0;
  56525. }
  56526. /* Make sure every page in the file is referenced
  56527. */
  56528. for(i=1; i<=sCheck.nPage && sCheck.mxErr; i++){
  56529. #ifdef SQLITE_OMIT_AUTOVACUUM
  56530. if( getPageReferenced(&sCheck, i)==0 ){
  56531. checkAppendMsg(&sCheck, "Page %d is never used", i);
  56532. }
  56533. #else
  56534. /* If the database supports auto-vacuum, make sure no tables contain
  56535. ** references to pointer-map pages.
  56536. */
  56537. if( getPageReferenced(&sCheck, i)==0 &&
  56538. (PTRMAP_PAGENO(pBt, i)!=i || !pBt->autoVacuum) ){
  56539. checkAppendMsg(&sCheck, "Page %d is never used", i);
  56540. }
  56541. if( getPageReferenced(&sCheck, i)!=0 &&
  56542. (PTRMAP_PAGENO(pBt, i)==i && pBt->autoVacuum) ){
  56543. checkAppendMsg(&sCheck, "Pointer map page %d is referenced", i);
  56544. }
  56545. #endif
  56546. }
  56547. /* Make sure this analysis did not leave any unref() pages.
  56548. ** This is an internal consistency check; an integrity check
  56549. ** of the integrity check.
  56550. */
  56551. if( NEVER(nRef != sqlite3PagerRefcount(pBt->pPager)) ){
  56552. checkAppendMsg(&sCheck,
  56553. "Outstanding page count goes from %d to %d during this analysis",
  56554. nRef, sqlite3PagerRefcount(pBt->pPager)
  56555. );
  56556. }
  56557. /* Clean up and report errors.
  56558. */
  56559. sqlite3BtreeLeave(p);
  56560. sqlite3_free(sCheck.aPgRef);
  56561. if( sCheck.mallocFailed ){
  56562. sqlite3StrAccumReset(&sCheck.errMsg);
  56563. *pnErr = sCheck.nErr+1;
  56564. return 0;
  56565. }
  56566. *pnErr = sCheck.nErr;
  56567. if( sCheck.nErr==0 ) sqlite3StrAccumReset(&sCheck.errMsg);
  56568. return sqlite3StrAccumFinish(&sCheck.errMsg);
  56569. }
  56570. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  56571. /*
  56572. ** Return the full pathname of the underlying database file. Return
  56573. ** an empty string if the database is in-memory or a TEMP database.
  56574. **
  56575. ** The pager filename is invariant as long as the pager is
  56576. ** open so it is safe to access without the BtShared mutex.
  56577. */
  56578. SQLITE_PRIVATE const char *sqlite3BtreeGetFilename(Btree *p){
  56579. assert( p->pBt->pPager!=0 );
  56580. return sqlite3PagerFilename(p->pBt->pPager, 1);
  56581. }
  56582. /*
  56583. ** Return the pathname of the journal file for this database. The return
  56584. ** value of this routine is the same regardless of whether the journal file
  56585. ** has been created or not.
  56586. **
  56587. ** The pager journal filename is invariant as long as the pager is
  56588. ** open so it is safe to access without the BtShared mutex.
  56589. */
  56590. SQLITE_PRIVATE const char *sqlite3BtreeGetJournalname(Btree *p){
  56591. assert( p->pBt->pPager!=0 );
  56592. return sqlite3PagerJournalname(p->pBt->pPager);
  56593. }
  56594. /*
  56595. ** Return non-zero if a transaction is active.
  56596. */
  56597. SQLITE_PRIVATE int sqlite3BtreeIsInTrans(Btree *p){
  56598. assert( p==0 || sqlite3_mutex_held(p->db->mutex) );
  56599. return (p && (p->inTrans==TRANS_WRITE));
  56600. }
  56601. #ifndef SQLITE_OMIT_WAL
  56602. /*
  56603. ** Run a checkpoint on the Btree passed as the first argument.
  56604. **
  56605. ** Return SQLITE_LOCKED if this or any other connection has an open
  56606. ** transaction on the shared-cache the argument Btree is connected to.
  56607. **
  56608. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  56609. */
  56610. SQLITE_PRIVATE int sqlite3BtreeCheckpoint(Btree *p, int eMode, int *pnLog, int *pnCkpt){
  56611. int rc = SQLITE_OK;
  56612. if( p ){
  56613. BtShared *pBt = p->pBt;
  56614. sqlite3BtreeEnter(p);
  56615. if( pBt->inTransaction!=TRANS_NONE ){
  56616. rc = SQLITE_LOCKED;
  56617. }else{
  56618. rc = sqlite3PagerCheckpoint(pBt->pPager, eMode, pnLog, pnCkpt);
  56619. }
  56620. sqlite3BtreeLeave(p);
  56621. }
  56622. return rc;
  56623. }
  56624. #endif
  56625. /*
  56626. ** Return non-zero if a read (or write) transaction is active.
  56627. */
  56628. SQLITE_PRIVATE int sqlite3BtreeIsInReadTrans(Btree *p){
  56629. assert( p );
  56630. assert( sqlite3_mutex_held(p->db->mutex) );
  56631. return p->inTrans!=TRANS_NONE;
  56632. }
  56633. SQLITE_PRIVATE int sqlite3BtreeIsInBackup(Btree *p){
  56634. assert( p );
  56635. assert( sqlite3_mutex_held(p->db->mutex) );
  56636. return p->nBackup!=0;
  56637. }
  56638. /*
  56639. ** This function returns a pointer to a blob of memory associated with
  56640. ** a single shared-btree. The memory is used by client code for its own
  56641. ** purposes (for example, to store a high-level schema associated with
  56642. ** the shared-btree). The btree layer manages reference counting issues.
  56643. **
  56644. ** The first time this is called on a shared-btree, nBytes bytes of memory
  56645. ** are allocated, zeroed, and returned to the caller. For each subsequent
  56646. ** call the nBytes parameter is ignored and a pointer to the same blob
  56647. ** of memory returned.
  56648. **
  56649. ** If the nBytes parameter is 0 and the blob of memory has not yet been
  56650. ** allocated, a null pointer is returned. If the blob has already been
  56651. ** allocated, it is returned as normal.
  56652. **
  56653. ** Just before the shared-btree is closed, the function passed as the
  56654. ** xFree argument when the memory allocation was made is invoked on the
  56655. ** blob of allocated memory. The xFree function should not call sqlite3_free()
  56656. ** on the memory, the btree layer does that.
  56657. */
  56658. SQLITE_PRIVATE void *sqlite3BtreeSchema(Btree *p, int nBytes, void(*xFree)(void *)){
  56659. BtShared *pBt = p->pBt;
  56660. sqlite3BtreeEnter(p);
  56661. if( !pBt->pSchema && nBytes ){
  56662. pBt->pSchema = sqlite3DbMallocZero(0, nBytes);
  56663. pBt->xFreeSchema = xFree;
  56664. }
  56665. sqlite3BtreeLeave(p);
  56666. return pBt->pSchema;
  56667. }
  56668. /*
  56669. ** Return SQLITE_LOCKED_SHAREDCACHE if another user of the same shared
  56670. ** btree as the argument handle holds an exclusive lock on the
  56671. ** sqlite_master table. Otherwise SQLITE_OK.
  56672. */
  56673. SQLITE_PRIVATE int sqlite3BtreeSchemaLocked(Btree *p){
  56674. int rc;
  56675. assert( sqlite3_mutex_held(p->db->mutex) );
  56676. sqlite3BtreeEnter(p);
  56677. rc = querySharedCacheTableLock(p, MASTER_ROOT, READ_LOCK);
  56678. assert( rc==SQLITE_OK || rc==SQLITE_LOCKED_SHAREDCACHE );
  56679. sqlite3BtreeLeave(p);
  56680. return rc;
  56681. }
  56682. #ifndef SQLITE_OMIT_SHARED_CACHE
  56683. /*
  56684. ** Obtain a lock on the table whose root page is iTab. The
  56685. ** lock is a write lock if isWritelock is true or a read lock
  56686. ** if it is false.
  56687. */
  56688. SQLITE_PRIVATE int sqlite3BtreeLockTable(Btree *p, int iTab, u8 isWriteLock){
  56689. int rc = SQLITE_OK;
  56690. assert( p->inTrans!=TRANS_NONE );
  56691. if( p->sharable ){
  56692. u8 lockType = READ_LOCK + isWriteLock;
  56693. assert( READ_LOCK+1==WRITE_LOCK );
  56694. assert( isWriteLock==0 || isWriteLock==1 );
  56695. sqlite3BtreeEnter(p);
  56696. rc = querySharedCacheTableLock(p, iTab, lockType);
  56697. if( rc==SQLITE_OK ){
  56698. rc = setSharedCacheTableLock(p, iTab, lockType);
  56699. }
  56700. sqlite3BtreeLeave(p);
  56701. }
  56702. return rc;
  56703. }
  56704. #endif
  56705. #ifndef SQLITE_OMIT_INCRBLOB
  56706. /*
  56707. ** Argument pCsr must be a cursor opened for writing on an
  56708. ** INTKEY table currently pointing at a valid table entry.
  56709. ** This function modifies the data stored as part of that entry.
  56710. **
  56711. ** Only the data content may only be modified, it is not possible to
  56712. ** change the length of the data stored. If this function is called with
  56713. ** parameters that attempt to write past the end of the existing data,
  56714. ** no modifications are made and SQLITE_CORRUPT is returned.
  56715. */
  56716. SQLITE_PRIVATE int sqlite3BtreePutData(BtCursor *pCsr, u32 offset, u32 amt, void *z){
  56717. int rc;
  56718. assert( cursorHoldsMutex(pCsr) );
  56719. assert( sqlite3_mutex_held(pCsr->pBtree->db->mutex) );
  56720. assert( pCsr->curFlags & BTCF_Incrblob );
  56721. rc = restoreCursorPosition(pCsr);
  56722. if( rc!=SQLITE_OK ){
  56723. return rc;
  56724. }
  56725. assert( pCsr->eState!=CURSOR_REQUIRESEEK );
  56726. if( pCsr->eState!=CURSOR_VALID ){
  56727. return SQLITE_ABORT;
  56728. }
  56729. /* Save the positions of all other cursors open on this table. This is
  56730. ** required in case any of them are holding references to an xFetch
  56731. ** version of the b-tree page modified by the accessPayload call below.
  56732. **
  56733. ** Note that pCsr must be open on a INTKEY table and saveCursorPosition()
  56734. ** and hence saveAllCursors() cannot fail on a BTREE_INTKEY table, hence
  56735. ** saveAllCursors can only return SQLITE_OK.
  56736. */
  56737. VVA_ONLY(rc =) saveAllCursors(pCsr->pBt, pCsr->pgnoRoot, pCsr);
  56738. assert( rc==SQLITE_OK );
  56739. /* Check some assumptions:
  56740. ** (a) the cursor is open for writing,
  56741. ** (b) there is a read/write transaction open,
  56742. ** (c) the connection holds a write-lock on the table (if required),
  56743. ** (d) there are no conflicting read-locks, and
  56744. ** (e) the cursor points at a valid row of an intKey table.
  56745. */
  56746. if( (pCsr->curFlags & BTCF_WriteFlag)==0 ){
  56747. return SQLITE_READONLY;
  56748. }
  56749. assert( (pCsr->pBt->btsFlags & BTS_READ_ONLY)==0
  56750. && pCsr->pBt->inTransaction==TRANS_WRITE );
  56751. assert( hasSharedCacheTableLock(pCsr->pBtree, pCsr->pgnoRoot, 0, 2) );
  56752. assert( !hasReadConflicts(pCsr->pBtree, pCsr->pgnoRoot) );
  56753. assert( pCsr->apPage[pCsr->iPage]->intKey );
  56754. return accessPayload(pCsr, offset, amt, (unsigned char *)z, 1);
  56755. }
  56756. /*
  56757. ** Mark this cursor as an incremental blob cursor.
  56758. */
  56759. SQLITE_PRIVATE void sqlite3BtreeIncrblobCursor(BtCursor *pCur){
  56760. pCur->curFlags |= BTCF_Incrblob;
  56761. }
  56762. #endif
  56763. /*
  56764. ** Set both the "read version" (single byte at byte offset 18) and
  56765. ** "write version" (single byte at byte offset 19) fields in the database
  56766. ** header to iVersion.
  56767. */
  56768. SQLITE_PRIVATE int sqlite3BtreeSetVersion(Btree *pBtree, int iVersion){
  56769. BtShared *pBt = pBtree->pBt;
  56770. int rc; /* Return code */
  56771. assert( iVersion==1 || iVersion==2 );
  56772. /* If setting the version fields to 1, do not automatically open the
  56773. ** WAL connection, even if the version fields are currently set to 2.
  56774. */
  56775. pBt->btsFlags &= ~BTS_NO_WAL;
  56776. if( iVersion==1 ) pBt->btsFlags |= BTS_NO_WAL;
  56777. rc = sqlite3BtreeBeginTrans(pBtree, 0);
  56778. if( rc==SQLITE_OK ){
  56779. u8 *aData = pBt->pPage1->aData;
  56780. if( aData[18]!=(u8)iVersion || aData[19]!=(u8)iVersion ){
  56781. rc = sqlite3BtreeBeginTrans(pBtree, 2);
  56782. if( rc==SQLITE_OK ){
  56783. rc = sqlite3PagerWrite(pBt->pPage1->pDbPage);
  56784. if( rc==SQLITE_OK ){
  56785. aData[18] = (u8)iVersion;
  56786. aData[19] = (u8)iVersion;
  56787. }
  56788. }
  56789. }
  56790. }
  56791. pBt->btsFlags &= ~BTS_NO_WAL;
  56792. return rc;
  56793. }
  56794. /*
  56795. ** set the mask of hint flags for cursor pCsr. Currently the only valid
  56796. ** values are 0 and BTREE_BULKLOAD.
  56797. */
  56798. SQLITE_PRIVATE void sqlite3BtreeCursorHints(BtCursor *pCsr, unsigned int mask){
  56799. assert( mask==BTREE_BULKLOAD || mask==0 );
  56800. pCsr->hints = mask;
  56801. }
  56802. /*
  56803. ** Return true if the given Btree is read-only.
  56804. */
  56805. SQLITE_PRIVATE int sqlite3BtreeIsReadonly(Btree *p){
  56806. return (p->pBt->btsFlags & BTS_READ_ONLY)!=0;
  56807. }
  56808. /************** End of btree.c ***********************************************/
  56809. /************** Begin file backup.c ******************************************/
  56810. /*
  56811. ** 2009 January 28
  56812. **
  56813. ** The author disclaims copyright to this source code. In place of
  56814. ** a legal notice, here is a blessing:
  56815. **
  56816. ** May you do good and not evil.
  56817. ** May you find forgiveness for yourself and forgive others.
  56818. ** May you share freely, never taking more than you give.
  56819. **
  56820. *************************************************************************
  56821. ** This file contains the implementation of the sqlite3_backup_XXX()
  56822. ** API functions and the related features.
  56823. */
  56824. /*
  56825. ** Structure allocated for each backup operation.
  56826. */
  56827. struct sqlite3_backup {
  56828. sqlite3* pDestDb; /* Destination database handle */
  56829. Btree *pDest; /* Destination b-tree file */
  56830. u32 iDestSchema; /* Original schema cookie in destination */
  56831. int bDestLocked; /* True once a write-transaction is open on pDest */
  56832. Pgno iNext; /* Page number of the next source page to copy */
  56833. sqlite3* pSrcDb; /* Source database handle */
  56834. Btree *pSrc; /* Source b-tree file */
  56835. int rc; /* Backup process error code */
  56836. /* These two variables are set by every call to backup_step(). They are
  56837. ** read by calls to backup_remaining() and backup_pagecount().
  56838. */
  56839. Pgno nRemaining; /* Number of pages left to copy */
  56840. Pgno nPagecount; /* Total number of pages to copy */
  56841. int isAttached; /* True once backup has been registered with pager */
  56842. sqlite3_backup *pNext; /* Next backup associated with source pager */
  56843. };
  56844. /*
  56845. ** THREAD SAFETY NOTES:
  56846. **
  56847. ** Once it has been created using backup_init(), a single sqlite3_backup
  56848. ** structure may be accessed via two groups of thread-safe entry points:
  56849. **
  56850. ** * Via the sqlite3_backup_XXX() API function backup_step() and
  56851. ** backup_finish(). Both these functions obtain the source database
  56852. ** handle mutex and the mutex associated with the source BtShared
  56853. ** structure, in that order.
  56854. **
  56855. ** * Via the BackupUpdate() and BackupRestart() functions, which are
  56856. ** invoked by the pager layer to report various state changes in
  56857. ** the page cache associated with the source database. The mutex
  56858. ** associated with the source database BtShared structure will always
  56859. ** be held when either of these functions are invoked.
  56860. **
  56861. ** The other sqlite3_backup_XXX() API functions, backup_remaining() and
  56862. ** backup_pagecount() are not thread-safe functions. If they are called
  56863. ** while some other thread is calling backup_step() or backup_finish(),
  56864. ** the values returned may be invalid. There is no way for a call to
  56865. ** BackupUpdate() or BackupRestart() to interfere with backup_remaining()
  56866. ** or backup_pagecount().
  56867. **
  56868. ** Depending on the SQLite configuration, the database handles and/or
  56869. ** the Btree objects may have their own mutexes that require locking.
  56870. ** Non-sharable Btrees (in-memory databases for example), do not have
  56871. ** associated mutexes.
  56872. */
  56873. /*
  56874. ** Return a pointer corresponding to database zDb (i.e. "main", "temp")
  56875. ** in connection handle pDb. If such a database cannot be found, return
  56876. ** a NULL pointer and write an error message to pErrorDb.
  56877. **
  56878. ** If the "temp" database is requested, it may need to be opened by this
  56879. ** function. If an error occurs while doing so, return 0 and write an
  56880. ** error message to pErrorDb.
  56881. */
  56882. static Btree *findBtree(sqlite3 *pErrorDb, sqlite3 *pDb, const char *zDb){
  56883. int i = sqlite3FindDbName(pDb, zDb);
  56884. if( i==1 ){
  56885. Parse *pParse;
  56886. int rc = 0;
  56887. pParse = sqlite3StackAllocZero(pErrorDb, sizeof(*pParse));
  56888. if( pParse==0 ){
  56889. sqlite3ErrorWithMsg(pErrorDb, SQLITE_NOMEM, "out of memory");
  56890. rc = SQLITE_NOMEM;
  56891. }else{
  56892. pParse->db = pDb;
  56893. if( sqlite3OpenTempDatabase(pParse) ){
  56894. sqlite3ErrorWithMsg(pErrorDb, pParse->rc, "%s", pParse->zErrMsg);
  56895. rc = SQLITE_ERROR;
  56896. }
  56897. sqlite3DbFree(pErrorDb, pParse->zErrMsg);
  56898. sqlite3ParserReset(pParse);
  56899. sqlite3StackFree(pErrorDb, pParse);
  56900. }
  56901. if( rc ){
  56902. return 0;
  56903. }
  56904. }
  56905. if( i<0 ){
  56906. sqlite3ErrorWithMsg(pErrorDb, SQLITE_ERROR, "unknown database %s", zDb);
  56907. return 0;
  56908. }
  56909. return pDb->aDb[i].pBt;
  56910. }
  56911. /*
  56912. ** Attempt to set the page size of the destination to match the page size
  56913. ** of the source.
  56914. */
  56915. static int setDestPgsz(sqlite3_backup *p){
  56916. int rc;
  56917. rc = sqlite3BtreeSetPageSize(p->pDest,sqlite3BtreeGetPageSize(p->pSrc),-1,0);
  56918. return rc;
  56919. }
  56920. /*
  56921. ** Create an sqlite3_backup process to copy the contents of zSrcDb from
  56922. ** connection handle pSrcDb to zDestDb in pDestDb. If successful, return
  56923. ** a pointer to the new sqlite3_backup object.
  56924. **
  56925. ** If an error occurs, NULL is returned and an error code and error message
  56926. ** stored in database handle pDestDb.
  56927. */
  56928. SQLITE_API sqlite3_backup *sqlite3_backup_init(
  56929. sqlite3* pDestDb, /* Database to write to */
  56930. const char *zDestDb, /* Name of database within pDestDb */
  56931. sqlite3* pSrcDb, /* Database connection to read from */
  56932. const char *zSrcDb /* Name of database within pSrcDb */
  56933. ){
  56934. sqlite3_backup *p; /* Value to return */
  56935. /* Lock the source database handle. The destination database
  56936. ** handle is not locked in this routine, but it is locked in
  56937. ** sqlite3_backup_step(). The user is required to ensure that no
  56938. ** other thread accesses the destination handle for the duration
  56939. ** of the backup operation. Any attempt to use the destination
  56940. ** database connection while a backup is in progress may cause
  56941. ** a malfunction or a deadlock.
  56942. */
  56943. sqlite3_mutex_enter(pSrcDb->mutex);
  56944. sqlite3_mutex_enter(pDestDb->mutex);
  56945. if( pSrcDb==pDestDb ){
  56946. sqlite3ErrorWithMsg(
  56947. pDestDb, SQLITE_ERROR, "source and destination must be distinct"
  56948. );
  56949. p = 0;
  56950. }else {
  56951. /* Allocate space for a new sqlite3_backup object...
  56952. ** EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  56953. ** call to sqlite3_backup_init() and is destroyed by a call to
  56954. ** sqlite3_backup_finish(). */
  56955. p = (sqlite3_backup *)sqlite3MallocZero(sizeof(sqlite3_backup));
  56956. if( !p ){
  56957. sqlite3Error(pDestDb, SQLITE_NOMEM);
  56958. }
  56959. }
  56960. /* If the allocation succeeded, populate the new object. */
  56961. if( p ){
  56962. p->pSrc = findBtree(pDestDb, pSrcDb, zSrcDb);
  56963. p->pDest = findBtree(pDestDb, pDestDb, zDestDb);
  56964. p->pDestDb = pDestDb;
  56965. p->pSrcDb = pSrcDb;
  56966. p->iNext = 1;
  56967. p->isAttached = 0;
  56968. if( 0==p->pSrc || 0==p->pDest || setDestPgsz(p)==SQLITE_NOMEM ){
  56969. /* One (or both) of the named databases did not exist or an OOM
  56970. ** error was hit. The error has already been written into the
  56971. ** pDestDb handle. All that is left to do here is free the
  56972. ** sqlite3_backup structure.
  56973. */
  56974. sqlite3_free(p);
  56975. p = 0;
  56976. }
  56977. }
  56978. if( p ){
  56979. p->pSrc->nBackup++;
  56980. }
  56981. sqlite3_mutex_leave(pDestDb->mutex);
  56982. sqlite3_mutex_leave(pSrcDb->mutex);
  56983. return p;
  56984. }
  56985. /*
  56986. ** Argument rc is an SQLite error code. Return true if this error is
  56987. ** considered fatal if encountered during a backup operation. All errors
  56988. ** are considered fatal except for SQLITE_BUSY and SQLITE_LOCKED.
  56989. */
  56990. static int isFatalError(int rc){
  56991. return (rc!=SQLITE_OK && rc!=SQLITE_BUSY && ALWAYS(rc!=SQLITE_LOCKED));
  56992. }
  56993. /*
  56994. ** Parameter zSrcData points to a buffer containing the data for
  56995. ** page iSrcPg from the source database. Copy this data into the
  56996. ** destination database.
  56997. */
  56998. static int backupOnePage(
  56999. sqlite3_backup *p, /* Backup handle */
  57000. Pgno iSrcPg, /* Source database page to backup */
  57001. const u8 *zSrcData, /* Source database page data */
  57002. int bUpdate /* True for an update, false otherwise */
  57003. ){
  57004. Pager * const pDestPager = sqlite3BtreePager(p->pDest);
  57005. const int nSrcPgsz = sqlite3BtreeGetPageSize(p->pSrc);
  57006. int nDestPgsz = sqlite3BtreeGetPageSize(p->pDest);
  57007. const int nCopy = MIN(nSrcPgsz, nDestPgsz);
  57008. const i64 iEnd = (i64)iSrcPg*(i64)nSrcPgsz;
  57009. #ifdef SQLITE_HAS_CODEC
  57010. /* Use BtreeGetReserveNoMutex() for the source b-tree, as although it is
  57011. ** guaranteed that the shared-mutex is held by this thread, handle
  57012. ** p->pSrc may not actually be the owner. */
  57013. int nSrcReserve = sqlite3BtreeGetReserveNoMutex(p->pSrc);
  57014. int nDestReserve = sqlite3BtreeGetReserve(p->pDest);
  57015. #endif
  57016. int rc = SQLITE_OK;
  57017. i64 iOff;
  57018. assert( sqlite3BtreeGetReserveNoMutex(p->pSrc)>=0 );
  57019. assert( p->bDestLocked );
  57020. assert( !isFatalError(p->rc) );
  57021. assert( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) );
  57022. assert( zSrcData );
  57023. /* Catch the case where the destination is an in-memory database and the
  57024. ** page sizes of the source and destination differ.
  57025. */
  57026. if( nSrcPgsz!=nDestPgsz && sqlite3PagerIsMemdb(pDestPager) ){
  57027. rc = SQLITE_READONLY;
  57028. }
  57029. #ifdef SQLITE_HAS_CODEC
  57030. /* Backup is not possible if the page size of the destination is changing
  57031. ** and a codec is in use.
  57032. */
  57033. if( nSrcPgsz!=nDestPgsz && sqlite3PagerGetCodec(pDestPager)!=0 ){
  57034. rc = SQLITE_READONLY;
  57035. }
  57036. /* Backup is not possible if the number of bytes of reserve space differ
  57037. ** between source and destination. If there is a difference, try to
  57038. ** fix the destination to agree with the source. If that is not possible,
  57039. ** then the backup cannot proceed.
  57040. */
  57041. if( nSrcReserve!=nDestReserve ){
  57042. u32 newPgsz = nSrcPgsz;
  57043. rc = sqlite3PagerSetPagesize(pDestPager, &newPgsz, nSrcReserve);
  57044. if( rc==SQLITE_OK && newPgsz!=nSrcPgsz ) rc = SQLITE_READONLY;
  57045. }
  57046. #endif
  57047. /* This loop runs once for each destination page spanned by the source
  57048. ** page. For each iteration, variable iOff is set to the byte offset
  57049. ** of the destination page.
  57050. */
  57051. for(iOff=iEnd-(i64)nSrcPgsz; rc==SQLITE_OK && iOff<iEnd; iOff+=nDestPgsz){
  57052. DbPage *pDestPg = 0;
  57053. Pgno iDest = (Pgno)(iOff/nDestPgsz)+1;
  57054. if( iDest==PENDING_BYTE_PAGE(p->pDest->pBt) ) continue;
  57055. if( SQLITE_OK==(rc = sqlite3PagerGet(pDestPager, iDest, &pDestPg))
  57056. && SQLITE_OK==(rc = sqlite3PagerWrite(pDestPg))
  57057. ){
  57058. const u8 *zIn = &zSrcData[iOff%nSrcPgsz];
  57059. u8 *zDestData = sqlite3PagerGetData(pDestPg);
  57060. u8 *zOut = &zDestData[iOff%nDestPgsz];
  57061. /* Copy the data from the source page into the destination page.
  57062. ** Then clear the Btree layer MemPage.isInit flag. Both this module
  57063. ** and the pager code use this trick (clearing the first byte
  57064. ** of the page 'extra' space to invalidate the Btree layers
  57065. ** cached parse of the page). MemPage.isInit is marked
  57066. ** "MUST BE FIRST" for this purpose.
  57067. */
  57068. memcpy(zOut, zIn, nCopy);
  57069. ((u8 *)sqlite3PagerGetExtra(pDestPg))[0] = 0;
  57070. if( iOff==0 && bUpdate==0 ){
  57071. sqlite3Put4byte(&zOut[28], sqlite3BtreeLastPage(p->pSrc));
  57072. }
  57073. }
  57074. sqlite3PagerUnref(pDestPg);
  57075. }
  57076. return rc;
  57077. }
  57078. /*
  57079. ** If pFile is currently larger than iSize bytes, then truncate it to
  57080. ** exactly iSize bytes. If pFile is not larger than iSize bytes, then
  57081. ** this function is a no-op.
  57082. **
  57083. ** Return SQLITE_OK if everything is successful, or an SQLite error
  57084. ** code if an error occurs.
  57085. */
  57086. static int backupTruncateFile(sqlite3_file *pFile, i64 iSize){
  57087. i64 iCurrent;
  57088. int rc = sqlite3OsFileSize(pFile, &iCurrent);
  57089. if( rc==SQLITE_OK && iCurrent>iSize ){
  57090. rc = sqlite3OsTruncate(pFile, iSize);
  57091. }
  57092. return rc;
  57093. }
  57094. /*
  57095. ** Register this backup object with the associated source pager for
  57096. ** callbacks when pages are changed or the cache invalidated.
  57097. */
  57098. static void attachBackupObject(sqlite3_backup *p){
  57099. sqlite3_backup **pp;
  57100. assert( sqlite3BtreeHoldsMutex(p->pSrc) );
  57101. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  57102. p->pNext = *pp;
  57103. *pp = p;
  57104. p->isAttached = 1;
  57105. }
  57106. /*
  57107. ** Copy nPage pages from the source b-tree to the destination.
  57108. */
  57109. SQLITE_API int sqlite3_backup_step(sqlite3_backup *p, int nPage){
  57110. int rc;
  57111. int destMode; /* Destination journal mode */
  57112. int pgszSrc = 0; /* Source page size */
  57113. int pgszDest = 0; /* Destination page size */
  57114. sqlite3_mutex_enter(p->pSrcDb->mutex);
  57115. sqlite3BtreeEnter(p->pSrc);
  57116. if( p->pDestDb ){
  57117. sqlite3_mutex_enter(p->pDestDb->mutex);
  57118. }
  57119. rc = p->rc;
  57120. if( !isFatalError(rc) ){
  57121. Pager * const pSrcPager = sqlite3BtreePager(p->pSrc); /* Source pager */
  57122. Pager * const pDestPager = sqlite3BtreePager(p->pDest); /* Dest pager */
  57123. int ii; /* Iterator variable */
  57124. int nSrcPage = -1; /* Size of source db in pages */
  57125. int bCloseTrans = 0; /* True if src db requires unlocking */
  57126. /* If the source pager is currently in a write-transaction, return
  57127. ** SQLITE_BUSY immediately.
  57128. */
  57129. if( p->pDestDb && p->pSrc->pBt->inTransaction==TRANS_WRITE ){
  57130. rc = SQLITE_BUSY;
  57131. }else{
  57132. rc = SQLITE_OK;
  57133. }
  57134. /* Lock the destination database, if it is not locked already. */
  57135. if( SQLITE_OK==rc && p->bDestLocked==0
  57136. && SQLITE_OK==(rc = sqlite3BtreeBeginTrans(p->pDest, 2))
  57137. ){
  57138. p->bDestLocked = 1;
  57139. sqlite3BtreeGetMeta(p->pDest, BTREE_SCHEMA_VERSION, &p->iDestSchema);
  57140. }
  57141. /* If there is no open read-transaction on the source database, open
  57142. ** one now. If a transaction is opened here, then it will be closed
  57143. ** before this function exits.
  57144. */
  57145. if( rc==SQLITE_OK && 0==sqlite3BtreeIsInReadTrans(p->pSrc) ){
  57146. rc = sqlite3BtreeBeginTrans(p->pSrc, 0);
  57147. bCloseTrans = 1;
  57148. }
  57149. /* Do not allow backup if the destination database is in WAL mode
  57150. ** and the page sizes are different between source and destination */
  57151. pgszSrc = sqlite3BtreeGetPageSize(p->pSrc);
  57152. pgszDest = sqlite3BtreeGetPageSize(p->pDest);
  57153. destMode = sqlite3PagerGetJournalMode(sqlite3BtreePager(p->pDest));
  57154. if( SQLITE_OK==rc && destMode==PAGER_JOURNALMODE_WAL && pgszSrc!=pgszDest ){
  57155. rc = SQLITE_READONLY;
  57156. }
  57157. /* Now that there is a read-lock on the source database, query the
  57158. ** source pager for the number of pages in the database.
  57159. */
  57160. nSrcPage = (int)sqlite3BtreeLastPage(p->pSrc);
  57161. assert( nSrcPage>=0 );
  57162. for(ii=0; (nPage<0 || ii<nPage) && p->iNext<=(Pgno)nSrcPage && !rc; ii++){
  57163. const Pgno iSrcPg = p->iNext; /* Source page number */
  57164. if( iSrcPg!=PENDING_BYTE_PAGE(p->pSrc->pBt) ){
  57165. DbPage *pSrcPg; /* Source page object */
  57166. rc = sqlite3PagerAcquire(pSrcPager, iSrcPg, &pSrcPg,
  57167. PAGER_GET_READONLY);
  57168. if( rc==SQLITE_OK ){
  57169. rc = backupOnePage(p, iSrcPg, sqlite3PagerGetData(pSrcPg), 0);
  57170. sqlite3PagerUnref(pSrcPg);
  57171. }
  57172. }
  57173. p->iNext++;
  57174. }
  57175. if( rc==SQLITE_OK ){
  57176. p->nPagecount = nSrcPage;
  57177. p->nRemaining = nSrcPage+1-p->iNext;
  57178. if( p->iNext>(Pgno)nSrcPage ){
  57179. rc = SQLITE_DONE;
  57180. }else if( !p->isAttached ){
  57181. attachBackupObject(p);
  57182. }
  57183. }
  57184. /* Update the schema version field in the destination database. This
  57185. ** is to make sure that the schema-version really does change in
  57186. ** the case where the source and destination databases have the
  57187. ** same schema version.
  57188. */
  57189. if( rc==SQLITE_DONE ){
  57190. if( nSrcPage==0 ){
  57191. rc = sqlite3BtreeNewDb(p->pDest);
  57192. nSrcPage = 1;
  57193. }
  57194. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  57195. rc = sqlite3BtreeUpdateMeta(p->pDest,1,p->iDestSchema+1);
  57196. }
  57197. if( rc==SQLITE_OK ){
  57198. if( p->pDestDb ){
  57199. sqlite3ResetAllSchemasOfConnection(p->pDestDb);
  57200. }
  57201. if( destMode==PAGER_JOURNALMODE_WAL ){
  57202. rc = sqlite3BtreeSetVersion(p->pDest, 2);
  57203. }
  57204. }
  57205. if( rc==SQLITE_OK ){
  57206. int nDestTruncate;
  57207. /* Set nDestTruncate to the final number of pages in the destination
  57208. ** database. The complication here is that the destination page
  57209. ** size may be different to the source page size.
  57210. **
  57211. ** If the source page size is smaller than the destination page size,
  57212. ** round up. In this case the call to sqlite3OsTruncate() below will
  57213. ** fix the size of the file. However it is important to call
  57214. ** sqlite3PagerTruncateImage() here so that any pages in the
  57215. ** destination file that lie beyond the nDestTruncate page mark are
  57216. ** journalled by PagerCommitPhaseOne() before they are destroyed
  57217. ** by the file truncation.
  57218. */
  57219. assert( pgszSrc==sqlite3BtreeGetPageSize(p->pSrc) );
  57220. assert( pgszDest==sqlite3BtreeGetPageSize(p->pDest) );
  57221. if( pgszSrc<pgszDest ){
  57222. int ratio = pgszDest/pgszSrc;
  57223. nDestTruncate = (nSrcPage+ratio-1)/ratio;
  57224. if( nDestTruncate==(int)PENDING_BYTE_PAGE(p->pDest->pBt) ){
  57225. nDestTruncate--;
  57226. }
  57227. }else{
  57228. nDestTruncate = nSrcPage * (pgszSrc/pgszDest);
  57229. }
  57230. assert( nDestTruncate>0 );
  57231. if( pgszSrc<pgszDest ){
  57232. /* If the source page-size is smaller than the destination page-size,
  57233. ** two extra things may need to happen:
  57234. **
  57235. ** * The destination may need to be truncated, and
  57236. **
  57237. ** * Data stored on the pages immediately following the
  57238. ** pending-byte page in the source database may need to be
  57239. ** copied into the destination database.
  57240. */
  57241. const i64 iSize = (i64)pgszSrc * (i64)nSrcPage;
  57242. sqlite3_file * const pFile = sqlite3PagerFile(pDestPager);
  57243. Pgno iPg;
  57244. int nDstPage;
  57245. i64 iOff;
  57246. i64 iEnd;
  57247. assert( pFile );
  57248. assert( nDestTruncate==0
  57249. || (i64)nDestTruncate*(i64)pgszDest >= iSize || (
  57250. nDestTruncate==(int)(PENDING_BYTE_PAGE(p->pDest->pBt)-1)
  57251. && iSize>=PENDING_BYTE && iSize<=PENDING_BYTE+pgszDest
  57252. ));
  57253. /* This block ensures that all data required to recreate the original
  57254. ** database has been stored in the journal for pDestPager and the
  57255. ** journal synced to disk. So at this point we may safely modify
  57256. ** the database file in any way, knowing that if a power failure
  57257. ** occurs, the original database will be reconstructed from the
  57258. ** journal file. */
  57259. sqlite3PagerPagecount(pDestPager, &nDstPage);
  57260. for(iPg=nDestTruncate; rc==SQLITE_OK && iPg<=(Pgno)nDstPage; iPg++){
  57261. if( iPg!=PENDING_BYTE_PAGE(p->pDest->pBt) ){
  57262. DbPage *pPg;
  57263. rc = sqlite3PagerGet(pDestPager, iPg, &pPg);
  57264. if( rc==SQLITE_OK ){
  57265. rc = sqlite3PagerWrite(pPg);
  57266. sqlite3PagerUnref(pPg);
  57267. }
  57268. }
  57269. }
  57270. if( rc==SQLITE_OK ){
  57271. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 1);
  57272. }
  57273. /* Write the extra pages and truncate the database file as required */
  57274. iEnd = MIN(PENDING_BYTE + pgszDest, iSize);
  57275. for(
  57276. iOff=PENDING_BYTE+pgszSrc;
  57277. rc==SQLITE_OK && iOff<iEnd;
  57278. iOff+=pgszSrc
  57279. ){
  57280. PgHdr *pSrcPg = 0;
  57281. const Pgno iSrcPg = (Pgno)((iOff/pgszSrc)+1);
  57282. rc = sqlite3PagerGet(pSrcPager, iSrcPg, &pSrcPg);
  57283. if( rc==SQLITE_OK ){
  57284. u8 *zData = sqlite3PagerGetData(pSrcPg);
  57285. rc = sqlite3OsWrite(pFile, zData, pgszSrc, iOff);
  57286. }
  57287. sqlite3PagerUnref(pSrcPg);
  57288. }
  57289. if( rc==SQLITE_OK ){
  57290. rc = backupTruncateFile(pFile, iSize);
  57291. }
  57292. /* Sync the database file to disk. */
  57293. if( rc==SQLITE_OK ){
  57294. rc = sqlite3PagerSync(pDestPager, 0);
  57295. }
  57296. }else{
  57297. sqlite3PagerTruncateImage(pDestPager, nDestTruncate);
  57298. rc = sqlite3PagerCommitPhaseOne(pDestPager, 0, 0);
  57299. }
  57300. /* Finish committing the transaction to the destination database. */
  57301. if( SQLITE_OK==rc
  57302. && SQLITE_OK==(rc = sqlite3BtreeCommitPhaseTwo(p->pDest, 0))
  57303. ){
  57304. rc = SQLITE_DONE;
  57305. }
  57306. }
  57307. }
  57308. /* If bCloseTrans is true, then this function opened a read transaction
  57309. ** on the source database. Close the read transaction here. There is
  57310. ** no need to check the return values of the btree methods here, as
  57311. ** "committing" a read-only transaction cannot fail.
  57312. */
  57313. if( bCloseTrans ){
  57314. TESTONLY( int rc2 );
  57315. TESTONLY( rc2 = ) sqlite3BtreeCommitPhaseOne(p->pSrc, 0);
  57316. TESTONLY( rc2 |= ) sqlite3BtreeCommitPhaseTwo(p->pSrc, 0);
  57317. assert( rc2==SQLITE_OK );
  57318. }
  57319. if( rc==SQLITE_IOERR_NOMEM ){
  57320. rc = SQLITE_NOMEM;
  57321. }
  57322. p->rc = rc;
  57323. }
  57324. if( p->pDestDb ){
  57325. sqlite3_mutex_leave(p->pDestDb->mutex);
  57326. }
  57327. sqlite3BtreeLeave(p->pSrc);
  57328. sqlite3_mutex_leave(p->pSrcDb->mutex);
  57329. return rc;
  57330. }
  57331. /*
  57332. ** Release all resources associated with an sqlite3_backup* handle.
  57333. */
  57334. SQLITE_API int sqlite3_backup_finish(sqlite3_backup *p){
  57335. sqlite3_backup **pp; /* Ptr to head of pagers backup list */
  57336. sqlite3 *pSrcDb; /* Source database connection */
  57337. int rc; /* Value to return */
  57338. /* Enter the mutexes */
  57339. if( p==0 ) return SQLITE_OK;
  57340. pSrcDb = p->pSrcDb;
  57341. sqlite3_mutex_enter(pSrcDb->mutex);
  57342. sqlite3BtreeEnter(p->pSrc);
  57343. if( p->pDestDb ){
  57344. sqlite3_mutex_enter(p->pDestDb->mutex);
  57345. }
  57346. /* Detach this backup from the source pager. */
  57347. if( p->pDestDb ){
  57348. p->pSrc->nBackup--;
  57349. }
  57350. if( p->isAttached ){
  57351. pp = sqlite3PagerBackupPtr(sqlite3BtreePager(p->pSrc));
  57352. while( *pp!=p ){
  57353. pp = &(*pp)->pNext;
  57354. }
  57355. *pp = p->pNext;
  57356. }
  57357. /* If a transaction is still open on the Btree, roll it back. */
  57358. sqlite3BtreeRollback(p->pDest, SQLITE_OK, 0);
  57359. /* Set the error code of the destination database handle. */
  57360. rc = (p->rc==SQLITE_DONE) ? SQLITE_OK : p->rc;
  57361. if( p->pDestDb ){
  57362. sqlite3Error(p->pDestDb, rc);
  57363. /* Exit the mutexes and free the backup context structure. */
  57364. sqlite3LeaveMutexAndCloseZombie(p->pDestDb);
  57365. }
  57366. sqlite3BtreeLeave(p->pSrc);
  57367. if( p->pDestDb ){
  57368. /* EVIDENCE-OF: R-64852-21591 The sqlite3_backup object is created by a
  57369. ** call to sqlite3_backup_init() and is destroyed by a call to
  57370. ** sqlite3_backup_finish(). */
  57371. sqlite3_free(p);
  57372. }
  57373. sqlite3LeaveMutexAndCloseZombie(pSrcDb);
  57374. return rc;
  57375. }
  57376. /*
  57377. ** Return the number of pages still to be backed up as of the most recent
  57378. ** call to sqlite3_backup_step().
  57379. */
  57380. SQLITE_API int sqlite3_backup_remaining(sqlite3_backup *p){
  57381. return p->nRemaining;
  57382. }
  57383. /*
  57384. ** Return the total number of pages in the source database as of the most
  57385. ** recent call to sqlite3_backup_step().
  57386. */
  57387. SQLITE_API int sqlite3_backup_pagecount(sqlite3_backup *p){
  57388. return p->nPagecount;
  57389. }
  57390. /*
  57391. ** This function is called after the contents of page iPage of the
  57392. ** source database have been modified. If page iPage has already been
  57393. ** copied into the destination database, then the data written to the
  57394. ** destination is now invalidated. The destination copy of iPage needs
  57395. ** to be updated with the new data before the backup operation is
  57396. ** complete.
  57397. **
  57398. ** It is assumed that the mutex associated with the BtShared object
  57399. ** corresponding to the source database is held when this function is
  57400. ** called.
  57401. */
  57402. SQLITE_PRIVATE void sqlite3BackupUpdate(sqlite3_backup *pBackup, Pgno iPage, const u8 *aData){
  57403. sqlite3_backup *p; /* Iterator variable */
  57404. for(p=pBackup; p; p=p->pNext){
  57405. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  57406. if( !isFatalError(p->rc) && iPage<p->iNext ){
  57407. /* The backup process p has already copied page iPage. But now it
  57408. ** has been modified by a transaction on the source pager. Copy
  57409. ** the new data into the backup.
  57410. */
  57411. int rc;
  57412. assert( p->pDestDb );
  57413. sqlite3_mutex_enter(p->pDestDb->mutex);
  57414. rc = backupOnePage(p, iPage, aData, 1);
  57415. sqlite3_mutex_leave(p->pDestDb->mutex);
  57416. assert( rc!=SQLITE_BUSY && rc!=SQLITE_LOCKED );
  57417. if( rc!=SQLITE_OK ){
  57418. p->rc = rc;
  57419. }
  57420. }
  57421. }
  57422. }
  57423. /*
  57424. ** Restart the backup process. This is called when the pager layer
  57425. ** detects that the database has been modified by an external database
  57426. ** connection. In this case there is no way of knowing which of the
  57427. ** pages that have been copied into the destination database are still
  57428. ** valid and which are not, so the entire process needs to be restarted.
  57429. **
  57430. ** It is assumed that the mutex associated with the BtShared object
  57431. ** corresponding to the source database is held when this function is
  57432. ** called.
  57433. */
  57434. SQLITE_PRIVATE void sqlite3BackupRestart(sqlite3_backup *pBackup){
  57435. sqlite3_backup *p; /* Iterator variable */
  57436. for(p=pBackup; p; p=p->pNext){
  57437. assert( sqlite3_mutex_held(p->pSrc->pBt->mutex) );
  57438. p->iNext = 1;
  57439. }
  57440. }
  57441. #ifndef SQLITE_OMIT_VACUUM
  57442. /*
  57443. ** Copy the complete content of pBtFrom into pBtTo. A transaction
  57444. ** must be active for both files.
  57445. **
  57446. ** The size of file pTo may be reduced by this operation. If anything
  57447. ** goes wrong, the transaction on pTo is rolled back. If successful, the
  57448. ** transaction is committed before returning.
  57449. */
  57450. SQLITE_PRIVATE int sqlite3BtreeCopyFile(Btree *pTo, Btree *pFrom){
  57451. int rc;
  57452. sqlite3_file *pFd; /* File descriptor for database pTo */
  57453. sqlite3_backup b;
  57454. sqlite3BtreeEnter(pTo);
  57455. sqlite3BtreeEnter(pFrom);
  57456. assert( sqlite3BtreeIsInTrans(pTo) );
  57457. pFd = sqlite3PagerFile(sqlite3BtreePager(pTo));
  57458. if( pFd->pMethods ){
  57459. i64 nByte = sqlite3BtreeGetPageSize(pFrom)*(i64)sqlite3BtreeLastPage(pFrom);
  57460. rc = sqlite3OsFileControl(pFd, SQLITE_FCNTL_OVERWRITE, &nByte);
  57461. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  57462. if( rc ) goto copy_finished;
  57463. }
  57464. /* Set up an sqlite3_backup object. sqlite3_backup.pDestDb must be set
  57465. ** to 0. This is used by the implementations of sqlite3_backup_step()
  57466. ** and sqlite3_backup_finish() to detect that they are being called
  57467. ** from this function, not directly by the user.
  57468. */
  57469. memset(&b, 0, sizeof(b));
  57470. b.pSrcDb = pFrom->db;
  57471. b.pSrc = pFrom;
  57472. b.pDest = pTo;
  57473. b.iNext = 1;
  57474. /* 0x7FFFFFFF is the hard limit for the number of pages in a database
  57475. ** file. By passing this as the number of pages to copy to
  57476. ** sqlite3_backup_step(), we can guarantee that the copy finishes
  57477. ** within a single call (unless an error occurs). The assert() statement
  57478. ** checks this assumption - (p->rc) should be set to either SQLITE_DONE
  57479. ** or an error code.
  57480. */
  57481. sqlite3_backup_step(&b, 0x7FFFFFFF);
  57482. assert( b.rc!=SQLITE_OK );
  57483. rc = sqlite3_backup_finish(&b);
  57484. if( rc==SQLITE_OK ){
  57485. pTo->pBt->btsFlags &= ~BTS_PAGESIZE_FIXED;
  57486. }else{
  57487. sqlite3PagerClearCache(sqlite3BtreePager(b.pDest));
  57488. }
  57489. assert( sqlite3BtreeIsInTrans(pTo)==0 );
  57490. copy_finished:
  57491. sqlite3BtreeLeave(pFrom);
  57492. sqlite3BtreeLeave(pTo);
  57493. return rc;
  57494. }
  57495. #endif /* SQLITE_OMIT_VACUUM */
  57496. /************** End of backup.c **********************************************/
  57497. /************** Begin file vdbemem.c *****************************************/
  57498. /*
  57499. ** 2004 May 26
  57500. **
  57501. ** The author disclaims copyright to this source code. In place of
  57502. ** a legal notice, here is a blessing:
  57503. **
  57504. ** May you do good and not evil.
  57505. ** May you find forgiveness for yourself and forgive others.
  57506. ** May you share freely, never taking more than you give.
  57507. **
  57508. *************************************************************************
  57509. **
  57510. ** This file contains code use to manipulate "Mem" structure. A "Mem"
  57511. ** stores a single value in the VDBE. Mem is an opaque structure visible
  57512. ** only within the VDBE. Interface routines refer to a Mem using the
  57513. ** name sqlite_value
  57514. */
  57515. #ifdef SQLITE_DEBUG
  57516. /*
  57517. ** Check invariants on a Mem object.
  57518. **
  57519. ** This routine is intended for use inside of assert() statements, like
  57520. ** this: assert( sqlite3VdbeCheckMemInvariants(pMem) );
  57521. */
  57522. SQLITE_PRIVATE int sqlite3VdbeCheckMemInvariants(Mem *p){
  57523. /* If MEM_Dyn is set then Mem.xDel!=0.
  57524. ** Mem.xDel is might not be initialized if MEM_Dyn is clear.
  57525. */
  57526. assert( (p->flags & MEM_Dyn)==0 || p->xDel!=0 );
  57527. /* MEM_Dyn may only be set if Mem.szMalloc==0. In this way we
  57528. ** ensure that if Mem.szMalloc>0 then it is safe to do
  57529. ** Mem.z = Mem.zMalloc without having to check Mem.flags&MEM_Dyn.
  57530. ** That saves a few cycles in inner loops. */
  57531. assert( (p->flags & MEM_Dyn)==0 || p->szMalloc==0 );
  57532. /* Cannot be both MEM_Int and MEM_Real at the same time */
  57533. assert( (p->flags & (MEM_Int|MEM_Real))!=(MEM_Int|MEM_Real) );
  57534. /* The szMalloc field holds the correct memory allocation size */
  57535. assert( p->szMalloc==0
  57536. || p->szMalloc==sqlite3DbMallocSize(p->db,p->zMalloc) );
  57537. /* If p holds a string or blob, the Mem.z must point to exactly
  57538. ** one of the following:
  57539. **
  57540. ** (1) Memory in Mem.zMalloc and managed by the Mem object
  57541. ** (2) Memory to be freed using Mem.xDel
  57542. ** (3) An ephemeral string or blob
  57543. ** (4) A static string or blob
  57544. */
  57545. if( (p->flags & (MEM_Str|MEM_Blob)) && p->n>0 ){
  57546. assert(
  57547. ((p->szMalloc>0 && p->z==p->zMalloc)? 1 : 0) +
  57548. ((p->flags&MEM_Dyn)!=0 ? 1 : 0) +
  57549. ((p->flags&MEM_Ephem)!=0 ? 1 : 0) +
  57550. ((p->flags&MEM_Static)!=0 ? 1 : 0) == 1
  57551. );
  57552. }
  57553. return 1;
  57554. }
  57555. #endif
  57556. /*
  57557. ** If pMem is an object with a valid string representation, this routine
  57558. ** ensures the internal encoding for the string representation is
  57559. ** 'desiredEnc', one of SQLITE_UTF8, SQLITE_UTF16LE or SQLITE_UTF16BE.
  57560. **
  57561. ** If pMem is not a string object, or the encoding of the string
  57562. ** representation is already stored using the requested encoding, then this
  57563. ** routine is a no-op.
  57564. **
  57565. ** SQLITE_OK is returned if the conversion is successful (or not required).
  57566. ** SQLITE_NOMEM may be returned if a malloc() fails during conversion
  57567. ** between formats.
  57568. */
  57569. SQLITE_PRIVATE int sqlite3VdbeChangeEncoding(Mem *pMem, int desiredEnc){
  57570. #ifndef SQLITE_OMIT_UTF16
  57571. int rc;
  57572. #endif
  57573. assert( (pMem->flags&MEM_RowSet)==0 );
  57574. assert( desiredEnc==SQLITE_UTF8 || desiredEnc==SQLITE_UTF16LE
  57575. || desiredEnc==SQLITE_UTF16BE );
  57576. if( !(pMem->flags&MEM_Str) || pMem->enc==desiredEnc ){
  57577. return SQLITE_OK;
  57578. }
  57579. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57580. #ifdef SQLITE_OMIT_UTF16
  57581. return SQLITE_ERROR;
  57582. #else
  57583. /* MemTranslate() may return SQLITE_OK or SQLITE_NOMEM. If NOMEM is returned,
  57584. ** then the encoding of the value may not have changed.
  57585. */
  57586. rc = sqlite3VdbeMemTranslate(pMem, (u8)desiredEnc);
  57587. assert(rc==SQLITE_OK || rc==SQLITE_NOMEM);
  57588. assert(rc==SQLITE_OK || pMem->enc!=desiredEnc);
  57589. assert(rc==SQLITE_NOMEM || pMem->enc==desiredEnc);
  57590. return rc;
  57591. #endif
  57592. }
  57593. /*
  57594. ** Make sure pMem->z points to a writable allocation of at least
  57595. ** min(n,32) bytes.
  57596. **
  57597. ** If the bPreserve argument is true, then copy of the content of
  57598. ** pMem->z into the new allocation. pMem must be either a string or
  57599. ** blob if bPreserve is true. If bPreserve is false, any prior content
  57600. ** in pMem->z is discarded.
  57601. */
  57602. SQLITE_PRIVATE SQLITE_NOINLINE int sqlite3VdbeMemGrow(Mem *pMem, int n, int bPreserve){
  57603. assert( sqlite3VdbeCheckMemInvariants(pMem) );
  57604. assert( (pMem->flags&MEM_RowSet)==0 );
  57605. /* If the bPreserve flag is set to true, then the memory cell must already
  57606. ** contain a valid string or blob value. */
  57607. assert( bPreserve==0 || pMem->flags&(MEM_Blob|MEM_Str) );
  57608. testcase( bPreserve && pMem->z==0 );
  57609. assert( pMem->szMalloc==0
  57610. || pMem->szMalloc==sqlite3DbMallocSize(pMem->db, pMem->zMalloc) );
  57611. if( pMem->szMalloc<n ){
  57612. if( n<32 ) n = 32;
  57613. if( bPreserve && pMem->szMalloc>0 && pMem->z==pMem->zMalloc ){
  57614. pMem->z = pMem->zMalloc = sqlite3DbReallocOrFree(pMem->db, pMem->z, n);
  57615. bPreserve = 0;
  57616. }else{
  57617. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  57618. pMem->zMalloc = sqlite3DbMallocRaw(pMem->db, n);
  57619. }
  57620. if( pMem->zMalloc==0 ){
  57621. sqlite3VdbeMemSetNull(pMem);
  57622. pMem->z = 0;
  57623. pMem->szMalloc = 0;
  57624. return SQLITE_NOMEM;
  57625. }else{
  57626. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  57627. }
  57628. }
  57629. if( bPreserve && pMem->z && pMem->z!=pMem->zMalloc ){
  57630. memcpy(pMem->zMalloc, pMem->z, pMem->n);
  57631. }
  57632. if( (pMem->flags&MEM_Dyn)!=0 ){
  57633. assert( pMem->xDel!=0 && pMem->xDel!=SQLITE_DYNAMIC );
  57634. pMem->xDel((void *)(pMem->z));
  57635. }
  57636. pMem->z = pMem->zMalloc;
  57637. pMem->flags &= ~(MEM_Dyn|MEM_Ephem|MEM_Static);
  57638. return SQLITE_OK;
  57639. }
  57640. /*
  57641. ** Change the pMem->zMalloc allocation to be at least szNew bytes.
  57642. ** If pMem->zMalloc already meets or exceeds the requested size, this
  57643. ** routine is a no-op.
  57644. **
  57645. ** Any prior string or blob content in the pMem object may be discarded.
  57646. ** The pMem->xDel destructor is called, if it exists. Though MEM_Str
  57647. ** and MEM_Blob values may be discarded, MEM_Int, MEM_Real, and MEM_Null
  57648. ** values are preserved.
  57649. **
  57650. ** Return SQLITE_OK on success or an error code (probably SQLITE_NOMEM)
  57651. ** if unable to complete the resizing.
  57652. */
  57653. SQLITE_PRIVATE int sqlite3VdbeMemClearAndResize(Mem *pMem, int szNew){
  57654. assert( szNew>0 );
  57655. assert( (pMem->flags & MEM_Dyn)==0 || pMem->szMalloc==0 );
  57656. if( pMem->szMalloc<szNew ){
  57657. return sqlite3VdbeMemGrow(pMem, szNew, 0);
  57658. }
  57659. assert( (pMem->flags & MEM_Dyn)==0 );
  57660. pMem->z = pMem->zMalloc;
  57661. pMem->flags &= (MEM_Null|MEM_Int|MEM_Real);
  57662. return SQLITE_OK;
  57663. }
  57664. /*
  57665. ** Change pMem so that its MEM_Str or MEM_Blob value is stored in
  57666. ** MEM.zMalloc, where it can be safely written.
  57667. **
  57668. ** Return SQLITE_OK on success or SQLITE_NOMEM if malloc fails.
  57669. */
  57670. SQLITE_PRIVATE int sqlite3VdbeMemMakeWriteable(Mem *pMem){
  57671. int f;
  57672. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57673. assert( (pMem->flags&MEM_RowSet)==0 );
  57674. ExpandBlob(pMem);
  57675. f = pMem->flags;
  57676. if( (f&(MEM_Str|MEM_Blob)) && (pMem->szMalloc==0 || pMem->z!=pMem->zMalloc) ){
  57677. if( sqlite3VdbeMemGrow(pMem, pMem->n + 2, 1) ){
  57678. return SQLITE_NOMEM;
  57679. }
  57680. pMem->z[pMem->n] = 0;
  57681. pMem->z[pMem->n+1] = 0;
  57682. pMem->flags |= MEM_Term;
  57683. #ifdef SQLITE_DEBUG
  57684. pMem->pScopyFrom = 0;
  57685. #endif
  57686. }
  57687. return SQLITE_OK;
  57688. }
  57689. /*
  57690. ** If the given Mem* has a zero-filled tail, turn it into an ordinary
  57691. ** blob stored in dynamically allocated space.
  57692. */
  57693. #ifndef SQLITE_OMIT_INCRBLOB
  57694. SQLITE_PRIVATE int sqlite3VdbeMemExpandBlob(Mem *pMem){
  57695. if( pMem->flags & MEM_Zero ){
  57696. int nByte;
  57697. assert( pMem->flags&MEM_Blob );
  57698. assert( (pMem->flags&MEM_RowSet)==0 );
  57699. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57700. /* Set nByte to the number of bytes required to store the expanded blob. */
  57701. nByte = pMem->n + pMem->u.nZero;
  57702. if( nByte<=0 ){
  57703. nByte = 1;
  57704. }
  57705. if( sqlite3VdbeMemGrow(pMem, nByte, 1) ){
  57706. return SQLITE_NOMEM;
  57707. }
  57708. memset(&pMem->z[pMem->n], 0, pMem->u.nZero);
  57709. pMem->n += pMem->u.nZero;
  57710. pMem->flags &= ~(MEM_Zero|MEM_Term);
  57711. }
  57712. return SQLITE_OK;
  57713. }
  57714. #endif
  57715. /*
  57716. ** It is already known that pMem contains an unterminated string.
  57717. ** Add the zero terminator.
  57718. */
  57719. static SQLITE_NOINLINE int vdbeMemAddTerminator(Mem *pMem){
  57720. if( sqlite3VdbeMemGrow(pMem, pMem->n+2, 1) ){
  57721. return SQLITE_NOMEM;
  57722. }
  57723. pMem->z[pMem->n] = 0;
  57724. pMem->z[pMem->n+1] = 0;
  57725. pMem->flags |= MEM_Term;
  57726. return SQLITE_OK;
  57727. }
  57728. /*
  57729. ** Make sure the given Mem is \u0000 terminated.
  57730. */
  57731. SQLITE_PRIVATE int sqlite3VdbeMemNulTerminate(Mem *pMem){
  57732. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57733. testcase( (pMem->flags & (MEM_Term|MEM_Str))==(MEM_Term|MEM_Str) );
  57734. testcase( (pMem->flags & (MEM_Term|MEM_Str))==0 );
  57735. if( (pMem->flags & (MEM_Term|MEM_Str))!=MEM_Str ){
  57736. return SQLITE_OK; /* Nothing to do */
  57737. }else{
  57738. return vdbeMemAddTerminator(pMem);
  57739. }
  57740. }
  57741. /*
  57742. ** Add MEM_Str to the set of representations for the given Mem. Numbers
  57743. ** are converted using sqlite3_snprintf(). Converting a BLOB to a string
  57744. ** is a no-op.
  57745. **
  57746. ** Existing representations MEM_Int and MEM_Real are invalidated if
  57747. ** bForce is true but are retained if bForce is false.
  57748. **
  57749. ** A MEM_Null value will never be passed to this function. This function is
  57750. ** used for converting values to text for returning to the user (i.e. via
  57751. ** sqlite3_value_text()), or for ensuring that values to be used as btree
  57752. ** keys are strings. In the former case a NULL pointer is returned the
  57753. ** user and the latter is an internal programming error.
  57754. */
  57755. SQLITE_PRIVATE int sqlite3VdbeMemStringify(Mem *pMem, u8 enc, u8 bForce){
  57756. int fg = pMem->flags;
  57757. const int nByte = 32;
  57758. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57759. assert( !(fg&MEM_Zero) );
  57760. assert( !(fg&(MEM_Str|MEM_Blob)) );
  57761. assert( fg&(MEM_Int|MEM_Real) );
  57762. assert( (pMem->flags&MEM_RowSet)==0 );
  57763. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  57764. if( sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  57765. return SQLITE_NOMEM;
  57766. }
  57767. /* For a Real or Integer, use sqlite3_snprintf() to produce the UTF-8
  57768. ** string representation of the value. Then, if the required encoding
  57769. ** is UTF-16le or UTF-16be do a translation.
  57770. **
  57771. ** FIX ME: It would be better if sqlite3_snprintf() could do UTF-16.
  57772. */
  57773. if( fg & MEM_Int ){
  57774. sqlite3_snprintf(nByte, pMem->z, "%lld", pMem->u.i);
  57775. }else{
  57776. assert( fg & MEM_Real );
  57777. sqlite3_snprintf(nByte, pMem->z, "%!.15g", pMem->u.r);
  57778. }
  57779. pMem->n = sqlite3Strlen30(pMem->z);
  57780. pMem->enc = SQLITE_UTF8;
  57781. pMem->flags |= MEM_Str|MEM_Term;
  57782. if( bForce ) pMem->flags &= ~(MEM_Int|MEM_Real);
  57783. sqlite3VdbeChangeEncoding(pMem, enc);
  57784. return SQLITE_OK;
  57785. }
  57786. /*
  57787. ** Memory cell pMem contains the context of an aggregate function.
  57788. ** This routine calls the finalize method for that function. The
  57789. ** result of the aggregate is stored back into pMem.
  57790. **
  57791. ** Return SQLITE_ERROR if the finalizer reports an error. SQLITE_OK
  57792. ** otherwise.
  57793. */
  57794. SQLITE_PRIVATE int sqlite3VdbeMemFinalize(Mem *pMem, FuncDef *pFunc){
  57795. int rc = SQLITE_OK;
  57796. if( ALWAYS(pFunc && pFunc->xFinalize) ){
  57797. sqlite3_context ctx;
  57798. Mem t;
  57799. assert( (pMem->flags & MEM_Null)!=0 || pFunc==pMem->u.pDef );
  57800. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57801. memset(&ctx, 0, sizeof(ctx));
  57802. memset(&t, 0, sizeof(t));
  57803. t.flags = MEM_Null;
  57804. t.db = pMem->db;
  57805. ctx.pOut = &t;
  57806. ctx.pMem = pMem;
  57807. ctx.pFunc = pFunc;
  57808. pFunc->xFinalize(&ctx); /* IMP: R-24505-23230 */
  57809. assert( (pMem->flags & MEM_Dyn)==0 );
  57810. if( pMem->szMalloc>0 ) sqlite3DbFree(pMem->db, pMem->zMalloc);
  57811. memcpy(pMem, &t, sizeof(t));
  57812. rc = ctx.isError;
  57813. }
  57814. return rc;
  57815. }
  57816. /*
  57817. ** If the memory cell contains a value that must be freed by
  57818. ** invoking the external callback in Mem.xDel, then this routine
  57819. ** will free that value. It also sets Mem.flags to MEM_Null.
  57820. **
  57821. ** This is a helper routine for sqlite3VdbeMemSetNull() and
  57822. ** for sqlite3VdbeMemRelease(). Use those other routines as the
  57823. ** entry point for releasing Mem resources.
  57824. */
  57825. static SQLITE_NOINLINE void vdbeMemClearExternAndSetNull(Mem *p){
  57826. assert( p->db==0 || sqlite3_mutex_held(p->db->mutex) );
  57827. assert( VdbeMemDynamic(p) );
  57828. if( p->flags&MEM_Agg ){
  57829. sqlite3VdbeMemFinalize(p, p->u.pDef);
  57830. assert( (p->flags & MEM_Agg)==0 );
  57831. testcase( p->flags & MEM_Dyn );
  57832. }
  57833. if( p->flags&MEM_Dyn ){
  57834. assert( (p->flags&MEM_RowSet)==0 );
  57835. assert( p->xDel!=SQLITE_DYNAMIC && p->xDel!=0 );
  57836. p->xDel((void *)p->z);
  57837. }else if( p->flags&MEM_RowSet ){
  57838. sqlite3RowSetClear(p->u.pRowSet);
  57839. }else if( p->flags&MEM_Frame ){
  57840. VdbeFrame *pFrame = p->u.pFrame;
  57841. pFrame->pParent = pFrame->v->pDelFrame;
  57842. pFrame->v->pDelFrame = pFrame;
  57843. }
  57844. p->flags = MEM_Null;
  57845. }
  57846. /*
  57847. ** Release memory held by the Mem p, both external memory cleared
  57848. ** by p->xDel and memory in p->zMalloc.
  57849. **
  57850. ** This is a helper routine invoked by sqlite3VdbeMemRelease() in
  57851. ** the unusual case where there really is memory in p that needs
  57852. ** to be freed.
  57853. */
  57854. static SQLITE_NOINLINE void vdbeMemClear(Mem *p){
  57855. if( VdbeMemDynamic(p) ){
  57856. vdbeMemClearExternAndSetNull(p);
  57857. }
  57858. if( p->szMalloc ){
  57859. sqlite3DbFree(p->db, p->zMalloc);
  57860. p->szMalloc = 0;
  57861. }
  57862. p->z = 0;
  57863. }
  57864. /*
  57865. ** Release any memory resources held by the Mem. Both the memory that is
  57866. ** free by Mem.xDel and the Mem.zMalloc allocation are freed.
  57867. **
  57868. ** Use this routine prior to clean up prior to abandoning a Mem, or to
  57869. ** reset a Mem back to its minimum memory utilization.
  57870. **
  57871. ** Use sqlite3VdbeMemSetNull() to release just the Mem.xDel space
  57872. ** prior to inserting new content into the Mem.
  57873. */
  57874. SQLITE_PRIVATE void sqlite3VdbeMemRelease(Mem *p){
  57875. assert( sqlite3VdbeCheckMemInvariants(p) );
  57876. if( VdbeMemDynamic(p) || p->szMalloc ){
  57877. vdbeMemClear(p);
  57878. }
  57879. }
  57880. /*
  57881. ** Convert a 64-bit IEEE double into a 64-bit signed integer.
  57882. ** If the double is out of range of a 64-bit signed integer then
  57883. ** return the closest available 64-bit signed integer.
  57884. */
  57885. static i64 doubleToInt64(double r){
  57886. #ifdef SQLITE_OMIT_FLOATING_POINT
  57887. /* When floating-point is omitted, double and int64 are the same thing */
  57888. return r;
  57889. #else
  57890. /*
  57891. ** Many compilers we encounter do not define constants for the
  57892. ** minimum and maximum 64-bit integers, or they define them
  57893. ** inconsistently. And many do not understand the "LL" notation.
  57894. ** So we define our own static constants here using nothing
  57895. ** larger than a 32-bit integer constant.
  57896. */
  57897. static const i64 maxInt = LARGEST_INT64;
  57898. static const i64 minInt = SMALLEST_INT64;
  57899. if( r<=(double)minInt ){
  57900. return minInt;
  57901. }else if( r>=(double)maxInt ){
  57902. return maxInt;
  57903. }else{
  57904. return (i64)r;
  57905. }
  57906. #endif
  57907. }
  57908. /*
  57909. ** Return some kind of integer value which is the best we can do
  57910. ** at representing the value that *pMem describes as an integer.
  57911. ** If pMem is an integer, then the value is exact. If pMem is
  57912. ** a floating-point then the value returned is the integer part.
  57913. ** If pMem is a string or blob, then we make an attempt to convert
  57914. ** it into an integer and return that. If pMem represents an
  57915. ** an SQL-NULL value, return 0.
  57916. **
  57917. ** If pMem represents a string value, its encoding might be changed.
  57918. */
  57919. SQLITE_PRIVATE i64 sqlite3VdbeIntValue(Mem *pMem){
  57920. int flags;
  57921. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57922. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  57923. flags = pMem->flags;
  57924. if( flags & MEM_Int ){
  57925. return pMem->u.i;
  57926. }else if( flags & MEM_Real ){
  57927. return doubleToInt64(pMem->u.r);
  57928. }else if( flags & (MEM_Str|MEM_Blob) ){
  57929. i64 value = 0;
  57930. assert( pMem->z || pMem->n==0 );
  57931. sqlite3Atoi64(pMem->z, &value, pMem->n, pMem->enc);
  57932. return value;
  57933. }else{
  57934. return 0;
  57935. }
  57936. }
  57937. /*
  57938. ** Return the best representation of pMem that we can get into a
  57939. ** double. If pMem is already a double or an integer, return its
  57940. ** value. If it is a string or blob, try to convert it to a double.
  57941. ** If it is a NULL, return 0.0.
  57942. */
  57943. SQLITE_PRIVATE double sqlite3VdbeRealValue(Mem *pMem){
  57944. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57945. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  57946. if( pMem->flags & MEM_Real ){
  57947. return pMem->u.r;
  57948. }else if( pMem->flags & MEM_Int ){
  57949. return (double)pMem->u.i;
  57950. }else if( pMem->flags & (MEM_Str|MEM_Blob) ){
  57951. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  57952. double val = (double)0;
  57953. sqlite3AtoF(pMem->z, &val, pMem->n, pMem->enc);
  57954. return val;
  57955. }else{
  57956. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  57957. return (double)0;
  57958. }
  57959. }
  57960. /*
  57961. ** The MEM structure is already a MEM_Real. Try to also make it a
  57962. ** MEM_Int if we can.
  57963. */
  57964. SQLITE_PRIVATE void sqlite3VdbeIntegerAffinity(Mem *pMem){
  57965. i64 ix;
  57966. assert( pMem->flags & MEM_Real );
  57967. assert( (pMem->flags & MEM_RowSet)==0 );
  57968. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57969. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  57970. ix = doubleToInt64(pMem->u.r);
  57971. /* Only mark the value as an integer if
  57972. **
  57973. ** (1) the round-trip conversion real->int->real is a no-op, and
  57974. ** (2) The integer is neither the largest nor the smallest
  57975. ** possible integer (ticket #3922)
  57976. **
  57977. ** The second and third terms in the following conditional enforces
  57978. ** the second condition under the assumption that addition overflow causes
  57979. ** values to wrap around.
  57980. */
  57981. if( pMem->u.r==ix && ix>SMALLEST_INT64 && ix<LARGEST_INT64 ){
  57982. pMem->u.i = ix;
  57983. MemSetTypeFlag(pMem, MEM_Int);
  57984. }
  57985. }
  57986. /*
  57987. ** Convert pMem to type integer. Invalidate any prior representations.
  57988. */
  57989. SQLITE_PRIVATE int sqlite3VdbeMemIntegerify(Mem *pMem){
  57990. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  57991. assert( (pMem->flags & MEM_RowSet)==0 );
  57992. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  57993. pMem->u.i = sqlite3VdbeIntValue(pMem);
  57994. MemSetTypeFlag(pMem, MEM_Int);
  57995. return SQLITE_OK;
  57996. }
  57997. /*
  57998. ** Convert pMem so that it is of type MEM_Real.
  57999. ** Invalidate any prior representations.
  58000. */
  58001. SQLITE_PRIVATE int sqlite3VdbeMemRealify(Mem *pMem){
  58002. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58003. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  58004. pMem->u.r = sqlite3VdbeRealValue(pMem);
  58005. MemSetTypeFlag(pMem, MEM_Real);
  58006. return SQLITE_OK;
  58007. }
  58008. /*
  58009. ** Convert pMem so that it has types MEM_Real or MEM_Int or both.
  58010. ** Invalidate any prior representations.
  58011. **
  58012. ** Every effort is made to force the conversion, even if the input
  58013. ** is a string that does not look completely like a number. Convert
  58014. ** as much of the string as we can and ignore the rest.
  58015. */
  58016. SQLITE_PRIVATE int sqlite3VdbeMemNumerify(Mem *pMem){
  58017. if( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))==0 ){
  58018. assert( (pMem->flags & (MEM_Blob|MEM_Str))!=0 );
  58019. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58020. if( 0==sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc) ){
  58021. MemSetTypeFlag(pMem, MEM_Int);
  58022. }else{
  58023. pMem->u.r = sqlite3VdbeRealValue(pMem);
  58024. MemSetTypeFlag(pMem, MEM_Real);
  58025. sqlite3VdbeIntegerAffinity(pMem);
  58026. }
  58027. }
  58028. assert( (pMem->flags & (MEM_Int|MEM_Real|MEM_Null))!=0 );
  58029. pMem->flags &= ~(MEM_Str|MEM_Blob);
  58030. return SQLITE_OK;
  58031. }
  58032. /*
  58033. ** Cast the datatype of the value in pMem according to the affinity
  58034. ** "aff". Casting is different from applying affinity in that a cast
  58035. ** is forced. In other words, the value is converted into the desired
  58036. ** affinity even if that results in loss of data. This routine is
  58037. ** used (for example) to implement the SQL "cast()" operator.
  58038. */
  58039. SQLITE_PRIVATE void sqlite3VdbeMemCast(Mem *pMem, u8 aff, u8 encoding){
  58040. if( pMem->flags & MEM_Null ) return;
  58041. switch( aff ){
  58042. case SQLITE_AFF_NONE: { /* Really a cast to BLOB */
  58043. if( (pMem->flags & MEM_Blob)==0 ){
  58044. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  58045. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  58046. MemSetTypeFlag(pMem, MEM_Blob);
  58047. }else{
  58048. pMem->flags &= ~(MEM_TypeMask&~MEM_Blob);
  58049. }
  58050. break;
  58051. }
  58052. case SQLITE_AFF_NUMERIC: {
  58053. sqlite3VdbeMemNumerify(pMem);
  58054. break;
  58055. }
  58056. case SQLITE_AFF_INTEGER: {
  58057. sqlite3VdbeMemIntegerify(pMem);
  58058. break;
  58059. }
  58060. case SQLITE_AFF_REAL: {
  58061. sqlite3VdbeMemRealify(pMem);
  58062. break;
  58063. }
  58064. default: {
  58065. assert( aff==SQLITE_AFF_TEXT );
  58066. assert( MEM_Str==(MEM_Blob>>3) );
  58067. pMem->flags |= (pMem->flags&MEM_Blob)>>3;
  58068. sqlite3ValueApplyAffinity(pMem, SQLITE_AFF_TEXT, encoding);
  58069. assert( pMem->flags & MEM_Str || pMem->db->mallocFailed );
  58070. pMem->flags &= ~(MEM_Int|MEM_Real|MEM_Blob|MEM_Zero);
  58071. break;
  58072. }
  58073. }
  58074. }
  58075. /*
  58076. ** Initialize bulk memory to be a consistent Mem object.
  58077. **
  58078. ** The minimum amount of initialization feasible is performed.
  58079. */
  58080. SQLITE_PRIVATE void sqlite3VdbeMemInit(Mem *pMem, sqlite3 *db, u16 flags){
  58081. assert( (flags & ~MEM_TypeMask)==0 );
  58082. pMem->flags = flags;
  58083. pMem->db = db;
  58084. pMem->szMalloc = 0;
  58085. }
  58086. /*
  58087. ** Delete any previous value and set the value stored in *pMem to NULL.
  58088. **
  58089. ** This routine calls the Mem.xDel destructor to dispose of values that
  58090. ** require the destructor. But it preserves the Mem.zMalloc memory allocation.
  58091. ** To free all resources, use sqlite3VdbeMemRelease(), which both calls this
  58092. ** routine to invoke the destructor and deallocates Mem.zMalloc.
  58093. **
  58094. ** Use this routine to reset the Mem prior to insert a new value.
  58095. **
  58096. ** Use sqlite3VdbeMemRelease() to complete erase the Mem prior to abandoning it.
  58097. */
  58098. SQLITE_PRIVATE void sqlite3VdbeMemSetNull(Mem *pMem){
  58099. if( VdbeMemDynamic(pMem) ){
  58100. vdbeMemClearExternAndSetNull(pMem);
  58101. }else{
  58102. pMem->flags = MEM_Null;
  58103. }
  58104. }
  58105. SQLITE_PRIVATE void sqlite3ValueSetNull(sqlite3_value *p){
  58106. sqlite3VdbeMemSetNull((Mem*)p);
  58107. }
  58108. /*
  58109. ** Delete any previous value and set the value to be a BLOB of length
  58110. ** n containing all zeros.
  58111. */
  58112. SQLITE_PRIVATE void sqlite3VdbeMemSetZeroBlob(Mem *pMem, int n){
  58113. sqlite3VdbeMemRelease(pMem);
  58114. pMem->flags = MEM_Blob|MEM_Zero;
  58115. pMem->n = 0;
  58116. if( n<0 ) n = 0;
  58117. pMem->u.nZero = n;
  58118. pMem->enc = SQLITE_UTF8;
  58119. pMem->z = 0;
  58120. }
  58121. /*
  58122. ** The pMem is known to contain content that needs to be destroyed prior
  58123. ** to a value change. So invoke the destructor, then set the value to
  58124. ** a 64-bit integer.
  58125. */
  58126. static SQLITE_NOINLINE void vdbeReleaseAndSetInt64(Mem *pMem, i64 val){
  58127. sqlite3VdbeMemSetNull(pMem);
  58128. pMem->u.i = val;
  58129. pMem->flags = MEM_Int;
  58130. }
  58131. /*
  58132. ** Delete any previous value and set the value stored in *pMem to val,
  58133. ** manifest type INTEGER.
  58134. */
  58135. SQLITE_PRIVATE void sqlite3VdbeMemSetInt64(Mem *pMem, i64 val){
  58136. if( VdbeMemDynamic(pMem) ){
  58137. vdbeReleaseAndSetInt64(pMem, val);
  58138. }else{
  58139. pMem->u.i = val;
  58140. pMem->flags = MEM_Int;
  58141. }
  58142. }
  58143. #ifndef SQLITE_OMIT_FLOATING_POINT
  58144. /*
  58145. ** Delete any previous value and set the value stored in *pMem to val,
  58146. ** manifest type REAL.
  58147. */
  58148. SQLITE_PRIVATE void sqlite3VdbeMemSetDouble(Mem *pMem, double val){
  58149. sqlite3VdbeMemSetNull(pMem);
  58150. if( !sqlite3IsNaN(val) ){
  58151. pMem->u.r = val;
  58152. pMem->flags = MEM_Real;
  58153. }
  58154. }
  58155. #endif
  58156. /*
  58157. ** Delete any previous value and set the value of pMem to be an
  58158. ** empty boolean index.
  58159. */
  58160. SQLITE_PRIVATE void sqlite3VdbeMemSetRowSet(Mem *pMem){
  58161. sqlite3 *db = pMem->db;
  58162. assert( db!=0 );
  58163. assert( (pMem->flags & MEM_RowSet)==0 );
  58164. sqlite3VdbeMemRelease(pMem);
  58165. pMem->zMalloc = sqlite3DbMallocRaw(db, 64);
  58166. if( db->mallocFailed ){
  58167. pMem->flags = MEM_Null;
  58168. pMem->szMalloc = 0;
  58169. }else{
  58170. assert( pMem->zMalloc );
  58171. pMem->szMalloc = sqlite3DbMallocSize(db, pMem->zMalloc);
  58172. pMem->u.pRowSet = sqlite3RowSetInit(db, pMem->zMalloc, pMem->szMalloc);
  58173. assert( pMem->u.pRowSet!=0 );
  58174. pMem->flags = MEM_RowSet;
  58175. }
  58176. }
  58177. /*
  58178. ** Return true if the Mem object contains a TEXT or BLOB that is
  58179. ** too large - whose size exceeds SQLITE_MAX_LENGTH.
  58180. */
  58181. SQLITE_PRIVATE int sqlite3VdbeMemTooBig(Mem *p){
  58182. assert( p->db!=0 );
  58183. if( p->flags & (MEM_Str|MEM_Blob) ){
  58184. int n = p->n;
  58185. if( p->flags & MEM_Zero ){
  58186. n += p->u.nZero;
  58187. }
  58188. return n>p->db->aLimit[SQLITE_LIMIT_LENGTH];
  58189. }
  58190. return 0;
  58191. }
  58192. #ifdef SQLITE_DEBUG
  58193. /*
  58194. ** This routine prepares a memory cell for modification by breaking
  58195. ** its link to a shallow copy and by marking any current shallow
  58196. ** copies of this cell as invalid.
  58197. **
  58198. ** This is used for testing and debugging only - to make sure shallow
  58199. ** copies are not misused.
  58200. */
  58201. SQLITE_PRIVATE void sqlite3VdbeMemAboutToChange(Vdbe *pVdbe, Mem *pMem){
  58202. int i;
  58203. Mem *pX;
  58204. for(i=1, pX=&pVdbe->aMem[1]; i<=pVdbe->nMem; i++, pX++){
  58205. if( pX->pScopyFrom==pMem ){
  58206. pX->flags |= MEM_Undefined;
  58207. pX->pScopyFrom = 0;
  58208. }
  58209. }
  58210. pMem->pScopyFrom = 0;
  58211. }
  58212. #endif /* SQLITE_DEBUG */
  58213. /*
  58214. ** Size of struct Mem not including the Mem.zMalloc member.
  58215. */
  58216. #define MEMCELLSIZE offsetof(Mem,zMalloc)
  58217. /*
  58218. ** Make an shallow copy of pFrom into pTo. Prior contents of
  58219. ** pTo are freed. The pFrom->z field is not duplicated. If
  58220. ** pFrom->z is used, then pTo->z points to the same thing as pFrom->z
  58221. ** and flags gets srcType (either MEM_Ephem or MEM_Static).
  58222. */
  58223. SQLITE_PRIVATE void sqlite3VdbeMemShallowCopy(Mem *pTo, const Mem *pFrom, int srcType){
  58224. assert( (pFrom->flags & MEM_RowSet)==0 );
  58225. assert( pTo->db==pFrom->db );
  58226. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  58227. memcpy(pTo, pFrom, MEMCELLSIZE);
  58228. if( (pFrom->flags&MEM_Static)==0 ){
  58229. pTo->flags &= ~(MEM_Dyn|MEM_Static|MEM_Ephem);
  58230. assert( srcType==MEM_Ephem || srcType==MEM_Static );
  58231. pTo->flags |= srcType;
  58232. }
  58233. }
  58234. /*
  58235. ** Make a full copy of pFrom into pTo. Prior contents of pTo are
  58236. ** freed before the copy is made.
  58237. */
  58238. SQLITE_PRIVATE int sqlite3VdbeMemCopy(Mem *pTo, const Mem *pFrom){
  58239. int rc = SQLITE_OK;
  58240. assert( pTo->db==pFrom->db );
  58241. assert( (pFrom->flags & MEM_RowSet)==0 );
  58242. if( VdbeMemDynamic(pTo) ) vdbeMemClearExternAndSetNull(pTo);
  58243. memcpy(pTo, pFrom, MEMCELLSIZE);
  58244. pTo->flags &= ~MEM_Dyn;
  58245. if( pTo->flags&(MEM_Str|MEM_Blob) ){
  58246. if( 0==(pFrom->flags&MEM_Static) ){
  58247. pTo->flags |= MEM_Ephem;
  58248. rc = sqlite3VdbeMemMakeWriteable(pTo);
  58249. }
  58250. }
  58251. return rc;
  58252. }
  58253. /*
  58254. ** Transfer the contents of pFrom to pTo. Any existing value in pTo is
  58255. ** freed. If pFrom contains ephemeral data, a copy is made.
  58256. **
  58257. ** pFrom contains an SQL NULL when this routine returns.
  58258. */
  58259. SQLITE_PRIVATE void sqlite3VdbeMemMove(Mem *pTo, Mem *pFrom){
  58260. assert( pFrom->db==0 || sqlite3_mutex_held(pFrom->db->mutex) );
  58261. assert( pTo->db==0 || sqlite3_mutex_held(pTo->db->mutex) );
  58262. assert( pFrom->db==0 || pTo->db==0 || pFrom->db==pTo->db );
  58263. sqlite3VdbeMemRelease(pTo);
  58264. memcpy(pTo, pFrom, sizeof(Mem));
  58265. pFrom->flags = MEM_Null;
  58266. pFrom->szMalloc = 0;
  58267. }
  58268. /*
  58269. ** Change the value of a Mem to be a string or a BLOB.
  58270. **
  58271. ** The memory management strategy depends on the value of the xDel
  58272. ** parameter. If the value passed is SQLITE_TRANSIENT, then the
  58273. ** string is copied into a (possibly existing) buffer managed by the
  58274. ** Mem structure. Otherwise, any existing buffer is freed and the
  58275. ** pointer copied.
  58276. **
  58277. ** If the string is too large (if it exceeds the SQLITE_LIMIT_LENGTH
  58278. ** size limit) then no memory allocation occurs. If the string can be
  58279. ** stored without allocating memory, then it is. If a memory allocation
  58280. ** is required to store the string, then value of pMem is unchanged. In
  58281. ** either case, SQLITE_TOOBIG is returned.
  58282. */
  58283. SQLITE_PRIVATE int sqlite3VdbeMemSetStr(
  58284. Mem *pMem, /* Memory cell to set to string value */
  58285. const char *z, /* String pointer */
  58286. int n, /* Bytes in string, or negative */
  58287. u8 enc, /* Encoding of z. 0 for BLOBs */
  58288. void (*xDel)(void*) /* Destructor function */
  58289. ){
  58290. int nByte = n; /* New value for pMem->n */
  58291. int iLimit; /* Maximum allowed string or blob size */
  58292. u16 flags = 0; /* New value for pMem->flags */
  58293. assert( pMem->db==0 || sqlite3_mutex_held(pMem->db->mutex) );
  58294. assert( (pMem->flags & MEM_RowSet)==0 );
  58295. /* If z is a NULL pointer, set pMem to contain an SQL NULL. */
  58296. if( !z ){
  58297. sqlite3VdbeMemSetNull(pMem);
  58298. return SQLITE_OK;
  58299. }
  58300. if( pMem->db ){
  58301. iLimit = pMem->db->aLimit[SQLITE_LIMIT_LENGTH];
  58302. }else{
  58303. iLimit = SQLITE_MAX_LENGTH;
  58304. }
  58305. flags = (enc==0?MEM_Blob:MEM_Str);
  58306. if( nByte<0 ){
  58307. assert( enc!=0 );
  58308. if( enc==SQLITE_UTF8 ){
  58309. nByte = sqlite3Strlen30(z);
  58310. if( nByte>iLimit ) nByte = iLimit+1;
  58311. }else{
  58312. for(nByte=0; nByte<=iLimit && (z[nByte] | z[nByte+1]); nByte+=2){}
  58313. }
  58314. flags |= MEM_Term;
  58315. }
  58316. /* The following block sets the new values of Mem.z and Mem.xDel. It
  58317. ** also sets a flag in local variable "flags" to indicate the memory
  58318. ** management (one of MEM_Dyn or MEM_Static).
  58319. */
  58320. if( xDel==SQLITE_TRANSIENT ){
  58321. int nAlloc = nByte;
  58322. if( flags&MEM_Term ){
  58323. nAlloc += (enc==SQLITE_UTF8?1:2);
  58324. }
  58325. if( nByte>iLimit ){
  58326. return SQLITE_TOOBIG;
  58327. }
  58328. testcase( nAlloc==0 );
  58329. testcase( nAlloc==31 );
  58330. testcase( nAlloc==32 );
  58331. if( sqlite3VdbeMemClearAndResize(pMem, MAX(nAlloc,32)) ){
  58332. return SQLITE_NOMEM;
  58333. }
  58334. memcpy(pMem->z, z, nAlloc);
  58335. }else if( xDel==SQLITE_DYNAMIC ){
  58336. sqlite3VdbeMemRelease(pMem);
  58337. pMem->zMalloc = pMem->z = (char *)z;
  58338. pMem->szMalloc = sqlite3DbMallocSize(pMem->db, pMem->zMalloc);
  58339. }else{
  58340. sqlite3VdbeMemRelease(pMem);
  58341. pMem->z = (char *)z;
  58342. pMem->xDel = xDel;
  58343. flags |= ((xDel==SQLITE_STATIC)?MEM_Static:MEM_Dyn);
  58344. }
  58345. pMem->n = nByte;
  58346. pMem->flags = flags;
  58347. pMem->enc = (enc==0 ? SQLITE_UTF8 : enc);
  58348. #ifndef SQLITE_OMIT_UTF16
  58349. if( pMem->enc!=SQLITE_UTF8 && sqlite3VdbeMemHandleBom(pMem) ){
  58350. return SQLITE_NOMEM;
  58351. }
  58352. #endif
  58353. if( nByte>iLimit ){
  58354. return SQLITE_TOOBIG;
  58355. }
  58356. return SQLITE_OK;
  58357. }
  58358. /*
  58359. ** Move data out of a btree key or data field and into a Mem structure.
  58360. ** The data or key is taken from the entry that pCur is currently pointing
  58361. ** to. offset and amt determine what portion of the data or key to retrieve.
  58362. ** key is true to get the key or false to get data. The result is written
  58363. ** into the pMem element.
  58364. **
  58365. ** The pMem object must have been initialized. This routine will use
  58366. ** pMem->zMalloc to hold the content from the btree, if possible. New
  58367. ** pMem->zMalloc space will be allocated if necessary. The calling routine
  58368. ** is responsible for making sure that the pMem object is eventually
  58369. ** destroyed.
  58370. **
  58371. ** If this routine fails for any reason (malloc returns NULL or unable
  58372. ** to read from the disk) then the pMem is left in an inconsistent state.
  58373. */
  58374. SQLITE_PRIVATE int sqlite3VdbeMemFromBtree(
  58375. BtCursor *pCur, /* Cursor pointing at record to retrieve. */
  58376. u32 offset, /* Offset from the start of data to return bytes from. */
  58377. u32 amt, /* Number of bytes to return. */
  58378. int key, /* If true, retrieve from the btree key, not data. */
  58379. Mem *pMem /* OUT: Return data in this Mem structure. */
  58380. ){
  58381. char *zData; /* Data from the btree layer */
  58382. u32 available = 0; /* Number of bytes available on the local btree page */
  58383. int rc = SQLITE_OK; /* Return code */
  58384. assert( sqlite3BtreeCursorIsValid(pCur) );
  58385. assert( !VdbeMemDynamic(pMem) );
  58386. /* Note: the calls to BtreeKeyFetch() and DataFetch() below assert()
  58387. ** that both the BtShared and database handle mutexes are held. */
  58388. assert( (pMem->flags & MEM_RowSet)==0 );
  58389. if( key ){
  58390. zData = (char *)sqlite3BtreeKeyFetch(pCur, &available);
  58391. }else{
  58392. zData = (char *)sqlite3BtreeDataFetch(pCur, &available);
  58393. }
  58394. assert( zData!=0 );
  58395. if( offset+amt<=available ){
  58396. pMem->z = &zData[offset];
  58397. pMem->flags = MEM_Blob|MEM_Ephem;
  58398. pMem->n = (int)amt;
  58399. }else{
  58400. pMem->flags = MEM_Null;
  58401. if( SQLITE_OK==(rc = sqlite3VdbeMemClearAndResize(pMem, amt+2)) ){
  58402. if( key ){
  58403. rc = sqlite3BtreeKey(pCur, offset, amt, pMem->z);
  58404. }else{
  58405. rc = sqlite3BtreeData(pCur, offset, amt, pMem->z);
  58406. }
  58407. if( rc==SQLITE_OK ){
  58408. pMem->z[amt] = 0;
  58409. pMem->z[amt+1] = 0;
  58410. pMem->flags = MEM_Blob|MEM_Term;
  58411. pMem->n = (int)amt;
  58412. }else{
  58413. sqlite3VdbeMemRelease(pMem);
  58414. }
  58415. }
  58416. }
  58417. return rc;
  58418. }
  58419. /*
  58420. ** The pVal argument is known to be a value other than NULL.
  58421. ** Convert it into a string with encoding enc and return a pointer
  58422. ** to a zero-terminated version of that string.
  58423. */
  58424. static SQLITE_NOINLINE const void *valueToText(sqlite3_value* pVal, u8 enc){
  58425. assert( pVal!=0 );
  58426. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  58427. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  58428. assert( (pVal->flags & MEM_RowSet)==0 );
  58429. assert( (pVal->flags & (MEM_Null))==0 );
  58430. if( pVal->flags & (MEM_Blob|MEM_Str) ){
  58431. pVal->flags |= MEM_Str;
  58432. if( pVal->flags & MEM_Zero ){
  58433. sqlite3VdbeMemExpandBlob(pVal);
  58434. }
  58435. if( pVal->enc != (enc & ~SQLITE_UTF16_ALIGNED) ){
  58436. sqlite3VdbeChangeEncoding(pVal, enc & ~SQLITE_UTF16_ALIGNED);
  58437. }
  58438. if( (enc & SQLITE_UTF16_ALIGNED)!=0 && 1==(1&SQLITE_PTR_TO_INT(pVal->z)) ){
  58439. assert( (pVal->flags & (MEM_Ephem|MEM_Static))!=0 );
  58440. if( sqlite3VdbeMemMakeWriteable(pVal)!=SQLITE_OK ){
  58441. return 0;
  58442. }
  58443. }
  58444. sqlite3VdbeMemNulTerminate(pVal); /* IMP: R-31275-44060 */
  58445. }else{
  58446. sqlite3VdbeMemStringify(pVal, enc, 0);
  58447. assert( 0==(1&SQLITE_PTR_TO_INT(pVal->z)) );
  58448. }
  58449. assert(pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) || pVal->db==0
  58450. || pVal->db->mallocFailed );
  58451. if( pVal->enc==(enc & ~SQLITE_UTF16_ALIGNED) ){
  58452. return pVal->z;
  58453. }else{
  58454. return 0;
  58455. }
  58456. }
  58457. /* This function is only available internally, it is not part of the
  58458. ** external API. It works in a similar way to sqlite3_value_text(),
  58459. ** except the data returned is in the encoding specified by the second
  58460. ** parameter, which must be one of SQLITE_UTF16BE, SQLITE_UTF16LE or
  58461. ** SQLITE_UTF8.
  58462. **
  58463. ** (2006-02-16:) The enc value can be or-ed with SQLITE_UTF16_ALIGNED.
  58464. ** If that is the case, then the result must be aligned on an even byte
  58465. ** boundary.
  58466. */
  58467. SQLITE_PRIVATE const void *sqlite3ValueText(sqlite3_value* pVal, u8 enc){
  58468. if( !pVal ) return 0;
  58469. assert( pVal->db==0 || sqlite3_mutex_held(pVal->db->mutex) );
  58470. assert( (enc&3)==(enc&~SQLITE_UTF16_ALIGNED) );
  58471. assert( (pVal->flags & MEM_RowSet)==0 );
  58472. if( (pVal->flags&(MEM_Str|MEM_Term))==(MEM_Str|MEM_Term) && pVal->enc==enc ){
  58473. return pVal->z;
  58474. }
  58475. if( pVal->flags&MEM_Null ){
  58476. return 0;
  58477. }
  58478. return valueToText(pVal, enc);
  58479. }
  58480. /*
  58481. ** Create a new sqlite3_value object.
  58482. */
  58483. SQLITE_PRIVATE sqlite3_value *sqlite3ValueNew(sqlite3 *db){
  58484. Mem *p = sqlite3DbMallocZero(db, sizeof(*p));
  58485. if( p ){
  58486. p->flags = MEM_Null;
  58487. p->db = db;
  58488. }
  58489. return p;
  58490. }
  58491. /*
  58492. ** Context object passed by sqlite3Stat4ProbeSetValue() through to
  58493. ** valueNew(). See comments above valueNew() for details.
  58494. */
  58495. struct ValueNewStat4Ctx {
  58496. Parse *pParse;
  58497. Index *pIdx;
  58498. UnpackedRecord **ppRec;
  58499. int iVal;
  58500. };
  58501. /*
  58502. ** Allocate and return a pointer to a new sqlite3_value object. If
  58503. ** the second argument to this function is NULL, the object is allocated
  58504. ** by calling sqlite3ValueNew().
  58505. **
  58506. ** Otherwise, if the second argument is non-zero, then this function is
  58507. ** being called indirectly by sqlite3Stat4ProbeSetValue(). If it has not
  58508. ** already been allocated, allocate the UnpackedRecord structure that
  58509. ** that function will return to its caller here. Then return a pointer
  58510. ** an sqlite3_value within the UnpackedRecord.a[] array.
  58511. */
  58512. static sqlite3_value *valueNew(sqlite3 *db, struct ValueNewStat4Ctx *p){
  58513. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  58514. if( p ){
  58515. UnpackedRecord *pRec = p->ppRec[0];
  58516. if( pRec==0 ){
  58517. Index *pIdx = p->pIdx; /* Index being probed */
  58518. int nByte; /* Bytes of space to allocate */
  58519. int i; /* Counter variable */
  58520. int nCol = pIdx->nColumn; /* Number of index columns including rowid */
  58521. nByte = sizeof(Mem) * nCol + ROUND8(sizeof(UnpackedRecord));
  58522. pRec = (UnpackedRecord*)sqlite3DbMallocZero(db, nByte);
  58523. if( pRec ){
  58524. pRec->pKeyInfo = sqlite3KeyInfoOfIndex(p->pParse, pIdx);
  58525. if( pRec->pKeyInfo ){
  58526. assert( pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField==nCol );
  58527. assert( pRec->pKeyInfo->enc==ENC(db) );
  58528. pRec->aMem = (Mem *)((u8*)pRec + ROUND8(sizeof(UnpackedRecord)));
  58529. for(i=0; i<nCol; i++){
  58530. pRec->aMem[i].flags = MEM_Null;
  58531. pRec->aMem[i].db = db;
  58532. }
  58533. }else{
  58534. sqlite3DbFree(db, pRec);
  58535. pRec = 0;
  58536. }
  58537. }
  58538. if( pRec==0 ) return 0;
  58539. p->ppRec[0] = pRec;
  58540. }
  58541. pRec->nField = p->iVal+1;
  58542. return &pRec->aMem[p->iVal];
  58543. }
  58544. #else
  58545. UNUSED_PARAMETER(p);
  58546. #endif /* defined(SQLITE_ENABLE_STAT3_OR_STAT4) */
  58547. return sqlite3ValueNew(db);
  58548. }
  58549. /*
  58550. ** Extract a value from the supplied expression in the manner described
  58551. ** above sqlite3ValueFromExpr(). Allocate the sqlite3_value object
  58552. ** using valueNew().
  58553. **
  58554. ** If pCtx is NULL and an error occurs after the sqlite3_value object
  58555. ** has been allocated, it is freed before returning. Or, if pCtx is not
  58556. ** NULL, it is assumed that the caller will free any allocated object
  58557. ** in all cases.
  58558. */
  58559. static int valueFromExpr(
  58560. sqlite3 *db, /* The database connection */
  58561. Expr *pExpr, /* The expression to evaluate */
  58562. u8 enc, /* Encoding to use */
  58563. u8 affinity, /* Affinity to use */
  58564. sqlite3_value **ppVal, /* Write the new value here */
  58565. struct ValueNewStat4Ctx *pCtx /* Second argument for valueNew() */
  58566. ){
  58567. int op;
  58568. char *zVal = 0;
  58569. sqlite3_value *pVal = 0;
  58570. int negInt = 1;
  58571. const char *zNeg = "";
  58572. int rc = SQLITE_OK;
  58573. if( !pExpr ){
  58574. *ppVal = 0;
  58575. return SQLITE_OK;
  58576. }
  58577. while( (op = pExpr->op)==TK_UPLUS ) pExpr = pExpr->pLeft;
  58578. if( NEVER(op==TK_REGISTER) ) op = pExpr->op2;
  58579. if( op==TK_CAST ){
  58580. u8 aff = sqlite3AffinityType(pExpr->u.zToken,0);
  58581. rc = valueFromExpr(db, pExpr->pLeft, enc, aff, ppVal, pCtx);
  58582. testcase( rc!=SQLITE_OK );
  58583. if( *ppVal ){
  58584. sqlite3VdbeMemCast(*ppVal, aff, SQLITE_UTF8);
  58585. sqlite3ValueApplyAffinity(*ppVal, affinity, SQLITE_UTF8);
  58586. }
  58587. return rc;
  58588. }
  58589. /* Handle negative integers in a single step. This is needed in the
  58590. ** case when the value is -9223372036854775808.
  58591. */
  58592. if( op==TK_UMINUS
  58593. && (pExpr->pLeft->op==TK_INTEGER || pExpr->pLeft->op==TK_FLOAT) ){
  58594. pExpr = pExpr->pLeft;
  58595. op = pExpr->op;
  58596. negInt = -1;
  58597. zNeg = "-";
  58598. }
  58599. if( op==TK_STRING || op==TK_FLOAT || op==TK_INTEGER ){
  58600. pVal = valueNew(db, pCtx);
  58601. if( pVal==0 ) goto no_mem;
  58602. if( ExprHasProperty(pExpr, EP_IntValue) ){
  58603. sqlite3VdbeMemSetInt64(pVal, (i64)pExpr->u.iValue*negInt);
  58604. }else{
  58605. zVal = sqlite3MPrintf(db, "%s%s", zNeg, pExpr->u.zToken);
  58606. if( zVal==0 ) goto no_mem;
  58607. sqlite3ValueSetStr(pVal, -1, zVal, SQLITE_UTF8, SQLITE_DYNAMIC);
  58608. }
  58609. if( (op==TK_INTEGER || op==TK_FLOAT ) && affinity==SQLITE_AFF_NONE ){
  58610. sqlite3ValueApplyAffinity(pVal, SQLITE_AFF_NUMERIC, SQLITE_UTF8);
  58611. }else{
  58612. sqlite3ValueApplyAffinity(pVal, affinity, SQLITE_UTF8);
  58613. }
  58614. if( pVal->flags & (MEM_Int|MEM_Real) ) pVal->flags &= ~MEM_Str;
  58615. if( enc!=SQLITE_UTF8 ){
  58616. rc = sqlite3VdbeChangeEncoding(pVal, enc);
  58617. }
  58618. }else if( op==TK_UMINUS ) {
  58619. /* This branch happens for multiple negative signs. Ex: -(-5) */
  58620. if( SQLITE_OK==sqlite3ValueFromExpr(db,pExpr->pLeft,enc,affinity,&pVal)
  58621. && pVal!=0
  58622. ){
  58623. sqlite3VdbeMemNumerify(pVal);
  58624. if( pVal->flags & MEM_Real ){
  58625. pVal->u.r = -pVal->u.r;
  58626. }else if( pVal->u.i==SMALLEST_INT64 ){
  58627. pVal->u.r = -(double)SMALLEST_INT64;
  58628. MemSetTypeFlag(pVal, MEM_Real);
  58629. }else{
  58630. pVal->u.i = -pVal->u.i;
  58631. }
  58632. sqlite3ValueApplyAffinity(pVal, affinity, enc);
  58633. }
  58634. }else if( op==TK_NULL ){
  58635. pVal = valueNew(db, pCtx);
  58636. if( pVal==0 ) goto no_mem;
  58637. }
  58638. #ifndef SQLITE_OMIT_BLOB_LITERAL
  58639. else if( op==TK_BLOB ){
  58640. int nVal;
  58641. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  58642. assert( pExpr->u.zToken[1]=='\'' );
  58643. pVal = valueNew(db, pCtx);
  58644. if( !pVal ) goto no_mem;
  58645. zVal = &pExpr->u.zToken[2];
  58646. nVal = sqlite3Strlen30(zVal)-1;
  58647. assert( zVal[nVal]=='\'' );
  58648. sqlite3VdbeMemSetStr(pVal, sqlite3HexToBlob(db, zVal, nVal), nVal/2,
  58649. 0, SQLITE_DYNAMIC);
  58650. }
  58651. #endif
  58652. *ppVal = pVal;
  58653. return rc;
  58654. no_mem:
  58655. db->mallocFailed = 1;
  58656. sqlite3DbFree(db, zVal);
  58657. assert( *ppVal==0 );
  58658. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  58659. if( pCtx==0 ) sqlite3ValueFree(pVal);
  58660. #else
  58661. assert( pCtx==0 ); sqlite3ValueFree(pVal);
  58662. #endif
  58663. return SQLITE_NOMEM;
  58664. }
  58665. /*
  58666. ** Create a new sqlite3_value object, containing the value of pExpr.
  58667. **
  58668. ** This only works for very simple expressions that consist of one constant
  58669. ** token (i.e. "5", "5.1", "'a string'"). If the expression can
  58670. ** be converted directly into a value, then the value is allocated and
  58671. ** a pointer written to *ppVal. The caller is responsible for deallocating
  58672. ** the value by passing it to sqlite3ValueFree() later on. If the expression
  58673. ** cannot be converted to a value, then *ppVal is set to NULL.
  58674. */
  58675. SQLITE_PRIVATE int sqlite3ValueFromExpr(
  58676. sqlite3 *db, /* The database connection */
  58677. Expr *pExpr, /* The expression to evaluate */
  58678. u8 enc, /* Encoding to use */
  58679. u8 affinity, /* Affinity to use */
  58680. sqlite3_value **ppVal /* Write the new value here */
  58681. ){
  58682. return valueFromExpr(db, pExpr, enc, affinity, ppVal, 0);
  58683. }
  58684. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  58685. /*
  58686. ** The implementation of the sqlite_record() function. This function accepts
  58687. ** a single argument of any type. The return value is a formatted database
  58688. ** record (a blob) containing the argument value.
  58689. **
  58690. ** This is used to convert the value stored in the 'sample' column of the
  58691. ** sqlite_stat3 table to the record format SQLite uses internally.
  58692. */
  58693. static void recordFunc(
  58694. sqlite3_context *context,
  58695. int argc,
  58696. sqlite3_value **argv
  58697. ){
  58698. const int file_format = 1;
  58699. int iSerial; /* Serial type */
  58700. int nSerial; /* Bytes of space for iSerial as varint */
  58701. int nVal; /* Bytes of space required for argv[0] */
  58702. int nRet;
  58703. sqlite3 *db;
  58704. u8 *aRet;
  58705. UNUSED_PARAMETER( argc );
  58706. iSerial = sqlite3VdbeSerialType(argv[0], file_format);
  58707. nSerial = sqlite3VarintLen(iSerial);
  58708. nVal = sqlite3VdbeSerialTypeLen(iSerial);
  58709. db = sqlite3_context_db_handle(context);
  58710. nRet = 1 + nSerial + nVal;
  58711. aRet = sqlite3DbMallocRaw(db, nRet);
  58712. if( aRet==0 ){
  58713. sqlite3_result_error_nomem(context);
  58714. }else{
  58715. aRet[0] = nSerial+1;
  58716. putVarint32(&aRet[1], iSerial);
  58717. sqlite3VdbeSerialPut(&aRet[1+nSerial], argv[0], iSerial);
  58718. sqlite3_result_blob(context, aRet, nRet, SQLITE_TRANSIENT);
  58719. sqlite3DbFree(db, aRet);
  58720. }
  58721. }
  58722. /*
  58723. ** Register built-in functions used to help read ANALYZE data.
  58724. */
  58725. SQLITE_PRIVATE void sqlite3AnalyzeFunctions(void){
  58726. static SQLITE_WSD FuncDef aAnalyzeTableFuncs[] = {
  58727. FUNCTION(sqlite_record, 1, 0, 0, recordFunc),
  58728. };
  58729. int i;
  58730. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  58731. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAnalyzeTableFuncs);
  58732. for(i=0; i<ArraySize(aAnalyzeTableFuncs); i++){
  58733. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  58734. }
  58735. }
  58736. /*
  58737. ** Attempt to extract a value from pExpr and use it to construct *ppVal.
  58738. **
  58739. ** If pAlloc is not NULL, then an UnpackedRecord object is created for
  58740. ** pAlloc if one does not exist and the new value is added to the
  58741. ** UnpackedRecord object.
  58742. **
  58743. ** A value is extracted in the following cases:
  58744. **
  58745. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  58746. **
  58747. ** * The expression is a bound variable, and this is a reprepare, or
  58748. **
  58749. ** * The expression is a literal value.
  58750. **
  58751. ** On success, *ppVal is made to point to the extracted value. The caller
  58752. ** is responsible for ensuring that the value is eventually freed.
  58753. */
  58754. static int stat4ValueFromExpr(
  58755. Parse *pParse, /* Parse context */
  58756. Expr *pExpr, /* The expression to extract a value from */
  58757. u8 affinity, /* Affinity to use */
  58758. struct ValueNewStat4Ctx *pAlloc,/* How to allocate space. Or NULL */
  58759. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  58760. ){
  58761. int rc = SQLITE_OK;
  58762. sqlite3_value *pVal = 0;
  58763. sqlite3 *db = pParse->db;
  58764. /* Skip over any TK_COLLATE nodes */
  58765. pExpr = sqlite3ExprSkipCollate(pExpr);
  58766. if( !pExpr ){
  58767. pVal = valueNew(db, pAlloc);
  58768. if( pVal ){
  58769. sqlite3VdbeMemSetNull((Mem*)pVal);
  58770. }
  58771. }else if( pExpr->op==TK_VARIABLE
  58772. || NEVER(pExpr->op==TK_REGISTER && pExpr->op2==TK_VARIABLE)
  58773. ){
  58774. Vdbe *v;
  58775. int iBindVar = pExpr->iColumn;
  58776. sqlite3VdbeSetVarmask(pParse->pVdbe, iBindVar);
  58777. if( (v = pParse->pReprepare)!=0 ){
  58778. pVal = valueNew(db, pAlloc);
  58779. if( pVal ){
  58780. rc = sqlite3VdbeMemCopy((Mem*)pVal, &v->aVar[iBindVar-1]);
  58781. if( rc==SQLITE_OK ){
  58782. sqlite3ValueApplyAffinity(pVal, affinity, ENC(db));
  58783. }
  58784. pVal->db = pParse->db;
  58785. }
  58786. }
  58787. }else{
  58788. rc = valueFromExpr(db, pExpr, ENC(db), affinity, &pVal, pAlloc);
  58789. }
  58790. assert( pVal==0 || pVal->db==db );
  58791. *ppVal = pVal;
  58792. return rc;
  58793. }
  58794. /*
  58795. ** This function is used to allocate and populate UnpackedRecord
  58796. ** structures intended to be compared against sample index keys stored
  58797. ** in the sqlite_stat4 table.
  58798. **
  58799. ** A single call to this function attempts to populates field iVal (leftmost
  58800. ** is 0 etc.) of the unpacked record with a value extracted from expression
  58801. ** pExpr. Extraction of values is possible if:
  58802. **
  58803. ** * (pExpr==0). In this case the value is assumed to be an SQL NULL,
  58804. **
  58805. ** * The expression is a bound variable, and this is a reprepare, or
  58806. **
  58807. ** * The sqlite3ValueFromExpr() function is able to extract a value
  58808. ** from the expression (i.e. the expression is a literal value).
  58809. **
  58810. ** If a value can be extracted, the affinity passed as the 5th argument
  58811. ** is applied to it before it is copied into the UnpackedRecord. Output
  58812. ** parameter *pbOk is set to true if a value is extracted, or false
  58813. ** otherwise.
  58814. **
  58815. ** When this function is called, *ppRec must either point to an object
  58816. ** allocated by an earlier call to this function, or must be NULL. If it
  58817. ** is NULL and a value can be successfully extracted, a new UnpackedRecord
  58818. ** is allocated (and *ppRec set to point to it) before returning.
  58819. **
  58820. ** Unless an error is encountered, SQLITE_OK is returned. It is not an
  58821. ** error if a value cannot be extracted from pExpr. If an error does
  58822. ** occur, an SQLite error code is returned.
  58823. */
  58824. SQLITE_PRIVATE int sqlite3Stat4ProbeSetValue(
  58825. Parse *pParse, /* Parse context */
  58826. Index *pIdx, /* Index being probed */
  58827. UnpackedRecord **ppRec, /* IN/OUT: Probe record */
  58828. Expr *pExpr, /* The expression to extract a value from */
  58829. u8 affinity, /* Affinity to use */
  58830. int iVal, /* Array element to populate */
  58831. int *pbOk /* OUT: True if value was extracted */
  58832. ){
  58833. int rc;
  58834. sqlite3_value *pVal = 0;
  58835. struct ValueNewStat4Ctx alloc;
  58836. alloc.pParse = pParse;
  58837. alloc.pIdx = pIdx;
  58838. alloc.ppRec = ppRec;
  58839. alloc.iVal = iVal;
  58840. rc = stat4ValueFromExpr(pParse, pExpr, affinity, &alloc, &pVal);
  58841. assert( pVal==0 || pVal->db==pParse->db );
  58842. *pbOk = (pVal!=0);
  58843. return rc;
  58844. }
  58845. /*
  58846. ** Attempt to extract a value from expression pExpr using the methods
  58847. ** as described for sqlite3Stat4ProbeSetValue() above.
  58848. **
  58849. ** If successful, set *ppVal to point to a new value object and return
  58850. ** SQLITE_OK. If no value can be extracted, but no other error occurs
  58851. ** (e.g. OOM), return SQLITE_OK and set *ppVal to NULL. Or, if an error
  58852. ** does occur, return an SQLite error code. The final value of *ppVal
  58853. ** is undefined in this case.
  58854. */
  58855. SQLITE_PRIVATE int sqlite3Stat4ValueFromExpr(
  58856. Parse *pParse, /* Parse context */
  58857. Expr *pExpr, /* The expression to extract a value from */
  58858. u8 affinity, /* Affinity to use */
  58859. sqlite3_value **ppVal /* OUT: New value object (or NULL) */
  58860. ){
  58861. return stat4ValueFromExpr(pParse, pExpr, affinity, 0, ppVal);
  58862. }
  58863. /*
  58864. ** Extract the iCol-th column from the nRec-byte record in pRec. Write
  58865. ** the column value into *ppVal. If *ppVal is initially NULL then a new
  58866. ** sqlite3_value object is allocated.
  58867. **
  58868. ** If *ppVal is initially NULL then the caller is responsible for
  58869. ** ensuring that the value written into *ppVal is eventually freed.
  58870. */
  58871. SQLITE_PRIVATE int sqlite3Stat4Column(
  58872. sqlite3 *db, /* Database handle */
  58873. const void *pRec, /* Pointer to buffer containing record */
  58874. int nRec, /* Size of buffer pRec in bytes */
  58875. int iCol, /* Column to extract */
  58876. sqlite3_value **ppVal /* OUT: Extracted value */
  58877. ){
  58878. u32 t; /* a column type code */
  58879. int nHdr; /* Size of the header in the record */
  58880. int iHdr; /* Next unread header byte */
  58881. int iField; /* Next unread data byte */
  58882. int szField; /* Size of the current data field */
  58883. int i; /* Column index */
  58884. u8 *a = (u8*)pRec; /* Typecast byte array */
  58885. Mem *pMem = *ppVal; /* Write result into this Mem object */
  58886. assert( iCol>0 );
  58887. iHdr = getVarint32(a, nHdr);
  58888. if( nHdr>nRec || iHdr>=nHdr ) return SQLITE_CORRUPT_BKPT;
  58889. iField = nHdr;
  58890. for(i=0; i<=iCol; i++){
  58891. iHdr += getVarint32(&a[iHdr], t);
  58892. testcase( iHdr==nHdr );
  58893. testcase( iHdr==nHdr+1 );
  58894. if( iHdr>nHdr ) return SQLITE_CORRUPT_BKPT;
  58895. szField = sqlite3VdbeSerialTypeLen(t);
  58896. iField += szField;
  58897. }
  58898. testcase( iField==nRec );
  58899. testcase( iField==nRec+1 );
  58900. if( iField>nRec ) return SQLITE_CORRUPT_BKPT;
  58901. if( pMem==0 ){
  58902. pMem = *ppVal = sqlite3ValueNew(db);
  58903. if( pMem==0 ) return SQLITE_NOMEM;
  58904. }
  58905. sqlite3VdbeSerialGet(&a[iField-szField], t, pMem);
  58906. pMem->enc = ENC(db);
  58907. return SQLITE_OK;
  58908. }
  58909. /*
  58910. ** Unless it is NULL, the argument must be an UnpackedRecord object returned
  58911. ** by an earlier call to sqlite3Stat4ProbeSetValue(). This call deletes
  58912. ** the object.
  58913. */
  58914. SQLITE_PRIVATE void sqlite3Stat4ProbeFree(UnpackedRecord *pRec){
  58915. if( pRec ){
  58916. int i;
  58917. int nCol = pRec->pKeyInfo->nField+pRec->pKeyInfo->nXField;
  58918. Mem *aMem = pRec->aMem;
  58919. sqlite3 *db = aMem[0].db;
  58920. for(i=0; i<nCol; i++){
  58921. if( aMem[i].szMalloc ) sqlite3DbFree(db, aMem[i].zMalloc);
  58922. }
  58923. sqlite3KeyInfoUnref(pRec->pKeyInfo);
  58924. sqlite3DbFree(db, pRec);
  58925. }
  58926. }
  58927. #endif /* ifdef SQLITE_ENABLE_STAT4 */
  58928. /*
  58929. ** Change the string value of an sqlite3_value object
  58930. */
  58931. SQLITE_PRIVATE void sqlite3ValueSetStr(
  58932. sqlite3_value *v, /* Value to be set */
  58933. int n, /* Length of string z */
  58934. const void *z, /* Text of the new string */
  58935. u8 enc, /* Encoding to use */
  58936. void (*xDel)(void*) /* Destructor for the string */
  58937. ){
  58938. if( v ) sqlite3VdbeMemSetStr((Mem *)v, z, n, enc, xDel);
  58939. }
  58940. /*
  58941. ** Free an sqlite3_value object
  58942. */
  58943. SQLITE_PRIVATE void sqlite3ValueFree(sqlite3_value *v){
  58944. if( !v ) return;
  58945. sqlite3VdbeMemRelease((Mem *)v);
  58946. sqlite3DbFree(((Mem*)v)->db, v);
  58947. }
  58948. /*
  58949. ** Return the number of bytes in the sqlite3_value object assuming
  58950. ** that it uses the encoding "enc"
  58951. */
  58952. SQLITE_PRIVATE int sqlite3ValueBytes(sqlite3_value *pVal, u8 enc){
  58953. Mem *p = (Mem*)pVal;
  58954. if( (p->flags & MEM_Blob)!=0 || sqlite3ValueText(pVal, enc) ){
  58955. if( p->flags & MEM_Zero ){
  58956. return p->n + p->u.nZero;
  58957. }else{
  58958. return p->n;
  58959. }
  58960. }
  58961. return 0;
  58962. }
  58963. /************** End of vdbemem.c *********************************************/
  58964. /************** Begin file vdbeaux.c *****************************************/
  58965. /*
  58966. ** 2003 September 6
  58967. **
  58968. ** The author disclaims copyright to this source code. In place of
  58969. ** a legal notice, here is a blessing:
  58970. **
  58971. ** May you do good and not evil.
  58972. ** May you find forgiveness for yourself and forgive others.
  58973. ** May you share freely, never taking more than you give.
  58974. **
  58975. *************************************************************************
  58976. ** This file contains code used for creating, destroying, and populating
  58977. ** a VDBE (or an "sqlite3_stmt" as it is known to the outside world.)
  58978. */
  58979. /*
  58980. ** Create a new virtual database engine.
  58981. */
  58982. SQLITE_PRIVATE Vdbe *sqlite3VdbeCreate(Parse *pParse){
  58983. sqlite3 *db = pParse->db;
  58984. Vdbe *p;
  58985. p = sqlite3DbMallocZero(db, sizeof(Vdbe) );
  58986. if( p==0 ) return 0;
  58987. p->db = db;
  58988. if( db->pVdbe ){
  58989. db->pVdbe->pPrev = p;
  58990. }
  58991. p->pNext = db->pVdbe;
  58992. p->pPrev = 0;
  58993. db->pVdbe = p;
  58994. p->magic = VDBE_MAGIC_INIT;
  58995. p->pParse = pParse;
  58996. assert( pParse->aLabel==0 );
  58997. assert( pParse->nLabel==0 );
  58998. assert( pParse->nOpAlloc==0 );
  58999. return p;
  59000. }
  59001. /*
  59002. ** Remember the SQL string for a prepared statement.
  59003. */
  59004. SQLITE_PRIVATE void sqlite3VdbeSetSql(Vdbe *p, const char *z, int n, int isPrepareV2){
  59005. assert( isPrepareV2==1 || isPrepareV2==0 );
  59006. if( p==0 ) return;
  59007. #if defined(SQLITE_OMIT_TRACE) && !defined(SQLITE_ENABLE_SQLLOG)
  59008. if( !isPrepareV2 ) return;
  59009. #endif
  59010. assert( p->zSql==0 );
  59011. p->zSql = sqlite3DbStrNDup(p->db, z, n);
  59012. p->isPrepareV2 = (u8)isPrepareV2;
  59013. }
  59014. /*
  59015. ** Return the SQL associated with a prepared statement
  59016. */
  59017. SQLITE_API const char *sqlite3_sql(sqlite3_stmt *pStmt){
  59018. Vdbe *p = (Vdbe *)pStmt;
  59019. return (p && p->isPrepareV2) ? p->zSql : 0;
  59020. }
  59021. /*
  59022. ** Swap all content between two VDBE structures.
  59023. */
  59024. SQLITE_PRIVATE void sqlite3VdbeSwap(Vdbe *pA, Vdbe *pB){
  59025. Vdbe tmp, *pTmp;
  59026. char *zTmp;
  59027. tmp = *pA;
  59028. *pA = *pB;
  59029. *pB = tmp;
  59030. pTmp = pA->pNext;
  59031. pA->pNext = pB->pNext;
  59032. pB->pNext = pTmp;
  59033. pTmp = pA->pPrev;
  59034. pA->pPrev = pB->pPrev;
  59035. pB->pPrev = pTmp;
  59036. zTmp = pA->zSql;
  59037. pA->zSql = pB->zSql;
  59038. pB->zSql = zTmp;
  59039. pB->isPrepareV2 = pA->isPrepareV2;
  59040. }
  59041. /*
  59042. ** Resize the Vdbe.aOp array so that it is at least nOp elements larger
  59043. ** than its current size. nOp is guaranteed to be less than or equal
  59044. ** to 1024/sizeof(Op).
  59045. **
  59046. ** If an out-of-memory error occurs while resizing the array, return
  59047. ** SQLITE_NOMEM. In this case Vdbe.aOp and Parse.nOpAlloc remain
  59048. ** unchanged (this is so that any opcodes already allocated can be
  59049. ** correctly deallocated along with the rest of the Vdbe).
  59050. */
  59051. static int growOpArray(Vdbe *v, int nOp){
  59052. VdbeOp *pNew;
  59053. Parse *p = v->pParse;
  59054. /* The SQLITE_TEST_REALLOC_STRESS compile-time option is designed to force
  59055. ** more frequent reallocs and hence provide more opportunities for
  59056. ** simulated OOM faults. SQLITE_TEST_REALLOC_STRESS is generally used
  59057. ** during testing only. With SQLITE_TEST_REALLOC_STRESS grow the op array
  59058. ** by the minimum* amount required until the size reaches 512. Normal
  59059. ** operation (without SQLITE_TEST_REALLOC_STRESS) is to double the current
  59060. ** size of the op array or add 1KB of space, whichever is smaller. */
  59061. #ifdef SQLITE_TEST_REALLOC_STRESS
  59062. int nNew = (p->nOpAlloc>=512 ? p->nOpAlloc*2 : p->nOpAlloc+nOp);
  59063. #else
  59064. int nNew = (p->nOpAlloc ? p->nOpAlloc*2 : (int)(1024/sizeof(Op)));
  59065. UNUSED_PARAMETER(nOp);
  59066. #endif
  59067. assert( nOp<=(1024/sizeof(Op)) );
  59068. assert( nNew>=(p->nOpAlloc+nOp) );
  59069. pNew = sqlite3DbRealloc(p->db, v->aOp, nNew*sizeof(Op));
  59070. if( pNew ){
  59071. p->nOpAlloc = sqlite3DbMallocSize(p->db, pNew)/sizeof(Op);
  59072. v->aOp = pNew;
  59073. }
  59074. return (pNew ? SQLITE_OK : SQLITE_NOMEM);
  59075. }
  59076. #ifdef SQLITE_DEBUG
  59077. /* This routine is just a convenient place to set a breakpoint that will
  59078. ** fire after each opcode is inserted and displayed using
  59079. ** "PRAGMA vdbe_addoptrace=on".
  59080. */
  59081. static void test_addop_breakpoint(void){
  59082. static int n = 0;
  59083. n++;
  59084. }
  59085. #endif
  59086. /*
  59087. ** Add a new instruction to the list of instructions current in the
  59088. ** VDBE. Return the address of the new instruction.
  59089. **
  59090. ** Parameters:
  59091. **
  59092. ** p Pointer to the VDBE
  59093. **
  59094. ** op The opcode for this instruction
  59095. **
  59096. ** p1, p2, p3 Operands
  59097. **
  59098. ** Use the sqlite3VdbeResolveLabel() function to fix an address and
  59099. ** the sqlite3VdbeChangeP4() function to change the value of the P4
  59100. ** operand.
  59101. */
  59102. SQLITE_PRIVATE int sqlite3VdbeAddOp3(Vdbe *p, int op, int p1, int p2, int p3){
  59103. int i;
  59104. VdbeOp *pOp;
  59105. i = p->nOp;
  59106. assert( p->magic==VDBE_MAGIC_INIT );
  59107. assert( op>0 && op<0xff );
  59108. if( p->pParse->nOpAlloc<=i ){
  59109. if( growOpArray(p, 1) ){
  59110. return 1;
  59111. }
  59112. }
  59113. p->nOp++;
  59114. pOp = &p->aOp[i];
  59115. pOp->opcode = (u8)op;
  59116. pOp->p5 = 0;
  59117. pOp->p1 = p1;
  59118. pOp->p2 = p2;
  59119. pOp->p3 = p3;
  59120. pOp->p4.p = 0;
  59121. pOp->p4type = P4_NOTUSED;
  59122. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  59123. pOp->zComment = 0;
  59124. #endif
  59125. #ifdef SQLITE_DEBUG
  59126. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  59127. int jj, kk;
  59128. Parse *pParse = p->pParse;
  59129. for(jj=kk=0; jj<SQLITE_N_COLCACHE; jj++){
  59130. struct yColCache *x = pParse->aColCache + jj;
  59131. if( x->iLevel>pParse->iCacheLevel || x->iReg==0 ) continue;
  59132. printf(" r[%d]={%d:%d}", x->iReg, x->iTable, x->iColumn);
  59133. kk++;
  59134. }
  59135. if( kk ) printf("\n");
  59136. sqlite3VdbePrintOp(0, i, &p->aOp[i]);
  59137. test_addop_breakpoint();
  59138. }
  59139. #endif
  59140. #ifdef VDBE_PROFILE
  59141. pOp->cycles = 0;
  59142. pOp->cnt = 0;
  59143. #endif
  59144. #ifdef SQLITE_VDBE_COVERAGE
  59145. pOp->iSrcLine = 0;
  59146. #endif
  59147. return i;
  59148. }
  59149. SQLITE_PRIVATE int sqlite3VdbeAddOp0(Vdbe *p, int op){
  59150. return sqlite3VdbeAddOp3(p, op, 0, 0, 0);
  59151. }
  59152. SQLITE_PRIVATE int sqlite3VdbeAddOp1(Vdbe *p, int op, int p1){
  59153. return sqlite3VdbeAddOp3(p, op, p1, 0, 0);
  59154. }
  59155. SQLITE_PRIVATE int sqlite3VdbeAddOp2(Vdbe *p, int op, int p1, int p2){
  59156. return sqlite3VdbeAddOp3(p, op, p1, p2, 0);
  59157. }
  59158. /*
  59159. ** Add an opcode that includes the p4 value as a pointer.
  59160. */
  59161. SQLITE_PRIVATE int sqlite3VdbeAddOp4(
  59162. Vdbe *p, /* Add the opcode to this VM */
  59163. int op, /* The new opcode */
  59164. int p1, /* The P1 operand */
  59165. int p2, /* The P2 operand */
  59166. int p3, /* The P3 operand */
  59167. const char *zP4, /* The P4 operand */
  59168. int p4type /* P4 operand type */
  59169. ){
  59170. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  59171. sqlite3VdbeChangeP4(p, addr, zP4, p4type);
  59172. return addr;
  59173. }
  59174. /*
  59175. ** Add an OP_ParseSchema opcode. This routine is broken out from
  59176. ** sqlite3VdbeAddOp4() since it needs to also needs to mark all btrees
  59177. ** as having been used.
  59178. **
  59179. ** The zWhere string must have been obtained from sqlite3_malloc().
  59180. ** This routine will take ownership of the allocated memory.
  59181. */
  59182. SQLITE_PRIVATE void sqlite3VdbeAddParseSchemaOp(Vdbe *p, int iDb, char *zWhere){
  59183. int j;
  59184. int addr = sqlite3VdbeAddOp3(p, OP_ParseSchema, iDb, 0, 0);
  59185. sqlite3VdbeChangeP4(p, addr, zWhere, P4_DYNAMIC);
  59186. for(j=0; j<p->db->nDb; j++) sqlite3VdbeUsesBtree(p, j);
  59187. }
  59188. /*
  59189. ** Add an opcode that includes the p4 value as an integer.
  59190. */
  59191. SQLITE_PRIVATE int sqlite3VdbeAddOp4Int(
  59192. Vdbe *p, /* Add the opcode to this VM */
  59193. int op, /* The new opcode */
  59194. int p1, /* The P1 operand */
  59195. int p2, /* The P2 operand */
  59196. int p3, /* The P3 operand */
  59197. int p4 /* The P4 operand as an integer */
  59198. ){
  59199. int addr = sqlite3VdbeAddOp3(p, op, p1, p2, p3);
  59200. sqlite3VdbeChangeP4(p, addr, SQLITE_INT_TO_PTR(p4), P4_INT32);
  59201. return addr;
  59202. }
  59203. /*
  59204. ** Create a new symbolic label for an instruction that has yet to be
  59205. ** coded. The symbolic label is really just a negative number. The
  59206. ** label can be used as the P2 value of an operation. Later, when
  59207. ** the label is resolved to a specific address, the VDBE will scan
  59208. ** through its operation list and change all values of P2 which match
  59209. ** the label into the resolved address.
  59210. **
  59211. ** The VDBE knows that a P2 value is a label because labels are
  59212. ** always negative and P2 values are suppose to be non-negative.
  59213. ** Hence, a negative P2 value is a label that has yet to be resolved.
  59214. **
  59215. ** Zero is returned if a malloc() fails.
  59216. */
  59217. SQLITE_PRIVATE int sqlite3VdbeMakeLabel(Vdbe *v){
  59218. Parse *p = v->pParse;
  59219. int i = p->nLabel++;
  59220. assert( v->magic==VDBE_MAGIC_INIT );
  59221. if( (i & (i-1))==0 ){
  59222. p->aLabel = sqlite3DbReallocOrFree(p->db, p->aLabel,
  59223. (i*2+1)*sizeof(p->aLabel[0]));
  59224. }
  59225. if( p->aLabel ){
  59226. p->aLabel[i] = -1;
  59227. }
  59228. return -1-i;
  59229. }
  59230. /*
  59231. ** Resolve label "x" to be the address of the next instruction to
  59232. ** be inserted. The parameter "x" must have been obtained from
  59233. ** a prior call to sqlite3VdbeMakeLabel().
  59234. */
  59235. SQLITE_PRIVATE void sqlite3VdbeResolveLabel(Vdbe *v, int x){
  59236. Parse *p = v->pParse;
  59237. int j = -1-x;
  59238. assert( v->magic==VDBE_MAGIC_INIT );
  59239. assert( j<p->nLabel );
  59240. if( ALWAYS(j>=0) && p->aLabel ){
  59241. p->aLabel[j] = v->nOp;
  59242. }
  59243. p->iFixedOp = v->nOp - 1;
  59244. }
  59245. /*
  59246. ** Mark the VDBE as one that can only be run one time.
  59247. */
  59248. SQLITE_PRIVATE void sqlite3VdbeRunOnlyOnce(Vdbe *p){
  59249. p->runOnlyOnce = 1;
  59250. }
  59251. #ifdef SQLITE_DEBUG /* sqlite3AssertMayAbort() logic */
  59252. /*
  59253. ** The following type and function are used to iterate through all opcodes
  59254. ** in a Vdbe main program and each of the sub-programs (triggers) it may
  59255. ** invoke directly or indirectly. It should be used as follows:
  59256. **
  59257. ** Op *pOp;
  59258. ** VdbeOpIter sIter;
  59259. **
  59260. ** memset(&sIter, 0, sizeof(sIter));
  59261. ** sIter.v = v; // v is of type Vdbe*
  59262. ** while( (pOp = opIterNext(&sIter)) ){
  59263. ** // Do something with pOp
  59264. ** }
  59265. ** sqlite3DbFree(v->db, sIter.apSub);
  59266. **
  59267. */
  59268. typedef struct VdbeOpIter VdbeOpIter;
  59269. struct VdbeOpIter {
  59270. Vdbe *v; /* Vdbe to iterate through the opcodes of */
  59271. SubProgram **apSub; /* Array of subprograms */
  59272. int nSub; /* Number of entries in apSub */
  59273. int iAddr; /* Address of next instruction to return */
  59274. int iSub; /* 0 = main program, 1 = first sub-program etc. */
  59275. };
  59276. static Op *opIterNext(VdbeOpIter *p){
  59277. Vdbe *v = p->v;
  59278. Op *pRet = 0;
  59279. Op *aOp;
  59280. int nOp;
  59281. if( p->iSub<=p->nSub ){
  59282. if( p->iSub==0 ){
  59283. aOp = v->aOp;
  59284. nOp = v->nOp;
  59285. }else{
  59286. aOp = p->apSub[p->iSub-1]->aOp;
  59287. nOp = p->apSub[p->iSub-1]->nOp;
  59288. }
  59289. assert( p->iAddr<nOp );
  59290. pRet = &aOp[p->iAddr];
  59291. p->iAddr++;
  59292. if( p->iAddr==nOp ){
  59293. p->iSub++;
  59294. p->iAddr = 0;
  59295. }
  59296. if( pRet->p4type==P4_SUBPROGRAM ){
  59297. int nByte = (p->nSub+1)*sizeof(SubProgram*);
  59298. int j;
  59299. for(j=0; j<p->nSub; j++){
  59300. if( p->apSub[j]==pRet->p4.pProgram ) break;
  59301. }
  59302. if( j==p->nSub ){
  59303. p->apSub = sqlite3DbReallocOrFree(v->db, p->apSub, nByte);
  59304. if( !p->apSub ){
  59305. pRet = 0;
  59306. }else{
  59307. p->apSub[p->nSub++] = pRet->p4.pProgram;
  59308. }
  59309. }
  59310. }
  59311. }
  59312. return pRet;
  59313. }
  59314. /*
  59315. ** Check if the program stored in the VM associated with pParse may
  59316. ** throw an ABORT exception (causing the statement, but not entire transaction
  59317. ** to be rolled back). This condition is true if the main program or any
  59318. ** sub-programs contains any of the following:
  59319. **
  59320. ** * OP_Halt with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  59321. ** * OP_HaltIfNull with P1=SQLITE_CONSTRAINT and P2=OE_Abort.
  59322. ** * OP_Destroy
  59323. ** * OP_VUpdate
  59324. ** * OP_VRename
  59325. ** * OP_FkCounter with P2==0 (immediate foreign key constraint)
  59326. **
  59327. ** Then check that the value of Parse.mayAbort is true if an
  59328. ** ABORT may be thrown, or false otherwise. Return true if it does
  59329. ** match, or false otherwise. This function is intended to be used as
  59330. ** part of an assert statement in the compiler. Similar to:
  59331. **
  59332. ** assert( sqlite3VdbeAssertMayAbort(pParse->pVdbe, pParse->mayAbort) );
  59333. */
  59334. SQLITE_PRIVATE int sqlite3VdbeAssertMayAbort(Vdbe *v, int mayAbort){
  59335. int hasAbort = 0;
  59336. Op *pOp;
  59337. VdbeOpIter sIter;
  59338. memset(&sIter, 0, sizeof(sIter));
  59339. sIter.v = v;
  59340. while( (pOp = opIterNext(&sIter))!=0 ){
  59341. int opcode = pOp->opcode;
  59342. if( opcode==OP_Destroy || opcode==OP_VUpdate || opcode==OP_VRename
  59343. #ifndef SQLITE_OMIT_FOREIGN_KEY
  59344. || (opcode==OP_FkCounter && pOp->p1==0 && pOp->p2==1)
  59345. #endif
  59346. || ((opcode==OP_Halt || opcode==OP_HaltIfNull)
  59347. && ((pOp->p1&0xff)==SQLITE_CONSTRAINT && pOp->p2==OE_Abort))
  59348. ){
  59349. hasAbort = 1;
  59350. break;
  59351. }
  59352. }
  59353. sqlite3DbFree(v->db, sIter.apSub);
  59354. /* Return true if hasAbort==mayAbort. Or if a malloc failure occurred.
  59355. ** If malloc failed, then the while() loop above may not have iterated
  59356. ** through all opcodes and hasAbort may be set incorrectly. Return
  59357. ** true for this case to prevent the assert() in the callers frame
  59358. ** from failing. */
  59359. return ( v->db->mallocFailed || hasAbort==mayAbort );
  59360. }
  59361. #endif /* SQLITE_DEBUG - the sqlite3AssertMayAbort() function */
  59362. /*
  59363. ** Loop through the program looking for P2 values that are negative
  59364. ** on jump instructions. Each such value is a label. Resolve the
  59365. ** label by setting the P2 value to its correct non-zero value.
  59366. **
  59367. ** This routine is called once after all opcodes have been inserted.
  59368. **
  59369. ** Variable *pMaxFuncArgs is set to the maximum value of any P2 argument
  59370. ** to an OP_Function, OP_AggStep or OP_VFilter opcode. This is used by
  59371. ** sqlite3VdbeMakeReady() to size the Vdbe.apArg[] array.
  59372. **
  59373. ** The Op.opflags field is set on all opcodes.
  59374. */
  59375. static void resolveP2Values(Vdbe *p, int *pMaxFuncArgs){
  59376. int i;
  59377. int nMaxArgs = *pMaxFuncArgs;
  59378. Op *pOp;
  59379. Parse *pParse = p->pParse;
  59380. int *aLabel = pParse->aLabel;
  59381. p->readOnly = 1;
  59382. p->bIsReader = 0;
  59383. for(pOp=p->aOp, i=p->nOp-1; i>=0; i--, pOp++){
  59384. u8 opcode = pOp->opcode;
  59385. /* NOTE: Be sure to update mkopcodeh.awk when adding or removing
  59386. ** cases from this switch! */
  59387. switch( opcode ){
  59388. case OP_Function:
  59389. case OP_AggStep: {
  59390. if( pOp->p5>nMaxArgs ) nMaxArgs = pOp->p5;
  59391. break;
  59392. }
  59393. case OP_Transaction: {
  59394. if( pOp->p2!=0 ) p->readOnly = 0;
  59395. /* fall thru */
  59396. }
  59397. case OP_AutoCommit:
  59398. case OP_Savepoint: {
  59399. p->bIsReader = 1;
  59400. break;
  59401. }
  59402. #ifndef SQLITE_OMIT_WAL
  59403. case OP_Checkpoint:
  59404. #endif
  59405. case OP_Vacuum:
  59406. case OP_JournalMode: {
  59407. p->readOnly = 0;
  59408. p->bIsReader = 1;
  59409. break;
  59410. }
  59411. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59412. case OP_VUpdate: {
  59413. if( pOp->p2>nMaxArgs ) nMaxArgs = pOp->p2;
  59414. break;
  59415. }
  59416. case OP_VFilter: {
  59417. int n;
  59418. assert( p->nOp - i >= 3 );
  59419. assert( pOp[-1].opcode==OP_Integer );
  59420. n = pOp[-1].p1;
  59421. if( n>nMaxArgs ) nMaxArgs = n;
  59422. break;
  59423. }
  59424. #endif
  59425. case OP_Next:
  59426. case OP_NextIfOpen:
  59427. case OP_SorterNext: {
  59428. pOp->p4.xAdvance = sqlite3BtreeNext;
  59429. pOp->p4type = P4_ADVANCE;
  59430. break;
  59431. }
  59432. case OP_Prev:
  59433. case OP_PrevIfOpen: {
  59434. pOp->p4.xAdvance = sqlite3BtreePrevious;
  59435. pOp->p4type = P4_ADVANCE;
  59436. break;
  59437. }
  59438. }
  59439. pOp->opflags = sqlite3OpcodeProperty[opcode];
  59440. if( (pOp->opflags & OPFLG_JUMP)!=0 && pOp->p2<0 ){
  59441. assert( -1-pOp->p2<pParse->nLabel );
  59442. pOp->p2 = aLabel[-1-pOp->p2];
  59443. }
  59444. }
  59445. sqlite3DbFree(p->db, pParse->aLabel);
  59446. pParse->aLabel = 0;
  59447. pParse->nLabel = 0;
  59448. *pMaxFuncArgs = nMaxArgs;
  59449. assert( p->bIsReader!=0 || DbMaskAllZero(p->btreeMask) );
  59450. }
  59451. /*
  59452. ** Return the address of the next instruction to be inserted.
  59453. */
  59454. SQLITE_PRIVATE int sqlite3VdbeCurrentAddr(Vdbe *p){
  59455. assert( p->magic==VDBE_MAGIC_INIT );
  59456. return p->nOp;
  59457. }
  59458. /*
  59459. ** This function returns a pointer to the array of opcodes associated with
  59460. ** the Vdbe passed as the first argument. It is the callers responsibility
  59461. ** to arrange for the returned array to be eventually freed using the
  59462. ** vdbeFreeOpArray() function.
  59463. **
  59464. ** Before returning, *pnOp is set to the number of entries in the returned
  59465. ** array. Also, *pnMaxArg is set to the larger of its current value and
  59466. ** the number of entries in the Vdbe.apArg[] array required to execute the
  59467. ** returned program.
  59468. */
  59469. SQLITE_PRIVATE VdbeOp *sqlite3VdbeTakeOpArray(Vdbe *p, int *pnOp, int *pnMaxArg){
  59470. VdbeOp *aOp = p->aOp;
  59471. assert( aOp && !p->db->mallocFailed );
  59472. /* Check that sqlite3VdbeUsesBtree() was not called on this VM */
  59473. assert( DbMaskAllZero(p->btreeMask) );
  59474. resolveP2Values(p, pnMaxArg);
  59475. *pnOp = p->nOp;
  59476. p->aOp = 0;
  59477. return aOp;
  59478. }
  59479. /*
  59480. ** Add a whole list of operations to the operation stack. Return the
  59481. ** address of the first operation added.
  59482. */
  59483. SQLITE_PRIVATE int sqlite3VdbeAddOpList(Vdbe *p, int nOp, VdbeOpList const *aOp, int iLineno){
  59484. int addr;
  59485. assert( p->magic==VDBE_MAGIC_INIT );
  59486. if( p->nOp + nOp > p->pParse->nOpAlloc && growOpArray(p, nOp) ){
  59487. return 0;
  59488. }
  59489. addr = p->nOp;
  59490. if( ALWAYS(nOp>0) ){
  59491. int i;
  59492. VdbeOpList const *pIn = aOp;
  59493. for(i=0; i<nOp; i++, pIn++){
  59494. int p2 = pIn->p2;
  59495. VdbeOp *pOut = &p->aOp[i+addr];
  59496. pOut->opcode = pIn->opcode;
  59497. pOut->p1 = pIn->p1;
  59498. if( p2<0 ){
  59499. assert( sqlite3OpcodeProperty[pOut->opcode] & OPFLG_JUMP );
  59500. pOut->p2 = addr + ADDR(p2);
  59501. }else{
  59502. pOut->p2 = p2;
  59503. }
  59504. pOut->p3 = pIn->p3;
  59505. pOut->p4type = P4_NOTUSED;
  59506. pOut->p4.p = 0;
  59507. pOut->p5 = 0;
  59508. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  59509. pOut->zComment = 0;
  59510. #endif
  59511. #ifdef SQLITE_VDBE_COVERAGE
  59512. pOut->iSrcLine = iLineno+i;
  59513. #else
  59514. (void)iLineno;
  59515. #endif
  59516. #ifdef SQLITE_DEBUG
  59517. if( p->db->flags & SQLITE_VdbeAddopTrace ){
  59518. sqlite3VdbePrintOp(0, i+addr, &p->aOp[i+addr]);
  59519. }
  59520. #endif
  59521. }
  59522. p->nOp += nOp;
  59523. }
  59524. return addr;
  59525. }
  59526. /*
  59527. ** Change the value of the P1 operand for a specific instruction.
  59528. ** This routine is useful when a large program is loaded from a
  59529. ** static array using sqlite3VdbeAddOpList but we want to make a
  59530. ** few minor changes to the program.
  59531. */
  59532. SQLITE_PRIVATE void sqlite3VdbeChangeP1(Vdbe *p, u32 addr, int val){
  59533. assert( p!=0 );
  59534. if( ((u32)p->nOp)>addr ){
  59535. p->aOp[addr].p1 = val;
  59536. }
  59537. }
  59538. /*
  59539. ** Change the value of the P2 operand for a specific instruction.
  59540. ** This routine is useful for setting a jump destination.
  59541. */
  59542. SQLITE_PRIVATE void sqlite3VdbeChangeP2(Vdbe *p, u32 addr, int val){
  59543. assert( p!=0 );
  59544. if( ((u32)p->nOp)>addr ){
  59545. p->aOp[addr].p2 = val;
  59546. }
  59547. }
  59548. /*
  59549. ** Change the value of the P3 operand for a specific instruction.
  59550. */
  59551. SQLITE_PRIVATE void sqlite3VdbeChangeP3(Vdbe *p, u32 addr, int val){
  59552. assert( p!=0 );
  59553. if( ((u32)p->nOp)>addr ){
  59554. p->aOp[addr].p3 = val;
  59555. }
  59556. }
  59557. /*
  59558. ** Change the value of the P5 operand for the most recently
  59559. ** added operation.
  59560. */
  59561. SQLITE_PRIVATE void sqlite3VdbeChangeP5(Vdbe *p, u8 val){
  59562. assert( p!=0 );
  59563. if( p->aOp ){
  59564. assert( p->nOp>0 );
  59565. p->aOp[p->nOp-1].p5 = val;
  59566. }
  59567. }
  59568. /*
  59569. ** Change the P2 operand of instruction addr so that it points to
  59570. ** the address of the next instruction to be coded.
  59571. */
  59572. SQLITE_PRIVATE void sqlite3VdbeJumpHere(Vdbe *p, int addr){
  59573. sqlite3VdbeChangeP2(p, addr, p->nOp);
  59574. p->pParse->iFixedOp = p->nOp - 1;
  59575. }
  59576. /*
  59577. ** If the input FuncDef structure is ephemeral, then free it. If
  59578. ** the FuncDef is not ephermal, then do nothing.
  59579. */
  59580. static void freeEphemeralFunction(sqlite3 *db, FuncDef *pDef){
  59581. if( ALWAYS(pDef) && (pDef->funcFlags & SQLITE_FUNC_EPHEM)!=0 ){
  59582. sqlite3DbFree(db, pDef);
  59583. }
  59584. }
  59585. static void vdbeFreeOpArray(sqlite3 *, Op *, int);
  59586. /*
  59587. ** Delete a P4 value if necessary.
  59588. */
  59589. static void freeP4(sqlite3 *db, int p4type, void *p4){
  59590. if( p4 ){
  59591. assert( db );
  59592. switch( p4type ){
  59593. case P4_REAL:
  59594. case P4_INT64:
  59595. case P4_DYNAMIC:
  59596. case P4_INTARRAY: {
  59597. sqlite3DbFree(db, p4);
  59598. break;
  59599. }
  59600. case P4_KEYINFO: {
  59601. if( db->pnBytesFreed==0 ) sqlite3KeyInfoUnref((KeyInfo*)p4);
  59602. break;
  59603. }
  59604. case P4_MPRINTF: {
  59605. if( db->pnBytesFreed==0 ) sqlite3_free(p4);
  59606. break;
  59607. }
  59608. case P4_FUNCDEF: {
  59609. freeEphemeralFunction(db, (FuncDef*)p4);
  59610. break;
  59611. }
  59612. case P4_MEM: {
  59613. if( db->pnBytesFreed==0 ){
  59614. sqlite3ValueFree((sqlite3_value*)p4);
  59615. }else{
  59616. Mem *p = (Mem*)p4;
  59617. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  59618. sqlite3DbFree(db, p);
  59619. }
  59620. break;
  59621. }
  59622. case P4_VTAB : {
  59623. if( db->pnBytesFreed==0 ) sqlite3VtabUnlock((VTable *)p4);
  59624. break;
  59625. }
  59626. }
  59627. }
  59628. }
  59629. /*
  59630. ** Free the space allocated for aOp and any p4 values allocated for the
  59631. ** opcodes contained within. If aOp is not NULL it is assumed to contain
  59632. ** nOp entries.
  59633. */
  59634. static void vdbeFreeOpArray(sqlite3 *db, Op *aOp, int nOp){
  59635. if( aOp ){
  59636. Op *pOp;
  59637. for(pOp=aOp; pOp<&aOp[nOp]; pOp++){
  59638. freeP4(db, pOp->p4type, pOp->p4.p);
  59639. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  59640. sqlite3DbFree(db, pOp->zComment);
  59641. #endif
  59642. }
  59643. }
  59644. sqlite3DbFree(db, aOp);
  59645. }
  59646. /*
  59647. ** Link the SubProgram object passed as the second argument into the linked
  59648. ** list at Vdbe.pSubProgram. This list is used to delete all sub-program
  59649. ** objects when the VM is no longer required.
  59650. */
  59651. SQLITE_PRIVATE void sqlite3VdbeLinkSubProgram(Vdbe *pVdbe, SubProgram *p){
  59652. p->pNext = pVdbe->pProgram;
  59653. pVdbe->pProgram = p;
  59654. }
  59655. /*
  59656. ** Change the opcode at addr into OP_Noop
  59657. */
  59658. SQLITE_PRIVATE void sqlite3VdbeChangeToNoop(Vdbe *p, int addr){
  59659. if( addr<p->nOp ){
  59660. VdbeOp *pOp = &p->aOp[addr];
  59661. sqlite3 *db = p->db;
  59662. freeP4(db, pOp->p4type, pOp->p4.p);
  59663. memset(pOp, 0, sizeof(pOp[0]));
  59664. pOp->opcode = OP_Noop;
  59665. if( addr==p->nOp-1 ) p->nOp--;
  59666. }
  59667. }
  59668. /*
  59669. ** If the last opcode is "op" and it is not a jump destination,
  59670. ** then remove it. Return true if and only if an opcode was removed.
  59671. */
  59672. SQLITE_PRIVATE int sqlite3VdbeDeletePriorOpcode(Vdbe *p, u8 op){
  59673. if( (p->nOp-1)>(p->pParse->iFixedOp) && p->aOp[p->nOp-1].opcode==op ){
  59674. sqlite3VdbeChangeToNoop(p, p->nOp-1);
  59675. return 1;
  59676. }else{
  59677. return 0;
  59678. }
  59679. }
  59680. /*
  59681. ** Change the value of the P4 operand for a specific instruction.
  59682. ** This routine is useful when a large program is loaded from a
  59683. ** static array using sqlite3VdbeAddOpList but we want to make a
  59684. ** few minor changes to the program.
  59685. **
  59686. ** If n>=0 then the P4 operand is dynamic, meaning that a copy of
  59687. ** the string is made into memory obtained from sqlite3_malloc().
  59688. ** A value of n==0 means copy bytes of zP4 up to and including the
  59689. ** first null byte. If n>0 then copy n+1 bytes of zP4.
  59690. **
  59691. ** Other values of n (P4_STATIC, P4_COLLSEQ etc.) indicate that zP4 points
  59692. ** to a string or structure that is guaranteed to exist for the lifetime of
  59693. ** the Vdbe. In these cases we can just copy the pointer.
  59694. **
  59695. ** If addr<0 then change P4 on the most recently inserted instruction.
  59696. */
  59697. SQLITE_PRIVATE void sqlite3VdbeChangeP4(Vdbe *p, int addr, const char *zP4, int n){
  59698. Op *pOp;
  59699. sqlite3 *db;
  59700. assert( p!=0 );
  59701. db = p->db;
  59702. assert( p->magic==VDBE_MAGIC_INIT );
  59703. if( p->aOp==0 || db->mallocFailed ){
  59704. if( n!=P4_VTAB ){
  59705. freeP4(db, n, (void*)*(char**)&zP4);
  59706. }
  59707. return;
  59708. }
  59709. assert( p->nOp>0 );
  59710. assert( addr<p->nOp );
  59711. if( addr<0 ){
  59712. addr = p->nOp - 1;
  59713. }
  59714. pOp = &p->aOp[addr];
  59715. assert( pOp->p4type==P4_NOTUSED
  59716. || pOp->p4type==P4_INT32
  59717. || pOp->p4type==P4_KEYINFO );
  59718. freeP4(db, pOp->p4type, pOp->p4.p);
  59719. pOp->p4.p = 0;
  59720. if( n==P4_INT32 ){
  59721. /* Note: this cast is safe, because the origin data point was an int
  59722. ** that was cast to a (const char *). */
  59723. pOp->p4.i = SQLITE_PTR_TO_INT(zP4);
  59724. pOp->p4type = P4_INT32;
  59725. }else if( zP4==0 ){
  59726. pOp->p4.p = 0;
  59727. pOp->p4type = P4_NOTUSED;
  59728. }else if( n==P4_KEYINFO ){
  59729. pOp->p4.p = (void*)zP4;
  59730. pOp->p4type = P4_KEYINFO;
  59731. }else if( n==P4_VTAB ){
  59732. pOp->p4.p = (void*)zP4;
  59733. pOp->p4type = P4_VTAB;
  59734. sqlite3VtabLock((VTable *)zP4);
  59735. assert( ((VTable *)zP4)->db==p->db );
  59736. }else if( n<0 ){
  59737. pOp->p4.p = (void*)zP4;
  59738. pOp->p4type = (signed char)n;
  59739. }else{
  59740. if( n==0 ) n = sqlite3Strlen30(zP4);
  59741. pOp->p4.z = sqlite3DbStrNDup(p->db, zP4, n);
  59742. pOp->p4type = P4_DYNAMIC;
  59743. }
  59744. }
  59745. /*
  59746. ** Set the P4 on the most recently added opcode to the KeyInfo for the
  59747. ** index given.
  59748. */
  59749. SQLITE_PRIVATE void sqlite3VdbeSetP4KeyInfo(Parse *pParse, Index *pIdx){
  59750. Vdbe *v = pParse->pVdbe;
  59751. assert( v!=0 );
  59752. assert( pIdx!=0 );
  59753. sqlite3VdbeChangeP4(v, -1, (char*)sqlite3KeyInfoOfIndex(pParse, pIdx),
  59754. P4_KEYINFO);
  59755. }
  59756. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  59757. /*
  59758. ** Change the comment on the most recently coded instruction. Or
  59759. ** insert a No-op and add the comment to that new instruction. This
  59760. ** makes the code easier to read during debugging. None of this happens
  59761. ** in a production build.
  59762. */
  59763. static void vdbeVComment(Vdbe *p, const char *zFormat, va_list ap){
  59764. assert( p->nOp>0 || p->aOp==0 );
  59765. assert( p->aOp==0 || p->aOp[p->nOp-1].zComment==0 || p->db->mallocFailed );
  59766. if( p->nOp ){
  59767. assert( p->aOp );
  59768. sqlite3DbFree(p->db, p->aOp[p->nOp-1].zComment);
  59769. p->aOp[p->nOp-1].zComment = sqlite3VMPrintf(p->db, zFormat, ap);
  59770. }
  59771. }
  59772. SQLITE_PRIVATE void sqlite3VdbeComment(Vdbe *p, const char *zFormat, ...){
  59773. va_list ap;
  59774. if( p ){
  59775. va_start(ap, zFormat);
  59776. vdbeVComment(p, zFormat, ap);
  59777. va_end(ap);
  59778. }
  59779. }
  59780. SQLITE_PRIVATE void sqlite3VdbeNoopComment(Vdbe *p, const char *zFormat, ...){
  59781. va_list ap;
  59782. if( p ){
  59783. sqlite3VdbeAddOp0(p, OP_Noop);
  59784. va_start(ap, zFormat);
  59785. vdbeVComment(p, zFormat, ap);
  59786. va_end(ap);
  59787. }
  59788. }
  59789. #endif /* NDEBUG */
  59790. #ifdef SQLITE_VDBE_COVERAGE
  59791. /*
  59792. ** Set the value if the iSrcLine field for the previously coded instruction.
  59793. */
  59794. SQLITE_PRIVATE void sqlite3VdbeSetLineNumber(Vdbe *v, int iLine){
  59795. sqlite3VdbeGetOp(v,-1)->iSrcLine = iLine;
  59796. }
  59797. #endif /* SQLITE_VDBE_COVERAGE */
  59798. /*
  59799. ** Return the opcode for a given address. If the address is -1, then
  59800. ** return the most recently inserted opcode.
  59801. **
  59802. ** If a memory allocation error has occurred prior to the calling of this
  59803. ** routine, then a pointer to a dummy VdbeOp will be returned. That opcode
  59804. ** is readable but not writable, though it is cast to a writable value.
  59805. ** The return of a dummy opcode allows the call to continue functioning
  59806. ** after an OOM fault without having to check to see if the return from
  59807. ** this routine is a valid pointer. But because the dummy.opcode is 0,
  59808. ** dummy will never be written to. This is verified by code inspection and
  59809. ** by running with Valgrind.
  59810. */
  59811. SQLITE_PRIVATE VdbeOp *sqlite3VdbeGetOp(Vdbe *p, int addr){
  59812. /* C89 specifies that the constant "dummy" will be initialized to all
  59813. ** zeros, which is correct. MSVC generates a warning, nevertheless. */
  59814. static VdbeOp dummy; /* Ignore the MSVC warning about no initializer */
  59815. assert( p->magic==VDBE_MAGIC_INIT );
  59816. if( addr<0 ){
  59817. addr = p->nOp - 1;
  59818. }
  59819. assert( (addr>=0 && addr<p->nOp) || p->db->mallocFailed );
  59820. if( p->db->mallocFailed ){
  59821. return (VdbeOp*)&dummy;
  59822. }else{
  59823. return &p->aOp[addr];
  59824. }
  59825. }
  59826. #if defined(SQLITE_ENABLE_EXPLAIN_COMMENTS)
  59827. /*
  59828. ** Return an integer value for one of the parameters to the opcode pOp
  59829. ** determined by character c.
  59830. */
  59831. static int translateP(char c, const Op *pOp){
  59832. if( c=='1' ) return pOp->p1;
  59833. if( c=='2' ) return pOp->p2;
  59834. if( c=='3' ) return pOp->p3;
  59835. if( c=='4' ) return pOp->p4.i;
  59836. return pOp->p5;
  59837. }
  59838. /*
  59839. ** Compute a string for the "comment" field of a VDBE opcode listing.
  59840. **
  59841. ** The Synopsis: field in comments in the vdbe.c source file gets converted
  59842. ** to an extra string that is appended to the sqlite3OpcodeName(). In the
  59843. ** absence of other comments, this synopsis becomes the comment on the opcode.
  59844. ** Some translation occurs:
  59845. **
  59846. ** "PX" -> "r[X]"
  59847. ** "PX@PY" -> "r[X..X+Y-1]" or "r[x]" if y is 0 or 1
  59848. ** "PX@PY+1" -> "r[X..X+Y]" or "r[x]" if y is 0
  59849. ** "PY..PY" -> "r[X..Y]" or "r[x]" if y<=x
  59850. */
  59851. static int displayComment(
  59852. const Op *pOp, /* The opcode to be commented */
  59853. const char *zP4, /* Previously obtained value for P4 */
  59854. char *zTemp, /* Write result here */
  59855. int nTemp /* Space available in zTemp[] */
  59856. ){
  59857. const char *zOpName;
  59858. const char *zSynopsis;
  59859. int nOpName;
  59860. int ii, jj;
  59861. zOpName = sqlite3OpcodeName(pOp->opcode);
  59862. nOpName = sqlite3Strlen30(zOpName);
  59863. if( zOpName[nOpName+1] ){
  59864. int seenCom = 0;
  59865. char c;
  59866. zSynopsis = zOpName += nOpName + 1;
  59867. for(ii=jj=0; jj<nTemp-1 && (c = zSynopsis[ii])!=0; ii++){
  59868. if( c=='P' ){
  59869. c = zSynopsis[++ii];
  59870. if( c=='4' ){
  59871. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", zP4);
  59872. }else if( c=='X' ){
  59873. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%s", pOp->zComment);
  59874. seenCom = 1;
  59875. }else{
  59876. int v1 = translateP(c, pOp);
  59877. int v2;
  59878. sqlite3_snprintf(nTemp-jj, zTemp+jj, "%d", v1);
  59879. if( strncmp(zSynopsis+ii+1, "@P", 2)==0 ){
  59880. ii += 3;
  59881. jj += sqlite3Strlen30(zTemp+jj);
  59882. v2 = translateP(zSynopsis[ii], pOp);
  59883. if( strncmp(zSynopsis+ii+1,"+1",2)==0 ){
  59884. ii += 2;
  59885. v2++;
  59886. }
  59887. if( v2>1 ){
  59888. sqlite3_snprintf(nTemp-jj, zTemp+jj, "..%d", v1+v2-1);
  59889. }
  59890. }else if( strncmp(zSynopsis+ii+1, "..P3", 4)==0 && pOp->p3==0 ){
  59891. ii += 4;
  59892. }
  59893. }
  59894. jj += sqlite3Strlen30(zTemp+jj);
  59895. }else{
  59896. zTemp[jj++] = c;
  59897. }
  59898. }
  59899. if( !seenCom && jj<nTemp-5 && pOp->zComment ){
  59900. sqlite3_snprintf(nTemp-jj, zTemp+jj, "; %s", pOp->zComment);
  59901. jj += sqlite3Strlen30(zTemp+jj);
  59902. }
  59903. if( jj<nTemp ) zTemp[jj] = 0;
  59904. }else if( pOp->zComment ){
  59905. sqlite3_snprintf(nTemp, zTemp, "%s", pOp->zComment);
  59906. jj = sqlite3Strlen30(zTemp);
  59907. }else{
  59908. zTemp[0] = 0;
  59909. jj = 0;
  59910. }
  59911. return jj;
  59912. }
  59913. #endif /* SQLITE_DEBUG */
  59914. #if !defined(SQLITE_OMIT_EXPLAIN) || !defined(NDEBUG) \
  59915. || defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  59916. /*
  59917. ** Compute a string that describes the P4 parameter for an opcode.
  59918. ** Use zTemp for any required temporary buffer space.
  59919. */
  59920. static char *displayP4(Op *pOp, char *zTemp, int nTemp){
  59921. char *zP4 = zTemp;
  59922. assert( nTemp>=20 );
  59923. switch( pOp->p4type ){
  59924. case P4_KEYINFO: {
  59925. int i, j;
  59926. KeyInfo *pKeyInfo = pOp->p4.pKeyInfo;
  59927. assert( pKeyInfo->aSortOrder!=0 );
  59928. sqlite3_snprintf(nTemp, zTemp, "k(%d", pKeyInfo->nField);
  59929. i = sqlite3Strlen30(zTemp);
  59930. for(j=0; j<pKeyInfo->nField; j++){
  59931. CollSeq *pColl = pKeyInfo->aColl[j];
  59932. const char *zColl = pColl ? pColl->zName : "nil";
  59933. int n = sqlite3Strlen30(zColl);
  59934. if( n==6 && memcmp(zColl,"BINARY",6)==0 ){
  59935. zColl = "B";
  59936. n = 1;
  59937. }
  59938. if( i+n>nTemp-6 ){
  59939. memcpy(&zTemp[i],",...",4);
  59940. break;
  59941. }
  59942. zTemp[i++] = ',';
  59943. if( pKeyInfo->aSortOrder[j] ){
  59944. zTemp[i++] = '-';
  59945. }
  59946. memcpy(&zTemp[i], zColl, n+1);
  59947. i += n;
  59948. }
  59949. zTemp[i++] = ')';
  59950. zTemp[i] = 0;
  59951. assert( i<nTemp );
  59952. break;
  59953. }
  59954. case P4_COLLSEQ: {
  59955. CollSeq *pColl = pOp->p4.pColl;
  59956. sqlite3_snprintf(nTemp, zTemp, "(%.20s)", pColl->zName);
  59957. break;
  59958. }
  59959. case P4_FUNCDEF: {
  59960. FuncDef *pDef = pOp->p4.pFunc;
  59961. sqlite3_snprintf(nTemp, zTemp, "%s(%d)", pDef->zName, pDef->nArg);
  59962. break;
  59963. }
  59964. case P4_INT64: {
  59965. sqlite3_snprintf(nTemp, zTemp, "%lld", *pOp->p4.pI64);
  59966. break;
  59967. }
  59968. case P4_INT32: {
  59969. sqlite3_snprintf(nTemp, zTemp, "%d", pOp->p4.i);
  59970. break;
  59971. }
  59972. case P4_REAL: {
  59973. sqlite3_snprintf(nTemp, zTemp, "%.16g", *pOp->p4.pReal);
  59974. break;
  59975. }
  59976. case P4_MEM: {
  59977. Mem *pMem = pOp->p4.pMem;
  59978. if( pMem->flags & MEM_Str ){
  59979. zP4 = pMem->z;
  59980. }else if( pMem->flags & MEM_Int ){
  59981. sqlite3_snprintf(nTemp, zTemp, "%lld", pMem->u.i);
  59982. }else if( pMem->flags & MEM_Real ){
  59983. sqlite3_snprintf(nTemp, zTemp, "%.16g", pMem->u.r);
  59984. }else if( pMem->flags & MEM_Null ){
  59985. sqlite3_snprintf(nTemp, zTemp, "NULL");
  59986. }else{
  59987. assert( pMem->flags & MEM_Blob );
  59988. zP4 = "(blob)";
  59989. }
  59990. break;
  59991. }
  59992. #ifndef SQLITE_OMIT_VIRTUALTABLE
  59993. case P4_VTAB: {
  59994. sqlite3_vtab *pVtab = pOp->p4.pVtab->pVtab;
  59995. sqlite3_snprintf(nTemp, zTemp, "vtab:%p:%p", pVtab, pVtab->pModule);
  59996. break;
  59997. }
  59998. #endif
  59999. case P4_INTARRAY: {
  60000. sqlite3_snprintf(nTemp, zTemp, "intarray");
  60001. break;
  60002. }
  60003. case P4_SUBPROGRAM: {
  60004. sqlite3_snprintf(nTemp, zTemp, "program");
  60005. break;
  60006. }
  60007. case P4_ADVANCE: {
  60008. zTemp[0] = 0;
  60009. break;
  60010. }
  60011. default: {
  60012. zP4 = pOp->p4.z;
  60013. if( zP4==0 ){
  60014. zP4 = zTemp;
  60015. zTemp[0] = 0;
  60016. }
  60017. }
  60018. }
  60019. assert( zP4!=0 );
  60020. return zP4;
  60021. }
  60022. #endif
  60023. /*
  60024. ** Declare to the Vdbe that the BTree object at db->aDb[i] is used.
  60025. **
  60026. ** The prepared statements need to know in advance the complete set of
  60027. ** attached databases that will be use. A mask of these databases
  60028. ** is maintained in p->btreeMask. The p->lockMask value is the subset of
  60029. ** p->btreeMask of databases that will require a lock.
  60030. */
  60031. SQLITE_PRIVATE void sqlite3VdbeUsesBtree(Vdbe *p, int i){
  60032. assert( i>=0 && i<p->db->nDb && i<(int)sizeof(yDbMask)*8 );
  60033. assert( i<(int)sizeof(p->btreeMask)*8 );
  60034. DbMaskSet(p->btreeMask, i);
  60035. if( i!=1 && sqlite3BtreeSharable(p->db->aDb[i].pBt) ){
  60036. DbMaskSet(p->lockMask, i);
  60037. }
  60038. }
  60039. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  60040. /*
  60041. ** If SQLite is compiled to support shared-cache mode and to be threadsafe,
  60042. ** this routine obtains the mutex associated with each BtShared structure
  60043. ** that may be accessed by the VM passed as an argument. In doing so it also
  60044. ** sets the BtShared.db member of each of the BtShared structures, ensuring
  60045. ** that the correct busy-handler callback is invoked if required.
  60046. **
  60047. ** If SQLite is not threadsafe but does support shared-cache mode, then
  60048. ** sqlite3BtreeEnter() is invoked to set the BtShared.db variables
  60049. ** of all of BtShared structures accessible via the database handle
  60050. ** associated with the VM.
  60051. **
  60052. ** If SQLite is not threadsafe and does not support shared-cache mode, this
  60053. ** function is a no-op.
  60054. **
  60055. ** The p->btreeMask field is a bitmask of all btrees that the prepared
  60056. ** statement p will ever use. Let N be the number of bits in p->btreeMask
  60057. ** corresponding to btrees that use shared cache. Then the runtime of
  60058. ** this routine is N*N. But as N is rarely more than 1, this should not
  60059. ** be a problem.
  60060. */
  60061. SQLITE_PRIVATE void sqlite3VdbeEnter(Vdbe *p){
  60062. int i;
  60063. sqlite3 *db;
  60064. Db *aDb;
  60065. int nDb;
  60066. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  60067. db = p->db;
  60068. aDb = db->aDb;
  60069. nDb = db->nDb;
  60070. for(i=0; i<nDb; i++){
  60071. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  60072. sqlite3BtreeEnter(aDb[i].pBt);
  60073. }
  60074. }
  60075. }
  60076. #endif
  60077. #if !defined(SQLITE_OMIT_SHARED_CACHE) && SQLITE_THREADSAFE>0
  60078. /*
  60079. ** Unlock all of the btrees previously locked by a call to sqlite3VdbeEnter().
  60080. */
  60081. SQLITE_PRIVATE void sqlite3VdbeLeave(Vdbe *p){
  60082. int i;
  60083. sqlite3 *db;
  60084. Db *aDb;
  60085. int nDb;
  60086. if( DbMaskAllZero(p->lockMask) ) return; /* The common case */
  60087. db = p->db;
  60088. aDb = db->aDb;
  60089. nDb = db->nDb;
  60090. for(i=0; i<nDb; i++){
  60091. if( i!=1 && DbMaskTest(p->lockMask,i) && ALWAYS(aDb[i].pBt!=0) ){
  60092. sqlite3BtreeLeave(aDb[i].pBt);
  60093. }
  60094. }
  60095. }
  60096. #endif
  60097. #if defined(VDBE_PROFILE) || defined(SQLITE_DEBUG)
  60098. /*
  60099. ** Print a single opcode. This routine is used for debugging only.
  60100. */
  60101. SQLITE_PRIVATE void sqlite3VdbePrintOp(FILE *pOut, int pc, Op *pOp){
  60102. char *zP4;
  60103. char zPtr[50];
  60104. char zCom[100];
  60105. static const char *zFormat1 = "%4d %-13s %4d %4d %4d %-13s %.2X %s\n";
  60106. if( pOut==0 ) pOut = stdout;
  60107. zP4 = displayP4(pOp, zPtr, sizeof(zPtr));
  60108. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  60109. displayComment(pOp, zP4, zCom, sizeof(zCom));
  60110. #else
  60111. zCom[0] = 0;
  60112. #endif
  60113. /* NB: The sqlite3OpcodeName() function is implemented by code created
  60114. ** by the mkopcodeh.awk and mkopcodec.awk scripts which extract the
  60115. ** information from the vdbe.c source text */
  60116. fprintf(pOut, zFormat1, pc,
  60117. sqlite3OpcodeName(pOp->opcode), pOp->p1, pOp->p2, pOp->p3, zP4, pOp->p5,
  60118. zCom
  60119. );
  60120. fflush(pOut);
  60121. }
  60122. #endif
  60123. /*
  60124. ** Release an array of N Mem elements
  60125. */
  60126. static void releaseMemArray(Mem *p, int N){
  60127. if( p && N ){
  60128. Mem *pEnd = &p[N];
  60129. sqlite3 *db = p->db;
  60130. u8 malloc_failed = db->mallocFailed;
  60131. if( db->pnBytesFreed ){
  60132. do{
  60133. if( p->szMalloc ) sqlite3DbFree(db, p->zMalloc);
  60134. }while( (++p)<pEnd );
  60135. return;
  60136. }
  60137. do{
  60138. assert( (&p[1])==pEnd || p[0].db==p[1].db );
  60139. assert( sqlite3VdbeCheckMemInvariants(p) );
  60140. /* This block is really an inlined version of sqlite3VdbeMemRelease()
  60141. ** that takes advantage of the fact that the memory cell value is
  60142. ** being set to NULL after releasing any dynamic resources.
  60143. **
  60144. ** The justification for duplicating code is that according to
  60145. ** callgrind, this causes a certain test case to hit the CPU 4.7
  60146. ** percent less (x86 linux, gcc version 4.1.2, -O6) than if
  60147. ** sqlite3MemRelease() were called from here. With -O2, this jumps
  60148. ** to 6.6 percent. The test case is inserting 1000 rows into a table
  60149. ** with no indexes using a single prepared INSERT statement, bind()
  60150. ** and reset(). Inserts are grouped into a transaction.
  60151. */
  60152. testcase( p->flags & MEM_Agg );
  60153. testcase( p->flags & MEM_Dyn );
  60154. testcase( p->flags & MEM_Frame );
  60155. testcase( p->flags & MEM_RowSet );
  60156. if( p->flags&(MEM_Agg|MEM_Dyn|MEM_Frame|MEM_RowSet) ){
  60157. sqlite3VdbeMemRelease(p);
  60158. }else if( p->szMalloc ){
  60159. sqlite3DbFree(db, p->zMalloc);
  60160. p->szMalloc = 0;
  60161. }
  60162. p->flags = MEM_Undefined;
  60163. }while( (++p)<pEnd );
  60164. db->mallocFailed = malloc_failed;
  60165. }
  60166. }
  60167. /*
  60168. ** Delete a VdbeFrame object and its contents. VdbeFrame objects are
  60169. ** allocated by the OP_Program opcode in sqlite3VdbeExec().
  60170. */
  60171. SQLITE_PRIVATE void sqlite3VdbeFrameDelete(VdbeFrame *p){
  60172. int i;
  60173. Mem *aMem = VdbeFrameMem(p);
  60174. VdbeCursor **apCsr = (VdbeCursor **)&aMem[p->nChildMem];
  60175. for(i=0; i<p->nChildCsr; i++){
  60176. sqlite3VdbeFreeCursor(p->v, apCsr[i]);
  60177. }
  60178. releaseMemArray(aMem, p->nChildMem);
  60179. sqlite3DbFree(p->v->db, p);
  60180. }
  60181. #ifndef SQLITE_OMIT_EXPLAIN
  60182. /*
  60183. ** Give a listing of the program in the virtual machine.
  60184. **
  60185. ** The interface is the same as sqlite3VdbeExec(). But instead of
  60186. ** running the code, it invokes the callback once for each instruction.
  60187. ** This feature is used to implement "EXPLAIN".
  60188. **
  60189. ** When p->explain==1, each instruction is listed. When
  60190. ** p->explain==2, only OP_Explain instructions are listed and these
  60191. ** are shown in a different format. p->explain==2 is used to implement
  60192. ** EXPLAIN QUERY PLAN.
  60193. **
  60194. ** When p->explain==1, first the main program is listed, then each of
  60195. ** the trigger subprograms are listed one by one.
  60196. */
  60197. SQLITE_PRIVATE int sqlite3VdbeList(
  60198. Vdbe *p /* The VDBE */
  60199. ){
  60200. int nRow; /* Stop when row count reaches this */
  60201. int nSub = 0; /* Number of sub-vdbes seen so far */
  60202. SubProgram **apSub = 0; /* Array of sub-vdbes */
  60203. Mem *pSub = 0; /* Memory cell hold array of subprogs */
  60204. sqlite3 *db = p->db; /* The database connection */
  60205. int i; /* Loop counter */
  60206. int rc = SQLITE_OK; /* Return code */
  60207. Mem *pMem = &p->aMem[1]; /* First Mem of result set */
  60208. assert( p->explain );
  60209. assert( p->magic==VDBE_MAGIC_RUN );
  60210. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY || p->rc==SQLITE_NOMEM );
  60211. /* Even though this opcode does not use dynamic strings for
  60212. ** the result, result columns may become dynamic if the user calls
  60213. ** sqlite3_column_text16(), causing a translation to UTF-16 encoding.
  60214. */
  60215. releaseMemArray(pMem, 8);
  60216. p->pResultSet = 0;
  60217. if( p->rc==SQLITE_NOMEM ){
  60218. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  60219. ** sqlite3_column_text16() failed. */
  60220. db->mallocFailed = 1;
  60221. return SQLITE_ERROR;
  60222. }
  60223. /* When the number of output rows reaches nRow, that means the
  60224. ** listing has finished and sqlite3_step() should return SQLITE_DONE.
  60225. ** nRow is the sum of the number of rows in the main program, plus
  60226. ** the sum of the number of rows in all trigger subprograms encountered
  60227. ** so far. The nRow value will increase as new trigger subprograms are
  60228. ** encountered, but p->pc will eventually catch up to nRow.
  60229. */
  60230. nRow = p->nOp;
  60231. if( p->explain==1 ){
  60232. /* The first 8 memory cells are used for the result set. So we will
  60233. ** commandeer the 9th cell to use as storage for an array of pointers
  60234. ** to trigger subprograms. The VDBE is guaranteed to have at least 9
  60235. ** cells. */
  60236. assert( p->nMem>9 );
  60237. pSub = &p->aMem[9];
  60238. if( pSub->flags&MEM_Blob ){
  60239. /* On the first call to sqlite3_step(), pSub will hold a NULL. It is
  60240. ** initialized to a BLOB by the P4_SUBPROGRAM processing logic below */
  60241. nSub = pSub->n/sizeof(Vdbe*);
  60242. apSub = (SubProgram **)pSub->z;
  60243. }
  60244. for(i=0; i<nSub; i++){
  60245. nRow += apSub[i]->nOp;
  60246. }
  60247. }
  60248. do{
  60249. i = p->pc++;
  60250. }while( i<nRow && p->explain==2 && p->aOp[i].opcode!=OP_Explain );
  60251. if( i>=nRow ){
  60252. p->rc = SQLITE_OK;
  60253. rc = SQLITE_DONE;
  60254. }else if( db->u1.isInterrupted ){
  60255. p->rc = SQLITE_INTERRUPT;
  60256. rc = SQLITE_ERROR;
  60257. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(p->rc));
  60258. }else{
  60259. char *zP4;
  60260. Op *pOp;
  60261. if( i<p->nOp ){
  60262. /* The output line number is small enough that we are still in the
  60263. ** main program. */
  60264. pOp = &p->aOp[i];
  60265. }else{
  60266. /* We are currently listing subprograms. Figure out which one and
  60267. ** pick up the appropriate opcode. */
  60268. int j;
  60269. i -= p->nOp;
  60270. for(j=0; i>=apSub[j]->nOp; j++){
  60271. i -= apSub[j]->nOp;
  60272. }
  60273. pOp = &apSub[j]->aOp[i];
  60274. }
  60275. if( p->explain==1 ){
  60276. pMem->flags = MEM_Int;
  60277. pMem->u.i = i; /* Program counter */
  60278. pMem++;
  60279. pMem->flags = MEM_Static|MEM_Str|MEM_Term;
  60280. pMem->z = (char*)sqlite3OpcodeName(pOp->opcode); /* Opcode */
  60281. assert( pMem->z!=0 );
  60282. pMem->n = sqlite3Strlen30(pMem->z);
  60283. pMem->enc = SQLITE_UTF8;
  60284. pMem++;
  60285. /* When an OP_Program opcode is encounter (the only opcode that has
  60286. ** a P4_SUBPROGRAM argument), expand the size of the array of subprograms
  60287. ** kept in p->aMem[9].z to hold the new program - assuming this subprogram
  60288. ** has not already been seen.
  60289. */
  60290. if( pOp->p4type==P4_SUBPROGRAM ){
  60291. int nByte = (nSub+1)*sizeof(SubProgram*);
  60292. int j;
  60293. for(j=0; j<nSub; j++){
  60294. if( apSub[j]==pOp->p4.pProgram ) break;
  60295. }
  60296. if( j==nSub && SQLITE_OK==sqlite3VdbeMemGrow(pSub, nByte, nSub!=0) ){
  60297. apSub = (SubProgram **)pSub->z;
  60298. apSub[nSub++] = pOp->p4.pProgram;
  60299. pSub->flags |= MEM_Blob;
  60300. pSub->n = nSub*sizeof(SubProgram*);
  60301. }
  60302. }
  60303. }
  60304. pMem->flags = MEM_Int;
  60305. pMem->u.i = pOp->p1; /* P1 */
  60306. pMem++;
  60307. pMem->flags = MEM_Int;
  60308. pMem->u.i = pOp->p2; /* P2 */
  60309. pMem++;
  60310. pMem->flags = MEM_Int;
  60311. pMem->u.i = pOp->p3; /* P3 */
  60312. pMem++;
  60313. if( sqlite3VdbeMemClearAndResize(pMem, 32) ){ /* P4 */
  60314. assert( p->db->mallocFailed );
  60315. return SQLITE_ERROR;
  60316. }
  60317. pMem->flags = MEM_Str|MEM_Term;
  60318. zP4 = displayP4(pOp, pMem->z, 32);
  60319. if( zP4!=pMem->z ){
  60320. sqlite3VdbeMemSetStr(pMem, zP4, -1, SQLITE_UTF8, 0);
  60321. }else{
  60322. assert( pMem->z!=0 );
  60323. pMem->n = sqlite3Strlen30(pMem->z);
  60324. pMem->enc = SQLITE_UTF8;
  60325. }
  60326. pMem++;
  60327. if( p->explain==1 ){
  60328. if( sqlite3VdbeMemClearAndResize(pMem, 4) ){
  60329. assert( p->db->mallocFailed );
  60330. return SQLITE_ERROR;
  60331. }
  60332. pMem->flags = MEM_Str|MEM_Term;
  60333. pMem->n = 2;
  60334. sqlite3_snprintf(3, pMem->z, "%.2x", pOp->p5); /* P5 */
  60335. pMem->enc = SQLITE_UTF8;
  60336. pMem++;
  60337. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  60338. if( sqlite3VdbeMemClearAndResize(pMem, 500) ){
  60339. assert( p->db->mallocFailed );
  60340. return SQLITE_ERROR;
  60341. }
  60342. pMem->flags = MEM_Str|MEM_Term;
  60343. pMem->n = displayComment(pOp, zP4, pMem->z, 500);
  60344. pMem->enc = SQLITE_UTF8;
  60345. #else
  60346. pMem->flags = MEM_Null; /* Comment */
  60347. #endif
  60348. }
  60349. p->nResColumn = 8 - 4*(p->explain-1);
  60350. p->pResultSet = &p->aMem[1];
  60351. p->rc = SQLITE_OK;
  60352. rc = SQLITE_ROW;
  60353. }
  60354. return rc;
  60355. }
  60356. #endif /* SQLITE_OMIT_EXPLAIN */
  60357. #ifdef SQLITE_DEBUG
  60358. /*
  60359. ** Print the SQL that was used to generate a VDBE program.
  60360. */
  60361. SQLITE_PRIVATE void sqlite3VdbePrintSql(Vdbe *p){
  60362. const char *z = 0;
  60363. if( p->zSql ){
  60364. z = p->zSql;
  60365. }else if( p->nOp>=1 ){
  60366. const VdbeOp *pOp = &p->aOp[0];
  60367. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  60368. z = pOp->p4.z;
  60369. while( sqlite3Isspace(*z) ) z++;
  60370. }
  60371. }
  60372. if( z ) printf("SQL: [%s]\n", z);
  60373. }
  60374. #endif
  60375. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  60376. /*
  60377. ** Print an IOTRACE message showing SQL content.
  60378. */
  60379. SQLITE_PRIVATE void sqlite3VdbeIOTraceSql(Vdbe *p){
  60380. int nOp = p->nOp;
  60381. VdbeOp *pOp;
  60382. if( sqlite3IoTrace==0 ) return;
  60383. if( nOp<1 ) return;
  60384. pOp = &p->aOp[0];
  60385. if( pOp->opcode==OP_Init && pOp->p4.z!=0 ){
  60386. int i, j;
  60387. char z[1000];
  60388. sqlite3_snprintf(sizeof(z), z, "%s", pOp->p4.z);
  60389. for(i=0; sqlite3Isspace(z[i]); i++){}
  60390. for(j=0; z[i]; i++){
  60391. if( sqlite3Isspace(z[i]) ){
  60392. if( z[i-1]!=' ' ){
  60393. z[j++] = ' ';
  60394. }
  60395. }else{
  60396. z[j++] = z[i];
  60397. }
  60398. }
  60399. z[j] = 0;
  60400. sqlite3IoTrace("SQL %s\n", z);
  60401. }
  60402. }
  60403. #endif /* !SQLITE_OMIT_TRACE && SQLITE_ENABLE_IOTRACE */
  60404. /*
  60405. ** Allocate space from a fixed size buffer and return a pointer to
  60406. ** that space. If insufficient space is available, return NULL.
  60407. **
  60408. ** The pBuf parameter is the initial value of a pointer which will
  60409. ** receive the new memory. pBuf is normally NULL. If pBuf is not
  60410. ** NULL, it means that memory space has already been allocated and that
  60411. ** this routine should not allocate any new memory. When pBuf is not
  60412. ** NULL simply return pBuf. Only allocate new memory space when pBuf
  60413. ** is NULL.
  60414. **
  60415. ** nByte is the number of bytes of space needed.
  60416. **
  60417. ** *ppFrom points to available space and pEnd points to the end of the
  60418. ** available space. When space is allocated, *ppFrom is advanced past
  60419. ** the end of the allocated space.
  60420. **
  60421. ** *pnByte is a counter of the number of bytes of space that have failed
  60422. ** to allocate. If there is insufficient space in *ppFrom to satisfy the
  60423. ** request, then increment *pnByte by the amount of the request.
  60424. */
  60425. static void *allocSpace(
  60426. void *pBuf, /* Where return pointer will be stored */
  60427. int nByte, /* Number of bytes to allocate */
  60428. u8 **ppFrom, /* IN/OUT: Allocate from *ppFrom */
  60429. u8 *pEnd, /* Pointer to 1 byte past the end of *ppFrom buffer */
  60430. int *pnByte /* If allocation cannot be made, increment *pnByte */
  60431. ){
  60432. assert( EIGHT_BYTE_ALIGNMENT(*ppFrom) );
  60433. if( pBuf ) return pBuf;
  60434. nByte = ROUND8(nByte);
  60435. if( &(*ppFrom)[nByte] <= pEnd ){
  60436. pBuf = (void*)*ppFrom;
  60437. *ppFrom += nByte;
  60438. }else{
  60439. *pnByte += nByte;
  60440. }
  60441. return pBuf;
  60442. }
  60443. /*
  60444. ** Rewind the VDBE back to the beginning in preparation for
  60445. ** running it.
  60446. */
  60447. SQLITE_PRIVATE void sqlite3VdbeRewind(Vdbe *p){
  60448. #if defined(SQLITE_DEBUG) || defined(VDBE_PROFILE)
  60449. int i;
  60450. #endif
  60451. assert( p!=0 );
  60452. assert( p->magic==VDBE_MAGIC_INIT );
  60453. /* There should be at least one opcode.
  60454. */
  60455. assert( p->nOp>0 );
  60456. /* Set the magic to VDBE_MAGIC_RUN sooner rather than later. */
  60457. p->magic = VDBE_MAGIC_RUN;
  60458. #ifdef SQLITE_DEBUG
  60459. for(i=1; i<p->nMem; i++){
  60460. assert( p->aMem[i].db==p->db );
  60461. }
  60462. #endif
  60463. p->pc = -1;
  60464. p->rc = SQLITE_OK;
  60465. p->errorAction = OE_Abort;
  60466. p->magic = VDBE_MAGIC_RUN;
  60467. p->nChange = 0;
  60468. p->cacheCtr = 1;
  60469. p->minWriteFileFormat = 255;
  60470. p->iStatement = 0;
  60471. p->nFkConstraint = 0;
  60472. #ifdef VDBE_PROFILE
  60473. for(i=0; i<p->nOp; i++){
  60474. p->aOp[i].cnt = 0;
  60475. p->aOp[i].cycles = 0;
  60476. }
  60477. #endif
  60478. }
  60479. /*
  60480. ** Prepare a virtual machine for execution for the first time after
  60481. ** creating the virtual machine. This involves things such
  60482. ** as allocating registers and initializing the program counter.
  60483. ** After the VDBE has be prepped, it can be executed by one or more
  60484. ** calls to sqlite3VdbeExec().
  60485. **
  60486. ** This function may be called exactly once on each virtual machine.
  60487. ** After this routine is called the VM has been "packaged" and is ready
  60488. ** to run. After this routine is called, further calls to
  60489. ** sqlite3VdbeAddOp() functions are prohibited. This routine disconnects
  60490. ** the Vdbe from the Parse object that helped generate it so that the
  60491. ** the Vdbe becomes an independent entity and the Parse object can be
  60492. ** destroyed.
  60493. **
  60494. ** Use the sqlite3VdbeRewind() procedure to restore a virtual machine back
  60495. ** to its initial state after it has been run.
  60496. */
  60497. SQLITE_PRIVATE void sqlite3VdbeMakeReady(
  60498. Vdbe *p, /* The VDBE */
  60499. Parse *pParse /* Parsing context */
  60500. ){
  60501. sqlite3 *db; /* The database connection */
  60502. int nVar; /* Number of parameters */
  60503. int nMem; /* Number of VM memory registers */
  60504. int nCursor; /* Number of cursors required */
  60505. int nArg; /* Number of arguments in subprograms */
  60506. int nOnce; /* Number of OP_Once instructions */
  60507. int n; /* Loop counter */
  60508. u8 *zCsr; /* Memory available for allocation */
  60509. u8 *zEnd; /* First byte past allocated memory */
  60510. int nByte; /* How much extra memory is needed */
  60511. assert( p!=0 );
  60512. assert( p->nOp>0 );
  60513. assert( pParse!=0 );
  60514. assert( p->magic==VDBE_MAGIC_INIT );
  60515. assert( pParse==p->pParse );
  60516. db = p->db;
  60517. assert( db->mallocFailed==0 );
  60518. nVar = pParse->nVar;
  60519. nMem = pParse->nMem;
  60520. nCursor = pParse->nTab;
  60521. nArg = pParse->nMaxArg;
  60522. nOnce = pParse->nOnce;
  60523. if( nOnce==0 ) nOnce = 1; /* Ensure at least one byte in p->aOnceFlag[] */
  60524. /* For each cursor required, also allocate a memory cell. Memory
  60525. ** cells (nMem+1-nCursor)..nMem, inclusive, will never be used by
  60526. ** the vdbe program. Instead they are used to allocate space for
  60527. ** VdbeCursor/BtCursor structures. The blob of memory associated with
  60528. ** cursor 0 is stored in memory cell nMem. Memory cell (nMem-1)
  60529. ** stores the blob of memory associated with cursor 1, etc.
  60530. **
  60531. ** See also: allocateCursor().
  60532. */
  60533. nMem += nCursor;
  60534. /* Allocate space for memory registers, SQL variables, VDBE cursors and
  60535. ** an array to marshal SQL function arguments in.
  60536. */
  60537. zCsr = (u8*)&p->aOp[p->nOp]; /* Memory avaliable for allocation */
  60538. zEnd = (u8*)&p->aOp[pParse->nOpAlloc]; /* First byte past end of zCsr[] */
  60539. resolveP2Values(p, &nArg);
  60540. p->usesStmtJournal = (u8)(pParse->isMultiWrite && pParse->mayAbort);
  60541. if( pParse->explain && nMem<10 ){
  60542. nMem = 10;
  60543. }
  60544. memset(zCsr, 0, zEnd-zCsr);
  60545. zCsr += (zCsr - (u8*)0)&7;
  60546. assert( EIGHT_BYTE_ALIGNMENT(zCsr) );
  60547. p->expired = 0;
  60548. /* Memory for registers, parameters, cursor, etc, is allocated in two
  60549. ** passes. On the first pass, we try to reuse unused space at the
  60550. ** end of the opcode array. If we are unable to satisfy all memory
  60551. ** requirements by reusing the opcode array tail, then the second
  60552. ** pass will fill in the rest using a fresh allocation.
  60553. **
  60554. ** This two-pass approach that reuses as much memory as possible from
  60555. ** the leftover space at the end of the opcode array can significantly
  60556. ** reduce the amount of memory held by a prepared statement.
  60557. */
  60558. do {
  60559. nByte = 0;
  60560. p->aMem = allocSpace(p->aMem, nMem*sizeof(Mem), &zCsr, zEnd, &nByte);
  60561. p->aVar = allocSpace(p->aVar, nVar*sizeof(Mem), &zCsr, zEnd, &nByte);
  60562. p->apArg = allocSpace(p->apArg, nArg*sizeof(Mem*), &zCsr, zEnd, &nByte);
  60563. p->azVar = allocSpace(p->azVar, nVar*sizeof(char*), &zCsr, zEnd, &nByte);
  60564. p->apCsr = allocSpace(p->apCsr, nCursor*sizeof(VdbeCursor*),
  60565. &zCsr, zEnd, &nByte);
  60566. p->aOnceFlag = allocSpace(p->aOnceFlag, nOnce, &zCsr, zEnd, &nByte);
  60567. if( nByte ){
  60568. p->pFree = sqlite3DbMallocZero(db, nByte);
  60569. }
  60570. zCsr = p->pFree;
  60571. zEnd = &zCsr[nByte];
  60572. }while( nByte && !db->mallocFailed );
  60573. p->nCursor = nCursor;
  60574. p->nOnceFlag = nOnce;
  60575. if( p->aVar ){
  60576. p->nVar = (ynVar)nVar;
  60577. for(n=0; n<nVar; n++){
  60578. p->aVar[n].flags = MEM_Null;
  60579. p->aVar[n].db = db;
  60580. }
  60581. }
  60582. if( p->azVar ){
  60583. p->nzVar = pParse->nzVar;
  60584. memcpy(p->azVar, pParse->azVar, p->nzVar*sizeof(p->azVar[0]));
  60585. memset(pParse->azVar, 0, pParse->nzVar*sizeof(pParse->azVar[0]));
  60586. }
  60587. if( p->aMem ){
  60588. p->aMem--; /* aMem[] goes from 1..nMem */
  60589. p->nMem = nMem; /* not from 0..nMem-1 */
  60590. for(n=1; n<=nMem; n++){
  60591. p->aMem[n].flags = MEM_Undefined;
  60592. p->aMem[n].db = db;
  60593. }
  60594. }
  60595. p->explain = pParse->explain;
  60596. sqlite3VdbeRewind(p);
  60597. }
  60598. /*
  60599. ** Close a VDBE cursor and release all the resources that cursor
  60600. ** happens to hold.
  60601. */
  60602. SQLITE_PRIVATE void sqlite3VdbeFreeCursor(Vdbe *p, VdbeCursor *pCx){
  60603. if( pCx==0 ){
  60604. return;
  60605. }
  60606. sqlite3VdbeSorterClose(p->db, pCx);
  60607. if( pCx->pBt ){
  60608. sqlite3BtreeClose(pCx->pBt);
  60609. /* The pCx->pCursor will be close automatically, if it exists, by
  60610. ** the call above. */
  60611. }else if( pCx->pCursor ){
  60612. sqlite3BtreeCloseCursor(pCx->pCursor);
  60613. }
  60614. #ifndef SQLITE_OMIT_VIRTUALTABLE
  60615. else if( pCx->pVtabCursor ){
  60616. sqlite3_vtab_cursor *pVtabCursor = pCx->pVtabCursor;
  60617. const sqlite3_module *pModule = pVtabCursor->pVtab->pModule;
  60618. p->inVtabMethod = 1;
  60619. pModule->xClose(pVtabCursor);
  60620. p->inVtabMethod = 0;
  60621. }
  60622. #endif
  60623. }
  60624. /*
  60625. ** Copy the values stored in the VdbeFrame structure to its Vdbe. This
  60626. ** is used, for example, when a trigger sub-program is halted to restore
  60627. ** control to the main program.
  60628. */
  60629. SQLITE_PRIVATE int sqlite3VdbeFrameRestore(VdbeFrame *pFrame){
  60630. Vdbe *v = pFrame->v;
  60631. v->aOnceFlag = pFrame->aOnceFlag;
  60632. v->nOnceFlag = pFrame->nOnceFlag;
  60633. v->aOp = pFrame->aOp;
  60634. v->nOp = pFrame->nOp;
  60635. v->aMem = pFrame->aMem;
  60636. v->nMem = pFrame->nMem;
  60637. v->apCsr = pFrame->apCsr;
  60638. v->nCursor = pFrame->nCursor;
  60639. v->db->lastRowid = pFrame->lastRowid;
  60640. v->nChange = pFrame->nChange;
  60641. return pFrame->pc;
  60642. }
  60643. /*
  60644. ** Close all cursors.
  60645. **
  60646. ** Also release any dynamic memory held by the VM in the Vdbe.aMem memory
  60647. ** cell array. This is necessary as the memory cell array may contain
  60648. ** pointers to VdbeFrame objects, which may in turn contain pointers to
  60649. ** open cursors.
  60650. */
  60651. static void closeAllCursors(Vdbe *p){
  60652. if( p->pFrame ){
  60653. VdbeFrame *pFrame;
  60654. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  60655. sqlite3VdbeFrameRestore(pFrame);
  60656. p->pFrame = 0;
  60657. p->nFrame = 0;
  60658. }
  60659. assert( p->nFrame==0 );
  60660. if( p->apCsr ){
  60661. int i;
  60662. for(i=0; i<p->nCursor; i++){
  60663. VdbeCursor *pC = p->apCsr[i];
  60664. if( pC ){
  60665. sqlite3VdbeFreeCursor(p, pC);
  60666. p->apCsr[i] = 0;
  60667. }
  60668. }
  60669. }
  60670. if( p->aMem ){
  60671. releaseMemArray(&p->aMem[1], p->nMem);
  60672. }
  60673. while( p->pDelFrame ){
  60674. VdbeFrame *pDel = p->pDelFrame;
  60675. p->pDelFrame = pDel->pParent;
  60676. sqlite3VdbeFrameDelete(pDel);
  60677. }
  60678. /* Delete any auxdata allocations made by the VM */
  60679. if( p->pAuxData ) sqlite3VdbeDeleteAuxData(p, -1, 0);
  60680. assert( p->pAuxData==0 );
  60681. }
  60682. /*
  60683. ** Clean up the VM after a single run.
  60684. */
  60685. static void Cleanup(Vdbe *p){
  60686. sqlite3 *db = p->db;
  60687. #ifdef SQLITE_DEBUG
  60688. /* Execute assert() statements to ensure that the Vdbe.apCsr[] and
  60689. ** Vdbe.aMem[] arrays have already been cleaned up. */
  60690. int i;
  60691. if( p->apCsr ) for(i=0; i<p->nCursor; i++) assert( p->apCsr[i]==0 );
  60692. if( p->aMem ){
  60693. for(i=1; i<=p->nMem; i++) assert( p->aMem[i].flags==MEM_Undefined );
  60694. }
  60695. #endif
  60696. sqlite3DbFree(db, p->zErrMsg);
  60697. p->zErrMsg = 0;
  60698. p->pResultSet = 0;
  60699. }
  60700. /*
  60701. ** Set the number of result columns that will be returned by this SQL
  60702. ** statement. This is now set at compile time, rather than during
  60703. ** execution of the vdbe program so that sqlite3_column_count() can
  60704. ** be called on an SQL statement before sqlite3_step().
  60705. */
  60706. SQLITE_PRIVATE void sqlite3VdbeSetNumCols(Vdbe *p, int nResColumn){
  60707. Mem *pColName;
  60708. int n;
  60709. sqlite3 *db = p->db;
  60710. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  60711. sqlite3DbFree(db, p->aColName);
  60712. n = nResColumn*COLNAME_N;
  60713. p->nResColumn = (u16)nResColumn;
  60714. p->aColName = pColName = (Mem*)sqlite3DbMallocZero(db, sizeof(Mem)*n );
  60715. if( p->aColName==0 ) return;
  60716. while( n-- > 0 ){
  60717. pColName->flags = MEM_Null;
  60718. pColName->db = p->db;
  60719. pColName++;
  60720. }
  60721. }
  60722. /*
  60723. ** Set the name of the idx'th column to be returned by the SQL statement.
  60724. ** zName must be a pointer to a nul terminated string.
  60725. **
  60726. ** This call must be made after a call to sqlite3VdbeSetNumCols().
  60727. **
  60728. ** The final parameter, xDel, must be one of SQLITE_DYNAMIC, SQLITE_STATIC
  60729. ** or SQLITE_TRANSIENT. If it is SQLITE_DYNAMIC, then the buffer pointed
  60730. ** to by zName will be freed by sqlite3DbFree() when the vdbe is destroyed.
  60731. */
  60732. SQLITE_PRIVATE int sqlite3VdbeSetColName(
  60733. Vdbe *p, /* Vdbe being configured */
  60734. int idx, /* Index of column zName applies to */
  60735. int var, /* One of the COLNAME_* constants */
  60736. const char *zName, /* Pointer to buffer containing name */
  60737. void (*xDel)(void*) /* Memory management strategy for zName */
  60738. ){
  60739. int rc;
  60740. Mem *pColName;
  60741. assert( idx<p->nResColumn );
  60742. assert( var<COLNAME_N );
  60743. if( p->db->mallocFailed ){
  60744. assert( !zName || xDel!=SQLITE_DYNAMIC );
  60745. return SQLITE_NOMEM;
  60746. }
  60747. assert( p->aColName!=0 );
  60748. pColName = &(p->aColName[idx+var*p->nResColumn]);
  60749. rc = sqlite3VdbeMemSetStr(pColName, zName, -1, SQLITE_UTF8, xDel);
  60750. assert( rc!=0 || !zName || (pColName->flags&MEM_Term)!=0 );
  60751. return rc;
  60752. }
  60753. /*
  60754. ** A read or write transaction may or may not be active on database handle
  60755. ** db. If a transaction is active, commit it. If there is a
  60756. ** write-transaction spanning more than one database file, this routine
  60757. ** takes care of the master journal trickery.
  60758. */
  60759. static int vdbeCommit(sqlite3 *db, Vdbe *p){
  60760. int i;
  60761. int nTrans = 0; /* Number of databases with an active write-transaction */
  60762. int rc = SQLITE_OK;
  60763. int needXcommit = 0;
  60764. #ifdef SQLITE_OMIT_VIRTUALTABLE
  60765. /* With this option, sqlite3VtabSync() is defined to be simply
  60766. ** SQLITE_OK so p is not used.
  60767. */
  60768. UNUSED_PARAMETER(p);
  60769. #endif
  60770. /* Before doing anything else, call the xSync() callback for any
  60771. ** virtual module tables written in this transaction. This has to
  60772. ** be done before determining whether a master journal file is
  60773. ** required, as an xSync() callback may add an attached database
  60774. ** to the transaction.
  60775. */
  60776. rc = sqlite3VtabSync(db, p);
  60777. /* This loop determines (a) if the commit hook should be invoked and
  60778. ** (b) how many database files have open write transactions, not
  60779. ** including the temp database. (b) is important because if more than
  60780. ** one database file has an open write transaction, a master journal
  60781. ** file is required for an atomic commit.
  60782. */
  60783. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  60784. Btree *pBt = db->aDb[i].pBt;
  60785. if( sqlite3BtreeIsInTrans(pBt) ){
  60786. needXcommit = 1;
  60787. if( i!=1 ) nTrans++;
  60788. sqlite3BtreeEnter(pBt);
  60789. rc = sqlite3PagerExclusiveLock(sqlite3BtreePager(pBt));
  60790. sqlite3BtreeLeave(pBt);
  60791. }
  60792. }
  60793. if( rc!=SQLITE_OK ){
  60794. return rc;
  60795. }
  60796. /* If there are any write-transactions at all, invoke the commit hook */
  60797. if( needXcommit && db->xCommitCallback ){
  60798. rc = db->xCommitCallback(db->pCommitArg);
  60799. if( rc ){
  60800. return SQLITE_CONSTRAINT_COMMITHOOK;
  60801. }
  60802. }
  60803. /* The simple case - no more than one database file (not counting the
  60804. ** TEMP database) has a transaction active. There is no need for the
  60805. ** master-journal.
  60806. **
  60807. ** If the return value of sqlite3BtreeGetFilename() is a zero length
  60808. ** string, it means the main database is :memory: or a temp file. In
  60809. ** that case we do not support atomic multi-file commits, so use the
  60810. ** simple case then too.
  60811. */
  60812. if( 0==sqlite3Strlen30(sqlite3BtreeGetFilename(db->aDb[0].pBt))
  60813. || nTrans<=1
  60814. ){
  60815. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  60816. Btree *pBt = db->aDb[i].pBt;
  60817. if( pBt ){
  60818. rc = sqlite3BtreeCommitPhaseOne(pBt, 0);
  60819. }
  60820. }
  60821. /* Do the commit only if all databases successfully complete phase 1.
  60822. ** If one of the BtreeCommitPhaseOne() calls fails, this indicates an
  60823. ** IO error while deleting or truncating a journal file. It is unlikely,
  60824. ** but could happen. In this case abandon processing and return the error.
  60825. */
  60826. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  60827. Btree *pBt = db->aDb[i].pBt;
  60828. if( pBt ){
  60829. rc = sqlite3BtreeCommitPhaseTwo(pBt, 0);
  60830. }
  60831. }
  60832. if( rc==SQLITE_OK ){
  60833. sqlite3VtabCommit(db);
  60834. }
  60835. }
  60836. /* The complex case - There is a multi-file write-transaction active.
  60837. ** This requires a master journal file to ensure the transaction is
  60838. ** committed atomically.
  60839. */
  60840. #ifndef SQLITE_OMIT_DISKIO
  60841. else{
  60842. sqlite3_vfs *pVfs = db->pVfs;
  60843. int needSync = 0;
  60844. char *zMaster = 0; /* File-name for the master journal */
  60845. char const *zMainFile = sqlite3BtreeGetFilename(db->aDb[0].pBt);
  60846. sqlite3_file *pMaster = 0;
  60847. i64 offset = 0;
  60848. int res;
  60849. int retryCount = 0;
  60850. int nMainFile;
  60851. /* Select a master journal file name */
  60852. nMainFile = sqlite3Strlen30(zMainFile);
  60853. zMaster = sqlite3MPrintf(db, "%s-mjXXXXXX9XXz", zMainFile);
  60854. if( zMaster==0 ) return SQLITE_NOMEM;
  60855. do {
  60856. u32 iRandom;
  60857. if( retryCount ){
  60858. if( retryCount>100 ){
  60859. sqlite3_log(SQLITE_FULL, "MJ delete: %s", zMaster);
  60860. sqlite3OsDelete(pVfs, zMaster, 0);
  60861. break;
  60862. }else if( retryCount==1 ){
  60863. sqlite3_log(SQLITE_FULL, "MJ collide: %s", zMaster);
  60864. }
  60865. }
  60866. retryCount++;
  60867. sqlite3_randomness(sizeof(iRandom), &iRandom);
  60868. sqlite3_snprintf(13, &zMaster[nMainFile], "-mj%06X9%02X",
  60869. (iRandom>>8)&0xffffff, iRandom&0xff);
  60870. /* The antipenultimate character of the master journal name must
  60871. ** be "9" to avoid name collisions when using 8+3 filenames. */
  60872. assert( zMaster[sqlite3Strlen30(zMaster)-3]=='9' );
  60873. sqlite3FileSuffix3(zMainFile, zMaster);
  60874. rc = sqlite3OsAccess(pVfs, zMaster, SQLITE_ACCESS_EXISTS, &res);
  60875. }while( rc==SQLITE_OK && res );
  60876. if( rc==SQLITE_OK ){
  60877. /* Open the master journal. */
  60878. rc = sqlite3OsOpenMalloc(pVfs, zMaster, &pMaster,
  60879. SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE|
  60880. SQLITE_OPEN_EXCLUSIVE|SQLITE_OPEN_MASTER_JOURNAL, 0
  60881. );
  60882. }
  60883. if( rc!=SQLITE_OK ){
  60884. sqlite3DbFree(db, zMaster);
  60885. return rc;
  60886. }
  60887. /* Write the name of each database file in the transaction into the new
  60888. ** master journal file. If an error occurs at this point close
  60889. ** and delete the master journal file. All the individual journal files
  60890. ** still have 'null' as the master journal pointer, so they will roll
  60891. ** back independently if a failure occurs.
  60892. */
  60893. for(i=0; i<db->nDb; i++){
  60894. Btree *pBt = db->aDb[i].pBt;
  60895. if( sqlite3BtreeIsInTrans(pBt) ){
  60896. char const *zFile = sqlite3BtreeGetJournalname(pBt);
  60897. if( zFile==0 ){
  60898. continue; /* Ignore TEMP and :memory: databases */
  60899. }
  60900. assert( zFile[0]!=0 );
  60901. if( !needSync && !sqlite3BtreeSyncDisabled(pBt) ){
  60902. needSync = 1;
  60903. }
  60904. rc = sqlite3OsWrite(pMaster, zFile, sqlite3Strlen30(zFile)+1, offset);
  60905. offset += sqlite3Strlen30(zFile)+1;
  60906. if( rc!=SQLITE_OK ){
  60907. sqlite3OsCloseFree(pMaster);
  60908. sqlite3OsDelete(pVfs, zMaster, 0);
  60909. sqlite3DbFree(db, zMaster);
  60910. return rc;
  60911. }
  60912. }
  60913. }
  60914. /* Sync the master journal file. If the IOCAP_SEQUENTIAL device
  60915. ** flag is set this is not required.
  60916. */
  60917. if( needSync
  60918. && 0==(sqlite3OsDeviceCharacteristics(pMaster)&SQLITE_IOCAP_SEQUENTIAL)
  60919. && SQLITE_OK!=(rc = sqlite3OsSync(pMaster, SQLITE_SYNC_NORMAL))
  60920. ){
  60921. sqlite3OsCloseFree(pMaster);
  60922. sqlite3OsDelete(pVfs, zMaster, 0);
  60923. sqlite3DbFree(db, zMaster);
  60924. return rc;
  60925. }
  60926. /* Sync all the db files involved in the transaction. The same call
  60927. ** sets the master journal pointer in each individual journal. If
  60928. ** an error occurs here, do not delete the master journal file.
  60929. **
  60930. ** If the error occurs during the first call to
  60931. ** sqlite3BtreeCommitPhaseOne(), then there is a chance that the
  60932. ** master journal file will be orphaned. But we cannot delete it,
  60933. ** in case the master journal file name was written into the journal
  60934. ** file before the failure occurred.
  60935. */
  60936. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  60937. Btree *pBt = db->aDb[i].pBt;
  60938. if( pBt ){
  60939. rc = sqlite3BtreeCommitPhaseOne(pBt, zMaster);
  60940. }
  60941. }
  60942. sqlite3OsCloseFree(pMaster);
  60943. assert( rc!=SQLITE_BUSY );
  60944. if( rc!=SQLITE_OK ){
  60945. sqlite3DbFree(db, zMaster);
  60946. return rc;
  60947. }
  60948. /* Delete the master journal file. This commits the transaction. After
  60949. ** doing this the directory is synced again before any individual
  60950. ** transaction files are deleted.
  60951. */
  60952. rc = sqlite3OsDelete(pVfs, zMaster, 1);
  60953. sqlite3DbFree(db, zMaster);
  60954. zMaster = 0;
  60955. if( rc ){
  60956. return rc;
  60957. }
  60958. /* All files and directories have already been synced, so the following
  60959. ** calls to sqlite3BtreeCommitPhaseTwo() are only closing files and
  60960. ** deleting or truncating journals. If something goes wrong while
  60961. ** this is happening we don't really care. The integrity of the
  60962. ** transaction is already guaranteed, but some stray 'cold' journals
  60963. ** may be lying around. Returning an error code won't help matters.
  60964. */
  60965. disable_simulated_io_errors();
  60966. sqlite3BeginBenignMalloc();
  60967. for(i=0; i<db->nDb; i++){
  60968. Btree *pBt = db->aDb[i].pBt;
  60969. if( pBt ){
  60970. sqlite3BtreeCommitPhaseTwo(pBt, 1);
  60971. }
  60972. }
  60973. sqlite3EndBenignMalloc();
  60974. enable_simulated_io_errors();
  60975. sqlite3VtabCommit(db);
  60976. }
  60977. #endif
  60978. return rc;
  60979. }
  60980. /*
  60981. ** This routine checks that the sqlite3.nVdbeActive count variable
  60982. ** matches the number of vdbe's in the list sqlite3.pVdbe that are
  60983. ** currently active. An assertion fails if the two counts do not match.
  60984. ** This is an internal self-check only - it is not an essential processing
  60985. ** step.
  60986. **
  60987. ** This is a no-op if NDEBUG is defined.
  60988. */
  60989. #ifndef NDEBUG
  60990. static void checkActiveVdbeCnt(sqlite3 *db){
  60991. Vdbe *p;
  60992. int cnt = 0;
  60993. int nWrite = 0;
  60994. int nRead = 0;
  60995. p = db->pVdbe;
  60996. while( p ){
  60997. if( sqlite3_stmt_busy((sqlite3_stmt*)p) ){
  60998. cnt++;
  60999. if( p->readOnly==0 ) nWrite++;
  61000. if( p->bIsReader ) nRead++;
  61001. }
  61002. p = p->pNext;
  61003. }
  61004. assert( cnt==db->nVdbeActive );
  61005. assert( nWrite==db->nVdbeWrite );
  61006. assert( nRead==db->nVdbeRead );
  61007. }
  61008. #else
  61009. #define checkActiveVdbeCnt(x)
  61010. #endif
  61011. /*
  61012. ** If the Vdbe passed as the first argument opened a statement-transaction,
  61013. ** close it now. Argument eOp must be either SAVEPOINT_ROLLBACK or
  61014. ** SAVEPOINT_RELEASE. If it is SAVEPOINT_ROLLBACK, then the statement
  61015. ** transaction is rolled back. If eOp is SAVEPOINT_RELEASE, then the
  61016. ** statement transaction is committed.
  61017. **
  61018. ** If an IO error occurs, an SQLITE_IOERR_XXX error code is returned.
  61019. ** Otherwise SQLITE_OK.
  61020. */
  61021. SQLITE_PRIVATE int sqlite3VdbeCloseStatement(Vdbe *p, int eOp){
  61022. sqlite3 *const db = p->db;
  61023. int rc = SQLITE_OK;
  61024. /* If p->iStatement is greater than zero, then this Vdbe opened a
  61025. ** statement transaction that should be closed here. The only exception
  61026. ** is that an IO error may have occurred, causing an emergency rollback.
  61027. ** In this case (db->nStatement==0), and there is nothing to do.
  61028. */
  61029. if( db->nStatement && p->iStatement ){
  61030. int i;
  61031. const int iSavepoint = p->iStatement-1;
  61032. assert( eOp==SAVEPOINT_ROLLBACK || eOp==SAVEPOINT_RELEASE);
  61033. assert( db->nStatement>0 );
  61034. assert( p->iStatement==(db->nStatement+db->nSavepoint) );
  61035. for(i=0; i<db->nDb; i++){
  61036. int rc2 = SQLITE_OK;
  61037. Btree *pBt = db->aDb[i].pBt;
  61038. if( pBt ){
  61039. if( eOp==SAVEPOINT_ROLLBACK ){
  61040. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_ROLLBACK, iSavepoint);
  61041. }
  61042. if( rc2==SQLITE_OK ){
  61043. rc2 = sqlite3BtreeSavepoint(pBt, SAVEPOINT_RELEASE, iSavepoint);
  61044. }
  61045. if( rc==SQLITE_OK ){
  61046. rc = rc2;
  61047. }
  61048. }
  61049. }
  61050. db->nStatement--;
  61051. p->iStatement = 0;
  61052. if( rc==SQLITE_OK ){
  61053. if( eOp==SAVEPOINT_ROLLBACK ){
  61054. rc = sqlite3VtabSavepoint(db, SAVEPOINT_ROLLBACK, iSavepoint);
  61055. }
  61056. if( rc==SQLITE_OK ){
  61057. rc = sqlite3VtabSavepoint(db, SAVEPOINT_RELEASE, iSavepoint);
  61058. }
  61059. }
  61060. /* If the statement transaction is being rolled back, also restore the
  61061. ** database handles deferred constraint counter to the value it had when
  61062. ** the statement transaction was opened. */
  61063. if( eOp==SAVEPOINT_ROLLBACK ){
  61064. db->nDeferredCons = p->nStmtDefCons;
  61065. db->nDeferredImmCons = p->nStmtDefImmCons;
  61066. }
  61067. }
  61068. return rc;
  61069. }
  61070. /*
  61071. ** This function is called when a transaction opened by the database
  61072. ** handle associated with the VM passed as an argument is about to be
  61073. ** committed. If there are outstanding deferred foreign key constraint
  61074. ** violations, return SQLITE_ERROR. Otherwise, SQLITE_OK.
  61075. **
  61076. ** If there are outstanding FK violations and this function returns
  61077. ** SQLITE_ERROR, set the result of the VM to SQLITE_CONSTRAINT_FOREIGNKEY
  61078. ** and write an error message to it. Then return SQLITE_ERROR.
  61079. */
  61080. #ifndef SQLITE_OMIT_FOREIGN_KEY
  61081. SQLITE_PRIVATE int sqlite3VdbeCheckFk(Vdbe *p, int deferred){
  61082. sqlite3 *db = p->db;
  61083. if( (deferred && (db->nDeferredCons+db->nDeferredImmCons)>0)
  61084. || (!deferred && p->nFkConstraint>0)
  61085. ){
  61086. p->rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  61087. p->errorAction = OE_Abort;
  61088. sqlite3SetString(&p->zErrMsg, db, "FOREIGN KEY constraint failed");
  61089. return SQLITE_ERROR;
  61090. }
  61091. return SQLITE_OK;
  61092. }
  61093. #endif
  61094. /*
  61095. ** This routine is called the when a VDBE tries to halt. If the VDBE
  61096. ** has made changes and is in autocommit mode, then commit those
  61097. ** changes. If a rollback is needed, then do the rollback.
  61098. **
  61099. ** This routine is the only way to move the state of a VM from
  61100. ** SQLITE_MAGIC_RUN to SQLITE_MAGIC_HALT. It is harmless to
  61101. ** call this on a VM that is in the SQLITE_MAGIC_HALT state.
  61102. **
  61103. ** Return an error code. If the commit could not complete because of
  61104. ** lock contention, return SQLITE_BUSY. If SQLITE_BUSY is returned, it
  61105. ** means the close did not happen and needs to be repeated.
  61106. */
  61107. SQLITE_PRIVATE int sqlite3VdbeHalt(Vdbe *p){
  61108. int rc; /* Used to store transient return codes */
  61109. sqlite3 *db = p->db;
  61110. /* This function contains the logic that determines if a statement or
  61111. ** transaction will be committed or rolled back as a result of the
  61112. ** execution of this virtual machine.
  61113. **
  61114. ** If any of the following errors occur:
  61115. **
  61116. ** SQLITE_NOMEM
  61117. ** SQLITE_IOERR
  61118. ** SQLITE_FULL
  61119. ** SQLITE_INTERRUPT
  61120. **
  61121. ** Then the internal cache might have been left in an inconsistent
  61122. ** state. We need to rollback the statement transaction, if there is
  61123. ** one, or the complete transaction if there is no statement transaction.
  61124. */
  61125. if( p->db->mallocFailed ){
  61126. p->rc = SQLITE_NOMEM;
  61127. }
  61128. if( p->aOnceFlag ) memset(p->aOnceFlag, 0, p->nOnceFlag);
  61129. closeAllCursors(p);
  61130. if( p->magic!=VDBE_MAGIC_RUN ){
  61131. return SQLITE_OK;
  61132. }
  61133. checkActiveVdbeCnt(db);
  61134. /* No commit or rollback needed if the program never started or if the
  61135. ** SQL statement does not read or write a database file. */
  61136. if( p->pc>=0 && p->bIsReader ){
  61137. int mrc; /* Primary error code from p->rc */
  61138. int eStatementOp = 0;
  61139. int isSpecialError; /* Set to true if a 'special' error */
  61140. /* Lock all btrees used by the statement */
  61141. sqlite3VdbeEnter(p);
  61142. /* Check for one of the special errors */
  61143. mrc = p->rc & 0xff;
  61144. isSpecialError = mrc==SQLITE_NOMEM || mrc==SQLITE_IOERR
  61145. || mrc==SQLITE_INTERRUPT || mrc==SQLITE_FULL;
  61146. if( isSpecialError ){
  61147. /* If the query was read-only and the error code is SQLITE_INTERRUPT,
  61148. ** no rollback is necessary. Otherwise, at least a savepoint
  61149. ** transaction must be rolled back to restore the database to a
  61150. ** consistent state.
  61151. **
  61152. ** Even if the statement is read-only, it is important to perform
  61153. ** a statement or transaction rollback operation. If the error
  61154. ** occurred while writing to the journal, sub-journal or database
  61155. ** file as part of an effort to free up cache space (see function
  61156. ** pagerStress() in pager.c), the rollback is required to restore
  61157. ** the pager to a consistent state.
  61158. */
  61159. if( !p->readOnly || mrc!=SQLITE_INTERRUPT ){
  61160. if( (mrc==SQLITE_NOMEM || mrc==SQLITE_FULL) && p->usesStmtJournal ){
  61161. eStatementOp = SAVEPOINT_ROLLBACK;
  61162. }else{
  61163. /* We are forced to roll back the active transaction. Before doing
  61164. ** so, abort any other statements this handle currently has active.
  61165. */
  61166. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61167. sqlite3CloseSavepoints(db);
  61168. db->autoCommit = 1;
  61169. }
  61170. }
  61171. }
  61172. /* Check for immediate foreign key violations. */
  61173. if( p->rc==SQLITE_OK ){
  61174. sqlite3VdbeCheckFk(p, 0);
  61175. }
  61176. /* If the auto-commit flag is set and this is the only active writer
  61177. ** VM, then we do either a commit or rollback of the current transaction.
  61178. **
  61179. ** Note: This block also runs if one of the special errors handled
  61180. ** above has occurred.
  61181. */
  61182. if( !sqlite3VtabInSync(db)
  61183. && db->autoCommit
  61184. && db->nVdbeWrite==(p->readOnly==0)
  61185. ){
  61186. if( p->rc==SQLITE_OK || (p->errorAction==OE_Fail && !isSpecialError) ){
  61187. rc = sqlite3VdbeCheckFk(p, 1);
  61188. if( rc!=SQLITE_OK ){
  61189. if( NEVER(p->readOnly) ){
  61190. sqlite3VdbeLeave(p);
  61191. return SQLITE_ERROR;
  61192. }
  61193. rc = SQLITE_CONSTRAINT_FOREIGNKEY;
  61194. }else{
  61195. /* The auto-commit flag is true, the vdbe program was successful
  61196. ** or hit an 'OR FAIL' constraint and there are no deferred foreign
  61197. ** key constraints to hold up the transaction. This means a commit
  61198. ** is required. */
  61199. rc = vdbeCommit(db, p);
  61200. }
  61201. if( rc==SQLITE_BUSY && p->readOnly ){
  61202. sqlite3VdbeLeave(p);
  61203. return SQLITE_BUSY;
  61204. }else if( rc!=SQLITE_OK ){
  61205. p->rc = rc;
  61206. sqlite3RollbackAll(db, SQLITE_OK);
  61207. }else{
  61208. db->nDeferredCons = 0;
  61209. db->nDeferredImmCons = 0;
  61210. db->flags &= ~SQLITE_DeferFKs;
  61211. sqlite3CommitInternalChanges(db);
  61212. }
  61213. }else{
  61214. sqlite3RollbackAll(db, SQLITE_OK);
  61215. }
  61216. db->nStatement = 0;
  61217. }else if( eStatementOp==0 ){
  61218. if( p->rc==SQLITE_OK || p->errorAction==OE_Fail ){
  61219. eStatementOp = SAVEPOINT_RELEASE;
  61220. }else if( p->errorAction==OE_Abort ){
  61221. eStatementOp = SAVEPOINT_ROLLBACK;
  61222. }else{
  61223. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61224. sqlite3CloseSavepoints(db);
  61225. db->autoCommit = 1;
  61226. }
  61227. }
  61228. /* If eStatementOp is non-zero, then a statement transaction needs to
  61229. ** be committed or rolled back. Call sqlite3VdbeCloseStatement() to
  61230. ** do so. If this operation returns an error, and the current statement
  61231. ** error code is SQLITE_OK or SQLITE_CONSTRAINT, then promote the
  61232. ** current statement error code.
  61233. */
  61234. if( eStatementOp ){
  61235. rc = sqlite3VdbeCloseStatement(p, eStatementOp);
  61236. if( rc ){
  61237. if( p->rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT ){
  61238. p->rc = rc;
  61239. sqlite3DbFree(db, p->zErrMsg);
  61240. p->zErrMsg = 0;
  61241. }
  61242. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  61243. sqlite3CloseSavepoints(db);
  61244. db->autoCommit = 1;
  61245. }
  61246. }
  61247. /* If this was an INSERT, UPDATE or DELETE and no statement transaction
  61248. ** has been rolled back, update the database connection change-counter.
  61249. */
  61250. if( p->changeCntOn ){
  61251. if( eStatementOp!=SAVEPOINT_ROLLBACK ){
  61252. sqlite3VdbeSetChanges(db, p->nChange);
  61253. }else{
  61254. sqlite3VdbeSetChanges(db, 0);
  61255. }
  61256. p->nChange = 0;
  61257. }
  61258. /* Release the locks */
  61259. sqlite3VdbeLeave(p);
  61260. }
  61261. /* We have successfully halted and closed the VM. Record this fact. */
  61262. if( p->pc>=0 ){
  61263. db->nVdbeActive--;
  61264. if( !p->readOnly ) db->nVdbeWrite--;
  61265. if( p->bIsReader ) db->nVdbeRead--;
  61266. assert( db->nVdbeActive>=db->nVdbeRead );
  61267. assert( db->nVdbeRead>=db->nVdbeWrite );
  61268. assert( db->nVdbeWrite>=0 );
  61269. }
  61270. p->magic = VDBE_MAGIC_HALT;
  61271. checkActiveVdbeCnt(db);
  61272. if( p->db->mallocFailed ){
  61273. p->rc = SQLITE_NOMEM;
  61274. }
  61275. /* If the auto-commit flag is set to true, then any locks that were held
  61276. ** by connection db have now been released. Call sqlite3ConnectionUnlocked()
  61277. ** to invoke any required unlock-notify callbacks.
  61278. */
  61279. if( db->autoCommit ){
  61280. sqlite3ConnectionUnlocked(db);
  61281. }
  61282. assert( db->nVdbeActive>0 || db->autoCommit==0 || db->nStatement==0 );
  61283. return (p->rc==SQLITE_BUSY ? SQLITE_BUSY : SQLITE_OK);
  61284. }
  61285. /*
  61286. ** Each VDBE holds the result of the most recent sqlite3_step() call
  61287. ** in p->rc. This routine sets that result back to SQLITE_OK.
  61288. */
  61289. SQLITE_PRIVATE void sqlite3VdbeResetStepResult(Vdbe *p){
  61290. p->rc = SQLITE_OK;
  61291. }
  61292. /*
  61293. ** Copy the error code and error message belonging to the VDBE passed
  61294. ** as the first argument to its database handle (so that they will be
  61295. ** returned by calls to sqlite3_errcode() and sqlite3_errmsg()).
  61296. **
  61297. ** This function does not clear the VDBE error code or message, just
  61298. ** copies them to the database handle.
  61299. */
  61300. SQLITE_PRIVATE int sqlite3VdbeTransferError(Vdbe *p){
  61301. sqlite3 *db = p->db;
  61302. int rc = p->rc;
  61303. if( p->zErrMsg ){
  61304. u8 mallocFailed = db->mallocFailed;
  61305. sqlite3BeginBenignMalloc();
  61306. if( db->pErr==0 ) db->pErr = sqlite3ValueNew(db);
  61307. sqlite3ValueSetStr(db->pErr, -1, p->zErrMsg, SQLITE_UTF8, SQLITE_TRANSIENT);
  61308. sqlite3EndBenignMalloc();
  61309. db->mallocFailed = mallocFailed;
  61310. db->errCode = rc;
  61311. }else{
  61312. sqlite3Error(db, rc);
  61313. }
  61314. return rc;
  61315. }
  61316. #ifdef SQLITE_ENABLE_SQLLOG
  61317. /*
  61318. ** If an SQLITE_CONFIG_SQLLOG hook is registered and the VM has been run,
  61319. ** invoke it.
  61320. */
  61321. static void vdbeInvokeSqllog(Vdbe *v){
  61322. if( sqlite3GlobalConfig.xSqllog && v->rc==SQLITE_OK && v->zSql && v->pc>=0 ){
  61323. char *zExpanded = sqlite3VdbeExpandSql(v, v->zSql);
  61324. assert( v->db->init.busy==0 );
  61325. if( zExpanded ){
  61326. sqlite3GlobalConfig.xSqllog(
  61327. sqlite3GlobalConfig.pSqllogArg, v->db, zExpanded, 1
  61328. );
  61329. sqlite3DbFree(v->db, zExpanded);
  61330. }
  61331. }
  61332. }
  61333. #else
  61334. # define vdbeInvokeSqllog(x)
  61335. #endif
  61336. /*
  61337. ** Clean up a VDBE after execution but do not delete the VDBE just yet.
  61338. ** Write any error messages into *pzErrMsg. Return the result code.
  61339. **
  61340. ** After this routine is run, the VDBE should be ready to be executed
  61341. ** again.
  61342. **
  61343. ** To look at it another way, this routine resets the state of the
  61344. ** virtual machine from VDBE_MAGIC_RUN or VDBE_MAGIC_HALT back to
  61345. ** VDBE_MAGIC_INIT.
  61346. */
  61347. SQLITE_PRIVATE int sqlite3VdbeReset(Vdbe *p){
  61348. sqlite3 *db;
  61349. db = p->db;
  61350. /* If the VM did not run to completion or if it encountered an
  61351. ** error, then it might not have been halted properly. So halt
  61352. ** it now.
  61353. */
  61354. sqlite3VdbeHalt(p);
  61355. /* If the VDBE has be run even partially, then transfer the error code
  61356. ** and error message from the VDBE into the main database structure. But
  61357. ** if the VDBE has just been set to run but has not actually executed any
  61358. ** instructions yet, leave the main database error information unchanged.
  61359. */
  61360. if( p->pc>=0 ){
  61361. vdbeInvokeSqllog(p);
  61362. sqlite3VdbeTransferError(p);
  61363. sqlite3DbFree(db, p->zErrMsg);
  61364. p->zErrMsg = 0;
  61365. if( p->runOnlyOnce ) p->expired = 1;
  61366. }else if( p->rc && p->expired ){
  61367. /* The expired flag was set on the VDBE before the first call
  61368. ** to sqlite3_step(). For consistency (since sqlite3_step() was
  61369. ** called), set the database error in this case as well.
  61370. */
  61371. sqlite3ErrorWithMsg(db, p->rc, p->zErrMsg ? "%s" : 0, p->zErrMsg);
  61372. sqlite3DbFree(db, p->zErrMsg);
  61373. p->zErrMsg = 0;
  61374. }
  61375. /* Reclaim all memory used by the VDBE
  61376. */
  61377. Cleanup(p);
  61378. /* Save profiling information from this VDBE run.
  61379. */
  61380. #ifdef VDBE_PROFILE
  61381. {
  61382. FILE *out = fopen("vdbe_profile.out", "a");
  61383. if( out ){
  61384. int i;
  61385. fprintf(out, "---- ");
  61386. for(i=0; i<p->nOp; i++){
  61387. fprintf(out, "%02x", p->aOp[i].opcode);
  61388. }
  61389. fprintf(out, "\n");
  61390. if( p->zSql ){
  61391. char c, pc = 0;
  61392. fprintf(out, "-- ");
  61393. for(i=0; (c = p->zSql[i])!=0; i++){
  61394. if( pc=='\n' ) fprintf(out, "-- ");
  61395. putc(c, out);
  61396. pc = c;
  61397. }
  61398. if( pc!='\n' ) fprintf(out, "\n");
  61399. }
  61400. for(i=0; i<p->nOp; i++){
  61401. char zHdr[100];
  61402. sqlite3_snprintf(sizeof(zHdr), zHdr, "%6u %12llu %8llu ",
  61403. p->aOp[i].cnt,
  61404. p->aOp[i].cycles,
  61405. p->aOp[i].cnt>0 ? p->aOp[i].cycles/p->aOp[i].cnt : 0
  61406. );
  61407. fprintf(out, "%s", zHdr);
  61408. sqlite3VdbePrintOp(out, i, &p->aOp[i]);
  61409. }
  61410. fclose(out);
  61411. }
  61412. }
  61413. #endif
  61414. p->iCurrentTime = 0;
  61415. p->magic = VDBE_MAGIC_INIT;
  61416. return p->rc & db->errMask;
  61417. }
  61418. /*
  61419. ** Clean up and delete a VDBE after execution. Return an integer which is
  61420. ** the result code. Write any error message text into *pzErrMsg.
  61421. */
  61422. SQLITE_PRIVATE int sqlite3VdbeFinalize(Vdbe *p){
  61423. int rc = SQLITE_OK;
  61424. if( p->magic==VDBE_MAGIC_RUN || p->magic==VDBE_MAGIC_HALT ){
  61425. rc = sqlite3VdbeReset(p);
  61426. assert( (rc & p->db->errMask)==rc );
  61427. }
  61428. sqlite3VdbeDelete(p);
  61429. return rc;
  61430. }
  61431. /*
  61432. ** If parameter iOp is less than zero, then invoke the destructor for
  61433. ** all auxiliary data pointers currently cached by the VM passed as
  61434. ** the first argument.
  61435. **
  61436. ** Or, if iOp is greater than or equal to zero, then the destructor is
  61437. ** only invoked for those auxiliary data pointers created by the user
  61438. ** function invoked by the OP_Function opcode at instruction iOp of
  61439. ** VM pVdbe, and only then if:
  61440. **
  61441. ** * the associated function parameter is the 32nd or later (counting
  61442. ** from left to right), or
  61443. **
  61444. ** * the corresponding bit in argument mask is clear (where the first
  61445. ** function parameter corresponds to bit 0 etc.).
  61446. */
  61447. SQLITE_PRIVATE void sqlite3VdbeDeleteAuxData(Vdbe *pVdbe, int iOp, int mask){
  61448. AuxData **pp = &pVdbe->pAuxData;
  61449. while( *pp ){
  61450. AuxData *pAux = *pp;
  61451. if( (iOp<0)
  61452. || (pAux->iOp==iOp && (pAux->iArg>31 || !(mask & MASKBIT32(pAux->iArg))))
  61453. ){
  61454. testcase( pAux->iArg==31 );
  61455. if( pAux->xDelete ){
  61456. pAux->xDelete(pAux->pAux);
  61457. }
  61458. *pp = pAux->pNext;
  61459. sqlite3DbFree(pVdbe->db, pAux);
  61460. }else{
  61461. pp= &pAux->pNext;
  61462. }
  61463. }
  61464. }
  61465. /*
  61466. ** Free all memory associated with the Vdbe passed as the second argument,
  61467. ** except for object itself, which is preserved.
  61468. **
  61469. ** The difference between this function and sqlite3VdbeDelete() is that
  61470. ** VdbeDelete() also unlinks the Vdbe from the list of VMs associated with
  61471. ** the database connection and frees the object itself.
  61472. */
  61473. SQLITE_PRIVATE void sqlite3VdbeClearObject(sqlite3 *db, Vdbe *p){
  61474. SubProgram *pSub, *pNext;
  61475. int i;
  61476. assert( p->db==0 || p->db==db );
  61477. releaseMemArray(p->aVar, p->nVar);
  61478. releaseMemArray(p->aColName, p->nResColumn*COLNAME_N);
  61479. for(pSub=p->pProgram; pSub; pSub=pNext){
  61480. pNext = pSub->pNext;
  61481. vdbeFreeOpArray(db, pSub->aOp, pSub->nOp);
  61482. sqlite3DbFree(db, pSub);
  61483. }
  61484. for(i=p->nzVar-1; i>=0; i--) sqlite3DbFree(db, p->azVar[i]);
  61485. vdbeFreeOpArray(db, p->aOp, p->nOp);
  61486. sqlite3DbFree(db, p->aColName);
  61487. sqlite3DbFree(db, p->zSql);
  61488. sqlite3DbFree(db, p->pFree);
  61489. }
  61490. /*
  61491. ** Delete an entire VDBE.
  61492. */
  61493. SQLITE_PRIVATE void sqlite3VdbeDelete(Vdbe *p){
  61494. sqlite3 *db;
  61495. if( NEVER(p==0) ) return;
  61496. db = p->db;
  61497. assert( sqlite3_mutex_held(db->mutex) );
  61498. sqlite3VdbeClearObject(db, p);
  61499. if( p->pPrev ){
  61500. p->pPrev->pNext = p->pNext;
  61501. }else{
  61502. assert( db->pVdbe==p );
  61503. db->pVdbe = p->pNext;
  61504. }
  61505. if( p->pNext ){
  61506. p->pNext->pPrev = p->pPrev;
  61507. }
  61508. p->magic = VDBE_MAGIC_DEAD;
  61509. p->db = 0;
  61510. sqlite3DbFree(db, p);
  61511. }
  61512. /*
  61513. ** The cursor "p" has a pending seek operation that has not yet been
  61514. ** carried out. Seek the cursor now. If an error occurs, return
  61515. ** the appropriate error code.
  61516. */
  61517. static int SQLITE_NOINLINE handleDeferredMoveto(VdbeCursor *p){
  61518. int res, rc;
  61519. #ifdef SQLITE_TEST
  61520. extern int sqlite3_search_count;
  61521. #endif
  61522. assert( p->deferredMoveto );
  61523. assert( p->isTable );
  61524. rc = sqlite3BtreeMovetoUnpacked(p->pCursor, 0, p->movetoTarget, 0, &res);
  61525. if( rc ) return rc;
  61526. if( res!=0 ) return SQLITE_CORRUPT_BKPT;
  61527. #ifdef SQLITE_TEST
  61528. sqlite3_search_count++;
  61529. #endif
  61530. p->deferredMoveto = 0;
  61531. p->cacheStatus = CACHE_STALE;
  61532. return SQLITE_OK;
  61533. }
  61534. /*
  61535. ** Something has moved cursor "p" out of place. Maybe the row it was
  61536. ** pointed to was deleted out from under it. Or maybe the btree was
  61537. ** rebalanced. Whatever the cause, try to restore "p" to the place it
  61538. ** is supposed to be pointing. If the row was deleted out from under the
  61539. ** cursor, set the cursor to point to a NULL row.
  61540. */
  61541. static int SQLITE_NOINLINE handleMovedCursor(VdbeCursor *p){
  61542. int isDifferentRow, rc;
  61543. assert( p->pCursor!=0 );
  61544. assert( sqlite3BtreeCursorHasMoved(p->pCursor) );
  61545. rc = sqlite3BtreeCursorRestore(p->pCursor, &isDifferentRow);
  61546. p->cacheStatus = CACHE_STALE;
  61547. if( isDifferentRow ) p->nullRow = 1;
  61548. return rc;
  61549. }
  61550. /*
  61551. ** Check to ensure that the cursor is valid. Restore the cursor
  61552. ** if need be. Return any I/O error from the restore operation.
  61553. */
  61554. SQLITE_PRIVATE int sqlite3VdbeCursorRestore(VdbeCursor *p){
  61555. if( sqlite3BtreeCursorHasMoved(p->pCursor) ){
  61556. return handleMovedCursor(p);
  61557. }
  61558. return SQLITE_OK;
  61559. }
  61560. /*
  61561. ** Make sure the cursor p is ready to read or write the row to which it
  61562. ** was last positioned. Return an error code if an OOM fault or I/O error
  61563. ** prevents us from positioning the cursor to its correct position.
  61564. **
  61565. ** If a MoveTo operation is pending on the given cursor, then do that
  61566. ** MoveTo now. If no move is pending, check to see if the row has been
  61567. ** deleted out from under the cursor and if it has, mark the row as
  61568. ** a NULL row.
  61569. **
  61570. ** If the cursor is already pointing to the correct row and that row has
  61571. ** not been deleted out from under the cursor, then this routine is a no-op.
  61572. */
  61573. SQLITE_PRIVATE int sqlite3VdbeCursorMoveto(VdbeCursor *p){
  61574. if( p->deferredMoveto ){
  61575. return handleDeferredMoveto(p);
  61576. }
  61577. if( p->pCursor && sqlite3BtreeCursorHasMoved(p->pCursor) ){
  61578. return handleMovedCursor(p);
  61579. }
  61580. return SQLITE_OK;
  61581. }
  61582. /*
  61583. ** The following functions:
  61584. **
  61585. ** sqlite3VdbeSerialType()
  61586. ** sqlite3VdbeSerialTypeLen()
  61587. ** sqlite3VdbeSerialLen()
  61588. ** sqlite3VdbeSerialPut()
  61589. ** sqlite3VdbeSerialGet()
  61590. **
  61591. ** encapsulate the code that serializes values for storage in SQLite
  61592. ** data and index records. Each serialized value consists of a
  61593. ** 'serial-type' and a blob of data. The serial type is an 8-byte unsigned
  61594. ** integer, stored as a varint.
  61595. **
  61596. ** In an SQLite index record, the serial type is stored directly before
  61597. ** the blob of data that it corresponds to. In a table record, all serial
  61598. ** types are stored at the start of the record, and the blobs of data at
  61599. ** the end. Hence these functions allow the caller to handle the
  61600. ** serial-type and data blob separately.
  61601. **
  61602. ** The following table describes the various storage classes for data:
  61603. **
  61604. ** serial type bytes of data type
  61605. ** -------------- --------------- ---------------
  61606. ** 0 0 NULL
  61607. ** 1 1 signed integer
  61608. ** 2 2 signed integer
  61609. ** 3 3 signed integer
  61610. ** 4 4 signed integer
  61611. ** 5 6 signed integer
  61612. ** 6 8 signed integer
  61613. ** 7 8 IEEE float
  61614. ** 8 0 Integer constant 0
  61615. ** 9 0 Integer constant 1
  61616. ** 10,11 reserved for expansion
  61617. ** N>=12 and even (N-12)/2 BLOB
  61618. ** N>=13 and odd (N-13)/2 text
  61619. **
  61620. ** The 8 and 9 types were added in 3.3.0, file format 4. Prior versions
  61621. ** of SQLite will not understand those serial types.
  61622. */
  61623. /*
  61624. ** Return the serial-type for the value stored in pMem.
  61625. */
  61626. SQLITE_PRIVATE u32 sqlite3VdbeSerialType(Mem *pMem, int file_format){
  61627. int flags = pMem->flags;
  61628. u32 n;
  61629. if( flags&MEM_Null ){
  61630. return 0;
  61631. }
  61632. if( flags&MEM_Int ){
  61633. /* Figure out whether to use 1, 2, 4, 6 or 8 bytes. */
  61634. # define MAX_6BYTE ((((i64)0x00008000)<<32)-1)
  61635. i64 i = pMem->u.i;
  61636. u64 u;
  61637. if( i<0 ){
  61638. if( i<(-MAX_6BYTE) ) return 6;
  61639. /* Previous test prevents: u = -(-9223372036854775808) */
  61640. u = -i;
  61641. }else{
  61642. u = i;
  61643. }
  61644. if( u<=127 ){
  61645. return ((i&1)==i && file_format>=4) ? 8+(u32)u : 1;
  61646. }
  61647. if( u<=32767 ) return 2;
  61648. if( u<=8388607 ) return 3;
  61649. if( u<=2147483647 ) return 4;
  61650. if( u<=MAX_6BYTE ) return 5;
  61651. return 6;
  61652. }
  61653. if( flags&MEM_Real ){
  61654. return 7;
  61655. }
  61656. assert( pMem->db->mallocFailed || flags&(MEM_Str|MEM_Blob) );
  61657. assert( pMem->n>=0 );
  61658. n = (u32)pMem->n;
  61659. if( flags & MEM_Zero ){
  61660. n += pMem->u.nZero;
  61661. }
  61662. return ((n*2) + 12 + ((flags&MEM_Str)!=0));
  61663. }
  61664. /*
  61665. ** Return the length of the data corresponding to the supplied serial-type.
  61666. */
  61667. SQLITE_PRIVATE u32 sqlite3VdbeSerialTypeLen(u32 serial_type){
  61668. if( serial_type>=12 ){
  61669. return (serial_type-12)/2;
  61670. }else{
  61671. static const u8 aSize[] = { 0, 1, 2, 3, 4, 6, 8, 8, 0, 0, 0, 0 };
  61672. return aSize[serial_type];
  61673. }
  61674. }
  61675. /*
  61676. ** If we are on an architecture with mixed-endian floating
  61677. ** points (ex: ARM7) then swap the lower 4 bytes with the
  61678. ** upper 4 bytes. Return the result.
  61679. **
  61680. ** For most architectures, this is a no-op.
  61681. **
  61682. ** (later): It is reported to me that the mixed-endian problem
  61683. ** on ARM7 is an issue with GCC, not with the ARM7 chip. It seems
  61684. ** that early versions of GCC stored the two words of a 64-bit
  61685. ** float in the wrong order. And that error has been propagated
  61686. ** ever since. The blame is not necessarily with GCC, though.
  61687. ** GCC might have just copying the problem from a prior compiler.
  61688. ** I am also told that newer versions of GCC that follow a different
  61689. ** ABI get the byte order right.
  61690. **
  61691. ** Developers using SQLite on an ARM7 should compile and run their
  61692. ** application using -DSQLITE_DEBUG=1 at least once. With DEBUG
  61693. ** enabled, some asserts below will ensure that the byte order of
  61694. ** floating point values is correct.
  61695. **
  61696. ** (2007-08-30) Frank van Vugt has studied this problem closely
  61697. ** and has send his findings to the SQLite developers. Frank
  61698. ** writes that some Linux kernels offer floating point hardware
  61699. ** emulation that uses only 32-bit mantissas instead of a full
  61700. ** 48-bits as required by the IEEE standard. (This is the
  61701. ** CONFIG_FPE_FASTFPE option.) On such systems, floating point
  61702. ** byte swapping becomes very complicated. To avoid problems,
  61703. ** the necessary byte swapping is carried out using a 64-bit integer
  61704. ** rather than a 64-bit float. Frank assures us that the code here
  61705. ** works for him. We, the developers, have no way to independently
  61706. ** verify this, but Frank seems to know what he is talking about
  61707. ** so we trust him.
  61708. */
  61709. #ifdef SQLITE_MIXED_ENDIAN_64BIT_FLOAT
  61710. static u64 floatSwap(u64 in){
  61711. union {
  61712. u64 r;
  61713. u32 i[2];
  61714. } u;
  61715. u32 t;
  61716. u.r = in;
  61717. t = u.i[0];
  61718. u.i[0] = u.i[1];
  61719. u.i[1] = t;
  61720. return u.r;
  61721. }
  61722. # define swapMixedEndianFloat(X) X = floatSwap(X)
  61723. #else
  61724. # define swapMixedEndianFloat(X)
  61725. #endif
  61726. /*
  61727. ** Write the serialized data blob for the value stored in pMem into
  61728. ** buf. It is assumed that the caller has allocated sufficient space.
  61729. ** Return the number of bytes written.
  61730. **
  61731. ** nBuf is the amount of space left in buf[]. The caller is responsible
  61732. ** for allocating enough space to buf[] to hold the entire field, exclusive
  61733. ** of the pMem->u.nZero bytes for a MEM_Zero value.
  61734. **
  61735. ** Return the number of bytes actually written into buf[]. The number
  61736. ** of bytes in the zero-filled tail is included in the return value only
  61737. ** if those bytes were zeroed in buf[].
  61738. */
  61739. SQLITE_PRIVATE u32 sqlite3VdbeSerialPut(u8 *buf, Mem *pMem, u32 serial_type){
  61740. u32 len;
  61741. /* Integer and Real */
  61742. if( serial_type<=7 && serial_type>0 ){
  61743. u64 v;
  61744. u32 i;
  61745. if( serial_type==7 ){
  61746. assert( sizeof(v)==sizeof(pMem->u.r) );
  61747. memcpy(&v, &pMem->u.r, sizeof(v));
  61748. swapMixedEndianFloat(v);
  61749. }else{
  61750. v = pMem->u.i;
  61751. }
  61752. len = i = sqlite3VdbeSerialTypeLen(serial_type);
  61753. assert( i>0 );
  61754. do{
  61755. buf[--i] = (u8)(v&0xFF);
  61756. v >>= 8;
  61757. }while( i );
  61758. return len;
  61759. }
  61760. /* String or blob */
  61761. if( serial_type>=12 ){
  61762. assert( pMem->n + ((pMem->flags & MEM_Zero)?pMem->u.nZero:0)
  61763. == (int)sqlite3VdbeSerialTypeLen(serial_type) );
  61764. len = pMem->n;
  61765. memcpy(buf, pMem->z, len);
  61766. return len;
  61767. }
  61768. /* NULL or constants 0 or 1 */
  61769. return 0;
  61770. }
  61771. /* Input "x" is a sequence of unsigned characters that represent a
  61772. ** big-endian integer. Return the equivalent native integer
  61773. */
  61774. #define ONE_BYTE_INT(x) ((i8)(x)[0])
  61775. #define TWO_BYTE_INT(x) (256*(i8)((x)[0])|(x)[1])
  61776. #define THREE_BYTE_INT(x) (65536*(i8)((x)[0])|((x)[1]<<8)|(x)[2])
  61777. #define FOUR_BYTE_UINT(x) (((u32)(x)[0]<<24)|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  61778. #define FOUR_BYTE_INT(x) (16777216*(i8)((x)[0])|((x)[1]<<16)|((x)[2]<<8)|(x)[3])
  61779. /*
  61780. ** Deserialize the data blob pointed to by buf as serial type serial_type
  61781. ** and store the result in pMem. Return the number of bytes read.
  61782. **
  61783. ** This function is implemented as two separate routines for performance.
  61784. ** The few cases that require local variables are broken out into a separate
  61785. ** routine so that in most cases the overhead of moving the stack pointer
  61786. ** is avoided.
  61787. */
  61788. static u32 SQLITE_NOINLINE serialGet(
  61789. const unsigned char *buf, /* Buffer to deserialize from */
  61790. u32 serial_type, /* Serial type to deserialize */
  61791. Mem *pMem /* Memory cell to write value into */
  61792. ){
  61793. u64 x = FOUR_BYTE_UINT(buf);
  61794. u32 y = FOUR_BYTE_UINT(buf+4);
  61795. x = (x<<32) + y;
  61796. if( serial_type==6 ){
  61797. pMem->u.i = *(i64*)&x;
  61798. pMem->flags = MEM_Int;
  61799. testcase( pMem->u.i<0 );
  61800. }else{
  61801. #if !defined(NDEBUG) && !defined(SQLITE_OMIT_FLOATING_POINT)
  61802. /* Verify that integers and floating point values use the same
  61803. ** byte order. Or, that if SQLITE_MIXED_ENDIAN_64BIT_FLOAT is
  61804. ** defined that 64-bit floating point values really are mixed
  61805. ** endian.
  61806. */
  61807. static const u64 t1 = ((u64)0x3ff00000)<<32;
  61808. static const double r1 = 1.0;
  61809. u64 t2 = t1;
  61810. swapMixedEndianFloat(t2);
  61811. assert( sizeof(r1)==sizeof(t2) && memcmp(&r1, &t2, sizeof(r1))==0 );
  61812. #endif
  61813. assert( sizeof(x)==8 && sizeof(pMem->u.r)==8 );
  61814. swapMixedEndianFloat(x);
  61815. memcpy(&pMem->u.r, &x, sizeof(x));
  61816. pMem->flags = sqlite3IsNaN(pMem->u.r) ? MEM_Null : MEM_Real;
  61817. }
  61818. return 8;
  61819. }
  61820. SQLITE_PRIVATE u32 sqlite3VdbeSerialGet(
  61821. const unsigned char *buf, /* Buffer to deserialize from */
  61822. u32 serial_type, /* Serial type to deserialize */
  61823. Mem *pMem /* Memory cell to write value into */
  61824. ){
  61825. switch( serial_type ){
  61826. case 10: /* Reserved for future use */
  61827. case 11: /* Reserved for future use */
  61828. case 0: { /* NULL */
  61829. pMem->flags = MEM_Null;
  61830. break;
  61831. }
  61832. case 1: { /* 1-byte signed integer */
  61833. pMem->u.i = ONE_BYTE_INT(buf);
  61834. pMem->flags = MEM_Int;
  61835. testcase( pMem->u.i<0 );
  61836. return 1;
  61837. }
  61838. case 2: { /* 2-byte signed integer */
  61839. pMem->u.i = TWO_BYTE_INT(buf);
  61840. pMem->flags = MEM_Int;
  61841. testcase( pMem->u.i<0 );
  61842. return 2;
  61843. }
  61844. case 3: { /* 3-byte signed integer */
  61845. pMem->u.i = THREE_BYTE_INT(buf);
  61846. pMem->flags = MEM_Int;
  61847. testcase( pMem->u.i<0 );
  61848. return 3;
  61849. }
  61850. case 4: { /* 4-byte signed integer */
  61851. pMem->u.i = FOUR_BYTE_INT(buf);
  61852. pMem->flags = MEM_Int;
  61853. testcase( pMem->u.i<0 );
  61854. return 4;
  61855. }
  61856. case 5: { /* 6-byte signed integer */
  61857. pMem->u.i = FOUR_BYTE_UINT(buf+2) + (((i64)1)<<32)*TWO_BYTE_INT(buf);
  61858. pMem->flags = MEM_Int;
  61859. testcase( pMem->u.i<0 );
  61860. return 6;
  61861. }
  61862. case 6: /* 8-byte signed integer */
  61863. case 7: { /* IEEE floating point */
  61864. /* These use local variables, so do them in a separate routine
  61865. ** to avoid having to move the frame pointer in the common case */
  61866. return serialGet(buf,serial_type,pMem);
  61867. }
  61868. case 8: /* Integer 0 */
  61869. case 9: { /* Integer 1 */
  61870. pMem->u.i = serial_type-8;
  61871. pMem->flags = MEM_Int;
  61872. return 0;
  61873. }
  61874. default: {
  61875. static const u16 aFlag[] = { MEM_Blob|MEM_Ephem, MEM_Str|MEM_Ephem };
  61876. pMem->z = (char *)buf;
  61877. pMem->n = (serial_type-12)/2;
  61878. pMem->flags = aFlag[serial_type&1];
  61879. return pMem->n;
  61880. }
  61881. }
  61882. return 0;
  61883. }
  61884. /*
  61885. ** This routine is used to allocate sufficient space for an UnpackedRecord
  61886. ** structure large enough to be used with sqlite3VdbeRecordUnpack() if
  61887. ** the first argument is a pointer to KeyInfo structure pKeyInfo.
  61888. **
  61889. ** The space is either allocated using sqlite3DbMallocRaw() or from within
  61890. ** the unaligned buffer passed via the second and third arguments (presumably
  61891. ** stack space). If the former, then *ppFree is set to a pointer that should
  61892. ** be eventually freed by the caller using sqlite3DbFree(). Or, if the
  61893. ** allocation comes from the pSpace/szSpace buffer, *ppFree is set to NULL
  61894. ** before returning.
  61895. **
  61896. ** If an OOM error occurs, NULL is returned.
  61897. */
  61898. SQLITE_PRIVATE UnpackedRecord *sqlite3VdbeAllocUnpackedRecord(
  61899. KeyInfo *pKeyInfo, /* Description of the record */
  61900. char *pSpace, /* Unaligned space available */
  61901. int szSpace, /* Size of pSpace[] in bytes */
  61902. char **ppFree /* OUT: Caller should free this pointer */
  61903. ){
  61904. UnpackedRecord *p; /* Unpacked record to return */
  61905. int nOff; /* Increment pSpace by nOff to align it */
  61906. int nByte; /* Number of bytes required for *p */
  61907. /* We want to shift the pointer pSpace up such that it is 8-byte aligned.
  61908. ** Thus, we need to calculate a value, nOff, between 0 and 7, to shift
  61909. ** it by. If pSpace is already 8-byte aligned, nOff should be zero.
  61910. */
  61911. nOff = (8 - (SQLITE_PTR_TO_INT(pSpace) & 7)) & 7;
  61912. nByte = ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*(pKeyInfo->nField+1);
  61913. if( nByte>szSpace+nOff ){
  61914. p = (UnpackedRecord *)sqlite3DbMallocRaw(pKeyInfo->db, nByte);
  61915. *ppFree = (char *)p;
  61916. if( !p ) return 0;
  61917. }else{
  61918. p = (UnpackedRecord*)&pSpace[nOff];
  61919. *ppFree = 0;
  61920. }
  61921. p->aMem = (Mem*)&((char*)p)[ROUND8(sizeof(UnpackedRecord))];
  61922. assert( pKeyInfo->aSortOrder!=0 );
  61923. p->pKeyInfo = pKeyInfo;
  61924. p->nField = pKeyInfo->nField + 1;
  61925. return p;
  61926. }
  61927. /*
  61928. ** Given the nKey-byte encoding of a record in pKey[], populate the
  61929. ** UnpackedRecord structure indicated by the fourth argument with the
  61930. ** contents of the decoded record.
  61931. */
  61932. SQLITE_PRIVATE void sqlite3VdbeRecordUnpack(
  61933. KeyInfo *pKeyInfo, /* Information about the record format */
  61934. int nKey, /* Size of the binary record */
  61935. const void *pKey, /* The binary record */
  61936. UnpackedRecord *p /* Populate this structure before returning. */
  61937. ){
  61938. const unsigned char *aKey = (const unsigned char *)pKey;
  61939. int d;
  61940. u32 idx; /* Offset in aKey[] to read from */
  61941. u16 u; /* Unsigned loop counter */
  61942. u32 szHdr;
  61943. Mem *pMem = p->aMem;
  61944. p->default_rc = 0;
  61945. assert( EIGHT_BYTE_ALIGNMENT(pMem) );
  61946. idx = getVarint32(aKey, szHdr);
  61947. d = szHdr;
  61948. u = 0;
  61949. while( idx<szHdr && d<=nKey ){
  61950. u32 serial_type;
  61951. idx += getVarint32(&aKey[idx], serial_type);
  61952. pMem->enc = pKeyInfo->enc;
  61953. pMem->db = pKeyInfo->db;
  61954. /* pMem->flags = 0; // sqlite3VdbeSerialGet() will set this for us */
  61955. pMem->szMalloc = 0;
  61956. d += sqlite3VdbeSerialGet(&aKey[d], serial_type, pMem);
  61957. pMem++;
  61958. if( (++u)>=p->nField ) break;
  61959. }
  61960. assert( u<=pKeyInfo->nField + 1 );
  61961. p->nField = u;
  61962. }
  61963. #if SQLITE_DEBUG
  61964. /*
  61965. ** This function compares two index or table record keys in the same way
  61966. ** as the sqlite3VdbeRecordCompare() routine. Unlike VdbeRecordCompare(),
  61967. ** this function deserializes and compares values using the
  61968. ** sqlite3VdbeSerialGet() and sqlite3MemCompare() functions. It is used
  61969. ** in assert() statements to ensure that the optimized code in
  61970. ** sqlite3VdbeRecordCompare() returns results with these two primitives.
  61971. **
  61972. ** Return true if the result of comparison is equivalent to desiredResult.
  61973. ** Return false if there is a disagreement.
  61974. */
  61975. static int vdbeRecordCompareDebug(
  61976. int nKey1, const void *pKey1, /* Left key */
  61977. const UnpackedRecord *pPKey2, /* Right key */
  61978. int desiredResult /* Correct answer */
  61979. ){
  61980. u32 d1; /* Offset into aKey[] of next data element */
  61981. u32 idx1; /* Offset into aKey[] of next header element */
  61982. u32 szHdr1; /* Number of bytes in header */
  61983. int i = 0;
  61984. int rc = 0;
  61985. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  61986. KeyInfo *pKeyInfo;
  61987. Mem mem1;
  61988. pKeyInfo = pPKey2->pKeyInfo;
  61989. if( pKeyInfo->db==0 ) return 1;
  61990. mem1.enc = pKeyInfo->enc;
  61991. mem1.db = pKeyInfo->db;
  61992. /* mem1.flags = 0; // Will be initialized by sqlite3VdbeSerialGet() */
  61993. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  61994. /* Compilers may complain that mem1.u.i is potentially uninitialized.
  61995. ** We could initialize it, as shown here, to silence those complaints.
  61996. ** But in fact, mem1.u.i will never actually be used uninitialized, and doing
  61997. ** the unnecessary initialization has a measurable negative performance
  61998. ** impact, since this routine is a very high runner. And so, we choose
  61999. ** to ignore the compiler warnings and leave this variable uninitialized.
  62000. */
  62001. /* mem1.u.i = 0; // not needed, here to silence compiler warning */
  62002. idx1 = getVarint32(aKey1, szHdr1);
  62003. d1 = szHdr1;
  62004. assert( pKeyInfo->nField+pKeyInfo->nXField>=pPKey2->nField || CORRUPT_DB );
  62005. assert( pKeyInfo->aSortOrder!=0 );
  62006. assert( pKeyInfo->nField>0 );
  62007. assert( idx1<=szHdr1 || CORRUPT_DB );
  62008. do{
  62009. u32 serial_type1;
  62010. /* Read the serial types for the next element in each key. */
  62011. idx1 += getVarint32( aKey1+idx1, serial_type1 );
  62012. /* Verify that there is enough key space remaining to avoid
  62013. ** a buffer overread. The "d1+serial_type1+2" subexpression will
  62014. ** always be greater than or equal to the amount of required key space.
  62015. ** Use that approximation to avoid the more expensive call to
  62016. ** sqlite3VdbeSerialTypeLen() in the common case.
  62017. */
  62018. if( d1+serial_type1+2>(u32)nKey1
  62019. && d1+sqlite3VdbeSerialTypeLen(serial_type1)>(u32)nKey1
  62020. ){
  62021. break;
  62022. }
  62023. /* Extract the values to be compared.
  62024. */
  62025. d1 += sqlite3VdbeSerialGet(&aKey1[d1], serial_type1, &mem1);
  62026. /* Do the comparison
  62027. */
  62028. rc = sqlite3MemCompare(&mem1, &pPKey2->aMem[i], pKeyInfo->aColl[i]);
  62029. if( rc!=0 ){
  62030. assert( mem1.szMalloc==0 ); /* See comment below */
  62031. if( pKeyInfo->aSortOrder[i] ){
  62032. rc = -rc; /* Invert the result for DESC sort order. */
  62033. }
  62034. goto debugCompareEnd;
  62035. }
  62036. i++;
  62037. }while( idx1<szHdr1 && i<pPKey2->nField );
  62038. /* No memory allocation is ever used on mem1. Prove this using
  62039. ** the following assert(). If the assert() fails, it indicates a
  62040. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1).
  62041. */
  62042. assert( mem1.szMalloc==0 );
  62043. /* rc==0 here means that one of the keys ran out of fields and
  62044. ** all the fields up to that point were equal. Return the default_rc
  62045. ** value. */
  62046. rc = pPKey2->default_rc;
  62047. debugCompareEnd:
  62048. if( desiredResult==0 && rc==0 ) return 1;
  62049. if( desiredResult<0 && rc<0 ) return 1;
  62050. if( desiredResult>0 && rc>0 ) return 1;
  62051. if( CORRUPT_DB ) return 1;
  62052. if( pKeyInfo->db->mallocFailed ) return 1;
  62053. return 0;
  62054. }
  62055. #endif
  62056. /*
  62057. ** Both *pMem1 and *pMem2 contain string values. Compare the two values
  62058. ** using the collation sequence pColl. As usual, return a negative , zero
  62059. ** or positive value if *pMem1 is less than, equal to or greater than
  62060. ** *pMem2, respectively. Similar in spirit to "rc = (*pMem1) - (*pMem2);".
  62061. */
  62062. static int vdbeCompareMemString(
  62063. const Mem *pMem1,
  62064. const Mem *pMem2,
  62065. const CollSeq *pColl,
  62066. u8 *prcErr /* If an OOM occurs, set to SQLITE_NOMEM */
  62067. ){
  62068. if( pMem1->enc==pColl->enc ){
  62069. /* The strings are already in the correct encoding. Call the
  62070. ** comparison function directly */
  62071. return pColl->xCmp(pColl->pUser,pMem1->n,pMem1->z,pMem2->n,pMem2->z);
  62072. }else{
  62073. int rc;
  62074. const void *v1, *v2;
  62075. int n1, n2;
  62076. Mem c1;
  62077. Mem c2;
  62078. sqlite3VdbeMemInit(&c1, pMem1->db, MEM_Null);
  62079. sqlite3VdbeMemInit(&c2, pMem1->db, MEM_Null);
  62080. sqlite3VdbeMemShallowCopy(&c1, pMem1, MEM_Ephem);
  62081. sqlite3VdbeMemShallowCopy(&c2, pMem2, MEM_Ephem);
  62082. v1 = sqlite3ValueText((sqlite3_value*)&c1, pColl->enc);
  62083. n1 = v1==0 ? 0 : c1.n;
  62084. v2 = sqlite3ValueText((sqlite3_value*)&c2, pColl->enc);
  62085. n2 = v2==0 ? 0 : c2.n;
  62086. rc = pColl->xCmp(pColl->pUser, n1, v1, n2, v2);
  62087. sqlite3VdbeMemRelease(&c1);
  62088. sqlite3VdbeMemRelease(&c2);
  62089. if( (v1==0 || v2==0) && prcErr ) *prcErr = SQLITE_NOMEM;
  62090. return rc;
  62091. }
  62092. }
  62093. /*
  62094. ** Compare two blobs. Return negative, zero, or positive if the first
  62095. ** is less than, equal to, or greater than the second, respectively.
  62096. ** If one blob is a prefix of the other, then the shorter is the lessor.
  62097. */
  62098. static SQLITE_NOINLINE int sqlite3BlobCompare(const Mem *pB1, const Mem *pB2){
  62099. int c = memcmp(pB1->z, pB2->z, pB1->n>pB2->n ? pB2->n : pB1->n);
  62100. if( c ) return c;
  62101. return pB1->n - pB2->n;
  62102. }
  62103. /*
  62104. ** Compare the values contained by the two memory cells, returning
  62105. ** negative, zero or positive if pMem1 is less than, equal to, or greater
  62106. ** than pMem2. Sorting order is NULL's first, followed by numbers (integers
  62107. ** and reals) sorted numerically, followed by text ordered by the collating
  62108. ** sequence pColl and finally blob's ordered by memcmp().
  62109. **
  62110. ** Two NULL values are considered equal by this function.
  62111. */
  62112. SQLITE_PRIVATE int sqlite3MemCompare(const Mem *pMem1, const Mem *pMem2, const CollSeq *pColl){
  62113. int f1, f2;
  62114. int combined_flags;
  62115. f1 = pMem1->flags;
  62116. f2 = pMem2->flags;
  62117. combined_flags = f1|f2;
  62118. assert( (combined_flags & MEM_RowSet)==0 );
  62119. /* If one value is NULL, it is less than the other. If both values
  62120. ** are NULL, return 0.
  62121. */
  62122. if( combined_flags&MEM_Null ){
  62123. return (f2&MEM_Null) - (f1&MEM_Null);
  62124. }
  62125. /* If one value is a number and the other is not, the number is less.
  62126. ** If both are numbers, compare as reals if one is a real, or as integers
  62127. ** if both values are integers.
  62128. */
  62129. if( combined_flags&(MEM_Int|MEM_Real) ){
  62130. double r1, r2;
  62131. if( (f1 & f2 & MEM_Int)!=0 ){
  62132. if( pMem1->u.i < pMem2->u.i ) return -1;
  62133. if( pMem1->u.i > pMem2->u.i ) return 1;
  62134. return 0;
  62135. }
  62136. if( (f1&MEM_Real)!=0 ){
  62137. r1 = pMem1->u.r;
  62138. }else if( (f1&MEM_Int)!=0 ){
  62139. r1 = (double)pMem1->u.i;
  62140. }else{
  62141. return 1;
  62142. }
  62143. if( (f2&MEM_Real)!=0 ){
  62144. r2 = pMem2->u.r;
  62145. }else if( (f2&MEM_Int)!=0 ){
  62146. r2 = (double)pMem2->u.i;
  62147. }else{
  62148. return -1;
  62149. }
  62150. if( r1<r2 ) return -1;
  62151. if( r1>r2 ) return 1;
  62152. return 0;
  62153. }
  62154. /* If one value is a string and the other is a blob, the string is less.
  62155. ** If both are strings, compare using the collating functions.
  62156. */
  62157. if( combined_flags&MEM_Str ){
  62158. if( (f1 & MEM_Str)==0 ){
  62159. return 1;
  62160. }
  62161. if( (f2 & MEM_Str)==0 ){
  62162. return -1;
  62163. }
  62164. assert( pMem1->enc==pMem2->enc );
  62165. assert( pMem1->enc==SQLITE_UTF8 ||
  62166. pMem1->enc==SQLITE_UTF16LE || pMem1->enc==SQLITE_UTF16BE );
  62167. /* The collation sequence must be defined at this point, even if
  62168. ** the user deletes the collation sequence after the vdbe program is
  62169. ** compiled (this was not always the case).
  62170. */
  62171. assert( !pColl || pColl->xCmp );
  62172. if( pColl ){
  62173. return vdbeCompareMemString(pMem1, pMem2, pColl, 0);
  62174. }
  62175. /* If a NULL pointer was passed as the collate function, fall through
  62176. ** to the blob case and use memcmp(). */
  62177. }
  62178. /* Both values must be blobs. Compare using memcmp(). */
  62179. return sqlite3BlobCompare(pMem1, pMem2);
  62180. }
  62181. /*
  62182. ** The first argument passed to this function is a serial-type that
  62183. ** corresponds to an integer - all values between 1 and 9 inclusive
  62184. ** except 7. The second points to a buffer containing an integer value
  62185. ** serialized according to serial_type. This function deserializes
  62186. ** and returns the value.
  62187. */
  62188. static i64 vdbeRecordDecodeInt(u32 serial_type, const u8 *aKey){
  62189. u32 y;
  62190. assert( CORRUPT_DB || (serial_type>=1 && serial_type<=9 && serial_type!=7) );
  62191. switch( serial_type ){
  62192. case 0:
  62193. case 1:
  62194. testcase( aKey[0]&0x80 );
  62195. return ONE_BYTE_INT(aKey);
  62196. case 2:
  62197. testcase( aKey[0]&0x80 );
  62198. return TWO_BYTE_INT(aKey);
  62199. case 3:
  62200. testcase( aKey[0]&0x80 );
  62201. return THREE_BYTE_INT(aKey);
  62202. case 4: {
  62203. testcase( aKey[0]&0x80 );
  62204. y = FOUR_BYTE_UINT(aKey);
  62205. return (i64)*(int*)&y;
  62206. }
  62207. case 5: {
  62208. testcase( aKey[0]&0x80 );
  62209. return FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  62210. }
  62211. case 6: {
  62212. u64 x = FOUR_BYTE_UINT(aKey);
  62213. testcase( aKey[0]&0x80 );
  62214. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  62215. return (i64)*(i64*)&x;
  62216. }
  62217. }
  62218. return (serial_type - 8);
  62219. }
  62220. /*
  62221. ** This function compares the two table rows or index records
  62222. ** specified by {nKey1, pKey1} and pPKey2. It returns a negative, zero
  62223. ** or positive integer if key1 is less than, equal to or
  62224. ** greater than key2. The {nKey1, pKey1} key must be a blob
  62225. ** created by the OP_MakeRecord opcode of the VDBE. The pPKey2
  62226. ** key must be a parsed key such as obtained from
  62227. ** sqlite3VdbeParseRecord.
  62228. **
  62229. ** If argument bSkip is non-zero, it is assumed that the caller has already
  62230. ** determined that the first fields of the keys are equal.
  62231. **
  62232. ** Key1 and Key2 do not have to contain the same number of fields. If all
  62233. ** fields that appear in both keys are equal, then pPKey2->default_rc is
  62234. ** returned.
  62235. **
  62236. ** If database corruption is discovered, set pPKey2->errCode to
  62237. ** SQLITE_CORRUPT and return 0. If an OOM error is encountered,
  62238. ** pPKey2->errCode is set to SQLITE_NOMEM and, if it is not NULL, the
  62239. ** malloc-failed flag set on database handle (pPKey2->pKeyInfo->db).
  62240. */
  62241. static int vdbeRecordCompareWithSkip(
  62242. int nKey1, const void *pKey1, /* Left key */
  62243. UnpackedRecord *pPKey2, /* Right key */
  62244. int bSkip /* If true, skip the first field */
  62245. ){
  62246. u32 d1; /* Offset into aKey[] of next data element */
  62247. int i; /* Index of next field to compare */
  62248. u32 szHdr1; /* Size of record header in bytes */
  62249. u32 idx1; /* Offset of first type in header */
  62250. int rc = 0; /* Return value */
  62251. Mem *pRhs = pPKey2->aMem; /* Next field of pPKey2 to compare */
  62252. KeyInfo *pKeyInfo = pPKey2->pKeyInfo;
  62253. const unsigned char *aKey1 = (const unsigned char *)pKey1;
  62254. Mem mem1;
  62255. /* If bSkip is true, then the caller has already determined that the first
  62256. ** two elements in the keys are equal. Fix the various stack variables so
  62257. ** that this routine begins comparing at the second field. */
  62258. if( bSkip ){
  62259. u32 s1;
  62260. idx1 = 1 + getVarint32(&aKey1[1], s1);
  62261. szHdr1 = aKey1[0];
  62262. d1 = szHdr1 + sqlite3VdbeSerialTypeLen(s1);
  62263. i = 1;
  62264. pRhs++;
  62265. }else{
  62266. idx1 = getVarint32(aKey1, szHdr1);
  62267. d1 = szHdr1;
  62268. if( d1>(unsigned)nKey1 ){
  62269. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  62270. return 0; /* Corruption */
  62271. }
  62272. i = 0;
  62273. }
  62274. VVA_ONLY( mem1.szMalloc = 0; ) /* Only needed by assert() statements */
  62275. assert( pPKey2->pKeyInfo->nField+pPKey2->pKeyInfo->nXField>=pPKey2->nField
  62276. || CORRUPT_DB );
  62277. assert( pPKey2->pKeyInfo->aSortOrder!=0 );
  62278. assert( pPKey2->pKeyInfo->nField>0 );
  62279. assert( idx1<=szHdr1 || CORRUPT_DB );
  62280. do{
  62281. u32 serial_type;
  62282. /* RHS is an integer */
  62283. if( pRhs->flags & MEM_Int ){
  62284. serial_type = aKey1[idx1];
  62285. testcase( serial_type==12 );
  62286. if( serial_type>=12 ){
  62287. rc = +1;
  62288. }else if( serial_type==0 ){
  62289. rc = -1;
  62290. }else if( serial_type==7 ){
  62291. double rhs = (double)pRhs->u.i;
  62292. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  62293. if( mem1.u.r<rhs ){
  62294. rc = -1;
  62295. }else if( mem1.u.r>rhs ){
  62296. rc = +1;
  62297. }
  62298. }else{
  62299. i64 lhs = vdbeRecordDecodeInt(serial_type, &aKey1[d1]);
  62300. i64 rhs = pRhs->u.i;
  62301. if( lhs<rhs ){
  62302. rc = -1;
  62303. }else if( lhs>rhs ){
  62304. rc = +1;
  62305. }
  62306. }
  62307. }
  62308. /* RHS is real */
  62309. else if( pRhs->flags & MEM_Real ){
  62310. serial_type = aKey1[idx1];
  62311. if( serial_type>=12 ){
  62312. rc = +1;
  62313. }else if( serial_type==0 ){
  62314. rc = -1;
  62315. }else{
  62316. double rhs = pRhs->u.r;
  62317. double lhs;
  62318. sqlite3VdbeSerialGet(&aKey1[d1], serial_type, &mem1);
  62319. if( serial_type==7 ){
  62320. lhs = mem1.u.r;
  62321. }else{
  62322. lhs = (double)mem1.u.i;
  62323. }
  62324. if( lhs<rhs ){
  62325. rc = -1;
  62326. }else if( lhs>rhs ){
  62327. rc = +1;
  62328. }
  62329. }
  62330. }
  62331. /* RHS is a string */
  62332. else if( pRhs->flags & MEM_Str ){
  62333. getVarint32(&aKey1[idx1], serial_type);
  62334. testcase( serial_type==12 );
  62335. if( serial_type<12 ){
  62336. rc = -1;
  62337. }else if( !(serial_type & 0x01) ){
  62338. rc = +1;
  62339. }else{
  62340. mem1.n = (serial_type - 12) / 2;
  62341. testcase( (d1+mem1.n)==(unsigned)nKey1 );
  62342. testcase( (d1+mem1.n+1)==(unsigned)nKey1 );
  62343. if( (d1+mem1.n) > (unsigned)nKey1 ){
  62344. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  62345. return 0; /* Corruption */
  62346. }else if( pKeyInfo->aColl[i] ){
  62347. mem1.enc = pKeyInfo->enc;
  62348. mem1.db = pKeyInfo->db;
  62349. mem1.flags = MEM_Str;
  62350. mem1.z = (char*)&aKey1[d1];
  62351. rc = vdbeCompareMemString(
  62352. &mem1, pRhs, pKeyInfo->aColl[i], &pPKey2->errCode
  62353. );
  62354. }else{
  62355. int nCmp = MIN(mem1.n, pRhs->n);
  62356. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  62357. if( rc==0 ) rc = mem1.n - pRhs->n;
  62358. }
  62359. }
  62360. }
  62361. /* RHS is a blob */
  62362. else if( pRhs->flags & MEM_Blob ){
  62363. getVarint32(&aKey1[idx1], serial_type);
  62364. testcase( serial_type==12 );
  62365. if( serial_type<12 || (serial_type & 0x01) ){
  62366. rc = -1;
  62367. }else{
  62368. int nStr = (serial_type - 12) / 2;
  62369. testcase( (d1+nStr)==(unsigned)nKey1 );
  62370. testcase( (d1+nStr+1)==(unsigned)nKey1 );
  62371. if( (d1+nStr) > (unsigned)nKey1 ){
  62372. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  62373. return 0; /* Corruption */
  62374. }else{
  62375. int nCmp = MIN(nStr, pRhs->n);
  62376. rc = memcmp(&aKey1[d1], pRhs->z, nCmp);
  62377. if( rc==0 ) rc = nStr - pRhs->n;
  62378. }
  62379. }
  62380. }
  62381. /* RHS is null */
  62382. else{
  62383. serial_type = aKey1[idx1];
  62384. rc = (serial_type!=0);
  62385. }
  62386. if( rc!=0 ){
  62387. if( pKeyInfo->aSortOrder[i] ){
  62388. rc = -rc;
  62389. }
  62390. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, rc) );
  62391. assert( mem1.szMalloc==0 ); /* See comment below */
  62392. return rc;
  62393. }
  62394. i++;
  62395. pRhs++;
  62396. d1 += sqlite3VdbeSerialTypeLen(serial_type);
  62397. idx1 += sqlite3VarintLen(serial_type);
  62398. }while( idx1<(unsigned)szHdr1 && i<pPKey2->nField && d1<=(unsigned)nKey1 );
  62399. /* No memory allocation is ever used on mem1. Prove this using
  62400. ** the following assert(). If the assert() fails, it indicates a
  62401. ** memory leak and a need to call sqlite3VdbeMemRelease(&mem1). */
  62402. assert( mem1.szMalloc==0 );
  62403. /* rc==0 here means that one or both of the keys ran out of fields and
  62404. ** all the fields up to that point were equal. Return the default_rc
  62405. ** value. */
  62406. assert( CORRUPT_DB
  62407. || vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, pPKey2->default_rc)
  62408. || pKeyInfo->db->mallocFailed
  62409. );
  62410. return pPKey2->default_rc;
  62411. }
  62412. SQLITE_PRIVATE int sqlite3VdbeRecordCompare(
  62413. int nKey1, const void *pKey1, /* Left key */
  62414. UnpackedRecord *pPKey2 /* Right key */
  62415. ){
  62416. return vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 0);
  62417. }
  62418. /*
  62419. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  62420. ** that (a) the first field of pPKey2 is an integer, and (b) the
  62421. ** size-of-header varint at the start of (pKey1/nKey1) fits in a single
  62422. ** byte (i.e. is less than 128).
  62423. **
  62424. ** To avoid concerns about buffer overreads, this routine is only used
  62425. ** on schemas where the maximum valid header size is 63 bytes or less.
  62426. */
  62427. static int vdbeRecordCompareInt(
  62428. int nKey1, const void *pKey1, /* Left key */
  62429. UnpackedRecord *pPKey2 /* Right key */
  62430. ){
  62431. const u8 *aKey = &((const u8*)pKey1)[*(const u8*)pKey1 & 0x3F];
  62432. int serial_type = ((const u8*)pKey1)[1];
  62433. int res;
  62434. u32 y;
  62435. u64 x;
  62436. i64 v = pPKey2->aMem[0].u.i;
  62437. i64 lhs;
  62438. assert( (*(u8*)pKey1)<=0x3F || CORRUPT_DB );
  62439. switch( serial_type ){
  62440. case 1: { /* 1-byte signed integer */
  62441. lhs = ONE_BYTE_INT(aKey);
  62442. testcase( lhs<0 );
  62443. break;
  62444. }
  62445. case 2: { /* 2-byte signed integer */
  62446. lhs = TWO_BYTE_INT(aKey);
  62447. testcase( lhs<0 );
  62448. break;
  62449. }
  62450. case 3: { /* 3-byte signed integer */
  62451. lhs = THREE_BYTE_INT(aKey);
  62452. testcase( lhs<0 );
  62453. break;
  62454. }
  62455. case 4: { /* 4-byte signed integer */
  62456. y = FOUR_BYTE_UINT(aKey);
  62457. lhs = (i64)*(int*)&y;
  62458. testcase( lhs<0 );
  62459. break;
  62460. }
  62461. case 5: { /* 6-byte signed integer */
  62462. lhs = FOUR_BYTE_UINT(aKey+2) + (((i64)1)<<32)*TWO_BYTE_INT(aKey);
  62463. testcase( lhs<0 );
  62464. break;
  62465. }
  62466. case 6: { /* 8-byte signed integer */
  62467. x = FOUR_BYTE_UINT(aKey);
  62468. x = (x<<32) | FOUR_BYTE_UINT(aKey+4);
  62469. lhs = *(i64*)&x;
  62470. testcase( lhs<0 );
  62471. break;
  62472. }
  62473. case 8:
  62474. lhs = 0;
  62475. break;
  62476. case 9:
  62477. lhs = 1;
  62478. break;
  62479. /* This case could be removed without changing the results of running
  62480. ** this code. Including it causes gcc to generate a faster switch
  62481. ** statement (since the range of switch targets now starts at zero and
  62482. ** is contiguous) but does not cause any duplicate code to be generated
  62483. ** (as gcc is clever enough to combine the two like cases). Other
  62484. ** compilers might be similar. */
  62485. case 0: case 7:
  62486. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  62487. default:
  62488. return sqlite3VdbeRecordCompare(nKey1, pKey1, pPKey2);
  62489. }
  62490. if( v>lhs ){
  62491. res = pPKey2->r1;
  62492. }else if( v<lhs ){
  62493. res = pPKey2->r2;
  62494. }else if( pPKey2->nField>1 ){
  62495. /* The first fields of the two keys are equal. Compare the trailing
  62496. ** fields. */
  62497. res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  62498. }else{
  62499. /* The first fields of the two keys are equal and there are no trailing
  62500. ** fields. Return pPKey2->default_rc in this case. */
  62501. res = pPKey2->default_rc;
  62502. }
  62503. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res) );
  62504. return res;
  62505. }
  62506. /*
  62507. ** This function is an optimized version of sqlite3VdbeRecordCompare()
  62508. ** that (a) the first field of pPKey2 is a string, that (b) the first field
  62509. ** uses the collation sequence BINARY and (c) that the size-of-header varint
  62510. ** at the start of (pKey1/nKey1) fits in a single byte.
  62511. */
  62512. static int vdbeRecordCompareString(
  62513. int nKey1, const void *pKey1, /* Left key */
  62514. UnpackedRecord *pPKey2 /* Right key */
  62515. ){
  62516. const u8 *aKey1 = (const u8*)pKey1;
  62517. int serial_type;
  62518. int res;
  62519. getVarint32(&aKey1[1], serial_type);
  62520. if( serial_type<12 ){
  62521. res = pPKey2->r1; /* (pKey1/nKey1) is a number or a null */
  62522. }else if( !(serial_type & 0x01) ){
  62523. res = pPKey2->r2; /* (pKey1/nKey1) is a blob */
  62524. }else{
  62525. int nCmp;
  62526. int nStr;
  62527. int szHdr = aKey1[0];
  62528. nStr = (serial_type-12) / 2;
  62529. if( (szHdr + nStr) > nKey1 ){
  62530. pPKey2->errCode = (u8)SQLITE_CORRUPT_BKPT;
  62531. return 0; /* Corruption */
  62532. }
  62533. nCmp = MIN( pPKey2->aMem[0].n, nStr );
  62534. res = memcmp(&aKey1[szHdr], pPKey2->aMem[0].z, nCmp);
  62535. if( res==0 ){
  62536. res = nStr - pPKey2->aMem[0].n;
  62537. if( res==0 ){
  62538. if( pPKey2->nField>1 ){
  62539. res = vdbeRecordCompareWithSkip(nKey1, pKey1, pPKey2, 1);
  62540. }else{
  62541. res = pPKey2->default_rc;
  62542. }
  62543. }else if( res>0 ){
  62544. res = pPKey2->r2;
  62545. }else{
  62546. res = pPKey2->r1;
  62547. }
  62548. }else if( res>0 ){
  62549. res = pPKey2->r2;
  62550. }else{
  62551. res = pPKey2->r1;
  62552. }
  62553. }
  62554. assert( vdbeRecordCompareDebug(nKey1, pKey1, pPKey2, res)
  62555. || CORRUPT_DB
  62556. || pPKey2->pKeyInfo->db->mallocFailed
  62557. );
  62558. return res;
  62559. }
  62560. /*
  62561. ** Return a pointer to an sqlite3VdbeRecordCompare() compatible function
  62562. ** suitable for comparing serialized records to the unpacked record passed
  62563. ** as the only argument.
  62564. */
  62565. SQLITE_PRIVATE RecordCompare sqlite3VdbeFindCompare(UnpackedRecord *p){
  62566. /* varintRecordCompareInt() and varintRecordCompareString() both assume
  62567. ** that the size-of-header varint that occurs at the start of each record
  62568. ** fits in a single byte (i.e. is 127 or less). varintRecordCompareInt()
  62569. ** also assumes that it is safe to overread a buffer by at least the
  62570. ** maximum possible legal header size plus 8 bytes. Because there is
  62571. ** guaranteed to be at least 74 (but not 136) bytes of padding following each
  62572. ** buffer passed to varintRecordCompareInt() this makes it convenient to
  62573. ** limit the size of the header to 64 bytes in cases where the first field
  62574. ** is an integer.
  62575. **
  62576. ** The easiest way to enforce this limit is to consider only records with
  62577. ** 13 fields or less. If the first field is an integer, the maximum legal
  62578. ** header size is (12*5 + 1 + 1) bytes. */
  62579. if( (p->pKeyInfo->nField + p->pKeyInfo->nXField)<=13 ){
  62580. int flags = p->aMem[0].flags;
  62581. if( p->pKeyInfo->aSortOrder[0] ){
  62582. p->r1 = 1;
  62583. p->r2 = -1;
  62584. }else{
  62585. p->r1 = -1;
  62586. p->r2 = 1;
  62587. }
  62588. if( (flags & MEM_Int) ){
  62589. return vdbeRecordCompareInt;
  62590. }
  62591. testcase( flags & MEM_Real );
  62592. testcase( flags & MEM_Null );
  62593. testcase( flags & MEM_Blob );
  62594. if( (flags & (MEM_Real|MEM_Null|MEM_Blob))==0 && p->pKeyInfo->aColl[0]==0 ){
  62595. assert( flags & MEM_Str );
  62596. return vdbeRecordCompareString;
  62597. }
  62598. }
  62599. return sqlite3VdbeRecordCompare;
  62600. }
  62601. /*
  62602. ** pCur points at an index entry created using the OP_MakeRecord opcode.
  62603. ** Read the rowid (the last field in the record) and store it in *rowid.
  62604. ** Return SQLITE_OK if everything works, or an error code otherwise.
  62605. **
  62606. ** pCur might be pointing to text obtained from a corrupt database file.
  62607. ** So the content cannot be trusted. Do appropriate checks on the content.
  62608. */
  62609. SQLITE_PRIVATE int sqlite3VdbeIdxRowid(sqlite3 *db, BtCursor *pCur, i64 *rowid){
  62610. i64 nCellKey = 0;
  62611. int rc;
  62612. u32 szHdr; /* Size of the header */
  62613. u32 typeRowid; /* Serial type of the rowid */
  62614. u32 lenRowid; /* Size of the rowid */
  62615. Mem m, v;
  62616. /* Get the size of the index entry. Only indices entries of less
  62617. ** than 2GiB are support - anything large must be database corruption.
  62618. ** Any corruption is detected in sqlite3BtreeParseCellPtr(), though, so
  62619. ** this code can safely assume that nCellKey is 32-bits
  62620. */
  62621. assert( sqlite3BtreeCursorIsValid(pCur) );
  62622. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  62623. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  62624. assert( (nCellKey & SQLITE_MAX_U32)==(u64)nCellKey );
  62625. /* Read in the complete content of the index entry */
  62626. sqlite3VdbeMemInit(&m, db, 0);
  62627. rc = sqlite3VdbeMemFromBtree(pCur, 0, (u32)nCellKey, 1, &m);
  62628. if( rc ){
  62629. return rc;
  62630. }
  62631. /* The index entry must begin with a header size */
  62632. (void)getVarint32((u8*)m.z, szHdr);
  62633. testcase( szHdr==3 );
  62634. testcase( szHdr==m.n );
  62635. if( unlikely(szHdr<3 || (int)szHdr>m.n) ){
  62636. goto idx_rowid_corruption;
  62637. }
  62638. /* The last field of the index should be an integer - the ROWID.
  62639. ** Verify that the last entry really is an integer. */
  62640. (void)getVarint32((u8*)&m.z[szHdr-1], typeRowid);
  62641. testcase( typeRowid==1 );
  62642. testcase( typeRowid==2 );
  62643. testcase( typeRowid==3 );
  62644. testcase( typeRowid==4 );
  62645. testcase( typeRowid==5 );
  62646. testcase( typeRowid==6 );
  62647. testcase( typeRowid==8 );
  62648. testcase( typeRowid==9 );
  62649. if( unlikely(typeRowid<1 || typeRowid>9 || typeRowid==7) ){
  62650. goto idx_rowid_corruption;
  62651. }
  62652. lenRowid = sqlite3VdbeSerialTypeLen(typeRowid);
  62653. testcase( (u32)m.n==szHdr+lenRowid );
  62654. if( unlikely((u32)m.n<szHdr+lenRowid) ){
  62655. goto idx_rowid_corruption;
  62656. }
  62657. /* Fetch the integer off the end of the index record */
  62658. sqlite3VdbeSerialGet((u8*)&m.z[m.n-lenRowid], typeRowid, &v);
  62659. *rowid = v.u.i;
  62660. sqlite3VdbeMemRelease(&m);
  62661. return SQLITE_OK;
  62662. /* Jump here if database corruption is detected after m has been
  62663. ** allocated. Free the m object and return SQLITE_CORRUPT. */
  62664. idx_rowid_corruption:
  62665. testcase( m.szMalloc!=0 );
  62666. sqlite3VdbeMemRelease(&m);
  62667. return SQLITE_CORRUPT_BKPT;
  62668. }
  62669. /*
  62670. ** Compare the key of the index entry that cursor pC is pointing to against
  62671. ** the key string in pUnpacked. Write into *pRes a number
  62672. ** that is negative, zero, or positive if pC is less than, equal to,
  62673. ** or greater than pUnpacked. Return SQLITE_OK on success.
  62674. **
  62675. ** pUnpacked is either created without a rowid or is truncated so that it
  62676. ** omits the rowid at the end. The rowid at the end of the index entry
  62677. ** is ignored as well. Hence, this routine only compares the prefixes
  62678. ** of the keys prior to the final rowid, not the entire key.
  62679. */
  62680. SQLITE_PRIVATE int sqlite3VdbeIdxKeyCompare(
  62681. sqlite3 *db, /* Database connection */
  62682. VdbeCursor *pC, /* The cursor to compare against */
  62683. UnpackedRecord *pUnpacked, /* Unpacked version of key */
  62684. int *res /* Write the comparison result here */
  62685. ){
  62686. i64 nCellKey = 0;
  62687. int rc;
  62688. BtCursor *pCur = pC->pCursor;
  62689. Mem m;
  62690. assert( sqlite3BtreeCursorIsValid(pCur) );
  62691. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCur, &nCellKey);
  62692. assert( rc==SQLITE_OK ); /* pCur is always valid so KeySize cannot fail */
  62693. /* nCellKey will always be between 0 and 0xffffffff because of the way
  62694. ** that btreeParseCellPtr() and sqlite3GetVarint32() are implemented */
  62695. if( nCellKey<=0 || nCellKey>0x7fffffff ){
  62696. *res = 0;
  62697. return SQLITE_CORRUPT_BKPT;
  62698. }
  62699. sqlite3VdbeMemInit(&m, db, 0);
  62700. rc = sqlite3VdbeMemFromBtree(pC->pCursor, 0, (u32)nCellKey, 1, &m);
  62701. if( rc ){
  62702. return rc;
  62703. }
  62704. *res = sqlite3VdbeRecordCompare(m.n, m.z, pUnpacked);
  62705. sqlite3VdbeMemRelease(&m);
  62706. return SQLITE_OK;
  62707. }
  62708. /*
  62709. ** This routine sets the value to be returned by subsequent calls to
  62710. ** sqlite3_changes() on the database handle 'db'.
  62711. */
  62712. SQLITE_PRIVATE void sqlite3VdbeSetChanges(sqlite3 *db, int nChange){
  62713. assert( sqlite3_mutex_held(db->mutex) );
  62714. db->nChange = nChange;
  62715. db->nTotalChange += nChange;
  62716. }
  62717. /*
  62718. ** Set a flag in the vdbe to update the change counter when it is finalised
  62719. ** or reset.
  62720. */
  62721. SQLITE_PRIVATE void sqlite3VdbeCountChanges(Vdbe *v){
  62722. v->changeCntOn = 1;
  62723. }
  62724. /*
  62725. ** Mark every prepared statement associated with a database connection
  62726. ** as expired.
  62727. **
  62728. ** An expired statement means that recompilation of the statement is
  62729. ** recommend. Statements expire when things happen that make their
  62730. ** programs obsolete. Removing user-defined functions or collating
  62731. ** sequences, or changing an authorization function are the types of
  62732. ** things that make prepared statements obsolete.
  62733. */
  62734. SQLITE_PRIVATE void sqlite3ExpirePreparedStatements(sqlite3 *db){
  62735. Vdbe *p;
  62736. for(p = db->pVdbe; p; p=p->pNext){
  62737. p->expired = 1;
  62738. }
  62739. }
  62740. /*
  62741. ** Return the database associated with the Vdbe.
  62742. */
  62743. SQLITE_PRIVATE sqlite3 *sqlite3VdbeDb(Vdbe *v){
  62744. return v->db;
  62745. }
  62746. /*
  62747. ** Return a pointer to an sqlite3_value structure containing the value bound
  62748. ** parameter iVar of VM v. Except, if the value is an SQL NULL, return
  62749. ** 0 instead. Unless it is NULL, apply affinity aff (one of the SQLITE_AFF_*
  62750. ** constants) to the value before returning it.
  62751. **
  62752. ** The returned value must be freed by the caller using sqlite3ValueFree().
  62753. */
  62754. SQLITE_PRIVATE sqlite3_value *sqlite3VdbeGetBoundValue(Vdbe *v, int iVar, u8 aff){
  62755. assert( iVar>0 );
  62756. if( v ){
  62757. Mem *pMem = &v->aVar[iVar-1];
  62758. if( 0==(pMem->flags & MEM_Null) ){
  62759. sqlite3_value *pRet = sqlite3ValueNew(v->db);
  62760. if( pRet ){
  62761. sqlite3VdbeMemCopy((Mem *)pRet, pMem);
  62762. sqlite3ValueApplyAffinity(pRet, aff, SQLITE_UTF8);
  62763. }
  62764. return pRet;
  62765. }
  62766. }
  62767. return 0;
  62768. }
  62769. /*
  62770. ** Configure SQL variable iVar so that binding a new value to it signals
  62771. ** to sqlite3_reoptimize() that re-preparing the statement may result
  62772. ** in a better query plan.
  62773. */
  62774. SQLITE_PRIVATE void sqlite3VdbeSetVarmask(Vdbe *v, int iVar){
  62775. assert( iVar>0 );
  62776. if( iVar>32 ){
  62777. v->expmask = 0xffffffff;
  62778. }else{
  62779. v->expmask |= ((u32)1 << (iVar-1));
  62780. }
  62781. }
  62782. #ifndef SQLITE_OMIT_VIRTUALTABLE
  62783. /*
  62784. ** Transfer error message text from an sqlite3_vtab.zErrMsg (text stored
  62785. ** in memory obtained from sqlite3_malloc) into a Vdbe.zErrMsg (text stored
  62786. ** in memory obtained from sqlite3DbMalloc).
  62787. */
  62788. SQLITE_PRIVATE void sqlite3VtabImportErrmsg(Vdbe *p, sqlite3_vtab *pVtab){
  62789. sqlite3 *db = p->db;
  62790. sqlite3DbFree(db, p->zErrMsg);
  62791. p->zErrMsg = sqlite3DbStrDup(db, pVtab->zErrMsg);
  62792. sqlite3_free(pVtab->zErrMsg);
  62793. pVtab->zErrMsg = 0;
  62794. }
  62795. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  62796. /************** End of vdbeaux.c *********************************************/
  62797. /************** Begin file vdbeapi.c *****************************************/
  62798. /*
  62799. ** 2004 May 26
  62800. **
  62801. ** The author disclaims copyright to this source code. In place of
  62802. ** a legal notice, here is a blessing:
  62803. **
  62804. ** May you do good and not evil.
  62805. ** May you find forgiveness for yourself and forgive others.
  62806. ** May you share freely, never taking more than you give.
  62807. **
  62808. *************************************************************************
  62809. **
  62810. ** This file contains code use to implement APIs that are part of the
  62811. ** VDBE.
  62812. */
  62813. #ifndef SQLITE_OMIT_DEPRECATED
  62814. /*
  62815. ** Return TRUE (non-zero) of the statement supplied as an argument needs
  62816. ** to be recompiled. A statement needs to be recompiled whenever the
  62817. ** execution environment changes in a way that would alter the program
  62818. ** that sqlite3_prepare() generates. For example, if new functions or
  62819. ** collating sequences are registered or if an authorizer function is
  62820. ** added or changed.
  62821. */
  62822. SQLITE_API int sqlite3_expired(sqlite3_stmt *pStmt){
  62823. Vdbe *p = (Vdbe*)pStmt;
  62824. return p==0 || p->expired;
  62825. }
  62826. #endif
  62827. /*
  62828. ** Check on a Vdbe to make sure it has not been finalized. Log
  62829. ** an error and return true if it has been finalized (or is otherwise
  62830. ** invalid). Return false if it is ok.
  62831. */
  62832. static int vdbeSafety(Vdbe *p){
  62833. if( p->db==0 ){
  62834. sqlite3_log(SQLITE_MISUSE, "API called with finalized prepared statement");
  62835. return 1;
  62836. }else{
  62837. return 0;
  62838. }
  62839. }
  62840. static int vdbeSafetyNotNull(Vdbe *p){
  62841. if( p==0 ){
  62842. sqlite3_log(SQLITE_MISUSE, "API called with NULL prepared statement");
  62843. return 1;
  62844. }else{
  62845. return vdbeSafety(p);
  62846. }
  62847. }
  62848. /*
  62849. ** The following routine destroys a virtual machine that is created by
  62850. ** the sqlite3_compile() routine. The integer returned is an SQLITE_
  62851. ** success/failure code that describes the result of executing the virtual
  62852. ** machine.
  62853. **
  62854. ** This routine sets the error code and string returned by
  62855. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  62856. */
  62857. SQLITE_API int sqlite3_finalize(sqlite3_stmt *pStmt){
  62858. int rc;
  62859. if( pStmt==0 ){
  62860. /* IMPLEMENTATION-OF: R-57228-12904 Invoking sqlite3_finalize() on a NULL
  62861. ** pointer is a harmless no-op. */
  62862. rc = SQLITE_OK;
  62863. }else{
  62864. Vdbe *v = (Vdbe*)pStmt;
  62865. sqlite3 *db = v->db;
  62866. if( vdbeSafety(v) ) return SQLITE_MISUSE_BKPT;
  62867. sqlite3_mutex_enter(db->mutex);
  62868. rc = sqlite3VdbeFinalize(v);
  62869. rc = sqlite3ApiExit(db, rc);
  62870. sqlite3LeaveMutexAndCloseZombie(db);
  62871. }
  62872. return rc;
  62873. }
  62874. /*
  62875. ** Terminate the current execution of an SQL statement and reset it
  62876. ** back to its starting state so that it can be reused. A success code from
  62877. ** the prior execution is returned.
  62878. **
  62879. ** This routine sets the error code and string returned by
  62880. ** sqlite3_errcode(), sqlite3_errmsg() and sqlite3_errmsg16().
  62881. */
  62882. SQLITE_API int sqlite3_reset(sqlite3_stmt *pStmt){
  62883. int rc;
  62884. if( pStmt==0 ){
  62885. rc = SQLITE_OK;
  62886. }else{
  62887. Vdbe *v = (Vdbe*)pStmt;
  62888. sqlite3_mutex_enter(v->db->mutex);
  62889. rc = sqlite3VdbeReset(v);
  62890. sqlite3VdbeRewind(v);
  62891. assert( (rc & (v->db->errMask))==rc );
  62892. rc = sqlite3ApiExit(v->db, rc);
  62893. sqlite3_mutex_leave(v->db->mutex);
  62894. }
  62895. return rc;
  62896. }
  62897. /*
  62898. ** Set all the parameters in the compiled SQL statement to NULL.
  62899. */
  62900. SQLITE_API int sqlite3_clear_bindings(sqlite3_stmt *pStmt){
  62901. int i;
  62902. int rc = SQLITE_OK;
  62903. Vdbe *p = (Vdbe*)pStmt;
  62904. #if SQLITE_THREADSAFE
  62905. sqlite3_mutex *mutex = ((Vdbe*)pStmt)->db->mutex;
  62906. #endif
  62907. sqlite3_mutex_enter(mutex);
  62908. for(i=0; i<p->nVar; i++){
  62909. sqlite3VdbeMemRelease(&p->aVar[i]);
  62910. p->aVar[i].flags = MEM_Null;
  62911. }
  62912. if( p->isPrepareV2 && p->expmask ){
  62913. p->expired = 1;
  62914. }
  62915. sqlite3_mutex_leave(mutex);
  62916. return rc;
  62917. }
  62918. /**************************** sqlite3_value_ *******************************
  62919. ** The following routines extract information from a Mem or sqlite3_value
  62920. ** structure.
  62921. */
  62922. SQLITE_API const void *sqlite3_value_blob(sqlite3_value *pVal){
  62923. Mem *p = (Mem*)pVal;
  62924. if( p->flags & (MEM_Blob|MEM_Str) ){
  62925. sqlite3VdbeMemExpandBlob(p);
  62926. p->flags |= MEM_Blob;
  62927. return p->n ? p->z : 0;
  62928. }else{
  62929. return sqlite3_value_text(pVal);
  62930. }
  62931. }
  62932. SQLITE_API int sqlite3_value_bytes(sqlite3_value *pVal){
  62933. return sqlite3ValueBytes(pVal, SQLITE_UTF8);
  62934. }
  62935. SQLITE_API int sqlite3_value_bytes16(sqlite3_value *pVal){
  62936. return sqlite3ValueBytes(pVal, SQLITE_UTF16NATIVE);
  62937. }
  62938. SQLITE_API double sqlite3_value_double(sqlite3_value *pVal){
  62939. return sqlite3VdbeRealValue((Mem*)pVal);
  62940. }
  62941. SQLITE_API int sqlite3_value_int(sqlite3_value *pVal){
  62942. return (int)sqlite3VdbeIntValue((Mem*)pVal);
  62943. }
  62944. SQLITE_API sqlite_int64 sqlite3_value_int64(sqlite3_value *pVal){
  62945. return sqlite3VdbeIntValue((Mem*)pVal);
  62946. }
  62947. SQLITE_API const unsigned char *sqlite3_value_text(sqlite3_value *pVal){
  62948. return (const unsigned char *)sqlite3ValueText(pVal, SQLITE_UTF8);
  62949. }
  62950. #ifndef SQLITE_OMIT_UTF16
  62951. SQLITE_API const void *sqlite3_value_text16(sqlite3_value* pVal){
  62952. return sqlite3ValueText(pVal, SQLITE_UTF16NATIVE);
  62953. }
  62954. SQLITE_API const void *sqlite3_value_text16be(sqlite3_value *pVal){
  62955. return sqlite3ValueText(pVal, SQLITE_UTF16BE);
  62956. }
  62957. SQLITE_API const void *sqlite3_value_text16le(sqlite3_value *pVal){
  62958. return sqlite3ValueText(pVal, SQLITE_UTF16LE);
  62959. }
  62960. #endif /* SQLITE_OMIT_UTF16 */
  62961. SQLITE_API int sqlite3_value_type(sqlite3_value* pVal){
  62962. static const u8 aType[] = {
  62963. SQLITE_BLOB, /* 0x00 */
  62964. SQLITE_NULL, /* 0x01 */
  62965. SQLITE_TEXT, /* 0x02 */
  62966. SQLITE_NULL, /* 0x03 */
  62967. SQLITE_INTEGER, /* 0x04 */
  62968. SQLITE_NULL, /* 0x05 */
  62969. SQLITE_INTEGER, /* 0x06 */
  62970. SQLITE_NULL, /* 0x07 */
  62971. SQLITE_FLOAT, /* 0x08 */
  62972. SQLITE_NULL, /* 0x09 */
  62973. SQLITE_FLOAT, /* 0x0a */
  62974. SQLITE_NULL, /* 0x0b */
  62975. SQLITE_INTEGER, /* 0x0c */
  62976. SQLITE_NULL, /* 0x0d */
  62977. SQLITE_INTEGER, /* 0x0e */
  62978. SQLITE_NULL, /* 0x0f */
  62979. SQLITE_BLOB, /* 0x10 */
  62980. SQLITE_NULL, /* 0x11 */
  62981. SQLITE_TEXT, /* 0x12 */
  62982. SQLITE_NULL, /* 0x13 */
  62983. SQLITE_INTEGER, /* 0x14 */
  62984. SQLITE_NULL, /* 0x15 */
  62985. SQLITE_INTEGER, /* 0x16 */
  62986. SQLITE_NULL, /* 0x17 */
  62987. SQLITE_FLOAT, /* 0x18 */
  62988. SQLITE_NULL, /* 0x19 */
  62989. SQLITE_FLOAT, /* 0x1a */
  62990. SQLITE_NULL, /* 0x1b */
  62991. SQLITE_INTEGER, /* 0x1c */
  62992. SQLITE_NULL, /* 0x1d */
  62993. SQLITE_INTEGER, /* 0x1e */
  62994. SQLITE_NULL, /* 0x1f */
  62995. };
  62996. return aType[pVal->flags&MEM_AffMask];
  62997. }
  62998. /**************************** sqlite3_result_ *******************************
  62999. ** The following routines are used by user-defined functions to specify
  63000. ** the function result.
  63001. **
  63002. ** The setStrOrError() function calls sqlite3VdbeMemSetStr() to store the
  63003. ** result as a string or blob but if the string or blob is too large, it
  63004. ** then sets the error code to SQLITE_TOOBIG
  63005. **
  63006. ** The invokeValueDestructor(P,X) routine invokes destructor function X()
  63007. ** on value P is not going to be used and need to be destroyed.
  63008. */
  63009. static void setResultStrOrError(
  63010. sqlite3_context *pCtx, /* Function context */
  63011. const char *z, /* String pointer */
  63012. int n, /* Bytes in string, or negative */
  63013. u8 enc, /* Encoding of z. 0 for BLOBs */
  63014. void (*xDel)(void*) /* Destructor function */
  63015. ){
  63016. if( sqlite3VdbeMemSetStr(pCtx->pOut, z, n, enc, xDel)==SQLITE_TOOBIG ){
  63017. sqlite3_result_error_toobig(pCtx);
  63018. }
  63019. }
  63020. static int invokeValueDestructor(
  63021. const void *p, /* Value to destroy */
  63022. void (*xDel)(void*), /* The destructor */
  63023. sqlite3_context *pCtx /* Set a SQLITE_TOOBIG error if no NULL */
  63024. ){
  63025. assert( xDel!=SQLITE_DYNAMIC );
  63026. if( xDel==0 ){
  63027. /* noop */
  63028. }else if( xDel==SQLITE_TRANSIENT ){
  63029. /* noop */
  63030. }else{
  63031. xDel((void*)p);
  63032. }
  63033. if( pCtx ) sqlite3_result_error_toobig(pCtx);
  63034. return SQLITE_TOOBIG;
  63035. }
  63036. SQLITE_API void sqlite3_result_blob(
  63037. sqlite3_context *pCtx,
  63038. const void *z,
  63039. int n,
  63040. void (*xDel)(void *)
  63041. ){
  63042. assert( n>=0 );
  63043. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63044. setResultStrOrError(pCtx, z, n, 0, xDel);
  63045. }
  63046. SQLITE_API void sqlite3_result_blob64(
  63047. sqlite3_context *pCtx,
  63048. const void *z,
  63049. sqlite3_uint64 n,
  63050. void (*xDel)(void *)
  63051. ){
  63052. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63053. assert( xDel!=SQLITE_DYNAMIC );
  63054. if( n>0x7fffffff ){
  63055. (void)invokeValueDestructor(z, xDel, pCtx);
  63056. }else{
  63057. setResultStrOrError(pCtx, z, (int)n, 0, xDel);
  63058. }
  63059. }
  63060. SQLITE_API void sqlite3_result_double(sqlite3_context *pCtx, double rVal){
  63061. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63062. sqlite3VdbeMemSetDouble(pCtx->pOut, rVal);
  63063. }
  63064. SQLITE_API void sqlite3_result_error(sqlite3_context *pCtx, const char *z, int n){
  63065. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63066. pCtx->isError = SQLITE_ERROR;
  63067. pCtx->fErrorOrAux = 1;
  63068. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF8, SQLITE_TRANSIENT);
  63069. }
  63070. #ifndef SQLITE_OMIT_UTF16
  63071. SQLITE_API void sqlite3_result_error16(sqlite3_context *pCtx, const void *z, int n){
  63072. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63073. pCtx->isError = SQLITE_ERROR;
  63074. pCtx->fErrorOrAux = 1;
  63075. sqlite3VdbeMemSetStr(pCtx->pOut, z, n, SQLITE_UTF16NATIVE, SQLITE_TRANSIENT);
  63076. }
  63077. #endif
  63078. SQLITE_API void sqlite3_result_int(sqlite3_context *pCtx, int iVal){
  63079. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63080. sqlite3VdbeMemSetInt64(pCtx->pOut, (i64)iVal);
  63081. }
  63082. SQLITE_API void sqlite3_result_int64(sqlite3_context *pCtx, i64 iVal){
  63083. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63084. sqlite3VdbeMemSetInt64(pCtx->pOut, iVal);
  63085. }
  63086. SQLITE_API void sqlite3_result_null(sqlite3_context *pCtx){
  63087. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63088. sqlite3VdbeMemSetNull(pCtx->pOut);
  63089. }
  63090. SQLITE_API void sqlite3_result_text(
  63091. sqlite3_context *pCtx,
  63092. const char *z,
  63093. int n,
  63094. void (*xDel)(void *)
  63095. ){
  63096. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63097. setResultStrOrError(pCtx, z, n, SQLITE_UTF8, xDel);
  63098. }
  63099. SQLITE_API void sqlite3_result_text64(
  63100. sqlite3_context *pCtx,
  63101. const char *z,
  63102. sqlite3_uint64 n,
  63103. void (*xDel)(void *),
  63104. unsigned char enc
  63105. ){
  63106. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63107. assert( xDel!=SQLITE_DYNAMIC );
  63108. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  63109. if( n>0x7fffffff ){
  63110. (void)invokeValueDestructor(z, xDel, pCtx);
  63111. }else{
  63112. setResultStrOrError(pCtx, z, (int)n, enc, xDel);
  63113. }
  63114. }
  63115. #ifndef SQLITE_OMIT_UTF16
  63116. SQLITE_API void sqlite3_result_text16(
  63117. sqlite3_context *pCtx,
  63118. const void *z,
  63119. int n,
  63120. void (*xDel)(void *)
  63121. ){
  63122. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63123. setResultStrOrError(pCtx, z, n, SQLITE_UTF16NATIVE, xDel);
  63124. }
  63125. SQLITE_API void sqlite3_result_text16be(
  63126. sqlite3_context *pCtx,
  63127. const void *z,
  63128. int n,
  63129. void (*xDel)(void *)
  63130. ){
  63131. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63132. setResultStrOrError(pCtx, z, n, SQLITE_UTF16BE, xDel);
  63133. }
  63134. SQLITE_API void sqlite3_result_text16le(
  63135. sqlite3_context *pCtx,
  63136. const void *z,
  63137. int n,
  63138. void (*xDel)(void *)
  63139. ){
  63140. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63141. setResultStrOrError(pCtx, z, n, SQLITE_UTF16LE, xDel);
  63142. }
  63143. #endif /* SQLITE_OMIT_UTF16 */
  63144. SQLITE_API void sqlite3_result_value(sqlite3_context *pCtx, sqlite3_value *pValue){
  63145. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63146. sqlite3VdbeMemCopy(pCtx->pOut, pValue);
  63147. }
  63148. SQLITE_API void sqlite3_result_zeroblob(sqlite3_context *pCtx, int n){
  63149. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63150. sqlite3VdbeMemSetZeroBlob(pCtx->pOut, n);
  63151. }
  63152. SQLITE_API void sqlite3_result_error_code(sqlite3_context *pCtx, int errCode){
  63153. pCtx->isError = errCode;
  63154. pCtx->fErrorOrAux = 1;
  63155. if( pCtx->pOut->flags & MEM_Null ){
  63156. sqlite3VdbeMemSetStr(pCtx->pOut, sqlite3ErrStr(errCode), -1,
  63157. SQLITE_UTF8, SQLITE_STATIC);
  63158. }
  63159. }
  63160. /* Force an SQLITE_TOOBIG error. */
  63161. SQLITE_API void sqlite3_result_error_toobig(sqlite3_context *pCtx){
  63162. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63163. pCtx->isError = SQLITE_TOOBIG;
  63164. pCtx->fErrorOrAux = 1;
  63165. sqlite3VdbeMemSetStr(pCtx->pOut, "string or blob too big", -1,
  63166. SQLITE_UTF8, SQLITE_STATIC);
  63167. }
  63168. /* An SQLITE_NOMEM error. */
  63169. SQLITE_API void sqlite3_result_error_nomem(sqlite3_context *pCtx){
  63170. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63171. sqlite3VdbeMemSetNull(pCtx->pOut);
  63172. pCtx->isError = SQLITE_NOMEM;
  63173. pCtx->fErrorOrAux = 1;
  63174. pCtx->pOut->db->mallocFailed = 1;
  63175. }
  63176. /*
  63177. ** This function is called after a transaction has been committed. It
  63178. ** invokes callbacks registered with sqlite3_wal_hook() as required.
  63179. */
  63180. static int doWalCallbacks(sqlite3 *db){
  63181. int rc = SQLITE_OK;
  63182. #ifndef SQLITE_OMIT_WAL
  63183. int i;
  63184. for(i=0; i<db->nDb; i++){
  63185. Btree *pBt = db->aDb[i].pBt;
  63186. if( pBt ){
  63187. int nEntry = sqlite3PagerWalCallback(sqlite3BtreePager(pBt));
  63188. if( db->xWalCallback && nEntry>0 && rc==SQLITE_OK ){
  63189. rc = db->xWalCallback(db->pWalArg, db, db->aDb[i].zName, nEntry);
  63190. }
  63191. }
  63192. }
  63193. #endif
  63194. return rc;
  63195. }
  63196. /*
  63197. ** Execute the statement pStmt, either until a row of data is ready, the
  63198. ** statement is completely executed or an error occurs.
  63199. **
  63200. ** This routine implements the bulk of the logic behind the sqlite_step()
  63201. ** API. The only thing omitted is the automatic recompile if a
  63202. ** schema change has occurred. That detail is handled by the
  63203. ** outer sqlite3_step() wrapper procedure.
  63204. */
  63205. static int sqlite3Step(Vdbe *p){
  63206. sqlite3 *db;
  63207. int rc;
  63208. assert(p);
  63209. if( p->magic!=VDBE_MAGIC_RUN ){
  63210. /* We used to require that sqlite3_reset() be called before retrying
  63211. ** sqlite3_step() after any error or after SQLITE_DONE. But beginning
  63212. ** with version 3.7.0, we changed this so that sqlite3_reset() would
  63213. ** be called automatically instead of throwing the SQLITE_MISUSE error.
  63214. ** This "automatic-reset" change is not technically an incompatibility,
  63215. ** since any application that receives an SQLITE_MISUSE is broken by
  63216. ** definition.
  63217. **
  63218. ** Nevertheless, some published applications that were originally written
  63219. ** for version 3.6.23 or earlier do in fact depend on SQLITE_MISUSE
  63220. ** returns, and those were broken by the automatic-reset change. As a
  63221. ** a work-around, the SQLITE_OMIT_AUTORESET compile-time restores the
  63222. ** legacy behavior of returning SQLITE_MISUSE for cases where the
  63223. ** previous sqlite3_step() returned something other than a SQLITE_LOCKED
  63224. ** or SQLITE_BUSY error.
  63225. */
  63226. #ifdef SQLITE_OMIT_AUTORESET
  63227. if( p->rc==SQLITE_BUSY || p->rc==SQLITE_LOCKED ){
  63228. sqlite3_reset((sqlite3_stmt*)p);
  63229. }else{
  63230. return SQLITE_MISUSE_BKPT;
  63231. }
  63232. #else
  63233. sqlite3_reset((sqlite3_stmt*)p);
  63234. #endif
  63235. }
  63236. /* Check that malloc() has not failed. If it has, return early. */
  63237. db = p->db;
  63238. if( db->mallocFailed ){
  63239. p->rc = SQLITE_NOMEM;
  63240. return SQLITE_NOMEM;
  63241. }
  63242. if( p->pc<=0 && p->expired ){
  63243. p->rc = SQLITE_SCHEMA;
  63244. rc = SQLITE_ERROR;
  63245. goto end_of_step;
  63246. }
  63247. if( p->pc<0 ){
  63248. /* If there are no other statements currently running, then
  63249. ** reset the interrupt flag. This prevents a call to sqlite3_interrupt
  63250. ** from interrupting a statement that has not yet started.
  63251. */
  63252. if( db->nVdbeActive==0 ){
  63253. db->u1.isInterrupted = 0;
  63254. }
  63255. assert( db->nVdbeWrite>0 || db->autoCommit==0
  63256. || (db->nDeferredCons==0 && db->nDeferredImmCons==0)
  63257. );
  63258. #ifndef SQLITE_OMIT_TRACE
  63259. if( db->xProfile && !db->init.busy ){
  63260. sqlite3OsCurrentTimeInt64(db->pVfs, &p->startTime);
  63261. }
  63262. #endif
  63263. db->nVdbeActive++;
  63264. if( p->readOnly==0 ) db->nVdbeWrite++;
  63265. if( p->bIsReader ) db->nVdbeRead++;
  63266. p->pc = 0;
  63267. }
  63268. #ifndef SQLITE_OMIT_EXPLAIN
  63269. if( p->explain ){
  63270. rc = sqlite3VdbeList(p);
  63271. }else
  63272. #endif /* SQLITE_OMIT_EXPLAIN */
  63273. {
  63274. db->nVdbeExec++;
  63275. rc = sqlite3VdbeExec(p);
  63276. db->nVdbeExec--;
  63277. }
  63278. #ifndef SQLITE_OMIT_TRACE
  63279. /* Invoke the profile callback if there is one
  63280. */
  63281. if( rc!=SQLITE_ROW && db->xProfile && !db->init.busy && p->zSql ){
  63282. sqlite3_int64 iNow;
  63283. sqlite3OsCurrentTimeInt64(db->pVfs, &iNow);
  63284. db->xProfile(db->pProfileArg, p->zSql, (iNow - p->startTime)*1000000);
  63285. }
  63286. #endif
  63287. if( rc==SQLITE_DONE ){
  63288. assert( p->rc==SQLITE_OK );
  63289. p->rc = doWalCallbacks(db);
  63290. if( p->rc!=SQLITE_OK ){
  63291. rc = SQLITE_ERROR;
  63292. }
  63293. }
  63294. db->errCode = rc;
  63295. if( SQLITE_NOMEM==sqlite3ApiExit(p->db, p->rc) ){
  63296. p->rc = SQLITE_NOMEM;
  63297. }
  63298. end_of_step:
  63299. /* At this point local variable rc holds the value that should be
  63300. ** returned if this statement was compiled using the legacy
  63301. ** sqlite3_prepare() interface. According to the docs, this can only
  63302. ** be one of the values in the first assert() below. Variable p->rc
  63303. ** contains the value that would be returned if sqlite3_finalize()
  63304. ** were called on statement p.
  63305. */
  63306. assert( rc==SQLITE_ROW || rc==SQLITE_DONE || rc==SQLITE_ERROR
  63307. || rc==SQLITE_BUSY || rc==SQLITE_MISUSE
  63308. );
  63309. assert( p->rc!=SQLITE_ROW && p->rc!=SQLITE_DONE );
  63310. if( p->isPrepareV2 && rc!=SQLITE_ROW && rc!=SQLITE_DONE ){
  63311. /* If this statement was prepared using sqlite3_prepare_v2(), and an
  63312. ** error has occurred, then return the error code in p->rc to the
  63313. ** caller. Set the error code in the database handle to the same value.
  63314. */
  63315. rc = sqlite3VdbeTransferError(p);
  63316. }
  63317. return (rc&db->errMask);
  63318. }
  63319. /*
  63320. ** This is the top-level implementation of sqlite3_step(). Call
  63321. ** sqlite3Step() to do most of the work. If a schema error occurs,
  63322. ** call sqlite3Reprepare() and try again.
  63323. */
  63324. SQLITE_API int sqlite3_step(sqlite3_stmt *pStmt){
  63325. int rc = SQLITE_OK; /* Result from sqlite3Step() */
  63326. int rc2 = SQLITE_OK; /* Result from sqlite3Reprepare() */
  63327. Vdbe *v = (Vdbe*)pStmt; /* the prepared statement */
  63328. int cnt = 0; /* Counter to prevent infinite loop of reprepares */
  63329. sqlite3 *db; /* The database connection */
  63330. if( vdbeSafetyNotNull(v) ){
  63331. return SQLITE_MISUSE_BKPT;
  63332. }
  63333. db = v->db;
  63334. sqlite3_mutex_enter(db->mutex);
  63335. v->doingRerun = 0;
  63336. while( (rc = sqlite3Step(v))==SQLITE_SCHEMA
  63337. && cnt++ < SQLITE_MAX_SCHEMA_RETRY ){
  63338. int savedPc = v->pc;
  63339. rc2 = rc = sqlite3Reprepare(v);
  63340. if( rc!=SQLITE_OK) break;
  63341. sqlite3_reset(pStmt);
  63342. if( savedPc>=0 ) v->doingRerun = 1;
  63343. assert( v->expired==0 );
  63344. }
  63345. if( rc2!=SQLITE_OK ){
  63346. /* This case occurs after failing to recompile an sql statement.
  63347. ** The error message from the SQL compiler has already been loaded
  63348. ** into the database handle. This block copies the error message
  63349. ** from the database handle into the statement and sets the statement
  63350. ** program counter to 0 to ensure that when the statement is
  63351. ** finalized or reset the parser error message is available via
  63352. ** sqlite3_errmsg() and sqlite3_errcode().
  63353. */
  63354. const char *zErr = (const char *)sqlite3_value_text(db->pErr);
  63355. assert( zErr!=0 || db->mallocFailed );
  63356. sqlite3DbFree(db, v->zErrMsg);
  63357. if( !db->mallocFailed ){
  63358. v->zErrMsg = sqlite3DbStrDup(db, zErr);
  63359. v->rc = rc2;
  63360. } else {
  63361. v->zErrMsg = 0;
  63362. v->rc = rc = SQLITE_NOMEM;
  63363. }
  63364. }
  63365. rc = sqlite3ApiExit(db, rc);
  63366. sqlite3_mutex_leave(db->mutex);
  63367. return rc;
  63368. }
  63369. /*
  63370. ** Extract the user data from a sqlite3_context structure and return a
  63371. ** pointer to it.
  63372. */
  63373. SQLITE_API void *sqlite3_user_data(sqlite3_context *p){
  63374. assert( p && p->pFunc );
  63375. return p->pFunc->pUserData;
  63376. }
  63377. /*
  63378. ** Extract the user data from a sqlite3_context structure and return a
  63379. ** pointer to it.
  63380. **
  63381. ** IMPLEMENTATION-OF: R-46798-50301 The sqlite3_context_db_handle() interface
  63382. ** returns a copy of the pointer to the database connection (the 1st
  63383. ** parameter) of the sqlite3_create_function() and
  63384. ** sqlite3_create_function16() routines that originally registered the
  63385. ** application defined function.
  63386. */
  63387. SQLITE_API sqlite3 *sqlite3_context_db_handle(sqlite3_context *p){
  63388. assert( p && p->pFunc );
  63389. return p->pOut->db;
  63390. }
  63391. /*
  63392. ** Return the current time for a statement
  63393. */
  63394. SQLITE_PRIVATE sqlite3_int64 sqlite3StmtCurrentTime(sqlite3_context *p){
  63395. Vdbe *v = p->pVdbe;
  63396. int rc;
  63397. if( v->iCurrentTime==0 ){
  63398. rc = sqlite3OsCurrentTimeInt64(p->pOut->db->pVfs, &v->iCurrentTime);
  63399. if( rc ) v->iCurrentTime = 0;
  63400. }
  63401. return v->iCurrentTime;
  63402. }
  63403. /*
  63404. ** The following is the implementation of an SQL function that always
  63405. ** fails with an error message stating that the function is used in the
  63406. ** wrong context. The sqlite3_overload_function() API might construct
  63407. ** SQL function that use this routine so that the functions will exist
  63408. ** for name resolution but are actually overloaded by the xFindFunction
  63409. ** method of virtual tables.
  63410. */
  63411. SQLITE_PRIVATE void sqlite3InvalidFunction(
  63412. sqlite3_context *context, /* The function calling context */
  63413. int NotUsed, /* Number of arguments to the function */
  63414. sqlite3_value **NotUsed2 /* Value of each argument */
  63415. ){
  63416. const char *zName = context->pFunc->zName;
  63417. char *zErr;
  63418. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  63419. zErr = sqlite3_mprintf(
  63420. "unable to use function %s in the requested context", zName);
  63421. sqlite3_result_error(context, zErr, -1);
  63422. sqlite3_free(zErr);
  63423. }
  63424. /*
  63425. ** Create a new aggregate context for p and return a pointer to
  63426. ** its pMem->z element.
  63427. */
  63428. static SQLITE_NOINLINE void *createAggContext(sqlite3_context *p, int nByte){
  63429. Mem *pMem = p->pMem;
  63430. assert( (pMem->flags & MEM_Agg)==0 );
  63431. if( nByte<=0 ){
  63432. sqlite3VdbeMemSetNull(pMem);
  63433. pMem->z = 0;
  63434. }else{
  63435. sqlite3VdbeMemClearAndResize(pMem, nByte);
  63436. pMem->flags = MEM_Agg;
  63437. pMem->u.pDef = p->pFunc;
  63438. if( pMem->z ){
  63439. memset(pMem->z, 0, nByte);
  63440. }
  63441. }
  63442. return (void*)pMem->z;
  63443. }
  63444. /*
  63445. ** Allocate or return the aggregate context for a user function. A new
  63446. ** context is allocated on the first call. Subsequent calls return the
  63447. ** same context that was returned on prior calls.
  63448. */
  63449. SQLITE_API void *sqlite3_aggregate_context(sqlite3_context *p, int nByte){
  63450. assert( p && p->pFunc && p->pFunc->xStep );
  63451. assert( sqlite3_mutex_held(p->pOut->db->mutex) );
  63452. testcase( nByte<0 );
  63453. if( (p->pMem->flags & MEM_Agg)==0 ){
  63454. return createAggContext(p, nByte);
  63455. }else{
  63456. return (void*)p->pMem->z;
  63457. }
  63458. }
  63459. /*
  63460. ** Return the auxiliary data pointer, if any, for the iArg'th argument to
  63461. ** the user-function defined by pCtx.
  63462. */
  63463. SQLITE_API void *sqlite3_get_auxdata(sqlite3_context *pCtx, int iArg){
  63464. AuxData *pAuxData;
  63465. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63466. for(pAuxData=pCtx->pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  63467. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  63468. }
  63469. return (pAuxData ? pAuxData->pAux : 0);
  63470. }
  63471. /*
  63472. ** Set the auxiliary data pointer and delete function, for the iArg'th
  63473. ** argument to the user-function defined by pCtx. Any previous value is
  63474. ** deleted by calling the delete function specified when it was set.
  63475. */
  63476. SQLITE_API void sqlite3_set_auxdata(
  63477. sqlite3_context *pCtx,
  63478. int iArg,
  63479. void *pAux,
  63480. void (*xDelete)(void*)
  63481. ){
  63482. AuxData *pAuxData;
  63483. Vdbe *pVdbe = pCtx->pVdbe;
  63484. assert( sqlite3_mutex_held(pCtx->pOut->db->mutex) );
  63485. if( iArg<0 ) goto failed;
  63486. for(pAuxData=pVdbe->pAuxData; pAuxData; pAuxData=pAuxData->pNext){
  63487. if( pAuxData->iOp==pCtx->iOp && pAuxData->iArg==iArg ) break;
  63488. }
  63489. if( pAuxData==0 ){
  63490. pAuxData = sqlite3DbMallocZero(pVdbe->db, sizeof(AuxData));
  63491. if( !pAuxData ) goto failed;
  63492. pAuxData->iOp = pCtx->iOp;
  63493. pAuxData->iArg = iArg;
  63494. pAuxData->pNext = pVdbe->pAuxData;
  63495. pVdbe->pAuxData = pAuxData;
  63496. if( pCtx->fErrorOrAux==0 ){
  63497. pCtx->isError = 0;
  63498. pCtx->fErrorOrAux = 1;
  63499. }
  63500. }else if( pAuxData->xDelete ){
  63501. pAuxData->xDelete(pAuxData->pAux);
  63502. }
  63503. pAuxData->pAux = pAux;
  63504. pAuxData->xDelete = xDelete;
  63505. return;
  63506. failed:
  63507. if( xDelete ){
  63508. xDelete(pAux);
  63509. }
  63510. }
  63511. #ifndef SQLITE_OMIT_DEPRECATED
  63512. /*
  63513. ** Return the number of times the Step function of an aggregate has been
  63514. ** called.
  63515. **
  63516. ** This function is deprecated. Do not use it for new code. It is
  63517. ** provide only to avoid breaking legacy code. New aggregate function
  63518. ** implementations should keep their own counts within their aggregate
  63519. ** context.
  63520. */
  63521. SQLITE_API int sqlite3_aggregate_count(sqlite3_context *p){
  63522. assert( p && p->pMem && p->pFunc && p->pFunc->xStep );
  63523. return p->pMem->n;
  63524. }
  63525. #endif
  63526. /*
  63527. ** Return the number of columns in the result set for the statement pStmt.
  63528. */
  63529. SQLITE_API int sqlite3_column_count(sqlite3_stmt *pStmt){
  63530. Vdbe *pVm = (Vdbe *)pStmt;
  63531. return pVm ? pVm->nResColumn : 0;
  63532. }
  63533. /*
  63534. ** Return the number of values available from the current row of the
  63535. ** currently executing statement pStmt.
  63536. */
  63537. SQLITE_API int sqlite3_data_count(sqlite3_stmt *pStmt){
  63538. Vdbe *pVm = (Vdbe *)pStmt;
  63539. if( pVm==0 || pVm->pResultSet==0 ) return 0;
  63540. return pVm->nResColumn;
  63541. }
  63542. /*
  63543. ** Return a pointer to static memory containing an SQL NULL value.
  63544. */
  63545. static const Mem *columnNullValue(void){
  63546. /* Even though the Mem structure contains an element
  63547. ** of type i64, on certain architectures (x86) with certain compiler
  63548. ** switches (-Os), gcc may align this Mem object on a 4-byte boundary
  63549. ** instead of an 8-byte one. This all works fine, except that when
  63550. ** running with SQLITE_DEBUG defined the SQLite code sometimes assert()s
  63551. ** that a Mem structure is located on an 8-byte boundary. To prevent
  63552. ** these assert()s from failing, when building with SQLITE_DEBUG defined
  63553. ** using gcc, we force nullMem to be 8-byte aligned using the magical
  63554. ** __attribute__((aligned(8))) macro. */
  63555. static const Mem nullMem
  63556. #if defined(SQLITE_DEBUG) && defined(__GNUC__)
  63557. __attribute__((aligned(8)))
  63558. #endif
  63559. = {
  63560. /* .u = */ {0},
  63561. /* .flags = */ MEM_Null,
  63562. /* .enc = */ 0,
  63563. /* .n = */ 0,
  63564. /* .z = */ 0,
  63565. /* .zMalloc = */ 0,
  63566. /* .szMalloc = */ 0,
  63567. /* .iPadding1 = */ 0,
  63568. /* .db = */ 0,
  63569. /* .xDel = */ 0,
  63570. #ifdef SQLITE_DEBUG
  63571. /* .pScopyFrom = */ 0,
  63572. /* .pFiller = */ 0,
  63573. #endif
  63574. };
  63575. return &nullMem;
  63576. }
  63577. /*
  63578. ** Check to see if column iCol of the given statement is valid. If
  63579. ** it is, return a pointer to the Mem for the value of that column.
  63580. ** If iCol is not valid, return a pointer to a Mem which has a value
  63581. ** of NULL.
  63582. */
  63583. static Mem *columnMem(sqlite3_stmt *pStmt, int i){
  63584. Vdbe *pVm;
  63585. Mem *pOut;
  63586. pVm = (Vdbe *)pStmt;
  63587. if( pVm && pVm->pResultSet!=0 && i<pVm->nResColumn && i>=0 ){
  63588. sqlite3_mutex_enter(pVm->db->mutex);
  63589. pOut = &pVm->pResultSet[i];
  63590. }else{
  63591. if( pVm && ALWAYS(pVm->db) ){
  63592. sqlite3_mutex_enter(pVm->db->mutex);
  63593. sqlite3Error(pVm->db, SQLITE_RANGE);
  63594. }
  63595. pOut = (Mem*)columnNullValue();
  63596. }
  63597. return pOut;
  63598. }
  63599. /*
  63600. ** This function is called after invoking an sqlite3_value_XXX function on a
  63601. ** column value (i.e. a value returned by evaluating an SQL expression in the
  63602. ** select list of a SELECT statement) that may cause a malloc() failure. If
  63603. ** malloc() has failed, the threads mallocFailed flag is cleared and the result
  63604. ** code of statement pStmt set to SQLITE_NOMEM.
  63605. **
  63606. ** Specifically, this is called from within:
  63607. **
  63608. ** sqlite3_column_int()
  63609. ** sqlite3_column_int64()
  63610. ** sqlite3_column_text()
  63611. ** sqlite3_column_text16()
  63612. ** sqlite3_column_real()
  63613. ** sqlite3_column_bytes()
  63614. ** sqlite3_column_bytes16()
  63615. ** sqiite3_column_blob()
  63616. */
  63617. static void columnMallocFailure(sqlite3_stmt *pStmt)
  63618. {
  63619. /* If malloc() failed during an encoding conversion within an
  63620. ** sqlite3_column_XXX API, then set the return code of the statement to
  63621. ** SQLITE_NOMEM. The next call to _step() (if any) will return SQLITE_ERROR
  63622. ** and _finalize() will return NOMEM.
  63623. */
  63624. Vdbe *p = (Vdbe *)pStmt;
  63625. if( p ){
  63626. p->rc = sqlite3ApiExit(p->db, p->rc);
  63627. sqlite3_mutex_leave(p->db->mutex);
  63628. }
  63629. }
  63630. /**************************** sqlite3_column_ *******************************
  63631. ** The following routines are used to access elements of the current row
  63632. ** in the result set.
  63633. */
  63634. SQLITE_API const void *sqlite3_column_blob(sqlite3_stmt *pStmt, int i){
  63635. const void *val;
  63636. val = sqlite3_value_blob( columnMem(pStmt,i) );
  63637. /* Even though there is no encoding conversion, value_blob() might
  63638. ** need to call malloc() to expand the result of a zeroblob()
  63639. ** expression.
  63640. */
  63641. columnMallocFailure(pStmt);
  63642. return val;
  63643. }
  63644. SQLITE_API int sqlite3_column_bytes(sqlite3_stmt *pStmt, int i){
  63645. int val = sqlite3_value_bytes( columnMem(pStmt,i) );
  63646. columnMallocFailure(pStmt);
  63647. return val;
  63648. }
  63649. SQLITE_API int sqlite3_column_bytes16(sqlite3_stmt *pStmt, int i){
  63650. int val = sqlite3_value_bytes16( columnMem(pStmt,i) );
  63651. columnMallocFailure(pStmt);
  63652. return val;
  63653. }
  63654. SQLITE_API double sqlite3_column_double(sqlite3_stmt *pStmt, int i){
  63655. double val = sqlite3_value_double( columnMem(pStmt,i) );
  63656. columnMallocFailure(pStmt);
  63657. return val;
  63658. }
  63659. SQLITE_API int sqlite3_column_int(sqlite3_stmt *pStmt, int i){
  63660. int val = sqlite3_value_int( columnMem(pStmt,i) );
  63661. columnMallocFailure(pStmt);
  63662. return val;
  63663. }
  63664. SQLITE_API sqlite_int64 sqlite3_column_int64(sqlite3_stmt *pStmt, int i){
  63665. sqlite_int64 val = sqlite3_value_int64( columnMem(pStmt,i) );
  63666. columnMallocFailure(pStmt);
  63667. return val;
  63668. }
  63669. SQLITE_API const unsigned char *sqlite3_column_text(sqlite3_stmt *pStmt, int i){
  63670. const unsigned char *val = sqlite3_value_text( columnMem(pStmt,i) );
  63671. columnMallocFailure(pStmt);
  63672. return val;
  63673. }
  63674. SQLITE_API sqlite3_value *sqlite3_column_value(sqlite3_stmt *pStmt, int i){
  63675. Mem *pOut = columnMem(pStmt, i);
  63676. if( pOut->flags&MEM_Static ){
  63677. pOut->flags &= ~MEM_Static;
  63678. pOut->flags |= MEM_Ephem;
  63679. }
  63680. columnMallocFailure(pStmt);
  63681. return (sqlite3_value *)pOut;
  63682. }
  63683. #ifndef SQLITE_OMIT_UTF16
  63684. SQLITE_API const void *sqlite3_column_text16(sqlite3_stmt *pStmt, int i){
  63685. const void *val = sqlite3_value_text16( columnMem(pStmt,i) );
  63686. columnMallocFailure(pStmt);
  63687. return val;
  63688. }
  63689. #endif /* SQLITE_OMIT_UTF16 */
  63690. SQLITE_API int sqlite3_column_type(sqlite3_stmt *pStmt, int i){
  63691. int iType = sqlite3_value_type( columnMem(pStmt,i) );
  63692. columnMallocFailure(pStmt);
  63693. return iType;
  63694. }
  63695. /*
  63696. ** Convert the N-th element of pStmt->pColName[] into a string using
  63697. ** xFunc() then return that string. If N is out of range, return 0.
  63698. **
  63699. ** There are up to 5 names for each column. useType determines which
  63700. ** name is returned. Here are the names:
  63701. **
  63702. ** 0 The column name as it should be displayed for output
  63703. ** 1 The datatype name for the column
  63704. ** 2 The name of the database that the column derives from
  63705. ** 3 The name of the table that the column derives from
  63706. ** 4 The name of the table column that the result column derives from
  63707. **
  63708. ** If the result is not a simple column reference (if it is an expression
  63709. ** or a constant) then useTypes 2, 3, and 4 return NULL.
  63710. */
  63711. static const void *columnName(
  63712. sqlite3_stmt *pStmt,
  63713. int N,
  63714. const void *(*xFunc)(Mem*),
  63715. int useType
  63716. ){
  63717. const void *ret = 0;
  63718. Vdbe *p = (Vdbe *)pStmt;
  63719. int n;
  63720. sqlite3 *db = p->db;
  63721. assert( db!=0 );
  63722. n = sqlite3_column_count(pStmt);
  63723. if( N<n && N>=0 ){
  63724. N += useType*n;
  63725. sqlite3_mutex_enter(db->mutex);
  63726. assert( db->mallocFailed==0 );
  63727. ret = xFunc(&p->aColName[N]);
  63728. /* A malloc may have failed inside of the xFunc() call. If this
  63729. ** is the case, clear the mallocFailed flag and return NULL.
  63730. */
  63731. if( db->mallocFailed ){
  63732. db->mallocFailed = 0;
  63733. ret = 0;
  63734. }
  63735. sqlite3_mutex_leave(db->mutex);
  63736. }
  63737. return ret;
  63738. }
  63739. /*
  63740. ** Return the name of the Nth column of the result set returned by SQL
  63741. ** statement pStmt.
  63742. */
  63743. SQLITE_API const char *sqlite3_column_name(sqlite3_stmt *pStmt, int N){
  63744. return columnName(
  63745. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_NAME);
  63746. }
  63747. #ifndef SQLITE_OMIT_UTF16
  63748. SQLITE_API const void *sqlite3_column_name16(sqlite3_stmt *pStmt, int N){
  63749. return columnName(
  63750. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_NAME);
  63751. }
  63752. #endif
  63753. /*
  63754. ** Constraint: If you have ENABLE_COLUMN_METADATA then you must
  63755. ** not define OMIT_DECLTYPE.
  63756. */
  63757. #if defined(SQLITE_OMIT_DECLTYPE) && defined(SQLITE_ENABLE_COLUMN_METADATA)
  63758. # error "Must not define both SQLITE_OMIT_DECLTYPE \
  63759. and SQLITE_ENABLE_COLUMN_METADATA"
  63760. #endif
  63761. #ifndef SQLITE_OMIT_DECLTYPE
  63762. /*
  63763. ** Return the column declaration type (if applicable) of the 'i'th column
  63764. ** of the result set of SQL statement pStmt.
  63765. */
  63766. SQLITE_API const char *sqlite3_column_decltype(sqlite3_stmt *pStmt, int N){
  63767. return columnName(
  63768. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DECLTYPE);
  63769. }
  63770. #ifndef SQLITE_OMIT_UTF16
  63771. SQLITE_API const void *sqlite3_column_decltype16(sqlite3_stmt *pStmt, int N){
  63772. return columnName(
  63773. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DECLTYPE);
  63774. }
  63775. #endif /* SQLITE_OMIT_UTF16 */
  63776. #endif /* SQLITE_OMIT_DECLTYPE */
  63777. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  63778. /*
  63779. ** Return the name of the database from which a result column derives.
  63780. ** NULL is returned if the result column is an expression or constant or
  63781. ** anything else which is not an unambiguous reference to a database column.
  63782. */
  63783. SQLITE_API const char *sqlite3_column_database_name(sqlite3_stmt *pStmt, int N){
  63784. return columnName(
  63785. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_DATABASE);
  63786. }
  63787. #ifndef SQLITE_OMIT_UTF16
  63788. SQLITE_API const void *sqlite3_column_database_name16(sqlite3_stmt *pStmt, int N){
  63789. return columnName(
  63790. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_DATABASE);
  63791. }
  63792. #endif /* SQLITE_OMIT_UTF16 */
  63793. /*
  63794. ** Return the name of the table from which a result column derives.
  63795. ** NULL is returned if the result column is an expression or constant or
  63796. ** anything else which is not an unambiguous reference to a database column.
  63797. */
  63798. SQLITE_API const char *sqlite3_column_table_name(sqlite3_stmt *pStmt, int N){
  63799. return columnName(
  63800. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_TABLE);
  63801. }
  63802. #ifndef SQLITE_OMIT_UTF16
  63803. SQLITE_API const void *sqlite3_column_table_name16(sqlite3_stmt *pStmt, int N){
  63804. return columnName(
  63805. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_TABLE);
  63806. }
  63807. #endif /* SQLITE_OMIT_UTF16 */
  63808. /*
  63809. ** Return the name of the table column from which a result column derives.
  63810. ** NULL is returned if the result column is an expression or constant or
  63811. ** anything else which is not an unambiguous reference to a database column.
  63812. */
  63813. SQLITE_API const char *sqlite3_column_origin_name(sqlite3_stmt *pStmt, int N){
  63814. return columnName(
  63815. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text, COLNAME_COLUMN);
  63816. }
  63817. #ifndef SQLITE_OMIT_UTF16
  63818. SQLITE_API const void *sqlite3_column_origin_name16(sqlite3_stmt *pStmt, int N){
  63819. return columnName(
  63820. pStmt, N, (const void*(*)(Mem*))sqlite3_value_text16, COLNAME_COLUMN);
  63821. }
  63822. #endif /* SQLITE_OMIT_UTF16 */
  63823. #endif /* SQLITE_ENABLE_COLUMN_METADATA */
  63824. /******************************* sqlite3_bind_ ***************************
  63825. **
  63826. ** Routines used to attach values to wildcards in a compiled SQL statement.
  63827. */
  63828. /*
  63829. ** Unbind the value bound to variable i in virtual machine p. This is the
  63830. ** the same as binding a NULL value to the column. If the "i" parameter is
  63831. ** out of range, then SQLITE_RANGE is returned. Othewise SQLITE_OK.
  63832. **
  63833. ** A successful evaluation of this routine acquires the mutex on p.
  63834. ** the mutex is released if any kind of error occurs.
  63835. **
  63836. ** The error code stored in database p->db is overwritten with the return
  63837. ** value in any case.
  63838. */
  63839. static int vdbeUnbind(Vdbe *p, int i){
  63840. Mem *pVar;
  63841. if( vdbeSafetyNotNull(p) ){
  63842. return SQLITE_MISUSE_BKPT;
  63843. }
  63844. sqlite3_mutex_enter(p->db->mutex);
  63845. if( p->magic!=VDBE_MAGIC_RUN || p->pc>=0 ){
  63846. sqlite3Error(p->db, SQLITE_MISUSE);
  63847. sqlite3_mutex_leave(p->db->mutex);
  63848. sqlite3_log(SQLITE_MISUSE,
  63849. "bind on a busy prepared statement: [%s]", p->zSql);
  63850. return SQLITE_MISUSE_BKPT;
  63851. }
  63852. if( i<1 || i>p->nVar ){
  63853. sqlite3Error(p->db, SQLITE_RANGE);
  63854. sqlite3_mutex_leave(p->db->mutex);
  63855. return SQLITE_RANGE;
  63856. }
  63857. i--;
  63858. pVar = &p->aVar[i];
  63859. sqlite3VdbeMemRelease(pVar);
  63860. pVar->flags = MEM_Null;
  63861. sqlite3Error(p->db, SQLITE_OK);
  63862. /* If the bit corresponding to this variable in Vdbe.expmask is set, then
  63863. ** binding a new value to this variable invalidates the current query plan.
  63864. **
  63865. ** IMPLEMENTATION-OF: R-48440-37595 If the specific value bound to host
  63866. ** parameter in the WHERE clause might influence the choice of query plan
  63867. ** for a statement, then the statement will be automatically recompiled,
  63868. ** as if there had been a schema change, on the first sqlite3_step() call
  63869. ** following any change to the bindings of that parameter.
  63870. */
  63871. if( p->isPrepareV2 &&
  63872. ((i<32 && p->expmask & ((u32)1 << i)) || p->expmask==0xffffffff)
  63873. ){
  63874. p->expired = 1;
  63875. }
  63876. return SQLITE_OK;
  63877. }
  63878. /*
  63879. ** Bind a text or BLOB value.
  63880. */
  63881. static int bindText(
  63882. sqlite3_stmt *pStmt, /* The statement to bind against */
  63883. int i, /* Index of the parameter to bind */
  63884. const void *zData, /* Pointer to the data to be bound */
  63885. int nData, /* Number of bytes of data to be bound */
  63886. void (*xDel)(void*), /* Destructor for the data */
  63887. u8 encoding /* Encoding for the data */
  63888. ){
  63889. Vdbe *p = (Vdbe *)pStmt;
  63890. Mem *pVar;
  63891. int rc;
  63892. rc = vdbeUnbind(p, i);
  63893. if( rc==SQLITE_OK ){
  63894. if( zData!=0 ){
  63895. pVar = &p->aVar[i-1];
  63896. rc = sqlite3VdbeMemSetStr(pVar, zData, nData, encoding, xDel);
  63897. if( rc==SQLITE_OK && encoding!=0 ){
  63898. rc = sqlite3VdbeChangeEncoding(pVar, ENC(p->db));
  63899. }
  63900. sqlite3Error(p->db, rc);
  63901. rc = sqlite3ApiExit(p->db, rc);
  63902. }
  63903. sqlite3_mutex_leave(p->db->mutex);
  63904. }else if( xDel!=SQLITE_STATIC && xDel!=SQLITE_TRANSIENT ){
  63905. xDel((void*)zData);
  63906. }
  63907. return rc;
  63908. }
  63909. /*
  63910. ** Bind a blob value to an SQL statement variable.
  63911. */
  63912. SQLITE_API int sqlite3_bind_blob(
  63913. sqlite3_stmt *pStmt,
  63914. int i,
  63915. const void *zData,
  63916. int nData,
  63917. void (*xDel)(void*)
  63918. ){
  63919. return bindText(pStmt, i, zData, nData, xDel, 0);
  63920. }
  63921. SQLITE_API int sqlite3_bind_blob64(
  63922. sqlite3_stmt *pStmt,
  63923. int i,
  63924. const void *zData,
  63925. sqlite3_uint64 nData,
  63926. void (*xDel)(void*)
  63927. ){
  63928. assert( xDel!=SQLITE_DYNAMIC );
  63929. if( nData>0x7fffffff ){
  63930. return invokeValueDestructor(zData, xDel, 0);
  63931. }else{
  63932. return bindText(pStmt, i, zData, (int)nData, xDel, 0);
  63933. }
  63934. }
  63935. SQLITE_API int sqlite3_bind_double(sqlite3_stmt *pStmt, int i, double rValue){
  63936. int rc;
  63937. Vdbe *p = (Vdbe *)pStmt;
  63938. rc = vdbeUnbind(p, i);
  63939. if( rc==SQLITE_OK ){
  63940. sqlite3VdbeMemSetDouble(&p->aVar[i-1], rValue);
  63941. sqlite3_mutex_leave(p->db->mutex);
  63942. }
  63943. return rc;
  63944. }
  63945. SQLITE_API int sqlite3_bind_int(sqlite3_stmt *p, int i, int iValue){
  63946. return sqlite3_bind_int64(p, i, (i64)iValue);
  63947. }
  63948. SQLITE_API int sqlite3_bind_int64(sqlite3_stmt *pStmt, int i, sqlite_int64 iValue){
  63949. int rc;
  63950. Vdbe *p = (Vdbe *)pStmt;
  63951. rc = vdbeUnbind(p, i);
  63952. if( rc==SQLITE_OK ){
  63953. sqlite3VdbeMemSetInt64(&p->aVar[i-1], iValue);
  63954. sqlite3_mutex_leave(p->db->mutex);
  63955. }
  63956. return rc;
  63957. }
  63958. SQLITE_API int sqlite3_bind_null(sqlite3_stmt *pStmt, int i){
  63959. int rc;
  63960. Vdbe *p = (Vdbe*)pStmt;
  63961. rc = vdbeUnbind(p, i);
  63962. if( rc==SQLITE_OK ){
  63963. sqlite3_mutex_leave(p->db->mutex);
  63964. }
  63965. return rc;
  63966. }
  63967. SQLITE_API int sqlite3_bind_text(
  63968. sqlite3_stmt *pStmt,
  63969. int i,
  63970. const char *zData,
  63971. int nData,
  63972. void (*xDel)(void*)
  63973. ){
  63974. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF8);
  63975. }
  63976. SQLITE_API int sqlite3_bind_text64(
  63977. sqlite3_stmt *pStmt,
  63978. int i,
  63979. const char *zData,
  63980. sqlite3_uint64 nData,
  63981. void (*xDel)(void*),
  63982. unsigned char enc
  63983. ){
  63984. assert( xDel!=SQLITE_DYNAMIC );
  63985. if( nData>0x7fffffff ){
  63986. return invokeValueDestructor(zData, xDel, 0);
  63987. }else{
  63988. if( enc==SQLITE_UTF16 ) enc = SQLITE_UTF16NATIVE;
  63989. return bindText(pStmt, i, zData, (int)nData, xDel, enc);
  63990. }
  63991. }
  63992. #ifndef SQLITE_OMIT_UTF16
  63993. SQLITE_API int sqlite3_bind_text16(
  63994. sqlite3_stmt *pStmt,
  63995. int i,
  63996. const void *zData,
  63997. int nData,
  63998. void (*xDel)(void*)
  63999. ){
  64000. return bindText(pStmt, i, zData, nData, xDel, SQLITE_UTF16NATIVE);
  64001. }
  64002. #endif /* SQLITE_OMIT_UTF16 */
  64003. SQLITE_API int sqlite3_bind_value(sqlite3_stmt *pStmt, int i, const sqlite3_value *pValue){
  64004. int rc;
  64005. switch( sqlite3_value_type((sqlite3_value*)pValue) ){
  64006. case SQLITE_INTEGER: {
  64007. rc = sqlite3_bind_int64(pStmt, i, pValue->u.i);
  64008. break;
  64009. }
  64010. case SQLITE_FLOAT: {
  64011. rc = sqlite3_bind_double(pStmt, i, pValue->u.r);
  64012. break;
  64013. }
  64014. case SQLITE_BLOB: {
  64015. if( pValue->flags & MEM_Zero ){
  64016. rc = sqlite3_bind_zeroblob(pStmt, i, pValue->u.nZero);
  64017. }else{
  64018. rc = sqlite3_bind_blob(pStmt, i, pValue->z, pValue->n,SQLITE_TRANSIENT);
  64019. }
  64020. break;
  64021. }
  64022. case SQLITE_TEXT: {
  64023. rc = bindText(pStmt,i, pValue->z, pValue->n, SQLITE_TRANSIENT,
  64024. pValue->enc);
  64025. break;
  64026. }
  64027. default: {
  64028. rc = sqlite3_bind_null(pStmt, i);
  64029. break;
  64030. }
  64031. }
  64032. return rc;
  64033. }
  64034. SQLITE_API int sqlite3_bind_zeroblob(sqlite3_stmt *pStmt, int i, int n){
  64035. int rc;
  64036. Vdbe *p = (Vdbe *)pStmt;
  64037. rc = vdbeUnbind(p, i);
  64038. if( rc==SQLITE_OK ){
  64039. sqlite3VdbeMemSetZeroBlob(&p->aVar[i-1], n);
  64040. sqlite3_mutex_leave(p->db->mutex);
  64041. }
  64042. return rc;
  64043. }
  64044. /*
  64045. ** Return the number of wildcards that can be potentially bound to.
  64046. ** This routine is added to support DBD::SQLite.
  64047. */
  64048. SQLITE_API int sqlite3_bind_parameter_count(sqlite3_stmt *pStmt){
  64049. Vdbe *p = (Vdbe*)pStmt;
  64050. return p ? p->nVar : 0;
  64051. }
  64052. /*
  64053. ** Return the name of a wildcard parameter. Return NULL if the index
  64054. ** is out of range or if the wildcard is unnamed.
  64055. **
  64056. ** The result is always UTF-8.
  64057. */
  64058. SQLITE_API const char *sqlite3_bind_parameter_name(sqlite3_stmt *pStmt, int i){
  64059. Vdbe *p = (Vdbe*)pStmt;
  64060. if( p==0 || i<1 || i>p->nzVar ){
  64061. return 0;
  64062. }
  64063. return p->azVar[i-1];
  64064. }
  64065. /*
  64066. ** Given a wildcard parameter name, return the index of the variable
  64067. ** with that name. If there is no variable with the given name,
  64068. ** return 0.
  64069. */
  64070. SQLITE_PRIVATE int sqlite3VdbeParameterIndex(Vdbe *p, const char *zName, int nName){
  64071. int i;
  64072. if( p==0 ){
  64073. return 0;
  64074. }
  64075. if( zName ){
  64076. for(i=0; i<p->nzVar; i++){
  64077. const char *z = p->azVar[i];
  64078. if( z && strncmp(z,zName,nName)==0 && z[nName]==0 ){
  64079. return i+1;
  64080. }
  64081. }
  64082. }
  64083. return 0;
  64084. }
  64085. SQLITE_API int sqlite3_bind_parameter_index(sqlite3_stmt *pStmt, const char *zName){
  64086. return sqlite3VdbeParameterIndex((Vdbe*)pStmt, zName, sqlite3Strlen30(zName));
  64087. }
  64088. /*
  64089. ** Transfer all bindings from the first statement over to the second.
  64090. */
  64091. SQLITE_PRIVATE int sqlite3TransferBindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  64092. Vdbe *pFrom = (Vdbe*)pFromStmt;
  64093. Vdbe *pTo = (Vdbe*)pToStmt;
  64094. int i;
  64095. assert( pTo->db==pFrom->db );
  64096. assert( pTo->nVar==pFrom->nVar );
  64097. sqlite3_mutex_enter(pTo->db->mutex);
  64098. for(i=0; i<pFrom->nVar; i++){
  64099. sqlite3VdbeMemMove(&pTo->aVar[i], &pFrom->aVar[i]);
  64100. }
  64101. sqlite3_mutex_leave(pTo->db->mutex);
  64102. return SQLITE_OK;
  64103. }
  64104. #ifndef SQLITE_OMIT_DEPRECATED
  64105. /*
  64106. ** Deprecated external interface. Internal/core SQLite code
  64107. ** should call sqlite3TransferBindings.
  64108. **
  64109. ** It is misuse to call this routine with statements from different
  64110. ** database connections. But as this is a deprecated interface, we
  64111. ** will not bother to check for that condition.
  64112. **
  64113. ** If the two statements contain a different number of bindings, then
  64114. ** an SQLITE_ERROR is returned. Nothing else can go wrong, so otherwise
  64115. ** SQLITE_OK is returned.
  64116. */
  64117. SQLITE_API int sqlite3_transfer_bindings(sqlite3_stmt *pFromStmt, sqlite3_stmt *pToStmt){
  64118. Vdbe *pFrom = (Vdbe*)pFromStmt;
  64119. Vdbe *pTo = (Vdbe*)pToStmt;
  64120. if( pFrom->nVar!=pTo->nVar ){
  64121. return SQLITE_ERROR;
  64122. }
  64123. if( pTo->isPrepareV2 && pTo->expmask ){
  64124. pTo->expired = 1;
  64125. }
  64126. if( pFrom->isPrepareV2 && pFrom->expmask ){
  64127. pFrom->expired = 1;
  64128. }
  64129. return sqlite3TransferBindings(pFromStmt, pToStmt);
  64130. }
  64131. #endif
  64132. /*
  64133. ** Return the sqlite3* database handle to which the prepared statement given
  64134. ** in the argument belongs. This is the same database handle that was
  64135. ** the first argument to the sqlite3_prepare() that was used to create
  64136. ** the statement in the first place.
  64137. */
  64138. SQLITE_API sqlite3 *sqlite3_db_handle(sqlite3_stmt *pStmt){
  64139. return pStmt ? ((Vdbe*)pStmt)->db : 0;
  64140. }
  64141. /*
  64142. ** Return true if the prepared statement is guaranteed to not modify the
  64143. ** database.
  64144. */
  64145. SQLITE_API int sqlite3_stmt_readonly(sqlite3_stmt *pStmt){
  64146. return pStmt ? ((Vdbe*)pStmt)->readOnly : 1;
  64147. }
  64148. /*
  64149. ** Return true if the prepared statement is in need of being reset.
  64150. */
  64151. SQLITE_API int sqlite3_stmt_busy(sqlite3_stmt *pStmt){
  64152. Vdbe *v = (Vdbe*)pStmt;
  64153. return v!=0 && v->pc>=0 && v->magic==VDBE_MAGIC_RUN;
  64154. }
  64155. /*
  64156. ** Return a pointer to the next prepared statement after pStmt associated
  64157. ** with database connection pDb. If pStmt is NULL, return the first
  64158. ** prepared statement for the database connection. Return NULL if there
  64159. ** are no more.
  64160. */
  64161. SQLITE_API sqlite3_stmt *sqlite3_next_stmt(sqlite3 *pDb, sqlite3_stmt *pStmt){
  64162. sqlite3_stmt *pNext;
  64163. sqlite3_mutex_enter(pDb->mutex);
  64164. if( pStmt==0 ){
  64165. pNext = (sqlite3_stmt*)pDb->pVdbe;
  64166. }else{
  64167. pNext = (sqlite3_stmt*)((Vdbe*)pStmt)->pNext;
  64168. }
  64169. sqlite3_mutex_leave(pDb->mutex);
  64170. return pNext;
  64171. }
  64172. /*
  64173. ** Return the value of a status counter for a prepared statement
  64174. */
  64175. SQLITE_API int sqlite3_stmt_status(sqlite3_stmt *pStmt, int op, int resetFlag){
  64176. Vdbe *pVdbe = (Vdbe*)pStmt;
  64177. u32 v = pVdbe->aCounter[op];
  64178. if( resetFlag ) pVdbe->aCounter[op] = 0;
  64179. return (int)v;
  64180. }
  64181. /************** End of vdbeapi.c *********************************************/
  64182. /************** Begin file vdbetrace.c ***************************************/
  64183. /*
  64184. ** 2009 November 25
  64185. **
  64186. ** The author disclaims copyright to this source code. In place of
  64187. ** a legal notice, here is a blessing:
  64188. **
  64189. ** May you do good and not evil.
  64190. ** May you find forgiveness for yourself and forgive others.
  64191. ** May you share freely, never taking more than you give.
  64192. **
  64193. *************************************************************************
  64194. **
  64195. ** This file contains code used to insert the values of host parameters
  64196. ** (aka "wildcards") into the SQL text output by sqlite3_trace().
  64197. **
  64198. ** The Vdbe parse-tree explainer is also found here.
  64199. */
  64200. #ifndef SQLITE_OMIT_TRACE
  64201. /*
  64202. ** zSql is a zero-terminated string of UTF-8 SQL text. Return the number of
  64203. ** bytes in this text up to but excluding the first character in
  64204. ** a host parameter. If the text contains no host parameters, return
  64205. ** the total number of bytes in the text.
  64206. */
  64207. static int findNextHostParameter(const char *zSql, int *pnToken){
  64208. int tokenType;
  64209. int nTotal = 0;
  64210. int n;
  64211. *pnToken = 0;
  64212. while( zSql[0] ){
  64213. n = sqlite3GetToken((u8*)zSql, &tokenType);
  64214. assert( n>0 && tokenType!=TK_ILLEGAL );
  64215. if( tokenType==TK_VARIABLE ){
  64216. *pnToken = n;
  64217. break;
  64218. }
  64219. nTotal += n;
  64220. zSql += n;
  64221. }
  64222. return nTotal;
  64223. }
  64224. /*
  64225. ** This function returns a pointer to a nul-terminated string in memory
  64226. ** obtained from sqlite3DbMalloc(). If sqlite3.nVdbeExec is 1, then the
  64227. ** string contains a copy of zRawSql but with host parameters expanded to
  64228. ** their current bindings. Or, if sqlite3.nVdbeExec is greater than 1,
  64229. ** then the returned string holds a copy of zRawSql with "-- " prepended
  64230. ** to each line of text.
  64231. **
  64232. ** If the SQLITE_TRACE_SIZE_LIMIT macro is defined to an integer, then
  64233. ** then long strings and blobs are truncated to that many bytes. This
  64234. ** can be used to prevent unreasonably large trace strings when dealing
  64235. ** with large (multi-megabyte) strings and blobs.
  64236. **
  64237. ** The calling function is responsible for making sure the memory returned
  64238. ** is eventually freed.
  64239. **
  64240. ** ALGORITHM: Scan the input string looking for host parameters in any of
  64241. ** these forms: ?, ?N, $A, @A, :A. Take care to avoid text within
  64242. ** string literals, quoted identifier names, and comments. For text forms,
  64243. ** the host parameter index is found by scanning the prepared
  64244. ** statement for the corresponding OP_Variable opcode. Once the host
  64245. ** parameter index is known, locate the value in p->aVar[]. Then render
  64246. ** the value as a literal in place of the host parameter name.
  64247. */
  64248. SQLITE_PRIVATE char *sqlite3VdbeExpandSql(
  64249. Vdbe *p, /* The prepared statement being evaluated */
  64250. const char *zRawSql /* Raw text of the SQL statement */
  64251. ){
  64252. sqlite3 *db; /* The database connection */
  64253. int idx = 0; /* Index of a host parameter */
  64254. int nextIndex = 1; /* Index of next ? host parameter */
  64255. int n; /* Length of a token prefix */
  64256. int nToken; /* Length of the parameter token */
  64257. int i; /* Loop counter */
  64258. Mem *pVar; /* Value of a host parameter */
  64259. StrAccum out; /* Accumulate the output here */
  64260. char zBase[100]; /* Initial working space */
  64261. db = p->db;
  64262. sqlite3StrAccumInit(&out, zBase, sizeof(zBase),
  64263. db->aLimit[SQLITE_LIMIT_LENGTH]);
  64264. out.db = db;
  64265. if( db->nVdbeExec>1 ){
  64266. while( *zRawSql ){
  64267. const char *zStart = zRawSql;
  64268. while( *(zRawSql++)!='\n' && *zRawSql );
  64269. sqlite3StrAccumAppend(&out, "-- ", 3);
  64270. assert( (zRawSql - zStart) > 0 );
  64271. sqlite3StrAccumAppend(&out, zStart, (int)(zRawSql-zStart));
  64272. }
  64273. }else{
  64274. while( zRawSql[0] ){
  64275. n = findNextHostParameter(zRawSql, &nToken);
  64276. assert( n>0 );
  64277. sqlite3StrAccumAppend(&out, zRawSql, n);
  64278. zRawSql += n;
  64279. assert( zRawSql[0] || nToken==0 );
  64280. if( nToken==0 ) break;
  64281. if( zRawSql[0]=='?' ){
  64282. if( nToken>1 ){
  64283. assert( sqlite3Isdigit(zRawSql[1]) );
  64284. sqlite3GetInt32(&zRawSql[1], &idx);
  64285. }else{
  64286. idx = nextIndex;
  64287. }
  64288. }else{
  64289. assert( zRawSql[0]==':' || zRawSql[0]=='$' || zRawSql[0]=='@' );
  64290. testcase( zRawSql[0]==':' );
  64291. testcase( zRawSql[0]=='$' );
  64292. testcase( zRawSql[0]=='@' );
  64293. idx = sqlite3VdbeParameterIndex(p, zRawSql, nToken);
  64294. assert( idx>0 );
  64295. }
  64296. zRawSql += nToken;
  64297. nextIndex = idx + 1;
  64298. assert( idx>0 && idx<=p->nVar );
  64299. pVar = &p->aVar[idx-1];
  64300. if( pVar->flags & MEM_Null ){
  64301. sqlite3StrAccumAppend(&out, "NULL", 4);
  64302. }else if( pVar->flags & MEM_Int ){
  64303. sqlite3XPrintf(&out, 0, "%lld", pVar->u.i);
  64304. }else if( pVar->flags & MEM_Real ){
  64305. sqlite3XPrintf(&out, 0, "%!.15g", pVar->u.r);
  64306. }else if( pVar->flags & MEM_Str ){
  64307. int nOut; /* Number of bytes of the string text to include in output */
  64308. #ifndef SQLITE_OMIT_UTF16
  64309. u8 enc = ENC(db);
  64310. Mem utf8;
  64311. if( enc!=SQLITE_UTF8 ){
  64312. memset(&utf8, 0, sizeof(utf8));
  64313. utf8.db = db;
  64314. sqlite3VdbeMemSetStr(&utf8, pVar->z, pVar->n, enc, SQLITE_STATIC);
  64315. sqlite3VdbeChangeEncoding(&utf8, SQLITE_UTF8);
  64316. pVar = &utf8;
  64317. }
  64318. #endif
  64319. nOut = pVar->n;
  64320. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64321. if( nOut>SQLITE_TRACE_SIZE_LIMIT ){
  64322. nOut = SQLITE_TRACE_SIZE_LIMIT;
  64323. while( nOut<pVar->n && (pVar->z[nOut]&0xc0)==0x80 ){ nOut++; }
  64324. }
  64325. #endif
  64326. sqlite3XPrintf(&out, 0, "'%.*q'", nOut, pVar->z);
  64327. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64328. if( nOut<pVar->n ){
  64329. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  64330. }
  64331. #endif
  64332. #ifndef SQLITE_OMIT_UTF16
  64333. if( enc!=SQLITE_UTF8 ) sqlite3VdbeMemRelease(&utf8);
  64334. #endif
  64335. }else if( pVar->flags & MEM_Zero ){
  64336. sqlite3XPrintf(&out, 0, "zeroblob(%d)", pVar->u.nZero);
  64337. }else{
  64338. int nOut; /* Number of bytes of the blob to include in output */
  64339. assert( pVar->flags & MEM_Blob );
  64340. sqlite3StrAccumAppend(&out, "x'", 2);
  64341. nOut = pVar->n;
  64342. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64343. if( nOut>SQLITE_TRACE_SIZE_LIMIT ) nOut = SQLITE_TRACE_SIZE_LIMIT;
  64344. #endif
  64345. for(i=0; i<nOut; i++){
  64346. sqlite3XPrintf(&out, 0, "%02x", pVar->z[i]&0xff);
  64347. }
  64348. sqlite3StrAccumAppend(&out, "'", 1);
  64349. #ifdef SQLITE_TRACE_SIZE_LIMIT
  64350. if( nOut<pVar->n ){
  64351. sqlite3XPrintf(&out, 0, "/*+%d bytes*/", pVar->n-nOut);
  64352. }
  64353. #endif
  64354. }
  64355. }
  64356. }
  64357. return sqlite3StrAccumFinish(&out);
  64358. }
  64359. #endif /* #ifndef SQLITE_OMIT_TRACE */
  64360. /************** End of vdbetrace.c *******************************************/
  64361. /************** Begin file vdbe.c ********************************************/
  64362. /*
  64363. ** 2001 September 15
  64364. **
  64365. ** The author disclaims copyright to this source code. In place of
  64366. ** a legal notice, here is a blessing:
  64367. **
  64368. ** May you do good and not evil.
  64369. ** May you find forgiveness for yourself and forgive others.
  64370. ** May you share freely, never taking more than you give.
  64371. **
  64372. *************************************************************************
  64373. ** The code in this file implements the function that runs the
  64374. ** bytecode of a prepared statement.
  64375. **
  64376. ** Various scripts scan this source file in order to generate HTML
  64377. ** documentation, headers files, or other derived files. The formatting
  64378. ** of the code in this file is, therefore, important. See other comments
  64379. ** in this file for details. If in doubt, do not deviate from existing
  64380. ** commenting and indentation practices when changing or adding code.
  64381. */
  64382. /*
  64383. ** Invoke this macro on memory cells just prior to changing the
  64384. ** value of the cell. This macro verifies that shallow copies are
  64385. ** not misused. A shallow copy of a string or blob just copies a
  64386. ** pointer to the string or blob, not the content. If the original
  64387. ** is changed while the copy is still in use, the string or blob might
  64388. ** be changed out from under the copy. This macro verifies that nothing
  64389. ** like that ever happens.
  64390. */
  64391. #ifdef SQLITE_DEBUG
  64392. # define memAboutToChange(P,M) sqlite3VdbeMemAboutToChange(P,M)
  64393. #else
  64394. # define memAboutToChange(P,M)
  64395. #endif
  64396. /*
  64397. ** The following global variable is incremented every time a cursor
  64398. ** moves, either by the OP_SeekXX, OP_Next, or OP_Prev opcodes. The test
  64399. ** procedures use this information to make sure that indices are
  64400. ** working correctly. This variable has no function other than to
  64401. ** help verify the correct operation of the library.
  64402. */
  64403. #ifdef SQLITE_TEST
  64404. SQLITE_API int sqlite3_search_count = 0;
  64405. #endif
  64406. /*
  64407. ** When this global variable is positive, it gets decremented once before
  64408. ** each instruction in the VDBE. When it reaches zero, the u1.isInterrupted
  64409. ** field of the sqlite3 structure is set in order to simulate an interrupt.
  64410. **
  64411. ** This facility is used for testing purposes only. It does not function
  64412. ** in an ordinary build.
  64413. */
  64414. #ifdef SQLITE_TEST
  64415. SQLITE_API int sqlite3_interrupt_count = 0;
  64416. #endif
  64417. /*
  64418. ** The next global variable is incremented each type the OP_Sort opcode
  64419. ** is executed. The test procedures use this information to make sure that
  64420. ** sorting is occurring or not occurring at appropriate times. This variable
  64421. ** has no function other than to help verify the correct operation of the
  64422. ** library.
  64423. */
  64424. #ifdef SQLITE_TEST
  64425. SQLITE_API int sqlite3_sort_count = 0;
  64426. #endif
  64427. /*
  64428. ** The next global variable records the size of the largest MEM_Blob
  64429. ** or MEM_Str that has been used by a VDBE opcode. The test procedures
  64430. ** use this information to make sure that the zero-blob functionality
  64431. ** is working correctly. This variable has no function other than to
  64432. ** help verify the correct operation of the library.
  64433. */
  64434. #ifdef SQLITE_TEST
  64435. SQLITE_API int sqlite3_max_blobsize = 0;
  64436. static void updateMaxBlobsize(Mem *p){
  64437. if( (p->flags & (MEM_Str|MEM_Blob))!=0 && p->n>sqlite3_max_blobsize ){
  64438. sqlite3_max_blobsize = p->n;
  64439. }
  64440. }
  64441. #endif
  64442. /*
  64443. ** The next global variable is incremented each time the OP_Found opcode
  64444. ** is executed. This is used to test whether or not the foreign key
  64445. ** operation implemented using OP_FkIsZero is working. This variable
  64446. ** has no function other than to help verify the correct operation of the
  64447. ** library.
  64448. */
  64449. #ifdef SQLITE_TEST
  64450. SQLITE_API int sqlite3_found_count = 0;
  64451. #endif
  64452. /*
  64453. ** Test a register to see if it exceeds the current maximum blob size.
  64454. ** If it does, record the new maximum blob size.
  64455. */
  64456. #if defined(SQLITE_TEST) && !defined(SQLITE_OMIT_BUILTIN_TEST)
  64457. # define UPDATE_MAX_BLOBSIZE(P) updateMaxBlobsize(P)
  64458. #else
  64459. # define UPDATE_MAX_BLOBSIZE(P)
  64460. #endif
  64461. /*
  64462. ** Invoke the VDBE coverage callback, if that callback is defined. This
  64463. ** feature is used for test suite validation only and does not appear an
  64464. ** production builds.
  64465. **
  64466. ** M is an integer, 2 or 3, that indices how many different ways the
  64467. ** branch can go. It is usually 2. "I" is the direction the branch
  64468. ** goes. 0 means falls through. 1 means branch is taken. 2 means the
  64469. ** second alternative branch is taken.
  64470. **
  64471. ** iSrcLine is the source code line (from the __LINE__ macro) that
  64472. ** generated the VDBE instruction. This instrumentation assumes that all
  64473. ** source code is in a single file (the amalgamation). Special values 1
  64474. ** and 2 for the iSrcLine parameter mean that this particular branch is
  64475. ** always taken or never taken, respectively.
  64476. */
  64477. #if !defined(SQLITE_VDBE_COVERAGE)
  64478. # define VdbeBranchTaken(I,M)
  64479. #else
  64480. # define VdbeBranchTaken(I,M) vdbeTakeBranch(pOp->iSrcLine,I,M)
  64481. static void vdbeTakeBranch(int iSrcLine, u8 I, u8 M){
  64482. if( iSrcLine<=2 && ALWAYS(iSrcLine>0) ){
  64483. M = iSrcLine;
  64484. /* Assert the truth of VdbeCoverageAlwaysTaken() and
  64485. ** VdbeCoverageNeverTaken() */
  64486. assert( (M & I)==I );
  64487. }else{
  64488. if( sqlite3GlobalConfig.xVdbeBranch==0 ) return; /*NO_TEST*/
  64489. sqlite3GlobalConfig.xVdbeBranch(sqlite3GlobalConfig.pVdbeBranchArg,
  64490. iSrcLine,I,M);
  64491. }
  64492. }
  64493. #endif
  64494. /*
  64495. ** Convert the given register into a string if it isn't one
  64496. ** already. Return non-zero if a malloc() fails.
  64497. */
  64498. #define Stringify(P, enc) \
  64499. if(((P)->flags&(MEM_Str|MEM_Blob))==0 && sqlite3VdbeMemStringify(P,enc,0)) \
  64500. { goto no_mem; }
  64501. /*
  64502. ** An ephemeral string value (signified by the MEM_Ephem flag) contains
  64503. ** a pointer to a dynamically allocated string where some other entity
  64504. ** is responsible for deallocating that string. Because the register
  64505. ** does not control the string, it might be deleted without the register
  64506. ** knowing it.
  64507. **
  64508. ** This routine converts an ephemeral string into a dynamically allocated
  64509. ** string that the register itself controls. In other words, it
  64510. ** converts an MEM_Ephem string into a string with P.z==P.zMalloc.
  64511. */
  64512. #define Deephemeralize(P) \
  64513. if( ((P)->flags&MEM_Ephem)!=0 \
  64514. && sqlite3VdbeMemMakeWriteable(P) ){ goto no_mem;}
  64515. /* Return true if the cursor was opened using the OP_OpenSorter opcode. */
  64516. #define isSorter(x) ((x)->pSorter!=0)
  64517. /*
  64518. ** Allocate VdbeCursor number iCur. Return a pointer to it. Return NULL
  64519. ** if we run out of memory.
  64520. */
  64521. static VdbeCursor *allocateCursor(
  64522. Vdbe *p, /* The virtual machine */
  64523. int iCur, /* Index of the new VdbeCursor */
  64524. int nField, /* Number of fields in the table or index */
  64525. int iDb, /* Database the cursor belongs to, or -1 */
  64526. int isBtreeCursor /* True for B-Tree. False for pseudo-table or vtab */
  64527. ){
  64528. /* Find the memory cell that will be used to store the blob of memory
  64529. ** required for this VdbeCursor structure. It is convenient to use a
  64530. ** vdbe memory cell to manage the memory allocation required for a
  64531. ** VdbeCursor structure for the following reasons:
  64532. **
  64533. ** * Sometimes cursor numbers are used for a couple of different
  64534. ** purposes in a vdbe program. The different uses might require
  64535. ** different sized allocations. Memory cells provide growable
  64536. ** allocations.
  64537. **
  64538. ** * When using ENABLE_MEMORY_MANAGEMENT, memory cell buffers can
  64539. ** be freed lazily via the sqlite3_release_memory() API. This
  64540. ** minimizes the number of malloc calls made by the system.
  64541. **
  64542. ** Memory cells for cursors are allocated at the top of the address
  64543. ** space. Memory cell (p->nMem) corresponds to cursor 0. Space for
  64544. ** cursor 1 is managed by memory cell (p->nMem-1), etc.
  64545. */
  64546. Mem *pMem = &p->aMem[p->nMem-iCur];
  64547. int nByte;
  64548. VdbeCursor *pCx = 0;
  64549. nByte =
  64550. ROUND8(sizeof(VdbeCursor)) + 2*sizeof(u32)*nField +
  64551. (isBtreeCursor?sqlite3BtreeCursorSize():0);
  64552. assert( iCur<p->nCursor );
  64553. if( p->apCsr[iCur] ){
  64554. sqlite3VdbeFreeCursor(p, p->apCsr[iCur]);
  64555. p->apCsr[iCur] = 0;
  64556. }
  64557. if( SQLITE_OK==sqlite3VdbeMemClearAndResize(pMem, nByte) ){
  64558. p->apCsr[iCur] = pCx = (VdbeCursor*)pMem->z;
  64559. memset(pCx, 0, sizeof(VdbeCursor));
  64560. pCx->iDb = iDb;
  64561. pCx->nField = nField;
  64562. pCx->aOffset = &pCx->aType[nField];
  64563. if( isBtreeCursor ){
  64564. pCx->pCursor = (BtCursor*)
  64565. &pMem->z[ROUND8(sizeof(VdbeCursor))+2*sizeof(u32)*nField];
  64566. sqlite3BtreeCursorZero(pCx->pCursor);
  64567. }
  64568. }
  64569. return pCx;
  64570. }
  64571. /*
  64572. ** Try to convert a value into a numeric representation if we can
  64573. ** do so without loss of information. In other words, if the string
  64574. ** looks like a number, convert it into a number. If it does not
  64575. ** look like a number, leave it alone.
  64576. **
  64577. ** If the bTryForInt flag is true, then extra effort is made to give
  64578. ** an integer representation. Strings that look like floating point
  64579. ** values but which have no fractional component (example: '48.00')
  64580. ** will have a MEM_Int representation when bTryForInt is true.
  64581. **
  64582. ** If bTryForInt is false, then if the input string contains a decimal
  64583. ** point or exponential notation, the result is only MEM_Real, even
  64584. ** if there is an exact integer representation of the quantity.
  64585. */
  64586. static void applyNumericAffinity(Mem *pRec, int bTryForInt){
  64587. double rValue;
  64588. i64 iValue;
  64589. u8 enc = pRec->enc;
  64590. assert( (pRec->flags & (MEM_Str|MEM_Int|MEM_Real))==MEM_Str );
  64591. if( sqlite3AtoF(pRec->z, &rValue, pRec->n, enc)==0 ) return;
  64592. if( 0==sqlite3Atoi64(pRec->z, &iValue, pRec->n, enc) ){
  64593. pRec->u.i = iValue;
  64594. pRec->flags |= MEM_Int;
  64595. }else{
  64596. pRec->u.r = rValue;
  64597. pRec->flags |= MEM_Real;
  64598. if( bTryForInt ) sqlite3VdbeIntegerAffinity(pRec);
  64599. }
  64600. }
  64601. /*
  64602. ** Processing is determine by the affinity parameter:
  64603. **
  64604. ** SQLITE_AFF_INTEGER:
  64605. ** SQLITE_AFF_REAL:
  64606. ** SQLITE_AFF_NUMERIC:
  64607. ** Try to convert pRec to an integer representation or a
  64608. ** floating-point representation if an integer representation
  64609. ** is not possible. Note that the integer representation is
  64610. ** always preferred, even if the affinity is REAL, because
  64611. ** an integer representation is more space efficient on disk.
  64612. **
  64613. ** SQLITE_AFF_TEXT:
  64614. ** Convert pRec to a text representation.
  64615. **
  64616. ** SQLITE_AFF_NONE:
  64617. ** No-op. pRec is unchanged.
  64618. */
  64619. static void applyAffinity(
  64620. Mem *pRec, /* The value to apply affinity to */
  64621. char affinity, /* The affinity to be applied */
  64622. u8 enc /* Use this text encoding */
  64623. ){
  64624. if( affinity>=SQLITE_AFF_NUMERIC ){
  64625. assert( affinity==SQLITE_AFF_INTEGER || affinity==SQLITE_AFF_REAL
  64626. || affinity==SQLITE_AFF_NUMERIC );
  64627. if( (pRec->flags & MEM_Int)==0 ){
  64628. if( (pRec->flags & MEM_Real)==0 ){
  64629. if( pRec->flags & MEM_Str ) applyNumericAffinity(pRec,1);
  64630. }else{
  64631. sqlite3VdbeIntegerAffinity(pRec);
  64632. }
  64633. }
  64634. }else if( affinity==SQLITE_AFF_TEXT ){
  64635. /* Only attempt the conversion to TEXT if there is an integer or real
  64636. ** representation (blob and NULL do not get converted) but no string
  64637. ** representation.
  64638. */
  64639. if( 0==(pRec->flags&MEM_Str) && (pRec->flags&(MEM_Real|MEM_Int)) ){
  64640. sqlite3VdbeMemStringify(pRec, enc, 1);
  64641. }
  64642. }
  64643. }
  64644. /*
  64645. ** Try to convert the type of a function argument or a result column
  64646. ** into a numeric representation. Use either INTEGER or REAL whichever
  64647. ** is appropriate. But only do the conversion if it is possible without
  64648. ** loss of information and return the revised type of the argument.
  64649. */
  64650. SQLITE_API int sqlite3_value_numeric_type(sqlite3_value *pVal){
  64651. int eType = sqlite3_value_type(pVal);
  64652. if( eType==SQLITE_TEXT ){
  64653. Mem *pMem = (Mem*)pVal;
  64654. applyNumericAffinity(pMem, 0);
  64655. eType = sqlite3_value_type(pVal);
  64656. }
  64657. return eType;
  64658. }
  64659. /*
  64660. ** Exported version of applyAffinity(). This one works on sqlite3_value*,
  64661. ** not the internal Mem* type.
  64662. */
  64663. SQLITE_PRIVATE void sqlite3ValueApplyAffinity(
  64664. sqlite3_value *pVal,
  64665. u8 affinity,
  64666. u8 enc
  64667. ){
  64668. applyAffinity((Mem *)pVal, affinity, enc);
  64669. }
  64670. /*
  64671. ** pMem currently only holds a string type (or maybe a BLOB that we can
  64672. ** interpret as a string if we want to). Compute its corresponding
  64673. ** numeric type, if has one. Set the pMem->u.r and pMem->u.i fields
  64674. ** accordingly.
  64675. */
  64676. static u16 SQLITE_NOINLINE computeNumericType(Mem *pMem){
  64677. assert( (pMem->flags & (MEM_Int|MEM_Real))==0 );
  64678. assert( (pMem->flags & (MEM_Str|MEM_Blob))!=0 );
  64679. if( sqlite3AtoF(pMem->z, &pMem->u.r, pMem->n, pMem->enc)==0 ){
  64680. return 0;
  64681. }
  64682. if( sqlite3Atoi64(pMem->z, &pMem->u.i, pMem->n, pMem->enc)==SQLITE_OK ){
  64683. return MEM_Int;
  64684. }
  64685. return MEM_Real;
  64686. }
  64687. /*
  64688. ** Return the numeric type for pMem, either MEM_Int or MEM_Real or both or
  64689. ** none.
  64690. **
  64691. ** Unlike applyNumericAffinity(), this routine does not modify pMem->flags.
  64692. ** But it does set pMem->u.r and pMem->u.i appropriately.
  64693. */
  64694. static u16 numericType(Mem *pMem){
  64695. if( pMem->flags & (MEM_Int|MEM_Real) ){
  64696. return pMem->flags & (MEM_Int|MEM_Real);
  64697. }
  64698. if( pMem->flags & (MEM_Str|MEM_Blob) ){
  64699. return computeNumericType(pMem);
  64700. }
  64701. return 0;
  64702. }
  64703. #ifdef SQLITE_DEBUG
  64704. /*
  64705. ** Write a nice string representation of the contents of cell pMem
  64706. ** into buffer zBuf, length nBuf.
  64707. */
  64708. SQLITE_PRIVATE void sqlite3VdbeMemPrettyPrint(Mem *pMem, char *zBuf){
  64709. char *zCsr = zBuf;
  64710. int f = pMem->flags;
  64711. static const char *const encnames[] = {"(X)", "(8)", "(16LE)", "(16BE)"};
  64712. if( f&MEM_Blob ){
  64713. int i;
  64714. char c;
  64715. if( f & MEM_Dyn ){
  64716. c = 'z';
  64717. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  64718. }else if( f & MEM_Static ){
  64719. c = 't';
  64720. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  64721. }else if( f & MEM_Ephem ){
  64722. c = 'e';
  64723. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  64724. }else{
  64725. c = 's';
  64726. }
  64727. sqlite3_snprintf(100, zCsr, "%c", c);
  64728. zCsr += sqlite3Strlen30(zCsr);
  64729. sqlite3_snprintf(100, zCsr, "%d[", pMem->n);
  64730. zCsr += sqlite3Strlen30(zCsr);
  64731. for(i=0; i<16 && i<pMem->n; i++){
  64732. sqlite3_snprintf(100, zCsr, "%02X", ((int)pMem->z[i] & 0xFF));
  64733. zCsr += sqlite3Strlen30(zCsr);
  64734. }
  64735. for(i=0; i<16 && i<pMem->n; i++){
  64736. char z = pMem->z[i];
  64737. if( z<32 || z>126 ) *zCsr++ = '.';
  64738. else *zCsr++ = z;
  64739. }
  64740. sqlite3_snprintf(100, zCsr, "]%s", encnames[pMem->enc]);
  64741. zCsr += sqlite3Strlen30(zCsr);
  64742. if( f & MEM_Zero ){
  64743. sqlite3_snprintf(100, zCsr,"+%dz",pMem->u.nZero);
  64744. zCsr += sqlite3Strlen30(zCsr);
  64745. }
  64746. *zCsr = '\0';
  64747. }else if( f & MEM_Str ){
  64748. int j, k;
  64749. zBuf[0] = ' ';
  64750. if( f & MEM_Dyn ){
  64751. zBuf[1] = 'z';
  64752. assert( (f & (MEM_Static|MEM_Ephem))==0 );
  64753. }else if( f & MEM_Static ){
  64754. zBuf[1] = 't';
  64755. assert( (f & (MEM_Dyn|MEM_Ephem))==0 );
  64756. }else if( f & MEM_Ephem ){
  64757. zBuf[1] = 'e';
  64758. assert( (f & (MEM_Static|MEM_Dyn))==0 );
  64759. }else{
  64760. zBuf[1] = 's';
  64761. }
  64762. k = 2;
  64763. sqlite3_snprintf(100, &zBuf[k], "%d", pMem->n);
  64764. k += sqlite3Strlen30(&zBuf[k]);
  64765. zBuf[k++] = '[';
  64766. for(j=0; j<15 && j<pMem->n; j++){
  64767. u8 c = pMem->z[j];
  64768. if( c>=0x20 && c<0x7f ){
  64769. zBuf[k++] = c;
  64770. }else{
  64771. zBuf[k++] = '.';
  64772. }
  64773. }
  64774. zBuf[k++] = ']';
  64775. sqlite3_snprintf(100,&zBuf[k], encnames[pMem->enc]);
  64776. k += sqlite3Strlen30(&zBuf[k]);
  64777. zBuf[k++] = 0;
  64778. }
  64779. }
  64780. #endif
  64781. #ifdef SQLITE_DEBUG
  64782. /*
  64783. ** Print the value of a register for tracing purposes:
  64784. */
  64785. static void memTracePrint(Mem *p){
  64786. if( p->flags & MEM_Undefined ){
  64787. printf(" undefined");
  64788. }else if( p->flags & MEM_Null ){
  64789. printf(" NULL");
  64790. }else if( (p->flags & (MEM_Int|MEM_Str))==(MEM_Int|MEM_Str) ){
  64791. printf(" si:%lld", p->u.i);
  64792. }else if( p->flags & MEM_Int ){
  64793. printf(" i:%lld", p->u.i);
  64794. #ifndef SQLITE_OMIT_FLOATING_POINT
  64795. }else if( p->flags & MEM_Real ){
  64796. printf(" r:%g", p->u.r);
  64797. #endif
  64798. }else if( p->flags & MEM_RowSet ){
  64799. printf(" (rowset)");
  64800. }else{
  64801. char zBuf[200];
  64802. sqlite3VdbeMemPrettyPrint(p, zBuf);
  64803. printf(" %s", zBuf);
  64804. }
  64805. }
  64806. static void registerTrace(int iReg, Mem *p){
  64807. printf("REG[%d] = ", iReg);
  64808. memTracePrint(p);
  64809. printf("\n");
  64810. }
  64811. #endif
  64812. #ifdef SQLITE_DEBUG
  64813. # define REGISTER_TRACE(R,M) if(db->flags&SQLITE_VdbeTrace)registerTrace(R,M)
  64814. #else
  64815. # define REGISTER_TRACE(R,M)
  64816. #endif
  64817. #ifdef VDBE_PROFILE
  64818. /*
  64819. ** hwtime.h contains inline assembler code for implementing
  64820. ** high-performance timing routines.
  64821. */
  64822. /************** Include hwtime.h in the middle of vdbe.c *********************/
  64823. /************** Begin file hwtime.h ******************************************/
  64824. /*
  64825. ** 2008 May 27
  64826. **
  64827. ** The author disclaims copyright to this source code. In place of
  64828. ** a legal notice, here is a blessing:
  64829. **
  64830. ** May you do good and not evil.
  64831. ** May you find forgiveness for yourself and forgive others.
  64832. ** May you share freely, never taking more than you give.
  64833. **
  64834. ******************************************************************************
  64835. **
  64836. ** This file contains inline asm code for retrieving "high-performance"
  64837. ** counters for x86 class CPUs.
  64838. */
  64839. #ifndef _HWTIME_H_
  64840. #define _HWTIME_H_
  64841. /*
  64842. ** The following routine only works on pentium-class (or newer) processors.
  64843. ** It uses the RDTSC opcode to read the cycle count value out of the
  64844. ** processor and returns that value. This can be used for high-res
  64845. ** profiling.
  64846. */
  64847. #if (defined(__GNUC__) || defined(_MSC_VER)) && \
  64848. (defined(i386) || defined(__i386__) || defined(_M_IX86))
  64849. #if defined(__GNUC__)
  64850. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64851. unsigned int lo, hi;
  64852. __asm__ __volatile__ ("rdtsc" : "=a" (lo), "=d" (hi));
  64853. return (sqlite_uint64)hi << 32 | lo;
  64854. }
  64855. #elif defined(_MSC_VER)
  64856. __declspec(naked) __inline sqlite_uint64 __cdecl sqlite3Hwtime(void){
  64857. __asm {
  64858. rdtsc
  64859. ret ; return value at EDX:EAX
  64860. }
  64861. }
  64862. #endif
  64863. #elif (defined(__GNUC__) && defined(__x86_64__))
  64864. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64865. unsigned long val;
  64866. __asm__ __volatile__ ("rdtsc" : "=A" (val));
  64867. return val;
  64868. }
  64869. #elif (defined(__GNUC__) && defined(__ppc__))
  64870. __inline__ sqlite_uint64 sqlite3Hwtime(void){
  64871. unsigned long long retval;
  64872. unsigned long junk;
  64873. __asm__ __volatile__ ("\n\
  64874. 1: mftbu %1\n\
  64875. mftb %L0\n\
  64876. mftbu %0\n\
  64877. cmpw %0,%1\n\
  64878. bne 1b"
  64879. : "=r" (retval), "=r" (junk));
  64880. return retval;
  64881. }
  64882. #else
  64883. #error Need implementation of sqlite3Hwtime() for your platform.
  64884. /*
  64885. ** To compile without implementing sqlite3Hwtime() for your platform,
  64886. ** you can remove the above #error and use the following
  64887. ** stub function. You will lose timing support for many
  64888. ** of the debugging and testing utilities, but it should at
  64889. ** least compile and run.
  64890. */
  64891. SQLITE_PRIVATE sqlite_uint64 sqlite3Hwtime(void){ return ((sqlite_uint64)0); }
  64892. #endif
  64893. #endif /* !defined(_HWTIME_H_) */
  64894. /************** End of hwtime.h **********************************************/
  64895. /************** Continuing where we left off in vdbe.c ***********************/
  64896. #endif
  64897. #ifndef NDEBUG
  64898. /*
  64899. ** This function is only called from within an assert() expression. It
  64900. ** checks that the sqlite3.nTransaction variable is correctly set to
  64901. ** the number of non-transaction savepoints currently in the
  64902. ** linked list starting at sqlite3.pSavepoint.
  64903. **
  64904. ** Usage:
  64905. **
  64906. ** assert( checkSavepointCount(db) );
  64907. */
  64908. static int checkSavepointCount(sqlite3 *db){
  64909. int n = 0;
  64910. Savepoint *p;
  64911. for(p=db->pSavepoint; p; p=p->pNext) n++;
  64912. assert( n==(db->nSavepoint + db->isTransactionSavepoint) );
  64913. return 1;
  64914. }
  64915. #endif
  64916. /*
  64917. ** Execute as much of a VDBE program as we can.
  64918. ** This is the core of sqlite3_step().
  64919. */
  64920. SQLITE_PRIVATE int sqlite3VdbeExec(
  64921. Vdbe *p /* The VDBE */
  64922. ){
  64923. int pc=0; /* The program counter */
  64924. Op *aOp = p->aOp; /* Copy of p->aOp */
  64925. Op *pOp; /* Current operation */
  64926. int rc = SQLITE_OK; /* Value to return */
  64927. sqlite3 *db = p->db; /* The database */
  64928. u8 resetSchemaOnFault = 0; /* Reset schema after an error if positive */
  64929. u8 encoding = ENC(db); /* The database encoding */
  64930. int iCompare = 0; /* Result of last OP_Compare operation */
  64931. unsigned nVmStep = 0; /* Number of virtual machine steps */
  64932. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  64933. unsigned nProgressLimit = 0;/* Invoke xProgress() when nVmStep reaches this */
  64934. #endif
  64935. Mem *aMem = p->aMem; /* Copy of p->aMem */
  64936. Mem *pIn1 = 0; /* 1st input operand */
  64937. Mem *pIn2 = 0; /* 2nd input operand */
  64938. Mem *pIn3 = 0; /* 3rd input operand */
  64939. Mem *pOut = 0; /* Output operand */
  64940. int *aPermute = 0; /* Permutation of columns for OP_Compare */
  64941. i64 lastRowid = db->lastRowid; /* Saved value of the last insert ROWID */
  64942. #ifdef VDBE_PROFILE
  64943. u64 start; /* CPU clock count at start of opcode */
  64944. #endif
  64945. /*** INSERT STACK UNION HERE ***/
  64946. assert( p->magic==VDBE_MAGIC_RUN ); /* sqlite3_step() verifies this */
  64947. sqlite3VdbeEnter(p);
  64948. if( p->rc==SQLITE_NOMEM ){
  64949. /* This happens if a malloc() inside a call to sqlite3_column_text() or
  64950. ** sqlite3_column_text16() failed. */
  64951. goto no_mem;
  64952. }
  64953. assert( p->rc==SQLITE_OK || p->rc==SQLITE_BUSY );
  64954. assert( p->bIsReader || p->readOnly!=0 );
  64955. p->rc = SQLITE_OK;
  64956. p->iCurrentTime = 0;
  64957. assert( p->explain==0 );
  64958. p->pResultSet = 0;
  64959. db->busyHandler.nBusy = 0;
  64960. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  64961. sqlite3VdbeIOTraceSql(p);
  64962. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  64963. if( db->xProgress ){
  64964. assert( 0 < db->nProgressOps );
  64965. nProgressLimit = (unsigned)p->aCounter[SQLITE_STMTSTATUS_VM_STEP];
  64966. if( nProgressLimit==0 ){
  64967. nProgressLimit = db->nProgressOps;
  64968. }else{
  64969. nProgressLimit %= (unsigned)db->nProgressOps;
  64970. }
  64971. }
  64972. #endif
  64973. #ifdef SQLITE_DEBUG
  64974. sqlite3BeginBenignMalloc();
  64975. if( p->pc==0
  64976. && (p->db->flags & (SQLITE_VdbeListing|SQLITE_VdbeEQP|SQLITE_VdbeTrace))!=0
  64977. ){
  64978. int i;
  64979. int once = 1;
  64980. sqlite3VdbePrintSql(p);
  64981. if( p->db->flags & SQLITE_VdbeListing ){
  64982. printf("VDBE Program Listing:\n");
  64983. for(i=0; i<p->nOp; i++){
  64984. sqlite3VdbePrintOp(stdout, i, &aOp[i]);
  64985. }
  64986. }
  64987. if( p->db->flags & SQLITE_VdbeEQP ){
  64988. for(i=0; i<p->nOp; i++){
  64989. if( aOp[i].opcode==OP_Explain ){
  64990. if( once ) printf("VDBE Query Plan:\n");
  64991. printf("%s\n", aOp[i].p4.z);
  64992. once = 0;
  64993. }
  64994. }
  64995. }
  64996. if( p->db->flags & SQLITE_VdbeTrace ) printf("VDBE Trace:\n");
  64997. }
  64998. sqlite3EndBenignMalloc();
  64999. #endif
  65000. for(pc=p->pc; rc==SQLITE_OK; pc++){
  65001. assert( pc>=0 && pc<p->nOp );
  65002. if( db->mallocFailed ) goto no_mem;
  65003. #ifdef VDBE_PROFILE
  65004. start = sqlite3Hwtime();
  65005. #endif
  65006. nVmStep++;
  65007. pOp = &aOp[pc];
  65008. /* Only allow tracing if SQLITE_DEBUG is defined.
  65009. */
  65010. #ifdef SQLITE_DEBUG
  65011. if( db->flags & SQLITE_VdbeTrace ){
  65012. sqlite3VdbePrintOp(stdout, pc, pOp);
  65013. }
  65014. #endif
  65015. /* Check to see if we need to simulate an interrupt. This only happens
  65016. ** if we have a special test build.
  65017. */
  65018. #ifdef SQLITE_TEST
  65019. if( sqlite3_interrupt_count>0 ){
  65020. sqlite3_interrupt_count--;
  65021. if( sqlite3_interrupt_count==0 ){
  65022. sqlite3_interrupt(db);
  65023. }
  65024. }
  65025. #endif
  65026. /* On any opcode with the "out2-prerelease" tag, free any
  65027. ** external allocations out of mem[p2] and set mem[p2] to be
  65028. ** an undefined integer. Opcodes will either fill in the integer
  65029. ** value or convert mem[p2] to a different type.
  65030. */
  65031. assert( pOp->opflags==sqlite3OpcodeProperty[pOp->opcode] );
  65032. if( pOp->opflags & OPFLG_OUT2_PRERELEASE ){
  65033. assert( pOp->p2>0 );
  65034. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65035. pOut = &aMem[pOp->p2];
  65036. memAboutToChange(p, pOut);
  65037. if( VdbeMemDynamic(pOut) ) sqlite3VdbeMemSetNull(pOut);
  65038. pOut->flags = MEM_Int;
  65039. }
  65040. /* Sanity checking on other operands */
  65041. #ifdef SQLITE_DEBUG
  65042. if( (pOp->opflags & OPFLG_IN1)!=0 ){
  65043. assert( pOp->p1>0 );
  65044. assert( pOp->p1<=(p->nMem-p->nCursor) );
  65045. assert( memIsValid(&aMem[pOp->p1]) );
  65046. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p1]) );
  65047. REGISTER_TRACE(pOp->p1, &aMem[pOp->p1]);
  65048. }
  65049. if( (pOp->opflags & OPFLG_IN2)!=0 ){
  65050. assert( pOp->p2>0 );
  65051. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65052. assert( memIsValid(&aMem[pOp->p2]) );
  65053. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p2]) );
  65054. REGISTER_TRACE(pOp->p2, &aMem[pOp->p2]);
  65055. }
  65056. if( (pOp->opflags & OPFLG_IN3)!=0 ){
  65057. assert( pOp->p3>0 );
  65058. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65059. assert( memIsValid(&aMem[pOp->p3]) );
  65060. assert( sqlite3VdbeCheckMemInvariants(&aMem[pOp->p3]) );
  65061. REGISTER_TRACE(pOp->p3, &aMem[pOp->p3]);
  65062. }
  65063. if( (pOp->opflags & OPFLG_OUT2)!=0 ){
  65064. assert( pOp->p2>0 );
  65065. assert( pOp->p2<=(p->nMem-p->nCursor) );
  65066. memAboutToChange(p, &aMem[pOp->p2]);
  65067. }
  65068. if( (pOp->opflags & OPFLG_OUT3)!=0 ){
  65069. assert( pOp->p3>0 );
  65070. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65071. memAboutToChange(p, &aMem[pOp->p3]);
  65072. }
  65073. #endif
  65074. switch( pOp->opcode ){
  65075. /*****************************************************************************
  65076. ** What follows is a massive switch statement where each case implements a
  65077. ** separate instruction in the virtual machine. If we follow the usual
  65078. ** indentation conventions, each case should be indented by 6 spaces. But
  65079. ** that is a lot of wasted space on the left margin. So the code within
  65080. ** the switch statement will break with convention and be flush-left. Another
  65081. ** big comment (similar to this one) will mark the point in the code where
  65082. ** we transition back to normal indentation.
  65083. **
  65084. ** The formatting of each case is important. The makefile for SQLite
  65085. ** generates two C files "opcodes.h" and "opcodes.c" by scanning this
  65086. ** file looking for lines that begin with "case OP_". The opcodes.h files
  65087. ** will be filled with #defines that give unique integer values to each
  65088. ** opcode and the opcodes.c file is filled with an array of strings where
  65089. ** each string is the symbolic name for the corresponding opcode. If the
  65090. ** case statement is followed by a comment of the form "/# same as ... #/"
  65091. ** that comment is used to determine the particular value of the opcode.
  65092. **
  65093. ** Other keywords in the comment that follows each case are used to
  65094. ** construct the OPFLG_INITIALIZER value that initializes opcodeProperty[].
  65095. ** Keywords include: in1, in2, in3, out2_prerelease, out2, out3. See
  65096. ** the mkopcodeh.awk script for additional information.
  65097. **
  65098. ** Documentation about VDBE opcodes is generated by scanning this file
  65099. ** for lines of that contain "Opcode:". That line and all subsequent
  65100. ** comment lines are used in the generation of the opcode.html documentation
  65101. ** file.
  65102. **
  65103. ** SUMMARY:
  65104. **
  65105. ** Formatting is important to scripts that scan this file.
  65106. ** Do not deviate from the formatting style currently in use.
  65107. **
  65108. *****************************************************************************/
  65109. /* Opcode: Goto * P2 * * *
  65110. **
  65111. ** An unconditional jump to address P2.
  65112. ** The next instruction executed will be
  65113. ** the one at index P2 from the beginning of
  65114. ** the program.
  65115. **
  65116. ** The P1 parameter is not actually used by this opcode. However, it
  65117. ** is sometimes set to 1 instead of 0 as a hint to the command-line shell
  65118. ** that this Goto is the bottom of a loop and that the lines from P2 down
  65119. ** to the current line should be indented for EXPLAIN output.
  65120. */
  65121. case OP_Goto: { /* jump */
  65122. pc = pOp->p2 - 1;
  65123. /* Opcodes that are used as the bottom of a loop (OP_Next, OP_Prev,
  65124. ** OP_VNext, OP_RowSetNext, or OP_SorterNext) all jump here upon
  65125. ** completion. Check to see if sqlite3_interrupt() has been called
  65126. ** or if the progress callback needs to be invoked.
  65127. **
  65128. ** This code uses unstructured "goto" statements and does not look clean.
  65129. ** But that is not due to sloppy coding habits. The code is written this
  65130. ** way for performance, to avoid having to run the interrupt and progress
  65131. ** checks on every opcode. This helps sqlite3_step() to run about 1.5%
  65132. ** faster according to "valgrind --tool=cachegrind" */
  65133. check_for_interrupt:
  65134. if( db->u1.isInterrupted ) goto abort_due_to_interrupt;
  65135. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65136. /* Call the progress callback if it is configured and the required number
  65137. ** of VDBE ops have been executed (either since this invocation of
  65138. ** sqlite3VdbeExec() or since last time the progress callback was called).
  65139. ** If the progress callback returns non-zero, exit the virtual machine with
  65140. ** a return code SQLITE_ABORT.
  65141. */
  65142. if( db->xProgress!=0 && nVmStep>=nProgressLimit ){
  65143. assert( db->nProgressOps!=0 );
  65144. nProgressLimit = nVmStep + db->nProgressOps - (nVmStep%db->nProgressOps);
  65145. if( db->xProgress(db->pProgressArg) ){
  65146. rc = SQLITE_INTERRUPT;
  65147. goto vdbe_error_halt;
  65148. }
  65149. }
  65150. #endif
  65151. break;
  65152. }
  65153. /* Opcode: Gosub P1 P2 * * *
  65154. **
  65155. ** Write the current address onto register P1
  65156. ** and then jump to address P2.
  65157. */
  65158. case OP_Gosub: { /* jump */
  65159. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  65160. pIn1 = &aMem[pOp->p1];
  65161. assert( VdbeMemDynamic(pIn1)==0 );
  65162. memAboutToChange(p, pIn1);
  65163. pIn1->flags = MEM_Int;
  65164. pIn1->u.i = pc;
  65165. REGISTER_TRACE(pOp->p1, pIn1);
  65166. pc = pOp->p2 - 1;
  65167. break;
  65168. }
  65169. /* Opcode: Return P1 * * * *
  65170. **
  65171. ** Jump to the next instruction after the address in register P1. After
  65172. ** the jump, register P1 becomes undefined.
  65173. */
  65174. case OP_Return: { /* in1 */
  65175. pIn1 = &aMem[pOp->p1];
  65176. assert( pIn1->flags==MEM_Int );
  65177. pc = (int)pIn1->u.i;
  65178. pIn1->flags = MEM_Undefined;
  65179. break;
  65180. }
  65181. /* Opcode: InitCoroutine P1 P2 P3 * *
  65182. **
  65183. ** Set up register P1 so that it will Yield to the coroutine
  65184. ** located at address P3.
  65185. **
  65186. ** If P2!=0 then the coroutine implementation immediately follows
  65187. ** this opcode. So jump over the coroutine implementation to
  65188. ** address P2.
  65189. **
  65190. ** See also: EndCoroutine
  65191. */
  65192. case OP_InitCoroutine: { /* jump */
  65193. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  65194. assert( pOp->p2>=0 && pOp->p2<p->nOp );
  65195. assert( pOp->p3>=0 && pOp->p3<p->nOp );
  65196. pOut = &aMem[pOp->p1];
  65197. assert( !VdbeMemDynamic(pOut) );
  65198. pOut->u.i = pOp->p3 - 1;
  65199. pOut->flags = MEM_Int;
  65200. if( pOp->p2 ) pc = pOp->p2 - 1;
  65201. break;
  65202. }
  65203. /* Opcode: EndCoroutine P1 * * * *
  65204. **
  65205. ** The instruction at the address in register P1 is a Yield.
  65206. ** Jump to the P2 parameter of that Yield.
  65207. ** After the jump, register P1 becomes undefined.
  65208. **
  65209. ** See also: InitCoroutine
  65210. */
  65211. case OP_EndCoroutine: { /* in1 */
  65212. VdbeOp *pCaller;
  65213. pIn1 = &aMem[pOp->p1];
  65214. assert( pIn1->flags==MEM_Int );
  65215. assert( pIn1->u.i>=0 && pIn1->u.i<p->nOp );
  65216. pCaller = &aOp[pIn1->u.i];
  65217. assert( pCaller->opcode==OP_Yield );
  65218. assert( pCaller->p2>=0 && pCaller->p2<p->nOp );
  65219. pc = pCaller->p2 - 1;
  65220. pIn1->flags = MEM_Undefined;
  65221. break;
  65222. }
  65223. /* Opcode: Yield P1 P2 * * *
  65224. **
  65225. ** Swap the program counter with the value in register P1. This
  65226. ** has the effect of yielding to a coroutine.
  65227. **
  65228. ** If the coroutine that is launched by this instruction ends with
  65229. ** Yield or Return then continue to the next instruction. But if
  65230. ** the coroutine launched by this instruction ends with
  65231. ** EndCoroutine, then jump to P2 rather than continuing with the
  65232. ** next instruction.
  65233. **
  65234. ** See also: InitCoroutine
  65235. */
  65236. case OP_Yield: { /* in1, jump */
  65237. int pcDest;
  65238. pIn1 = &aMem[pOp->p1];
  65239. assert( VdbeMemDynamic(pIn1)==0 );
  65240. pIn1->flags = MEM_Int;
  65241. pcDest = (int)pIn1->u.i;
  65242. pIn1->u.i = pc;
  65243. REGISTER_TRACE(pOp->p1, pIn1);
  65244. pc = pcDest;
  65245. break;
  65246. }
  65247. /* Opcode: HaltIfNull P1 P2 P3 P4 P5
  65248. ** Synopsis: if r[P3]=null halt
  65249. **
  65250. ** Check the value in register P3. If it is NULL then Halt using
  65251. ** parameter P1, P2, and P4 as if this were a Halt instruction. If the
  65252. ** value in register P3 is not NULL, then this routine is a no-op.
  65253. ** The P5 parameter should be 1.
  65254. */
  65255. case OP_HaltIfNull: { /* in3 */
  65256. pIn3 = &aMem[pOp->p3];
  65257. if( (pIn3->flags & MEM_Null)==0 ) break;
  65258. /* Fall through into OP_Halt */
  65259. }
  65260. /* Opcode: Halt P1 P2 * P4 P5
  65261. **
  65262. ** Exit immediately. All open cursors, etc are closed
  65263. ** automatically.
  65264. **
  65265. ** P1 is the result code returned by sqlite3_exec(), sqlite3_reset(),
  65266. ** or sqlite3_finalize(). For a normal halt, this should be SQLITE_OK (0).
  65267. ** For errors, it can be some other value. If P1!=0 then P2 will determine
  65268. ** whether or not to rollback the current transaction. Do not rollback
  65269. ** if P2==OE_Fail. Do the rollback if P2==OE_Rollback. If P2==OE_Abort,
  65270. ** then back out all changes that have occurred during this execution of the
  65271. ** VDBE, but do not rollback the transaction.
  65272. **
  65273. ** If P4 is not null then it is an error message string.
  65274. **
  65275. ** P5 is a value between 0 and 4, inclusive, that modifies the P4 string.
  65276. **
  65277. ** 0: (no change)
  65278. ** 1: NOT NULL contraint failed: P4
  65279. ** 2: UNIQUE constraint failed: P4
  65280. ** 3: CHECK constraint failed: P4
  65281. ** 4: FOREIGN KEY constraint failed: P4
  65282. **
  65283. ** If P5 is not zero and P4 is NULL, then everything after the ":" is
  65284. ** omitted.
  65285. **
  65286. ** There is an implied "Halt 0 0 0" instruction inserted at the very end of
  65287. ** every program. So a jump past the last instruction of the program
  65288. ** is the same as executing Halt.
  65289. */
  65290. case OP_Halt: {
  65291. const char *zType;
  65292. const char *zLogFmt;
  65293. if( pOp->p1==SQLITE_OK && p->pFrame ){
  65294. /* Halt the sub-program. Return control to the parent frame. */
  65295. VdbeFrame *pFrame = p->pFrame;
  65296. p->pFrame = pFrame->pParent;
  65297. p->nFrame--;
  65298. sqlite3VdbeSetChanges(db, p->nChange);
  65299. pc = sqlite3VdbeFrameRestore(pFrame);
  65300. lastRowid = db->lastRowid;
  65301. if( pOp->p2==OE_Ignore ){
  65302. /* Instruction pc is the OP_Program that invoked the sub-program
  65303. ** currently being halted. If the p2 instruction of this OP_Halt
  65304. ** instruction is set to OE_Ignore, then the sub-program is throwing
  65305. ** an IGNORE exception. In this case jump to the address specified
  65306. ** as the p2 of the calling OP_Program. */
  65307. pc = p->aOp[pc].p2-1;
  65308. }
  65309. aOp = p->aOp;
  65310. aMem = p->aMem;
  65311. break;
  65312. }
  65313. p->rc = pOp->p1;
  65314. p->errorAction = (u8)pOp->p2;
  65315. p->pc = pc;
  65316. if( p->rc ){
  65317. if( pOp->p5 ){
  65318. static const char * const azType[] = { "NOT NULL", "UNIQUE", "CHECK",
  65319. "FOREIGN KEY" };
  65320. assert( pOp->p5>=1 && pOp->p5<=4 );
  65321. testcase( pOp->p5==1 );
  65322. testcase( pOp->p5==2 );
  65323. testcase( pOp->p5==3 );
  65324. testcase( pOp->p5==4 );
  65325. zType = azType[pOp->p5-1];
  65326. }else{
  65327. zType = 0;
  65328. }
  65329. assert( zType!=0 || pOp->p4.z!=0 );
  65330. zLogFmt = "abort at %d in [%s]: %s";
  65331. if( zType && pOp->p4.z ){
  65332. sqlite3SetString(&p->zErrMsg, db, "%s constraint failed: %s",
  65333. zType, pOp->p4.z);
  65334. }else if( pOp->p4.z ){
  65335. sqlite3SetString(&p->zErrMsg, db, "%s", pOp->p4.z);
  65336. }else{
  65337. sqlite3SetString(&p->zErrMsg, db, "%s constraint failed", zType);
  65338. }
  65339. sqlite3_log(pOp->p1, zLogFmt, pc, p->zSql, p->zErrMsg);
  65340. }
  65341. rc = sqlite3VdbeHalt(p);
  65342. assert( rc==SQLITE_BUSY || rc==SQLITE_OK || rc==SQLITE_ERROR );
  65343. if( rc==SQLITE_BUSY ){
  65344. p->rc = rc = SQLITE_BUSY;
  65345. }else{
  65346. assert( rc==SQLITE_OK || (p->rc&0xff)==SQLITE_CONSTRAINT );
  65347. assert( rc==SQLITE_OK || db->nDeferredCons>0 || db->nDeferredImmCons>0 );
  65348. rc = p->rc ? SQLITE_ERROR : SQLITE_DONE;
  65349. }
  65350. goto vdbe_return;
  65351. }
  65352. /* Opcode: Integer P1 P2 * * *
  65353. ** Synopsis: r[P2]=P1
  65354. **
  65355. ** The 32-bit integer value P1 is written into register P2.
  65356. */
  65357. case OP_Integer: { /* out2-prerelease */
  65358. pOut->u.i = pOp->p1;
  65359. break;
  65360. }
  65361. /* Opcode: Int64 * P2 * P4 *
  65362. ** Synopsis: r[P2]=P4
  65363. **
  65364. ** P4 is a pointer to a 64-bit integer value.
  65365. ** Write that value into register P2.
  65366. */
  65367. case OP_Int64: { /* out2-prerelease */
  65368. assert( pOp->p4.pI64!=0 );
  65369. pOut->u.i = *pOp->p4.pI64;
  65370. break;
  65371. }
  65372. #ifndef SQLITE_OMIT_FLOATING_POINT
  65373. /* Opcode: Real * P2 * P4 *
  65374. ** Synopsis: r[P2]=P4
  65375. **
  65376. ** P4 is a pointer to a 64-bit floating point value.
  65377. ** Write that value into register P2.
  65378. */
  65379. case OP_Real: { /* same as TK_FLOAT, out2-prerelease */
  65380. pOut->flags = MEM_Real;
  65381. assert( !sqlite3IsNaN(*pOp->p4.pReal) );
  65382. pOut->u.r = *pOp->p4.pReal;
  65383. break;
  65384. }
  65385. #endif
  65386. /* Opcode: String8 * P2 * P4 *
  65387. ** Synopsis: r[P2]='P4'
  65388. **
  65389. ** P4 points to a nul terminated UTF-8 string. This opcode is transformed
  65390. ** into a String before it is executed for the first time. During
  65391. ** this transformation, the length of string P4 is computed and stored
  65392. ** as the P1 parameter.
  65393. */
  65394. case OP_String8: { /* same as TK_STRING, out2-prerelease */
  65395. assert( pOp->p4.z!=0 );
  65396. pOp->opcode = OP_String;
  65397. pOp->p1 = sqlite3Strlen30(pOp->p4.z);
  65398. #ifndef SQLITE_OMIT_UTF16
  65399. if( encoding!=SQLITE_UTF8 ){
  65400. rc = sqlite3VdbeMemSetStr(pOut, pOp->p4.z, -1, SQLITE_UTF8, SQLITE_STATIC);
  65401. if( rc==SQLITE_TOOBIG ) goto too_big;
  65402. if( SQLITE_OK!=sqlite3VdbeChangeEncoding(pOut, encoding) ) goto no_mem;
  65403. assert( pOut->szMalloc>0 && pOut->zMalloc==pOut->z );
  65404. assert( VdbeMemDynamic(pOut)==0 );
  65405. pOut->szMalloc = 0;
  65406. pOut->flags |= MEM_Static;
  65407. if( pOp->p4type==P4_DYNAMIC ){
  65408. sqlite3DbFree(db, pOp->p4.z);
  65409. }
  65410. pOp->p4type = P4_DYNAMIC;
  65411. pOp->p4.z = pOut->z;
  65412. pOp->p1 = pOut->n;
  65413. }
  65414. #endif
  65415. if( pOp->p1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65416. goto too_big;
  65417. }
  65418. /* Fall through to the next case, OP_String */
  65419. }
  65420. /* Opcode: String P1 P2 * P4 *
  65421. ** Synopsis: r[P2]='P4' (len=P1)
  65422. **
  65423. ** The string value P4 of length P1 (bytes) is stored in register P2.
  65424. */
  65425. case OP_String: { /* out2-prerelease */
  65426. assert( pOp->p4.z!=0 );
  65427. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  65428. pOut->z = pOp->p4.z;
  65429. pOut->n = pOp->p1;
  65430. pOut->enc = encoding;
  65431. UPDATE_MAX_BLOBSIZE(pOut);
  65432. break;
  65433. }
  65434. /* Opcode: Null P1 P2 P3 * *
  65435. ** Synopsis: r[P2..P3]=NULL
  65436. **
  65437. ** Write a NULL into registers P2. If P3 greater than P2, then also write
  65438. ** NULL into register P3 and every register in between P2 and P3. If P3
  65439. ** is less than P2 (typically P3 is zero) then only register P2 is
  65440. ** set to NULL.
  65441. **
  65442. ** If the P1 value is non-zero, then also set the MEM_Cleared flag so that
  65443. ** NULL values will not compare equal even if SQLITE_NULLEQ is set on
  65444. ** OP_Ne or OP_Eq.
  65445. */
  65446. case OP_Null: { /* out2-prerelease */
  65447. int cnt;
  65448. u16 nullFlag;
  65449. cnt = pOp->p3-pOp->p2;
  65450. assert( pOp->p3<=(p->nMem-p->nCursor) );
  65451. pOut->flags = nullFlag = pOp->p1 ? (MEM_Null|MEM_Cleared) : MEM_Null;
  65452. while( cnt>0 ){
  65453. pOut++;
  65454. memAboutToChange(p, pOut);
  65455. sqlite3VdbeMemSetNull(pOut);
  65456. pOut->flags = nullFlag;
  65457. cnt--;
  65458. }
  65459. break;
  65460. }
  65461. /* Opcode: SoftNull P1 * * * *
  65462. ** Synopsis: r[P1]=NULL
  65463. **
  65464. ** Set register P1 to have the value NULL as seen by the OP_MakeRecord
  65465. ** instruction, but do not free any string or blob memory associated with
  65466. ** the register, so that if the value was a string or blob that was
  65467. ** previously copied using OP_SCopy, the copies will continue to be valid.
  65468. */
  65469. case OP_SoftNull: {
  65470. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  65471. pOut = &aMem[pOp->p1];
  65472. pOut->flags = (pOut->flags|MEM_Null)&~MEM_Undefined;
  65473. break;
  65474. }
  65475. /* Opcode: Blob P1 P2 * P4 *
  65476. ** Synopsis: r[P2]=P4 (len=P1)
  65477. **
  65478. ** P4 points to a blob of data P1 bytes long. Store this
  65479. ** blob in register P2.
  65480. */
  65481. case OP_Blob: { /* out2-prerelease */
  65482. assert( pOp->p1 <= SQLITE_MAX_LENGTH );
  65483. sqlite3VdbeMemSetStr(pOut, pOp->p4.z, pOp->p1, 0, 0);
  65484. pOut->enc = encoding;
  65485. UPDATE_MAX_BLOBSIZE(pOut);
  65486. break;
  65487. }
  65488. /* Opcode: Variable P1 P2 * P4 *
  65489. ** Synopsis: r[P2]=parameter(P1,P4)
  65490. **
  65491. ** Transfer the values of bound parameter P1 into register P2
  65492. **
  65493. ** If the parameter is named, then its name appears in P4.
  65494. ** The P4 value is used by sqlite3_bind_parameter_name().
  65495. */
  65496. case OP_Variable: { /* out2-prerelease */
  65497. Mem *pVar; /* Value being transferred */
  65498. assert( pOp->p1>0 && pOp->p1<=p->nVar );
  65499. assert( pOp->p4.z==0 || pOp->p4.z==p->azVar[pOp->p1-1] );
  65500. pVar = &p->aVar[pOp->p1 - 1];
  65501. if( sqlite3VdbeMemTooBig(pVar) ){
  65502. goto too_big;
  65503. }
  65504. sqlite3VdbeMemShallowCopy(pOut, pVar, MEM_Static);
  65505. UPDATE_MAX_BLOBSIZE(pOut);
  65506. break;
  65507. }
  65508. /* Opcode: Move P1 P2 P3 * *
  65509. ** Synopsis: r[P2@P3]=r[P1@P3]
  65510. **
  65511. ** Move the P3 values in register P1..P1+P3-1 over into
  65512. ** registers P2..P2+P3-1. Registers P1..P1+P3-1 are
  65513. ** left holding a NULL. It is an error for register ranges
  65514. ** P1..P1+P3-1 and P2..P2+P3-1 to overlap. It is an error
  65515. ** for P3 to be less than 1.
  65516. */
  65517. case OP_Move: {
  65518. int n; /* Number of registers left to copy */
  65519. int p1; /* Register to copy from */
  65520. int p2; /* Register to copy to */
  65521. n = pOp->p3;
  65522. p1 = pOp->p1;
  65523. p2 = pOp->p2;
  65524. assert( n>0 && p1>0 && p2>0 );
  65525. assert( p1+n<=p2 || p2+n<=p1 );
  65526. pIn1 = &aMem[p1];
  65527. pOut = &aMem[p2];
  65528. do{
  65529. assert( pOut<=&aMem[(p->nMem-p->nCursor)] );
  65530. assert( pIn1<=&aMem[(p->nMem-p->nCursor)] );
  65531. assert( memIsValid(pIn1) );
  65532. memAboutToChange(p, pOut);
  65533. sqlite3VdbeMemMove(pOut, pIn1);
  65534. #ifdef SQLITE_DEBUG
  65535. if( pOut->pScopyFrom>=&aMem[p1] && pOut->pScopyFrom<&aMem[p1+pOp->p3] ){
  65536. pOut->pScopyFrom += p1 - pOp->p2;
  65537. }
  65538. #endif
  65539. REGISTER_TRACE(p2++, pOut);
  65540. pIn1++;
  65541. pOut++;
  65542. }while( --n );
  65543. break;
  65544. }
  65545. /* Opcode: Copy P1 P2 P3 * *
  65546. ** Synopsis: r[P2@P3+1]=r[P1@P3+1]
  65547. **
  65548. ** Make a copy of registers P1..P1+P3 into registers P2..P2+P3.
  65549. **
  65550. ** This instruction makes a deep copy of the value. A duplicate
  65551. ** is made of any string or blob constant. See also OP_SCopy.
  65552. */
  65553. case OP_Copy: {
  65554. int n;
  65555. n = pOp->p3;
  65556. pIn1 = &aMem[pOp->p1];
  65557. pOut = &aMem[pOp->p2];
  65558. assert( pOut!=pIn1 );
  65559. while( 1 ){
  65560. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  65561. Deephemeralize(pOut);
  65562. #ifdef SQLITE_DEBUG
  65563. pOut->pScopyFrom = 0;
  65564. #endif
  65565. REGISTER_TRACE(pOp->p2+pOp->p3-n, pOut);
  65566. if( (n--)==0 ) break;
  65567. pOut++;
  65568. pIn1++;
  65569. }
  65570. break;
  65571. }
  65572. /* Opcode: SCopy P1 P2 * * *
  65573. ** Synopsis: r[P2]=r[P1]
  65574. **
  65575. ** Make a shallow copy of register P1 into register P2.
  65576. **
  65577. ** This instruction makes a shallow copy of the value. If the value
  65578. ** is a string or blob, then the copy is only a pointer to the
  65579. ** original and hence if the original changes so will the copy.
  65580. ** Worse, if the original is deallocated, the copy becomes invalid.
  65581. ** Thus the program must guarantee that the original will not change
  65582. ** during the lifetime of the copy. Use OP_Copy to make a complete
  65583. ** copy.
  65584. */
  65585. case OP_SCopy: { /* out2 */
  65586. pIn1 = &aMem[pOp->p1];
  65587. pOut = &aMem[pOp->p2];
  65588. assert( pOut!=pIn1 );
  65589. sqlite3VdbeMemShallowCopy(pOut, pIn1, MEM_Ephem);
  65590. #ifdef SQLITE_DEBUG
  65591. if( pOut->pScopyFrom==0 ) pOut->pScopyFrom = pIn1;
  65592. #endif
  65593. break;
  65594. }
  65595. /* Opcode: ResultRow P1 P2 * * *
  65596. ** Synopsis: output=r[P1@P2]
  65597. **
  65598. ** The registers P1 through P1+P2-1 contain a single row of
  65599. ** results. This opcode causes the sqlite3_step() call to terminate
  65600. ** with an SQLITE_ROW return code and it sets up the sqlite3_stmt
  65601. ** structure to provide access to the r(P1)..r(P1+P2-1) values as
  65602. ** the result row.
  65603. */
  65604. case OP_ResultRow: {
  65605. Mem *pMem;
  65606. int i;
  65607. assert( p->nResColumn==pOp->p2 );
  65608. assert( pOp->p1>0 );
  65609. assert( pOp->p1+pOp->p2<=(p->nMem-p->nCursor)+1 );
  65610. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  65611. /* Run the progress counter just before returning.
  65612. */
  65613. if( db->xProgress!=0
  65614. && nVmStep>=nProgressLimit
  65615. && db->xProgress(db->pProgressArg)!=0
  65616. ){
  65617. rc = SQLITE_INTERRUPT;
  65618. goto vdbe_error_halt;
  65619. }
  65620. #endif
  65621. /* If this statement has violated immediate foreign key constraints, do
  65622. ** not return the number of rows modified. And do not RELEASE the statement
  65623. ** transaction. It needs to be rolled back. */
  65624. if( SQLITE_OK!=(rc = sqlite3VdbeCheckFk(p, 0)) ){
  65625. assert( db->flags&SQLITE_CountRows );
  65626. assert( p->usesStmtJournal );
  65627. break;
  65628. }
  65629. /* If the SQLITE_CountRows flag is set in sqlite3.flags mask, then
  65630. ** DML statements invoke this opcode to return the number of rows
  65631. ** modified to the user. This is the only way that a VM that
  65632. ** opens a statement transaction may invoke this opcode.
  65633. **
  65634. ** In case this is such a statement, close any statement transaction
  65635. ** opened by this VM before returning control to the user. This is to
  65636. ** ensure that statement-transactions are always nested, not overlapping.
  65637. ** If the open statement-transaction is not closed here, then the user
  65638. ** may step another VM that opens its own statement transaction. This
  65639. ** may lead to overlapping statement transactions.
  65640. **
  65641. ** The statement transaction is never a top-level transaction. Hence
  65642. ** the RELEASE call below can never fail.
  65643. */
  65644. assert( p->iStatement==0 || db->flags&SQLITE_CountRows );
  65645. rc = sqlite3VdbeCloseStatement(p, SAVEPOINT_RELEASE);
  65646. if( NEVER(rc!=SQLITE_OK) ){
  65647. break;
  65648. }
  65649. /* Invalidate all ephemeral cursor row caches */
  65650. p->cacheCtr = (p->cacheCtr + 2)|1;
  65651. /* Make sure the results of the current row are \000 terminated
  65652. ** and have an assigned type. The results are de-ephemeralized as
  65653. ** a side effect.
  65654. */
  65655. pMem = p->pResultSet = &aMem[pOp->p1];
  65656. for(i=0; i<pOp->p2; i++){
  65657. assert( memIsValid(&pMem[i]) );
  65658. Deephemeralize(&pMem[i]);
  65659. assert( (pMem[i].flags & MEM_Ephem)==0
  65660. || (pMem[i].flags & (MEM_Str|MEM_Blob))==0 );
  65661. sqlite3VdbeMemNulTerminate(&pMem[i]);
  65662. REGISTER_TRACE(pOp->p1+i, &pMem[i]);
  65663. }
  65664. if( db->mallocFailed ) goto no_mem;
  65665. /* Return SQLITE_ROW
  65666. */
  65667. p->pc = pc + 1;
  65668. rc = SQLITE_ROW;
  65669. goto vdbe_return;
  65670. }
  65671. /* Opcode: Concat P1 P2 P3 * *
  65672. ** Synopsis: r[P3]=r[P2]+r[P1]
  65673. **
  65674. ** Add the text in register P1 onto the end of the text in
  65675. ** register P2 and store the result in register P3.
  65676. ** If either the P1 or P2 text are NULL then store NULL in P3.
  65677. **
  65678. ** P3 = P2 || P1
  65679. **
  65680. ** It is illegal for P1 and P3 to be the same register. Sometimes,
  65681. ** if P3 is the same register as P2, the implementation is able
  65682. ** to avoid a memcpy().
  65683. */
  65684. case OP_Concat: { /* same as TK_CONCAT, in1, in2, out3 */
  65685. i64 nByte;
  65686. pIn1 = &aMem[pOp->p1];
  65687. pIn2 = &aMem[pOp->p2];
  65688. pOut = &aMem[pOp->p3];
  65689. assert( pIn1!=pOut );
  65690. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  65691. sqlite3VdbeMemSetNull(pOut);
  65692. break;
  65693. }
  65694. if( ExpandBlob(pIn1) || ExpandBlob(pIn2) ) goto no_mem;
  65695. Stringify(pIn1, encoding);
  65696. Stringify(pIn2, encoding);
  65697. nByte = pIn1->n + pIn2->n;
  65698. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  65699. goto too_big;
  65700. }
  65701. if( sqlite3VdbeMemGrow(pOut, (int)nByte+2, pOut==pIn2) ){
  65702. goto no_mem;
  65703. }
  65704. MemSetTypeFlag(pOut, MEM_Str);
  65705. if( pOut!=pIn2 ){
  65706. memcpy(pOut->z, pIn2->z, pIn2->n);
  65707. }
  65708. memcpy(&pOut->z[pIn2->n], pIn1->z, pIn1->n);
  65709. pOut->z[nByte]=0;
  65710. pOut->z[nByte+1] = 0;
  65711. pOut->flags |= MEM_Term;
  65712. pOut->n = (int)nByte;
  65713. pOut->enc = encoding;
  65714. UPDATE_MAX_BLOBSIZE(pOut);
  65715. break;
  65716. }
  65717. /* Opcode: Add P1 P2 P3 * *
  65718. ** Synopsis: r[P3]=r[P1]+r[P2]
  65719. **
  65720. ** Add the value in register P1 to the value in register P2
  65721. ** and store the result in register P3.
  65722. ** If either input is NULL, the result is NULL.
  65723. */
  65724. /* Opcode: Multiply P1 P2 P3 * *
  65725. ** Synopsis: r[P3]=r[P1]*r[P2]
  65726. **
  65727. **
  65728. ** Multiply the value in register P1 by the value in register P2
  65729. ** and store the result in register P3.
  65730. ** If either input is NULL, the result is NULL.
  65731. */
  65732. /* Opcode: Subtract P1 P2 P3 * *
  65733. ** Synopsis: r[P3]=r[P2]-r[P1]
  65734. **
  65735. ** Subtract the value in register P1 from the value in register P2
  65736. ** and store the result in register P3.
  65737. ** If either input is NULL, the result is NULL.
  65738. */
  65739. /* Opcode: Divide P1 P2 P3 * *
  65740. ** Synopsis: r[P3]=r[P2]/r[P1]
  65741. **
  65742. ** Divide the value in register P1 by the value in register P2
  65743. ** and store the result in register P3 (P3=P2/P1). If the value in
  65744. ** register P1 is zero, then the result is NULL. If either input is
  65745. ** NULL, the result is NULL.
  65746. */
  65747. /* Opcode: Remainder P1 P2 P3 * *
  65748. ** Synopsis: r[P3]=r[P2]%r[P1]
  65749. **
  65750. ** Compute the remainder after integer register P2 is divided by
  65751. ** register P1 and store the result in register P3.
  65752. ** If the value in register P1 is zero the result is NULL.
  65753. ** If either operand is NULL, the result is NULL.
  65754. */
  65755. case OP_Add: /* same as TK_PLUS, in1, in2, out3 */
  65756. case OP_Subtract: /* same as TK_MINUS, in1, in2, out3 */
  65757. case OP_Multiply: /* same as TK_STAR, in1, in2, out3 */
  65758. case OP_Divide: /* same as TK_SLASH, in1, in2, out3 */
  65759. case OP_Remainder: { /* same as TK_REM, in1, in2, out3 */
  65760. char bIntint; /* Started out as two integer operands */
  65761. u16 flags; /* Combined MEM_* flags from both inputs */
  65762. u16 type1; /* Numeric type of left operand */
  65763. u16 type2; /* Numeric type of right operand */
  65764. i64 iA; /* Integer value of left operand */
  65765. i64 iB; /* Integer value of right operand */
  65766. double rA; /* Real value of left operand */
  65767. double rB; /* Real value of right operand */
  65768. pIn1 = &aMem[pOp->p1];
  65769. type1 = numericType(pIn1);
  65770. pIn2 = &aMem[pOp->p2];
  65771. type2 = numericType(pIn2);
  65772. pOut = &aMem[pOp->p3];
  65773. flags = pIn1->flags | pIn2->flags;
  65774. if( (flags & MEM_Null)!=0 ) goto arithmetic_result_is_null;
  65775. if( (type1 & type2 & MEM_Int)!=0 ){
  65776. iA = pIn1->u.i;
  65777. iB = pIn2->u.i;
  65778. bIntint = 1;
  65779. switch( pOp->opcode ){
  65780. case OP_Add: if( sqlite3AddInt64(&iB,iA) ) goto fp_math; break;
  65781. case OP_Subtract: if( sqlite3SubInt64(&iB,iA) ) goto fp_math; break;
  65782. case OP_Multiply: if( sqlite3MulInt64(&iB,iA) ) goto fp_math; break;
  65783. case OP_Divide: {
  65784. if( iA==0 ) goto arithmetic_result_is_null;
  65785. if( iA==-1 && iB==SMALLEST_INT64 ) goto fp_math;
  65786. iB /= iA;
  65787. break;
  65788. }
  65789. default: {
  65790. if( iA==0 ) goto arithmetic_result_is_null;
  65791. if( iA==-1 ) iA = 1;
  65792. iB %= iA;
  65793. break;
  65794. }
  65795. }
  65796. pOut->u.i = iB;
  65797. MemSetTypeFlag(pOut, MEM_Int);
  65798. }else{
  65799. bIntint = 0;
  65800. fp_math:
  65801. rA = sqlite3VdbeRealValue(pIn1);
  65802. rB = sqlite3VdbeRealValue(pIn2);
  65803. switch( pOp->opcode ){
  65804. case OP_Add: rB += rA; break;
  65805. case OP_Subtract: rB -= rA; break;
  65806. case OP_Multiply: rB *= rA; break;
  65807. case OP_Divide: {
  65808. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  65809. if( rA==(double)0 ) goto arithmetic_result_is_null;
  65810. rB /= rA;
  65811. break;
  65812. }
  65813. default: {
  65814. iA = (i64)rA;
  65815. iB = (i64)rB;
  65816. if( iA==0 ) goto arithmetic_result_is_null;
  65817. if( iA==-1 ) iA = 1;
  65818. rB = (double)(iB % iA);
  65819. break;
  65820. }
  65821. }
  65822. #ifdef SQLITE_OMIT_FLOATING_POINT
  65823. pOut->u.i = rB;
  65824. MemSetTypeFlag(pOut, MEM_Int);
  65825. #else
  65826. if( sqlite3IsNaN(rB) ){
  65827. goto arithmetic_result_is_null;
  65828. }
  65829. pOut->u.r = rB;
  65830. MemSetTypeFlag(pOut, MEM_Real);
  65831. if( ((type1|type2)&MEM_Real)==0 && !bIntint ){
  65832. sqlite3VdbeIntegerAffinity(pOut);
  65833. }
  65834. #endif
  65835. }
  65836. break;
  65837. arithmetic_result_is_null:
  65838. sqlite3VdbeMemSetNull(pOut);
  65839. break;
  65840. }
  65841. /* Opcode: CollSeq P1 * * P4
  65842. **
  65843. ** P4 is a pointer to a CollSeq struct. If the next call to a user function
  65844. ** or aggregate calls sqlite3GetFuncCollSeq(), this collation sequence will
  65845. ** be returned. This is used by the built-in min(), max() and nullif()
  65846. ** functions.
  65847. **
  65848. ** If P1 is not zero, then it is a register that a subsequent min() or
  65849. ** max() aggregate will set to 1 if the current row is not the minimum or
  65850. ** maximum. The P1 register is initialized to 0 by this instruction.
  65851. **
  65852. ** The interface used by the implementation of the aforementioned functions
  65853. ** to retrieve the collation sequence set by this opcode is not available
  65854. ** publicly, only to user functions defined in func.c.
  65855. */
  65856. case OP_CollSeq: {
  65857. assert( pOp->p4type==P4_COLLSEQ );
  65858. if( pOp->p1 ){
  65859. sqlite3VdbeMemSetInt64(&aMem[pOp->p1], 0);
  65860. }
  65861. break;
  65862. }
  65863. /* Opcode: Function P1 P2 P3 P4 P5
  65864. ** Synopsis: r[P3]=func(r[P2@P5])
  65865. **
  65866. ** Invoke a user function (P4 is a pointer to a Function structure that
  65867. ** defines the function) with P5 arguments taken from register P2 and
  65868. ** successors. The result of the function is stored in register P3.
  65869. ** Register P3 must not be one of the function inputs.
  65870. **
  65871. ** P1 is a 32-bit bitmask indicating whether or not each argument to the
  65872. ** function was determined to be constant at compile time. If the first
  65873. ** argument was constant then bit 0 of P1 is set. This is used to determine
  65874. ** whether meta data associated with a user function argument using the
  65875. ** sqlite3_set_auxdata() API may be safely retained until the next
  65876. ** invocation of this opcode.
  65877. **
  65878. ** See also: AggStep and AggFinal
  65879. */
  65880. case OP_Function: {
  65881. int i;
  65882. Mem *pArg;
  65883. sqlite3_context ctx;
  65884. sqlite3_value **apVal;
  65885. int n;
  65886. n = pOp->p5;
  65887. apVal = p->apArg;
  65888. assert( apVal || n==0 );
  65889. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  65890. ctx.pOut = &aMem[pOp->p3];
  65891. memAboutToChange(p, ctx.pOut);
  65892. assert( n==0 || (pOp->p2>0 && pOp->p2+n<=(p->nMem-p->nCursor)+1) );
  65893. assert( pOp->p3<pOp->p2 || pOp->p3>=pOp->p2+n );
  65894. pArg = &aMem[pOp->p2];
  65895. for(i=0; i<n; i++, pArg++){
  65896. assert( memIsValid(pArg) );
  65897. apVal[i] = pArg;
  65898. Deephemeralize(pArg);
  65899. REGISTER_TRACE(pOp->p2+i, pArg);
  65900. }
  65901. assert( pOp->p4type==P4_FUNCDEF );
  65902. ctx.pFunc = pOp->p4.pFunc;
  65903. ctx.iOp = pc;
  65904. ctx.pVdbe = p;
  65905. MemSetTypeFlag(ctx.pOut, MEM_Null);
  65906. ctx.fErrorOrAux = 0;
  65907. db->lastRowid = lastRowid;
  65908. (*ctx.pFunc->xFunc)(&ctx, n, apVal); /* IMP: R-24505-23230 */
  65909. lastRowid = db->lastRowid; /* Remember rowid changes made by xFunc */
  65910. /* If the function returned an error, throw an exception */
  65911. if( ctx.fErrorOrAux ){
  65912. if( ctx.isError ){
  65913. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(ctx.pOut));
  65914. rc = ctx.isError;
  65915. }
  65916. sqlite3VdbeDeleteAuxData(p, pc, pOp->p1);
  65917. }
  65918. /* Copy the result of the function into register P3 */
  65919. sqlite3VdbeChangeEncoding(ctx.pOut, encoding);
  65920. if( sqlite3VdbeMemTooBig(ctx.pOut) ){
  65921. goto too_big;
  65922. }
  65923. REGISTER_TRACE(pOp->p3, ctx.pOut);
  65924. UPDATE_MAX_BLOBSIZE(ctx.pOut);
  65925. break;
  65926. }
  65927. /* Opcode: BitAnd P1 P2 P3 * *
  65928. ** Synopsis: r[P3]=r[P1]&r[P2]
  65929. **
  65930. ** Take the bit-wise AND of the values in register P1 and P2 and
  65931. ** store the result in register P3.
  65932. ** If either input is NULL, the result is NULL.
  65933. */
  65934. /* Opcode: BitOr P1 P2 P3 * *
  65935. ** Synopsis: r[P3]=r[P1]|r[P2]
  65936. **
  65937. ** Take the bit-wise OR of the values in register P1 and P2 and
  65938. ** store the result in register P3.
  65939. ** If either input is NULL, the result is NULL.
  65940. */
  65941. /* Opcode: ShiftLeft P1 P2 P3 * *
  65942. ** Synopsis: r[P3]=r[P2]<<r[P1]
  65943. **
  65944. ** Shift the integer value in register P2 to the left by the
  65945. ** number of bits specified by the integer in register P1.
  65946. ** Store the result in register P3.
  65947. ** If either input is NULL, the result is NULL.
  65948. */
  65949. /* Opcode: ShiftRight P1 P2 P3 * *
  65950. ** Synopsis: r[P3]=r[P2]>>r[P1]
  65951. **
  65952. ** Shift the integer value in register P2 to the right by the
  65953. ** number of bits specified by the integer in register P1.
  65954. ** Store the result in register P3.
  65955. ** If either input is NULL, the result is NULL.
  65956. */
  65957. case OP_BitAnd: /* same as TK_BITAND, in1, in2, out3 */
  65958. case OP_BitOr: /* same as TK_BITOR, in1, in2, out3 */
  65959. case OP_ShiftLeft: /* same as TK_LSHIFT, in1, in2, out3 */
  65960. case OP_ShiftRight: { /* same as TK_RSHIFT, in1, in2, out3 */
  65961. i64 iA;
  65962. u64 uA;
  65963. i64 iB;
  65964. u8 op;
  65965. pIn1 = &aMem[pOp->p1];
  65966. pIn2 = &aMem[pOp->p2];
  65967. pOut = &aMem[pOp->p3];
  65968. if( (pIn1->flags | pIn2->flags) & MEM_Null ){
  65969. sqlite3VdbeMemSetNull(pOut);
  65970. break;
  65971. }
  65972. iA = sqlite3VdbeIntValue(pIn2);
  65973. iB = sqlite3VdbeIntValue(pIn1);
  65974. op = pOp->opcode;
  65975. if( op==OP_BitAnd ){
  65976. iA &= iB;
  65977. }else if( op==OP_BitOr ){
  65978. iA |= iB;
  65979. }else if( iB!=0 ){
  65980. assert( op==OP_ShiftRight || op==OP_ShiftLeft );
  65981. /* If shifting by a negative amount, shift in the other direction */
  65982. if( iB<0 ){
  65983. assert( OP_ShiftRight==OP_ShiftLeft+1 );
  65984. op = 2*OP_ShiftLeft + 1 - op;
  65985. iB = iB>(-64) ? -iB : 64;
  65986. }
  65987. if( iB>=64 ){
  65988. iA = (iA>=0 || op==OP_ShiftLeft) ? 0 : -1;
  65989. }else{
  65990. memcpy(&uA, &iA, sizeof(uA));
  65991. if( op==OP_ShiftLeft ){
  65992. uA <<= iB;
  65993. }else{
  65994. uA >>= iB;
  65995. /* Sign-extend on a right shift of a negative number */
  65996. if( iA<0 ) uA |= ((((u64)0xffffffff)<<32)|0xffffffff) << (64-iB);
  65997. }
  65998. memcpy(&iA, &uA, sizeof(iA));
  65999. }
  66000. }
  66001. pOut->u.i = iA;
  66002. MemSetTypeFlag(pOut, MEM_Int);
  66003. break;
  66004. }
  66005. /* Opcode: AddImm P1 P2 * * *
  66006. ** Synopsis: r[P1]=r[P1]+P2
  66007. **
  66008. ** Add the constant P2 to the value in register P1.
  66009. ** The result is always an integer.
  66010. **
  66011. ** To force any register to be an integer, just add 0.
  66012. */
  66013. case OP_AddImm: { /* in1 */
  66014. pIn1 = &aMem[pOp->p1];
  66015. memAboutToChange(p, pIn1);
  66016. sqlite3VdbeMemIntegerify(pIn1);
  66017. pIn1->u.i += pOp->p2;
  66018. break;
  66019. }
  66020. /* Opcode: MustBeInt P1 P2 * * *
  66021. **
  66022. ** Force the value in register P1 to be an integer. If the value
  66023. ** in P1 is not an integer and cannot be converted into an integer
  66024. ** without data loss, then jump immediately to P2, or if P2==0
  66025. ** raise an SQLITE_MISMATCH exception.
  66026. */
  66027. case OP_MustBeInt: { /* jump, in1 */
  66028. pIn1 = &aMem[pOp->p1];
  66029. if( (pIn1->flags & MEM_Int)==0 ){
  66030. applyAffinity(pIn1, SQLITE_AFF_NUMERIC, encoding);
  66031. VdbeBranchTaken((pIn1->flags&MEM_Int)==0, 2);
  66032. if( (pIn1->flags & MEM_Int)==0 ){
  66033. if( pOp->p2==0 ){
  66034. rc = SQLITE_MISMATCH;
  66035. goto abort_due_to_error;
  66036. }else{
  66037. pc = pOp->p2 - 1;
  66038. break;
  66039. }
  66040. }
  66041. }
  66042. MemSetTypeFlag(pIn1, MEM_Int);
  66043. break;
  66044. }
  66045. #ifndef SQLITE_OMIT_FLOATING_POINT
  66046. /* Opcode: RealAffinity P1 * * * *
  66047. **
  66048. ** If register P1 holds an integer convert it to a real value.
  66049. **
  66050. ** This opcode is used when extracting information from a column that
  66051. ** has REAL affinity. Such column values may still be stored as
  66052. ** integers, for space efficiency, but after extraction we want them
  66053. ** to have only a real value.
  66054. */
  66055. case OP_RealAffinity: { /* in1 */
  66056. pIn1 = &aMem[pOp->p1];
  66057. if( pIn1->flags & MEM_Int ){
  66058. sqlite3VdbeMemRealify(pIn1);
  66059. }
  66060. break;
  66061. }
  66062. #endif
  66063. #ifndef SQLITE_OMIT_CAST
  66064. /* Opcode: Cast P1 P2 * * *
  66065. ** Synopsis: affinity(r[P1])
  66066. **
  66067. ** Force the value in register P1 to be the type defined by P2.
  66068. **
  66069. ** <ul>
  66070. ** <li value="97"> TEXT
  66071. ** <li value="98"> BLOB
  66072. ** <li value="99"> NUMERIC
  66073. ** <li value="100"> INTEGER
  66074. ** <li value="101"> REAL
  66075. ** </ul>
  66076. **
  66077. ** A NULL value is not changed by this routine. It remains NULL.
  66078. */
  66079. case OP_Cast: { /* in1 */
  66080. assert( pOp->p2>=SQLITE_AFF_NONE && pOp->p2<=SQLITE_AFF_REAL );
  66081. testcase( pOp->p2==SQLITE_AFF_TEXT );
  66082. testcase( pOp->p2==SQLITE_AFF_NONE );
  66083. testcase( pOp->p2==SQLITE_AFF_NUMERIC );
  66084. testcase( pOp->p2==SQLITE_AFF_INTEGER );
  66085. testcase( pOp->p2==SQLITE_AFF_REAL );
  66086. pIn1 = &aMem[pOp->p1];
  66087. memAboutToChange(p, pIn1);
  66088. rc = ExpandBlob(pIn1);
  66089. sqlite3VdbeMemCast(pIn1, pOp->p2, encoding);
  66090. UPDATE_MAX_BLOBSIZE(pIn1);
  66091. break;
  66092. }
  66093. #endif /* SQLITE_OMIT_CAST */
  66094. /* Opcode: Lt P1 P2 P3 P4 P5
  66095. ** Synopsis: if r[P1]<r[P3] goto P2
  66096. **
  66097. ** Compare the values in register P1 and P3. If reg(P3)<reg(P1) then
  66098. ** jump to address P2.
  66099. **
  66100. ** If the SQLITE_JUMPIFNULL bit of P5 is set and either reg(P1) or
  66101. ** reg(P3) is NULL then take the jump. If the SQLITE_JUMPIFNULL
  66102. ** bit is clear then fall through if either operand is NULL.
  66103. **
  66104. ** The SQLITE_AFF_MASK portion of P5 must be an affinity character -
  66105. ** SQLITE_AFF_TEXT, SQLITE_AFF_INTEGER, and so forth. An attempt is made
  66106. ** to coerce both inputs according to this affinity before the
  66107. ** comparison is made. If the SQLITE_AFF_MASK is 0x00, then numeric
  66108. ** affinity is used. Note that the affinity conversions are stored
  66109. ** back into the input registers P1 and P3. So this opcode can cause
  66110. ** persistent changes to registers P1 and P3.
  66111. **
  66112. ** Once any conversions have taken place, and neither value is NULL,
  66113. ** the values are compared. If both values are blobs then memcmp() is
  66114. ** used to determine the results of the comparison. If both values
  66115. ** are text, then the appropriate collating function specified in
  66116. ** P4 is used to do the comparison. If P4 is not specified then
  66117. ** memcmp() is used to compare text string. If both values are
  66118. ** numeric, then a numeric comparison is used. If the two values
  66119. ** are of different types, then numbers are considered less than
  66120. ** strings and strings are considered less than blobs.
  66121. **
  66122. ** If the SQLITE_STOREP2 bit of P5 is set, then do not jump. Instead,
  66123. ** store a boolean result (either 0, or 1, or NULL) in register P2.
  66124. **
  66125. ** If the SQLITE_NULLEQ bit is set in P5, then NULL values are considered
  66126. ** equal to one another, provided that they do not have their MEM_Cleared
  66127. ** bit set.
  66128. */
  66129. /* Opcode: Ne P1 P2 P3 P4 P5
  66130. ** Synopsis: if r[P1]!=r[P3] goto P2
  66131. **
  66132. ** This works just like the Lt opcode except that the jump is taken if
  66133. ** the operands in registers P1 and P3 are not equal. See the Lt opcode for
  66134. ** additional information.
  66135. **
  66136. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  66137. ** true or false and is never NULL. If both operands are NULL then the result
  66138. ** of comparison is false. If either operand is NULL then the result is true.
  66139. ** If neither operand is NULL the result is the same as it would be if
  66140. ** the SQLITE_NULLEQ flag were omitted from P5.
  66141. */
  66142. /* Opcode: Eq P1 P2 P3 P4 P5
  66143. ** Synopsis: if r[P1]==r[P3] goto P2
  66144. **
  66145. ** This works just like the Lt opcode except that the jump is taken if
  66146. ** the operands in registers P1 and P3 are equal.
  66147. ** See the Lt opcode for additional information.
  66148. **
  66149. ** If SQLITE_NULLEQ is set in P5 then the result of comparison is always either
  66150. ** true or false and is never NULL. If both operands are NULL then the result
  66151. ** of comparison is true. If either operand is NULL then the result is false.
  66152. ** If neither operand is NULL the result is the same as it would be if
  66153. ** the SQLITE_NULLEQ flag were omitted from P5.
  66154. */
  66155. /* Opcode: Le P1 P2 P3 P4 P5
  66156. ** Synopsis: if r[P1]<=r[P3] goto P2
  66157. **
  66158. ** This works just like the Lt opcode except that the jump is taken if
  66159. ** the content of register P3 is less than or equal to the content of
  66160. ** register P1. See the Lt opcode for additional information.
  66161. */
  66162. /* Opcode: Gt P1 P2 P3 P4 P5
  66163. ** Synopsis: if r[P1]>r[P3] goto P2
  66164. **
  66165. ** This works just like the Lt opcode except that the jump is taken if
  66166. ** the content of register P3 is greater than the content of
  66167. ** register P1. See the Lt opcode for additional information.
  66168. */
  66169. /* Opcode: Ge P1 P2 P3 P4 P5
  66170. ** Synopsis: if r[P1]>=r[P3] goto P2
  66171. **
  66172. ** This works just like the Lt opcode except that the jump is taken if
  66173. ** the content of register P3 is greater than or equal to the content of
  66174. ** register P1. See the Lt opcode for additional information.
  66175. */
  66176. case OP_Eq: /* same as TK_EQ, jump, in1, in3 */
  66177. case OP_Ne: /* same as TK_NE, jump, in1, in3 */
  66178. case OP_Lt: /* same as TK_LT, jump, in1, in3 */
  66179. case OP_Le: /* same as TK_LE, jump, in1, in3 */
  66180. case OP_Gt: /* same as TK_GT, jump, in1, in3 */
  66181. case OP_Ge: { /* same as TK_GE, jump, in1, in3 */
  66182. int res; /* Result of the comparison of pIn1 against pIn3 */
  66183. char affinity; /* Affinity to use for comparison */
  66184. u16 flags1; /* Copy of initial value of pIn1->flags */
  66185. u16 flags3; /* Copy of initial value of pIn3->flags */
  66186. pIn1 = &aMem[pOp->p1];
  66187. pIn3 = &aMem[pOp->p3];
  66188. flags1 = pIn1->flags;
  66189. flags3 = pIn3->flags;
  66190. if( (flags1 | flags3)&MEM_Null ){
  66191. /* One or both operands are NULL */
  66192. if( pOp->p5 & SQLITE_NULLEQ ){
  66193. /* If SQLITE_NULLEQ is set (which will only happen if the operator is
  66194. ** OP_Eq or OP_Ne) then take the jump or not depending on whether
  66195. ** or not both operands are null.
  66196. */
  66197. assert( pOp->opcode==OP_Eq || pOp->opcode==OP_Ne );
  66198. assert( (flags1 & MEM_Cleared)==0 );
  66199. assert( (pOp->p5 & SQLITE_JUMPIFNULL)==0 );
  66200. if( (flags1&MEM_Null)!=0
  66201. && (flags3&MEM_Null)!=0
  66202. && (flags3&MEM_Cleared)==0
  66203. ){
  66204. res = 0; /* Results are equal */
  66205. }else{
  66206. res = 1; /* Results are not equal */
  66207. }
  66208. }else{
  66209. /* SQLITE_NULLEQ is clear and at least one operand is NULL,
  66210. ** then the result is always NULL.
  66211. ** The jump is taken if the SQLITE_JUMPIFNULL bit is set.
  66212. */
  66213. if( pOp->p5 & SQLITE_STOREP2 ){
  66214. pOut = &aMem[pOp->p2];
  66215. MemSetTypeFlag(pOut, MEM_Null);
  66216. REGISTER_TRACE(pOp->p2, pOut);
  66217. }else{
  66218. VdbeBranchTaken(2,3);
  66219. if( pOp->p5 & SQLITE_JUMPIFNULL ){
  66220. pc = pOp->p2-1;
  66221. }
  66222. }
  66223. break;
  66224. }
  66225. }else{
  66226. /* Neither operand is NULL. Do a comparison. */
  66227. affinity = pOp->p5 & SQLITE_AFF_MASK;
  66228. if( affinity>=SQLITE_AFF_NUMERIC ){
  66229. if( (pIn1->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  66230. applyNumericAffinity(pIn1,0);
  66231. }
  66232. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  66233. applyNumericAffinity(pIn3,0);
  66234. }
  66235. }else if( affinity==SQLITE_AFF_TEXT ){
  66236. if( (pIn1->flags & MEM_Str)==0 && (pIn1->flags & (MEM_Int|MEM_Real))!=0 ){
  66237. testcase( pIn1->flags & MEM_Int );
  66238. testcase( pIn1->flags & MEM_Real );
  66239. sqlite3VdbeMemStringify(pIn1, encoding, 1);
  66240. }
  66241. if( (pIn3->flags & MEM_Str)==0 && (pIn3->flags & (MEM_Int|MEM_Real))!=0 ){
  66242. testcase( pIn3->flags & MEM_Int );
  66243. testcase( pIn3->flags & MEM_Real );
  66244. sqlite3VdbeMemStringify(pIn3, encoding, 1);
  66245. }
  66246. }
  66247. assert( pOp->p4type==P4_COLLSEQ || pOp->p4.pColl==0 );
  66248. if( pIn1->flags & MEM_Zero ){
  66249. sqlite3VdbeMemExpandBlob(pIn1);
  66250. flags1 &= ~MEM_Zero;
  66251. }
  66252. if( pIn3->flags & MEM_Zero ){
  66253. sqlite3VdbeMemExpandBlob(pIn3);
  66254. flags3 &= ~MEM_Zero;
  66255. }
  66256. if( db->mallocFailed ) goto no_mem;
  66257. res = sqlite3MemCompare(pIn3, pIn1, pOp->p4.pColl);
  66258. }
  66259. switch( pOp->opcode ){
  66260. case OP_Eq: res = res==0; break;
  66261. case OP_Ne: res = res!=0; break;
  66262. case OP_Lt: res = res<0; break;
  66263. case OP_Le: res = res<=0; break;
  66264. case OP_Gt: res = res>0; break;
  66265. default: res = res>=0; break;
  66266. }
  66267. if( pOp->p5 & SQLITE_STOREP2 ){
  66268. pOut = &aMem[pOp->p2];
  66269. memAboutToChange(p, pOut);
  66270. MemSetTypeFlag(pOut, MEM_Int);
  66271. pOut->u.i = res;
  66272. REGISTER_TRACE(pOp->p2, pOut);
  66273. }else{
  66274. VdbeBranchTaken(res!=0, (pOp->p5 & SQLITE_NULLEQ)?2:3);
  66275. if( res ){
  66276. pc = pOp->p2-1;
  66277. }
  66278. }
  66279. /* Undo any changes made by applyAffinity() to the input registers. */
  66280. pIn1->flags = flags1;
  66281. pIn3->flags = flags3;
  66282. break;
  66283. }
  66284. /* Opcode: Permutation * * * P4 *
  66285. **
  66286. ** Set the permutation used by the OP_Compare operator to be the array
  66287. ** of integers in P4.
  66288. **
  66289. ** The permutation is only valid until the next OP_Compare that has
  66290. ** the OPFLAG_PERMUTE bit set in P5. Typically the OP_Permutation should
  66291. ** occur immediately prior to the OP_Compare.
  66292. */
  66293. case OP_Permutation: {
  66294. assert( pOp->p4type==P4_INTARRAY );
  66295. assert( pOp->p4.ai );
  66296. aPermute = pOp->p4.ai;
  66297. break;
  66298. }
  66299. /* Opcode: Compare P1 P2 P3 P4 P5
  66300. ** Synopsis: r[P1@P3] <-> r[P2@P3]
  66301. **
  66302. ** Compare two vectors of registers in reg(P1)..reg(P1+P3-1) (call this
  66303. ** vector "A") and in reg(P2)..reg(P2+P3-1) ("B"). Save the result of
  66304. ** the comparison for use by the next OP_Jump instruct.
  66305. **
  66306. ** If P5 has the OPFLAG_PERMUTE bit set, then the order of comparison is
  66307. ** determined by the most recent OP_Permutation operator. If the
  66308. ** OPFLAG_PERMUTE bit is clear, then register are compared in sequential
  66309. ** order.
  66310. **
  66311. ** P4 is a KeyInfo structure that defines collating sequences and sort
  66312. ** orders for the comparison. The permutation applies to registers
  66313. ** only. The KeyInfo elements are used sequentially.
  66314. **
  66315. ** The comparison is a sort comparison, so NULLs compare equal,
  66316. ** NULLs are less than numbers, numbers are less than strings,
  66317. ** and strings are less than blobs.
  66318. */
  66319. case OP_Compare: {
  66320. int n;
  66321. int i;
  66322. int p1;
  66323. int p2;
  66324. const KeyInfo *pKeyInfo;
  66325. int idx;
  66326. CollSeq *pColl; /* Collating sequence to use on this term */
  66327. int bRev; /* True for DESCENDING sort order */
  66328. if( (pOp->p5 & OPFLAG_PERMUTE)==0 ) aPermute = 0;
  66329. n = pOp->p3;
  66330. pKeyInfo = pOp->p4.pKeyInfo;
  66331. assert( n>0 );
  66332. assert( pKeyInfo!=0 );
  66333. p1 = pOp->p1;
  66334. p2 = pOp->p2;
  66335. #if SQLITE_DEBUG
  66336. if( aPermute ){
  66337. int k, mx = 0;
  66338. for(k=0; k<n; k++) if( aPermute[k]>mx ) mx = aPermute[k];
  66339. assert( p1>0 && p1+mx<=(p->nMem-p->nCursor)+1 );
  66340. assert( p2>0 && p2+mx<=(p->nMem-p->nCursor)+1 );
  66341. }else{
  66342. assert( p1>0 && p1+n<=(p->nMem-p->nCursor)+1 );
  66343. assert( p2>0 && p2+n<=(p->nMem-p->nCursor)+1 );
  66344. }
  66345. #endif /* SQLITE_DEBUG */
  66346. for(i=0; i<n; i++){
  66347. idx = aPermute ? aPermute[i] : i;
  66348. assert( memIsValid(&aMem[p1+idx]) );
  66349. assert( memIsValid(&aMem[p2+idx]) );
  66350. REGISTER_TRACE(p1+idx, &aMem[p1+idx]);
  66351. REGISTER_TRACE(p2+idx, &aMem[p2+idx]);
  66352. assert( i<pKeyInfo->nField );
  66353. pColl = pKeyInfo->aColl[i];
  66354. bRev = pKeyInfo->aSortOrder[i];
  66355. iCompare = sqlite3MemCompare(&aMem[p1+idx], &aMem[p2+idx], pColl);
  66356. if( iCompare ){
  66357. if( bRev ) iCompare = -iCompare;
  66358. break;
  66359. }
  66360. }
  66361. aPermute = 0;
  66362. break;
  66363. }
  66364. /* Opcode: Jump P1 P2 P3 * *
  66365. **
  66366. ** Jump to the instruction at address P1, P2, or P3 depending on whether
  66367. ** in the most recent OP_Compare instruction the P1 vector was less than
  66368. ** equal to, or greater than the P2 vector, respectively.
  66369. */
  66370. case OP_Jump: { /* jump */
  66371. if( iCompare<0 ){
  66372. pc = pOp->p1 - 1; VdbeBranchTaken(0,3);
  66373. }else if( iCompare==0 ){
  66374. pc = pOp->p2 - 1; VdbeBranchTaken(1,3);
  66375. }else{
  66376. pc = pOp->p3 - 1; VdbeBranchTaken(2,3);
  66377. }
  66378. break;
  66379. }
  66380. /* Opcode: And P1 P2 P3 * *
  66381. ** Synopsis: r[P3]=(r[P1] && r[P2])
  66382. **
  66383. ** Take the logical AND of the values in registers P1 and P2 and
  66384. ** write the result into register P3.
  66385. **
  66386. ** If either P1 or P2 is 0 (false) then the result is 0 even if
  66387. ** the other input is NULL. A NULL and true or two NULLs give
  66388. ** a NULL output.
  66389. */
  66390. /* Opcode: Or P1 P2 P3 * *
  66391. ** Synopsis: r[P3]=(r[P1] || r[P2])
  66392. **
  66393. ** Take the logical OR of the values in register P1 and P2 and
  66394. ** store the answer in register P3.
  66395. **
  66396. ** If either P1 or P2 is nonzero (true) then the result is 1 (true)
  66397. ** even if the other input is NULL. A NULL and false or two NULLs
  66398. ** give a NULL output.
  66399. */
  66400. case OP_And: /* same as TK_AND, in1, in2, out3 */
  66401. case OP_Or: { /* same as TK_OR, in1, in2, out3 */
  66402. int v1; /* Left operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  66403. int v2; /* Right operand: 0==FALSE, 1==TRUE, 2==UNKNOWN or NULL */
  66404. pIn1 = &aMem[pOp->p1];
  66405. if( pIn1->flags & MEM_Null ){
  66406. v1 = 2;
  66407. }else{
  66408. v1 = sqlite3VdbeIntValue(pIn1)!=0;
  66409. }
  66410. pIn2 = &aMem[pOp->p2];
  66411. if( pIn2->flags & MEM_Null ){
  66412. v2 = 2;
  66413. }else{
  66414. v2 = sqlite3VdbeIntValue(pIn2)!=0;
  66415. }
  66416. if( pOp->opcode==OP_And ){
  66417. static const unsigned char and_logic[] = { 0, 0, 0, 0, 1, 2, 0, 2, 2 };
  66418. v1 = and_logic[v1*3+v2];
  66419. }else{
  66420. static const unsigned char or_logic[] = { 0, 1, 2, 1, 1, 1, 2, 1, 2 };
  66421. v1 = or_logic[v1*3+v2];
  66422. }
  66423. pOut = &aMem[pOp->p3];
  66424. if( v1==2 ){
  66425. MemSetTypeFlag(pOut, MEM_Null);
  66426. }else{
  66427. pOut->u.i = v1;
  66428. MemSetTypeFlag(pOut, MEM_Int);
  66429. }
  66430. break;
  66431. }
  66432. /* Opcode: Not P1 P2 * * *
  66433. ** Synopsis: r[P2]= !r[P1]
  66434. **
  66435. ** Interpret the value in register P1 as a boolean value. Store the
  66436. ** boolean complement in register P2. If the value in register P1 is
  66437. ** NULL, then a NULL is stored in P2.
  66438. */
  66439. case OP_Not: { /* same as TK_NOT, in1, out2 */
  66440. pIn1 = &aMem[pOp->p1];
  66441. pOut = &aMem[pOp->p2];
  66442. sqlite3VdbeMemSetNull(pOut);
  66443. if( (pIn1->flags & MEM_Null)==0 ){
  66444. pOut->flags = MEM_Int;
  66445. pOut->u.i = !sqlite3VdbeIntValue(pIn1);
  66446. }
  66447. break;
  66448. }
  66449. /* Opcode: BitNot P1 P2 * * *
  66450. ** Synopsis: r[P1]= ~r[P1]
  66451. **
  66452. ** Interpret the content of register P1 as an integer. Store the
  66453. ** ones-complement of the P1 value into register P2. If P1 holds
  66454. ** a NULL then store a NULL in P2.
  66455. */
  66456. case OP_BitNot: { /* same as TK_BITNOT, in1, out2 */
  66457. pIn1 = &aMem[pOp->p1];
  66458. pOut = &aMem[pOp->p2];
  66459. sqlite3VdbeMemSetNull(pOut);
  66460. if( (pIn1->flags & MEM_Null)==0 ){
  66461. pOut->flags = MEM_Int;
  66462. pOut->u.i = ~sqlite3VdbeIntValue(pIn1);
  66463. }
  66464. break;
  66465. }
  66466. /* Opcode: Once P1 P2 * * *
  66467. **
  66468. ** Check the "once" flag number P1. If it is set, jump to instruction P2.
  66469. ** Otherwise, set the flag and fall through to the next instruction.
  66470. ** In other words, this opcode causes all following opcodes up through P2
  66471. ** (but not including P2) to run just once and to be skipped on subsequent
  66472. ** times through the loop.
  66473. **
  66474. ** All "once" flags are initially cleared whenever a prepared statement
  66475. ** first begins to run.
  66476. */
  66477. case OP_Once: { /* jump */
  66478. assert( pOp->p1<p->nOnceFlag );
  66479. VdbeBranchTaken(p->aOnceFlag[pOp->p1]!=0, 2);
  66480. if( p->aOnceFlag[pOp->p1] ){
  66481. pc = pOp->p2-1;
  66482. }else{
  66483. p->aOnceFlag[pOp->p1] = 1;
  66484. }
  66485. break;
  66486. }
  66487. /* Opcode: If P1 P2 P3 * *
  66488. **
  66489. ** Jump to P2 if the value in register P1 is true. The value
  66490. ** is considered true if it is numeric and non-zero. If the value
  66491. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  66492. */
  66493. /* Opcode: IfNot P1 P2 P3 * *
  66494. **
  66495. ** Jump to P2 if the value in register P1 is False. The value
  66496. ** is considered false if it has a numeric value of zero. If the value
  66497. ** in P1 is NULL then take the jump if and only if P3 is non-zero.
  66498. */
  66499. case OP_If: /* jump, in1 */
  66500. case OP_IfNot: { /* jump, in1 */
  66501. int c;
  66502. pIn1 = &aMem[pOp->p1];
  66503. if( pIn1->flags & MEM_Null ){
  66504. c = pOp->p3;
  66505. }else{
  66506. #ifdef SQLITE_OMIT_FLOATING_POINT
  66507. c = sqlite3VdbeIntValue(pIn1)!=0;
  66508. #else
  66509. c = sqlite3VdbeRealValue(pIn1)!=0.0;
  66510. #endif
  66511. if( pOp->opcode==OP_IfNot ) c = !c;
  66512. }
  66513. VdbeBranchTaken(c!=0, 2);
  66514. if( c ){
  66515. pc = pOp->p2-1;
  66516. }
  66517. break;
  66518. }
  66519. /* Opcode: IsNull P1 P2 * * *
  66520. ** Synopsis: if r[P1]==NULL goto P2
  66521. **
  66522. ** Jump to P2 if the value in register P1 is NULL.
  66523. */
  66524. case OP_IsNull: { /* same as TK_ISNULL, jump, in1 */
  66525. pIn1 = &aMem[pOp->p1];
  66526. VdbeBranchTaken( (pIn1->flags & MEM_Null)!=0, 2);
  66527. if( (pIn1->flags & MEM_Null)!=0 ){
  66528. pc = pOp->p2 - 1;
  66529. }
  66530. break;
  66531. }
  66532. /* Opcode: NotNull P1 P2 * * *
  66533. ** Synopsis: if r[P1]!=NULL goto P2
  66534. **
  66535. ** Jump to P2 if the value in register P1 is not NULL.
  66536. */
  66537. case OP_NotNull: { /* same as TK_NOTNULL, jump, in1 */
  66538. pIn1 = &aMem[pOp->p1];
  66539. VdbeBranchTaken( (pIn1->flags & MEM_Null)==0, 2);
  66540. if( (pIn1->flags & MEM_Null)==0 ){
  66541. pc = pOp->p2 - 1;
  66542. }
  66543. break;
  66544. }
  66545. /* Opcode: Column P1 P2 P3 P4 P5
  66546. ** Synopsis: r[P3]=PX
  66547. **
  66548. ** Interpret the data that cursor P1 points to as a structure built using
  66549. ** the MakeRecord instruction. (See the MakeRecord opcode for additional
  66550. ** information about the format of the data.) Extract the P2-th column
  66551. ** from this record. If there are less that (P2+1)
  66552. ** values in the record, extract a NULL.
  66553. **
  66554. ** The value extracted is stored in register P3.
  66555. **
  66556. ** If the column contains fewer than P2 fields, then extract a NULL. Or,
  66557. ** if the P4 argument is a P4_MEM use the value of the P4 argument as
  66558. ** the result.
  66559. **
  66560. ** If the OPFLAG_CLEARCACHE bit is set on P5 and P1 is a pseudo-table cursor,
  66561. ** then the cache of the cursor is reset prior to extracting the column.
  66562. ** The first OP_Column against a pseudo-table after the value of the content
  66563. ** register has changed should have this bit set.
  66564. **
  66565. ** If the OPFLAG_LENGTHARG and OPFLAG_TYPEOFARG bits are set on P5 when
  66566. ** the result is guaranteed to only be used as the argument of a length()
  66567. ** or typeof() function, respectively. The loading of large blobs can be
  66568. ** skipped for length() and all content loading can be skipped for typeof().
  66569. */
  66570. case OP_Column: {
  66571. i64 payloadSize64; /* Number of bytes in the record */
  66572. int p2; /* column number to retrieve */
  66573. VdbeCursor *pC; /* The VDBE cursor */
  66574. BtCursor *pCrsr; /* The BTree cursor */
  66575. u32 *aOffset; /* aOffset[i] is offset to start of data for i-th column */
  66576. int len; /* The length of the serialized data for the column */
  66577. int i; /* Loop counter */
  66578. Mem *pDest; /* Where to write the extracted value */
  66579. Mem sMem; /* For storing the record being decoded */
  66580. const u8 *zData; /* Part of the record being decoded */
  66581. const u8 *zHdr; /* Next unparsed byte of the header */
  66582. const u8 *zEndHdr; /* Pointer to first byte after the header */
  66583. u32 offset; /* Offset into the data */
  66584. u32 szField; /* Number of bytes in the content of a field */
  66585. u32 avail; /* Number of bytes of available data */
  66586. u32 t; /* A type code from the record header */
  66587. u16 fx; /* pDest->flags value */
  66588. Mem *pReg; /* PseudoTable input register */
  66589. p2 = pOp->p2;
  66590. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  66591. pDest = &aMem[pOp->p3];
  66592. memAboutToChange(p, pDest);
  66593. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  66594. pC = p->apCsr[pOp->p1];
  66595. assert( pC!=0 );
  66596. assert( p2<pC->nField );
  66597. aOffset = pC->aOffset;
  66598. #ifndef SQLITE_OMIT_VIRTUALTABLE
  66599. assert( pC->pVtabCursor==0 ); /* OP_Column never called on virtual table */
  66600. #endif
  66601. pCrsr = pC->pCursor;
  66602. assert( pCrsr!=0 || pC->pseudoTableReg>0 ); /* pCrsr NULL on PseudoTables */
  66603. assert( pCrsr!=0 || pC->nullRow ); /* pC->nullRow on PseudoTables */
  66604. /* If the cursor cache is stale, bring it up-to-date */
  66605. rc = sqlite3VdbeCursorMoveto(pC);
  66606. if( rc ) goto abort_due_to_error;
  66607. if( pC->cacheStatus!=p->cacheCtr ){
  66608. if( pC->nullRow ){
  66609. if( pCrsr==0 ){
  66610. assert( pC->pseudoTableReg>0 );
  66611. pReg = &aMem[pC->pseudoTableReg];
  66612. assert( pReg->flags & MEM_Blob );
  66613. assert( memIsValid(pReg) );
  66614. pC->payloadSize = pC->szRow = avail = pReg->n;
  66615. pC->aRow = (u8*)pReg->z;
  66616. }else{
  66617. sqlite3VdbeMemSetNull(pDest);
  66618. goto op_column_out;
  66619. }
  66620. }else{
  66621. assert( pCrsr );
  66622. if( pC->isTable==0 ){
  66623. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  66624. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &payloadSize64);
  66625. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  66626. /* sqlite3BtreeParseCellPtr() uses getVarint32() to extract the
  66627. ** payload size, so it is impossible for payloadSize64 to be
  66628. ** larger than 32 bits. */
  66629. assert( (payloadSize64 & SQLITE_MAX_U32)==(u64)payloadSize64 );
  66630. pC->aRow = sqlite3BtreeKeyFetch(pCrsr, &avail);
  66631. pC->payloadSize = (u32)payloadSize64;
  66632. }else{
  66633. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  66634. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &pC->payloadSize);
  66635. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  66636. pC->aRow = sqlite3BtreeDataFetch(pCrsr, &avail);
  66637. }
  66638. assert( avail<=65536 ); /* Maximum page size is 64KiB */
  66639. if( pC->payloadSize <= (u32)avail ){
  66640. pC->szRow = pC->payloadSize;
  66641. }else{
  66642. pC->szRow = avail;
  66643. }
  66644. if( pC->payloadSize > (u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  66645. goto too_big;
  66646. }
  66647. }
  66648. pC->cacheStatus = p->cacheCtr;
  66649. pC->iHdrOffset = getVarint32(pC->aRow, offset);
  66650. pC->nHdrParsed = 0;
  66651. aOffset[0] = offset;
  66652. /* Make sure a corrupt database has not given us an oversize header.
  66653. ** Do this now to avoid an oversize memory allocation.
  66654. **
  66655. ** Type entries can be between 1 and 5 bytes each. But 4 and 5 byte
  66656. ** types use so much data space that there can only be 4096 and 32 of
  66657. ** them, respectively. So the maximum header length results from a
  66658. ** 3-byte type for each of the maximum of 32768 columns plus three
  66659. ** extra bytes for the header length itself. 32768*3 + 3 = 98307.
  66660. */
  66661. if( offset > 98307 || offset > pC->payloadSize ){
  66662. rc = SQLITE_CORRUPT_BKPT;
  66663. goto op_column_error;
  66664. }
  66665. if( avail<offset ){
  66666. /* pC->aRow does not have to hold the entire row, but it does at least
  66667. ** need to cover the header of the record. If pC->aRow does not contain
  66668. ** the complete header, then set it to zero, forcing the header to be
  66669. ** dynamically allocated. */
  66670. pC->aRow = 0;
  66671. pC->szRow = 0;
  66672. }
  66673. /* The following goto is an optimization. It can be omitted and
  66674. ** everything will still work. But OP_Column is measurably faster
  66675. ** by skipping the subsequent conditional, which is always true.
  66676. */
  66677. assert( pC->nHdrParsed<=p2 ); /* Conditional skipped */
  66678. goto op_column_read_header;
  66679. }
  66680. /* Make sure at least the first p2+1 entries of the header have been
  66681. ** parsed and valid information is in aOffset[] and pC->aType[].
  66682. */
  66683. if( pC->nHdrParsed<=p2 ){
  66684. /* If there is more header available for parsing in the record, try
  66685. ** to extract additional fields up through the p2+1-th field
  66686. */
  66687. op_column_read_header:
  66688. if( pC->iHdrOffset<aOffset[0] ){
  66689. /* Make sure zData points to enough of the record to cover the header. */
  66690. if( pC->aRow==0 ){
  66691. memset(&sMem, 0, sizeof(sMem));
  66692. rc = sqlite3VdbeMemFromBtree(pCrsr, 0, aOffset[0],
  66693. !pC->isTable, &sMem);
  66694. if( rc!=SQLITE_OK ){
  66695. goto op_column_error;
  66696. }
  66697. zData = (u8*)sMem.z;
  66698. }else{
  66699. zData = pC->aRow;
  66700. }
  66701. /* Fill in pC->aType[i] and aOffset[i] values through the p2-th field. */
  66702. i = pC->nHdrParsed;
  66703. offset = aOffset[i];
  66704. zHdr = zData + pC->iHdrOffset;
  66705. zEndHdr = zData + aOffset[0];
  66706. assert( i<=p2 && zHdr<zEndHdr );
  66707. do{
  66708. if( zHdr[0]<0x80 ){
  66709. t = zHdr[0];
  66710. zHdr++;
  66711. }else{
  66712. zHdr += sqlite3GetVarint32(zHdr, &t);
  66713. }
  66714. pC->aType[i] = t;
  66715. szField = sqlite3VdbeSerialTypeLen(t);
  66716. offset += szField;
  66717. if( offset<szField ){ /* True if offset overflows */
  66718. zHdr = &zEndHdr[1]; /* Forces SQLITE_CORRUPT return below */
  66719. break;
  66720. }
  66721. i++;
  66722. aOffset[i] = offset;
  66723. }while( i<=p2 && zHdr<zEndHdr );
  66724. pC->nHdrParsed = i;
  66725. pC->iHdrOffset = (u32)(zHdr - zData);
  66726. if( pC->aRow==0 ){
  66727. sqlite3VdbeMemRelease(&sMem);
  66728. sMem.flags = MEM_Null;
  66729. }
  66730. /* The record is corrupt if any of the following are true:
  66731. ** (1) the bytes of the header extend past the declared header size
  66732. ** (zHdr>zEndHdr)
  66733. ** (2) the entire header was used but not all data was used
  66734. ** (zHdr==zEndHdr && offset!=pC->payloadSize)
  66735. ** (3) the end of the data extends beyond the end of the record.
  66736. ** (offset > pC->payloadSize)
  66737. */
  66738. if( (zHdr>=zEndHdr && (zHdr>zEndHdr || offset!=pC->payloadSize))
  66739. || (offset > pC->payloadSize)
  66740. ){
  66741. rc = SQLITE_CORRUPT_BKPT;
  66742. goto op_column_error;
  66743. }
  66744. }
  66745. /* If after trying to extra new entries from the header, nHdrParsed is
  66746. ** still not up to p2, that means that the record has fewer than p2
  66747. ** columns. So the result will be either the default value or a NULL.
  66748. */
  66749. if( pC->nHdrParsed<=p2 ){
  66750. if( pOp->p4type==P4_MEM ){
  66751. sqlite3VdbeMemShallowCopy(pDest, pOp->p4.pMem, MEM_Static);
  66752. }else{
  66753. sqlite3VdbeMemSetNull(pDest);
  66754. }
  66755. goto op_column_out;
  66756. }
  66757. }
  66758. /* Extract the content for the p2+1-th column. Control can only
  66759. ** reach this point if aOffset[p2], aOffset[p2+1], and pC->aType[p2] are
  66760. ** all valid.
  66761. */
  66762. assert( p2<pC->nHdrParsed );
  66763. assert( rc==SQLITE_OK );
  66764. assert( sqlite3VdbeCheckMemInvariants(pDest) );
  66765. if( VdbeMemDynamic(pDest) ) sqlite3VdbeMemSetNull(pDest);
  66766. t = pC->aType[p2];
  66767. if( pC->szRow>=aOffset[p2+1] ){
  66768. /* This is the common case where the desired content fits on the original
  66769. ** page - where the content is not on an overflow page */
  66770. sqlite3VdbeSerialGet(pC->aRow+aOffset[p2], t, pDest);
  66771. }else{
  66772. /* This branch happens only when content is on overflow pages */
  66773. if( ((pOp->p5 & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG))!=0
  66774. && ((t>=12 && (t&1)==0) || (pOp->p5 & OPFLAG_TYPEOFARG)!=0))
  66775. || (len = sqlite3VdbeSerialTypeLen(t))==0
  66776. ){
  66777. /* Content is irrelevant for
  66778. ** 1. the typeof() function,
  66779. ** 2. the length(X) function if X is a blob, and
  66780. ** 3. if the content length is zero.
  66781. ** So we might as well use bogus content rather than reading
  66782. ** content from disk. NULL will work for the value for strings
  66783. ** and blobs and whatever is in the payloadSize64 variable
  66784. ** will work for everything else. */
  66785. sqlite3VdbeSerialGet(t<=13 ? (u8*)&payloadSize64 : 0, t, pDest);
  66786. }else{
  66787. rc = sqlite3VdbeMemFromBtree(pCrsr, aOffset[p2], len, !pC->isTable,
  66788. pDest);
  66789. if( rc!=SQLITE_OK ){
  66790. goto op_column_error;
  66791. }
  66792. sqlite3VdbeSerialGet((const u8*)pDest->z, t, pDest);
  66793. pDest->flags &= ~MEM_Ephem;
  66794. }
  66795. }
  66796. pDest->enc = encoding;
  66797. op_column_out:
  66798. /* If the column value is an ephemeral string, go ahead and persist
  66799. ** that string in case the cursor moves before the column value is
  66800. ** used. The following code does the equivalent of Deephemeralize()
  66801. ** but does it faster. */
  66802. if( (pDest->flags & MEM_Ephem)!=0 && pDest->z ){
  66803. fx = pDest->flags & (MEM_Str|MEM_Blob);
  66804. assert( fx!=0 );
  66805. zData = (const u8*)pDest->z;
  66806. len = pDest->n;
  66807. if( sqlite3VdbeMemClearAndResize(pDest, len+2) ) goto no_mem;
  66808. memcpy(pDest->z, zData, len);
  66809. pDest->z[len] = 0;
  66810. pDest->z[len+1] = 0;
  66811. pDest->flags = fx|MEM_Term;
  66812. }
  66813. op_column_error:
  66814. UPDATE_MAX_BLOBSIZE(pDest);
  66815. REGISTER_TRACE(pOp->p3, pDest);
  66816. break;
  66817. }
  66818. /* Opcode: Affinity P1 P2 * P4 *
  66819. ** Synopsis: affinity(r[P1@P2])
  66820. **
  66821. ** Apply affinities to a range of P2 registers starting with P1.
  66822. **
  66823. ** P4 is a string that is P2 characters long. The nth character of the
  66824. ** string indicates the column affinity that should be used for the nth
  66825. ** memory cell in the range.
  66826. */
  66827. case OP_Affinity: {
  66828. const char *zAffinity; /* The affinity to be applied */
  66829. char cAff; /* A single character of affinity */
  66830. zAffinity = pOp->p4.z;
  66831. assert( zAffinity!=0 );
  66832. assert( zAffinity[pOp->p2]==0 );
  66833. pIn1 = &aMem[pOp->p1];
  66834. while( (cAff = *(zAffinity++))!=0 ){
  66835. assert( pIn1 <= &p->aMem[(p->nMem-p->nCursor)] );
  66836. assert( memIsValid(pIn1) );
  66837. applyAffinity(pIn1, cAff, encoding);
  66838. pIn1++;
  66839. }
  66840. break;
  66841. }
  66842. /* Opcode: MakeRecord P1 P2 P3 P4 *
  66843. ** Synopsis: r[P3]=mkrec(r[P1@P2])
  66844. **
  66845. ** Convert P2 registers beginning with P1 into the [record format]
  66846. ** use as a data record in a database table or as a key
  66847. ** in an index. The OP_Column opcode can decode the record later.
  66848. **
  66849. ** P4 may be a string that is P2 characters long. The nth character of the
  66850. ** string indicates the column affinity that should be used for the nth
  66851. ** field of the index key.
  66852. **
  66853. ** The mapping from character to affinity is given by the SQLITE_AFF_
  66854. ** macros defined in sqliteInt.h.
  66855. **
  66856. ** If P4 is NULL then all index fields have the affinity NONE.
  66857. */
  66858. case OP_MakeRecord: {
  66859. u8 *zNewRecord; /* A buffer to hold the data for the new record */
  66860. Mem *pRec; /* The new record */
  66861. u64 nData; /* Number of bytes of data space */
  66862. int nHdr; /* Number of bytes of header space */
  66863. i64 nByte; /* Data space required for this record */
  66864. int nZero; /* Number of zero bytes at the end of the record */
  66865. int nVarint; /* Number of bytes in a varint */
  66866. u32 serial_type; /* Type field */
  66867. Mem *pData0; /* First field to be combined into the record */
  66868. Mem *pLast; /* Last field of the record */
  66869. int nField; /* Number of fields in the record */
  66870. char *zAffinity; /* The affinity string for the record */
  66871. int file_format; /* File format to use for encoding */
  66872. int i; /* Space used in zNewRecord[] header */
  66873. int j; /* Space used in zNewRecord[] content */
  66874. int len; /* Length of a field */
  66875. /* Assuming the record contains N fields, the record format looks
  66876. ** like this:
  66877. **
  66878. ** ------------------------------------------------------------------------
  66879. ** | hdr-size | type 0 | type 1 | ... | type N-1 | data0 | ... | data N-1 |
  66880. ** ------------------------------------------------------------------------
  66881. **
  66882. ** Data(0) is taken from register P1. Data(1) comes from register P1+1
  66883. ** and so forth.
  66884. **
  66885. ** Each type field is a varint representing the serial type of the
  66886. ** corresponding data element (see sqlite3VdbeSerialType()). The
  66887. ** hdr-size field is also a varint which is the offset from the beginning
  66888. ** of the record to data0.
  66889. */
  66890. nData = 0; /* Number of bytes of data space */
  66891. nHdr = 0; /* Number of bytes of header space */
  66892. nZero = 0; /* Number of zero bytes at the end of the record */
  66893. nField = pOp->p1;
  66894. zAffinity = pOp->p4.z;
  66895. assert( nField>0 && pOp->p2>0 && pOp->p2+nField<=(p->nMem-p->nCursor)+1 );
  66896. pData0 = &aMem[nField];
  66897. nField = pOp->p2;
  66898. pLast = &pData0[nField-1];
  66899. file_format = p->minWriteFileFormat;
  66900. /* Identify the output register */
  66901. assert( pOp->p3<pOp->p1 || pOp->p3>=pOp->p1+pOp->p2 );
  66902. pOut = &aMem[pOp->p3];
  66903. memAboutToChange(p, pOut);
  66904. /* Apply the requested affinity to all inputs
  66905. */
  66906. assert( pData0<=pLast );
  66907. if( zAffinity ){
  66908. pRec = pData0;
  66909. do{
  66910. applyAffinity(pRec++, *(zAffinity++), encoding);
  66911. assert( zAffinity[0]==0 || pRec<=pLast );
  66912. }while( zAffinity[0] );
  66913. }
  66914. /* Loop through the elements that will make up the record to figure
  66915. ** out how much space is required for the new record.
  66916. */
  66917. pRec = pLast;
  66918. do{
  66919. assert( memIsValid(pRec) );
  66920. pRec->uTemp = serial_type = sqlite3VdbeSerialType(pRec, file_format);
  66921. len = sqlite3VdbeSerialTypeLen(serial_type);
  66922. if( pRec->flags & MEM_Zero ){
  66923. if( nData ){
  66924. sqlite3VdbeMemExpandBlob(pRec);
  66925. }else{
  66926. nZero += pRec->u.nZero;
  66927. len -= pRec->u.nZero;
  66928. }
  66929. }
  66930. nData += len;
  66931. testcase( serial_type==127 );
  66932. testcase( serial_type==128 );
  66933. nHdr += serial_type<=127 ? 1 : sqlite3VarintLen(serial_type);
  66934. }while( (--pRec)>=pData0 );
  66935. /* Add the initial header varint and total the size */
  66936. testcase( nHdr==126 );
  66937. testcase( nHdr==127 );
  66938. if( nHdr<=126 ){
  66939. /* The common case */
  66940. nHdr += 1;
  66941. }else{
  66942. /* Rare case of a really large header */
  66943. nVarint = sqlite3VarintLen(nHdr);
  66944. nHdr += nVarint;
  66945. if( nVarint<sqlite3VarintLen(nHdr) ) nHdr++;
  66946. }
  66947. nByte = nHdr+nData;
  66948. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  66949. goto too_big;
  66950. }
  66951. /* Make sure the output register has a buffer large enough to store
  66952. ** the new record. The output register (pOp->p3) is not allowed to
  66953. ** be one of the input registers (because the following call to
  66954. ** sqlite3VdbeMemClearAndResize() could clobber the value before it is used).
  66955. */
  66956. if( sqlite3VdbeMemClearAndResize(pOut, (int)nByte) ){
  66957. goto no_mem;
  66958. }
  66959. zNewRecord = (u8 *)pOut->z;
  66960. /* Write the record */
  66961. i = putVarint32(zNewRecord, nHdr);
  66962. j = nHdr;
  66963. assert( pData0<=pLast );
  66964. pRec = pData0;
  66965. do{
  66966. serial_type = pRec->uTemp;
  66967. i += putVarint32(&zNewRecord[i], serial_type); /* serial type */
  66968. j += sqlite3VdbeSerialPut(&zNewRecord[j], pRec, serial_type); /* content */
  66969. }while( (++pRec)<=pLast );
  66970. assert( i==nHdr );
  66971. assert( j==nByte );
  66972. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  66973. pOut->n = (int)nByte;
  66974. pOut->flags = MEM_Blob;
  66975. if( nZero ){
  66976. pOut->u.nZero = nZero;
  66977. pOut->flags |= MEM_Zero;
  66978. }
  66979. pOut->enc = SQLITE_UTF8; /* In case the blob is ever converted to text */
  66980. REGISTER_TRACE(pOp->p3, pOut);
  66981. UPDATE_MAX_BLOBSIZE(pOut);
  66982. break;
  66983. }
  66984. /* Opcode: Count P1 P2 * * *
  66985. ** Synopsis: r[P2]=count()
  66986. **
  66987. ** Store the number of entries (an integer value) in the table or index
  66988. ** opened by cursor P1 in register P2
  66989. */
  66990. #ifndef SQLITE_OMIT_BTREECOUNT
  66991. case OP_Count: { /* out2-prerelease */
  66992. i64 nEntry;
  66993. BtCursor *pCrsr;
  66994. pCrsr = p->apCsr[pOp->p1]->pCursor;
  66995. assert( pCrsr );
  66996. nEntry = 0; /* Not needed. Only used to silence a warning. */
  66997. rc = sqlite3BtreeCount(pCrsr, &nEntry);
  66998. pOut->u.i = nEntry;
  66999. break;
  67000. }
  67001. #endif
  67002. /* Opcode: Savepoint P1 * * P4 *
  67003. **
  67004. ** Open, release or rollback the savepoint named by parameter P4, depending
  67005. ** on the value of P1. To open a new savepoint, P1==0. To release (commit) an
  67006. ** existing savepoint, P1==1, or to rollback an existing savepoint P1==2.
  67007. */
  67008. case OP_Savepoint: {
  67009. int p1; /* Value of P1 operand */
  67010. char *zName; /* Name of savepoint */
  67011. int nName;
  67012. Savepoint *pNew;
  67013. Savepoint *pSavepoint;
  67014. Savepoint *pTmp;
  67015. int iSavepoint;
  67016. int ii;
  67017. p1 = pOp->p1;
  67018. zName = pOp->p4.z;
  67019. /* Assert that the p1 parameter is valid. Also that if there is no open
  67020. ** transaction, then there cannot be any savepoints.
  67021. */
  67022. assert( db->pSavepoint==0 || db->autoCommit==0 );
  67023. assert( p1==SAVEPOINT_BEGIN||p1==SAVEPOINT_RELEASE||p1==SAVEPOINT_ROLLBACK );
  67024. assert( db->pSavepoint || db->isTransactionSavepoint==0 );
  67025. assert( checkSavepointCount(db) );
  67026. assert( p->bIsReader );
  67027. if( p1==SAVEPOINT_BEGIN ){
  67028. if( db->nVdbeWrite>0 ){
  67029. /* A new savepoint cannot be created if there are active write
  67030. ** statements (i.e. open read/write incremental blob handles).
  67031. */
  67032. sqlite3SetString(&p->zErrMsg, db, "cannot open savepoint - "
  67033. "SQL statements in progress");
  67034. rc = SQLITE_BUSY;
  67035. }else{
  67036. nName = sqlite3Strlen30(zName);
  67037. #ifndef SQLITE_OMIT_VIRTUALTABLE
  67038. /* This call is Ok even if this savepoint is actually a transaction
  67039. ** savepoint (and therefore should not prompt xSavepoint()) callbacks.
  67040. ** If this is a transaction savepoint being opened, it is guaranteed
  67041. ** that the db->aVTrans[] array is empty. */
  67042. assert( db->autoCommit==0 || db->nVTrans==0 );
  67043. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN,
  67044. db->nStatement+db->nSavepoint);
  67045. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67046. #endif
  67047. /* Create a new savepoint structure. */
  67048. pNew = sqlite3DbMallocRaw(db, sizeof(Savepoint)+nName+1);
  67049. if( pNew ){
  67050. pNew->zName = (char *)&pNew[1];
  67051. memcpy(pNew->zName, zName, nName+1);
  67052. /* If there is no open transaction, then mark this as a special
  67053. ** "transaction savepoint". */
  67054. if( db->autoCommit ){
  67055. db->autoCommit = 0;
  67056. db->isTransactionSavepoint = 1;
  67057. }else{
  67058. db->nSavepoint++;
  67059. }
  67060. /* Link the new savepoint into the database handle's list. */
  67061. pNew->pNext = db->pSavepoint;
  67062. db->pSavepoint = pNew;
  67063. pNew->nDeferredCons = db->nDeferredCons;
  67064. pNew->nDeferredImmCons = db->nDeferredImmCons;
  67065. }
  67066. }
  67067. }else{
  67068. iSavepoint = 0;
  67069. /* Find the named savepoint. If there is no such savepoint, then an
  67070. ** an error is returned to the user. */
  67071. for(
  67072. pSavepoint = db->pSavepoint;
  67073. pSavepoint && sqlite3StrICmp(pSavepoint->zName, zName);
  67074. pSavepoint = pSavepoint->pNext
  67075. ){
  67076. iSavepoint++;
  67077. }
  67078. if( !pSavepoint ){
  67079. sqlite3SetString(&p->zErrMsg, db, "no such savepoint: %s", zName);
  67080. rc = SQLITE_ERROR;
  67081. }else if( db->nVdbeWrite>0 && p1==SAVEPOINT_RELEASE ){
  67082. /* It is not possible to release (commit) a savepoint if there are
  67083. ** active write statements.
  67084. */
  67085. sqlite3SetString(&p->zErrMsg, db,
  67086. "cannot release savepoint - SQL statements in progress"
  67087. );
  67088. rc = SQLITE_BUSY;
  67089. }else{
  67090. /* Determine whether or not this is a transaction savepoint. If so,
  67091. ** and this is a RELEASE command, then the current transaction
  67092. ** is committed.
  67093. */
  67094. int isTransaction = pSavepoint->pNext==0 && db->isTransactionSavepoint;
  67095. if( isTransaction && p1==SAVEPOINT_RELEASE ){
  67096. if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  67097. goto vdbe_return;
  67098. }
  67099. db->autoCommit = 1;
  67100. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  67101. p->pc = pc;
  67102. db->autoCommit = 0;
  67103. p->rc = rc = SQLITE_BUSY;
  67104. goto vdbe_return;
  67105. }
  67106. db->isTransactionSavepoint = 0;
  67107. rc = p->rc;
  67108. }else{
  67109. int isSchemaChange;
  67110. iSavepoint = db->nSavepoint - iSavepoint - 1;
  67111. if( p1==SAVEPOINT_ROLLBACK ){
  67112. isSchemaChange = (db->flags & SQLITE_InternChanges)!=0;
  67113. for(ii=0; ii<db->nDb; ii++){
  67114. rc = sqlite3BtreeTripAllCursors(db->aDb[ii].pBt,
  67115. SQLITE_ABORT_ROLLBACK,
  67116. isSchemaChange==0);
  67117. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67118. }
  67119. }else{
  67120. isSchemaChange = 0;
  67121. }
  67122. for(ii=0; ii<db->nDb; ii++){
  67123. rc = sqlite3BtreeSavepoint(db->aDb[ii].pBt, p1, iSavepoint);
  67124. if( rc!=SQLITE_OK ){
  67125. goto abort_due_to_error;
  67126. }
  67127. }
  67128. if( isSchemaChange ){
  67129. sqlite3ExpirePreparedStatements(db);
  67130. sqlite3ResetAllSchemasOfConnection(db);
  67131. db->flags = (db->flags | SQLITE_InternChanges);
  67132. }
  67133. }
  67134. /* Regardless of whether this is a RELEASE or ROLLBACK, destroy all
  67135. ** savepoints nested inside of the savepoint being operated on. */
  67136. while( db->pSavepoint!=pSavepoint ){
  67137. pTmp = db->pSavepoint;
  67138. db->pSavepoint = pTmp->pNext;
  67139. sqlite3DbFree(db, pTmp);
  67140. db->nSavepoint--;
  67141. }
  67142. /* If it is a RELEASE, then destroy the savepoint being operated on
  67143. ** too. If it is a ROLLBACK TO, then set the number of deferred
  67144. ** constraint violations present in the database to the value stored
  67145. ** when the savepoint was created. */
  67146. if( p1==SAVEPOINT_RELEASE ){
  67147. assert( pSavepoint==db->pSavepoint );
  67148. db->pSavepoint = pSavepoint->pNext;
  67149. sqlite3DbFree(db, pSavepoint);
  67150. if( !isTransaction ){
  67151. db->nSavepoint--;
  67152. }
  67153. }else{
  67154. db->nDeferredCons = pSavepoint->nDeferredCons;
  67155. db->nDeferredImmCons = pSavepoint->nDeferredImmCons;
  67156. }
  67157. if( !isTransaction ){
  67158. rc = sqlite3VtabSavepoint(db, p1, iSavepoint);
  67159. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67160. }
  67161. }
  67162. }
  67163. break;
  67164. }
  67165. /* Opcode: AutoCommit P1 P2 * * *
  67166. **
  67167. ** Set the database auto-commit flag to P1 (1 or 0). If P2 is true, roll
  67168. ** back any currently active btree transactions. If there are any active
  67169. ** VMs (apart from this one), then a ROLLBACK fails. A COMMIT fails if
  67170. ** there are active writing VMs or active VMs that use shared cache.
  67171. **
  67172. ** This instruction causes the VM to halt.
  67173. */
  67174. case OP_AutoCommit: {
  67175. int desiredAutoCommit;
  67176. int iRollback;
  67177. int turnOnAC;
  67178. desiredAutoCommit = pOp->p1;
  67179. iRollback = pOp->p2;
  67180. turnOnAC = desiredAutoCommit && !db->autoCommit;
  67181. assert( desiredAutoCommit==1 || desiredAutoCommit==0 );
  67182. assert( desiredAutoCommit==1 || iRollback==0 );
  67183. assert( db->nVdbeActive>0 ); /* At least this one VM is active */
  67184. assert( p->bIsReader );
  67185. #if 0
  67186. if( turnOnAC && iRollback && db->nVdbeActive>1 ){
  67187. /* If this instruction implements a ROLLBACK and other VMs are
  67188. ** still running, and a transaction is active, return an error indicating
  67189. ** that the other VMs must complete first.
  67190. */
  67191. sqlite3SetString(&p->zErrMsg, db, "cannot rollback transaction - "
  67192. "SQL statements in progress");
  67193. rc = SQLITE_BUSY;
  67194. }else
  67195. #endif
  67196. if( turnOnAC && !iRollback && db->nVdbeWrite>0 ){
  67197. /* If this instruction implements a COMMIT and other VMs are writing
  67198. ** return an error indicating that the other VMs must complete first.
  67199. */
  67200. sqlite3SetString(&p->zErrMsg, db, "cannot commit transaction - "
  67201. "SQL statements in progress");
  67202. rc = SQLITE_BUSY;
  67203. }else if( desiredAutoCommit!=db->autoCommit ){
  67204. if( iRollback ){
  67205. assert( desiredAutoCommit==1 );
  67206. sqlite3RollbackAll(db, SQLITE_ABORT_ROLLBACK);
  67207. db->autoCommit = 1;
  67208. }else if( (rc = sqlite3VdbeCheckFk(p, 1))!=SQLITE_OK ){
  67209. goto vdbe_return;
  67210. }else{
  67211. db->autoCommit = (u8)desiredAutoCommit;
  67212. if( sqlite3VdbeHalt(p)==SQLITE_BUSY ){
  67213. p->pc = pc;
  67214. db->autoCommit = (u8)(1-desiredAutoCommit);
  67215. p->rc = rc = SQLITE_BUSY;
  67216. goto vdbe_return;
  67217. }
  67218. }
  67219. assert( db->nStatement==0 );
  67220. sqlite3CloseSavepoints(db);
  67221. if( p->rc==SQLITE_OK ){
  67222. rc = SQLITE_DONE;
  67223. }else{
  67224. rc = SQLITE_ERROR;
  67225. }
  67226. goto vdbe_return;
  67227. }else{
  67228. sqlite3SetString(&p->zErrMsg, db,
  67229. (!desiredAutoCommit)?"cannot start a transaction within a transaction":(
  67230. (iRollback)?"cannot rollback - no transaction is active":
  67231. "cannot commit - no transaction is active"));
  67232. rc = SQLITE_ERROR;
  67233. }
  67234. break;
  67235. }
  67236. /* Opcode: Transaction P1 P2 P3 P4 P5
  67237. **
  67238. ** Begin a transaction on database P1 if a transaction is not already
  67239. ** active.
  67240. ** If P2 is non-zero, then a write-transaction is started, or if a
  67241. ** read-transaction is already active, it is upgraded to a write-transaction.
  67242. ** If P2 is zero, then a read-transaction is started.
  67243. **
  67244. ** P1 is the index of the database file on which the transaction is
  67245. ** started. Index 0 is the main database file and index 1 is the
  67246. ** file used for temporary tables. Indices of 2 or more are used for
  67247. ** attached databases.
  67248. **
  67249. ** If a write-transaction is started and the Vdbe.usesStmtJournal flag is
  67250. ** true (this flag is set if the Vdbe may modify more than one row and may
  67251. ** throw an ABORT exception), a statement transaction may also be opened.
  67252. ** More specifically, a statement transaction is opened iff the database
  67253. ** connection is currently not in autocommit mode, or if there are other
  67254. ** active statements. A statement transaction allows the changes made by this
  67255. ** VDBE to be rolled back after an error without having to roll back the
  67256. ** entire transaction. If no error is encountered, the statement transaction
  67257. ** will automatically commit when the VDBE halts.
  67258. **
  67259. ** If P5!=0 then this opcode also checks the schema cookie against P3
  67260. ** and the schema generation counter against P4.
  67261. ** The cookie changes its value whenever the database schema changes.
  67262. ** This operation is used to detect when that the cookie has changed
  67263. ** and that the current process needs to reread the schema. If the schema
  67264. ** cookie in P3 differs from the schema cookie in the database header or
  67265. ** if the schema generation counter in P4 differs from the current
  67266. ** generation counter, then an SQLITE_SCHEMA error is raised and execution
  67267. ** halts. The sqlite3_step() wrapper function might then reprepare the
  67268. ** statement and rerun it from the beginning.
  67269. */
  67270. case OP_Transaction: {
  67271. Btree *pBt;
  67272. int iMeta;
  67273. int iGen;
  67274. assert( p->bIsReader );
  67275. assert( p->readOnly==0 || pOp->p2==0 );
  67276. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67277. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  67278. if( pOp->p2 && (db->flags & SQLITE_QueryOnly)!=0 ){
  67279. rc = SQLITE_READONLY;
  67280. goto abort_due_to_error;
  67281. }
  67282. pBt = db->aDb[pOp->p1].pBt;
  67283. if( pBt ){
  67284. rc = sqlite3BtreeBeginTrans(pBt, pOp->p2);
  67285. if( rc==SQLITE_BUSY ){
  67286. p->pc = pc;
  67287. p->rc = rc = SQLITE_BUSY;
  67288. goto vdbe_return;
  67289. }
  67290. if( rc!=SQLITE_OK ){
  67291. goto abort_due_to_error;
  67292. }
  67293. if( pOp->p2 && p->usesStmtJournal
  67294. && (db->autoCommit==0 || db->nVdbeRead>1)
  67295. ){
  67296. assert( sqlite3BtreeIsInTrans(pBt) );
  67297. if( p->iStatement==0 ){
  67298. assert( db->nStatement>=0 && db->nSavepoint>=0 );
  67299. db->nStatement++;
  67300. p->iStatement = db->nSavepoint + db->nStatement;
  67301. }
  67302. rc = sqlite3VtabSavepoint(db, SAVEPOINT_BEGIN, p->iStatement-1);
  67303. if( rc==SQLITE_OK ){
  67304. rc = sqlite3BtreeBeginStmt(pBt, p->iStatement);
  67305. }
  67306. /* Store the current value of the database handles deferred constraint
  67307. ** counter. If the statement transaction needs to be rolled back,
  67308. ** the value of this counter needs to be restored too. */
  67309. p->nStmtDefCons = db->nDeferredCons;
  67310. p->nStmtDefImmCons = db->nDeferredImmCons;
  67311. }
  67312. /* Gather the schema version number for checking */
  67313. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&iMeta);
  67314. iGen = db->aDb[pOp->p1].pSchema->iGeneration;
  67315. }else{
  67316. iGen = iMeta = 0;
  67317. }
  67318. assert( pOp->p5==0 || pOp->p4type==P4_INT32 );
  67319. if( pOp->p5 && (iMeta!=pOp->p3 || iGen!=pOp->p4.i) ){
  67320. sqlite3DbFree(db, p->zErrMsg);
  67321. p->zErrMsg = sqlite3DbStrDup(db, "database schema has changed");
  67322. /* If the schema-cookie from the database file matches the cookie
  67323. ** stored with the in-memory representation of the schema, do
  67324. ** not reload the schema from the database file.
  67325. **
  67326. ** If virtual-tables are in use, this is not just an optimization.
  67327. ** Often, v-tables store their data in other SQLite tables, which
  67328. ** are queried from within xNext() and other v-table methods using
  67329. ** prepared queries. If such a query is out-of-date, we do not want to
  67330. ** discard the database schema, as the user code implementing the
  67331. ** v-table would have to be ready for the sqlite3_vtab structure itself
  67332. ** to be invalidated whenever sqlite3_step() is called from within
  67333. ** a v-table method.
  67334. */
  67335. if( db->aDb[pOp->p1].pSchema->schema_cookie!=iMeta ){
  67336. sqlite3ResetOneSchema(db, pOp->p1);
  67337. }
  67338. p->expired = 1;
  67339. rc = SQLITE_SCHEMA;
  67340. }
  67341. break;
  67342. }
  67343. /* Opcode: ReadCookie P1 P2 P3 * *
  67344. **
  67345. ** Read cookie number P3 from database P1 and write it into register P2.
  67346. ** P3==1 is the schema version. P3==2 is the database format.
  67347. ** P3==3 is the recommended pager cache size, and so forth. P1==0 is
  67348. ** the main database file and P1==1 is the database file used to store
  67349. ** temporary tables.
  67350. **
  67351. ** There must be a read-lock on the database (either a transaction
  67352. ** must be started or there must be an open cursor) before
  67353. ** executing this instruction.
  67354. */
  67355. case OP_ReadCookie: { /* out2-prerelease */
  67356. int iMeta;
  67357. int iDb;
  67358. int iCookie;
  67359. assert( p->bIsReader );
  67360. iDb = pOp->p1;
  67361. iCookie = pOp->p3;
  67362. assert( pOp->p3<SQLITE_N_BTREE_META );
  67363. assert( iDb>=0 && iDb<db->nDb );
  67364. assert( db->aDb[iDb].pBt!=0 );
  67365. assert( DbMaskTest(p->btreeMask, iDb) );
  67366. sqlite3BtreeGetMeta(db->aDb[iDb].pBt, iCookie, (u32 *)&iMeta);
  67367. pOut->u.i = iMeta;
  67368. break;
  67369. }
  67370. /* Opcode: SetCookie P1 P2 P3 * *
  67371. **
  67372. ** Write the content of register P3 (interpreted as an integer)
  67373. ** into cookie number P2 of database P1. P2==1 is the schema version.
  67374. ** P2==2 is the database format. P2==3 is the recommended pager cache
  67375. ** size, and so forth. P1==0 is the main database file and P1==1 is the
  67376. ** database file used to store temporary tables.
  67377. **
  67378. ** A transaction must be started before executing this opcode.
  67379. */
  67380. case OP_SetCookie: { /* in3 */
  67381. Db *pDb;
  67382. assert( pOp->p2<SQLITE_N_BTREE_META );
  67383. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  67384. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  67385. assert( p->readOnly==0 );
  67386. pDb = &db->aDb[pOp->p1];
  67387. assert( pDb->pBt!=0 );
  67388. assert( sqlite3SchemaMutexHeld(db, pOp->p1, 0) );
  67389. pIn3 = &aMem[pOp->p3];
  67390. sqlite3VdbeMemIntegerify(pIn3);
  67391. /* See note about index shifting on OP_ReadCookie */
  67392. rc = sqlite3BtreeUpdateMeta(pDb->pBt, pOp->p2, (int)pIn3->u.i);
  67393. if( pOp->p2==BTREE_SCHEMA_VERSION ){
  67394. /* When the schema cookie changes, record the new cookie internally */
  67395. pDb->pSchema->schema_cookie = (int)pIn3->u.i;
  67396. db->flags |= SQLITE_InternChanges;
  67397. }else if( pOp->p2==BTREE_FILE_FORMAT ){
  67398. /* Record changes in the file format */
  67399. pDb->pSchema->file_format = (u8)pIn3->u.i;
  67400. }
  67401. if( pOp->p1==1 ){
  67402. /* Invalidate all prepared statements whenever the TEMP database
  67403. ** schema is changed. Ticket #1644 */
  67404. sqlite3ExpirePreparedStatements(db);
  67405. p->expired = 0;
  67406. }
  67407. break;
  67408. }
  67409. /* Opcode: OpenRead P1 P2 P3 P4 P5
  67410. ** Synopsis: root=P2 iDb=P3
  67411. **
  67412. ** Open a read-only cursor for the database table whose root page is
  67413. ** P2 in a database file. The database file is determined by P3.
  67414. ** P3==0 means the main database, P3==1 means the database used for
  67415. ** temporary tables, and P3>1 means used the corresponding attached
  67416. ** database. Give the new cursor an identifier of P1. The P1
  67417. ** values need not be contiguous but all P1 values should be small integers.
  67418. ** It is an error for P1 to be negative.
  67419. **
  67420. ** If P5!=0 then use the content of register P2 as the root page, not
  67421. ** the value of P2 itself.
  67422. **
  67423. ** There will be a read lock on the database whenever there is an
  67424. ** open cursor. If the database was unlocked prior to this instruction
  67425. ** then a read lock is acquired as part of this instruction. A read
  67426. ** lock allows other processes to read the database but prohibits
  67427. ** any other process from modifying the database. The read lock is
  67428. ** released when all cursors are closed. If this instruction attempts
  67429. ** to get a read lock but fails, the script terminates with an
  67430. ** SQLITE_BUSY error code.
  67431. **
  67432. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  67433. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  67434. ** structure, then said structure defines the content and collating
  67435. ** sequence of the index being opened. Otherwise, if P4 is an integer
  67436. ** value, it is set to the number of columns in the table.
  67437. **
  67438. ** See also: OpenWrite, ReopenIdx
  67439. */
  67440. /* Opcode: ReopenIdx P1 P2 P3 P4 P5
  67441. ** Synopsis: root=P2 iDb=P3
  67442. **
  67443. ** The ReopenIdx opcode works exactly like ReadOpen except that it first
  67444. ** checks to see if the cursor on P1 is already open with a root page
  67445. ** number of P2 and if it is this opcode becomes a no-op. In other words,
  67446. ** if the cursor is already open, do not reopen it.
  67447. **
  67448. ** The ReopenIdx opcode may only be used with P5==0 and with P4 being
  67449. ** a P4_KEYINFO object. Furthermore, the P3 value must be the same as
  67450. ** every other ReopenIdx or OpenRead for the same cursor number.
  67451. **
  67452. ** See the OpenRead opcode documentation for additional information.
  67453. */
  67454. /* Opcode: OpenWrite P1 P2 P3 P4 P5
  67455. ** Synopsis: root=P2 iDb=P3
  67456. **
  67457. ** Open a read/write cursor named P1 on the table or index whose root
  67458. ** page is P2. Or if P5!=0 use the content of register P2 to find the
  67459. ** root page.
  67460. **
  67461. ** The P4 value may be either an integer (P4_INT32) or a pointer to
  67462. ** a KeyInfo structure (P4_KEYINFO). If it is a pointer to a KeyInfo
  67463. ** structure, then said structure defines the content and collating
  67464. ** sequence of the index being opened. Otherwise, if P4 is an integer
  67465. ** value, it is set to the number of columns in the table, or to the
  67466. ** largest index of any column of the table that is actually used.
  67467. **
  67468. ** This instruction works just like OpenRead except that it opens the cursor
  67469. ** in read/write mode. For a given table, there can be one or more read-only
  67470. ** cursors or a single read/write cursor but not both.
  67471. **
  67472. ** See also OpenRead.
  67473. */
  67474. case OP_ReopenIdx: {
  67475. VdbeCursor *pCur;
  67476. assert( pOp->p5==0 );
  67477. assert( pOp->p4type==P4_KEYINFO );
  67478. pCur = p->apCsr[pOp->p1];
  67479. if( pCur && pCur->pgnoRoot==(u32)pOp->p2 ){
  67480. assert( pCur->iDb==pOp->p3 ); /* Guaranteed by the code generator */
  67481. break;
  67482. }
  67483. /* If the cursor is not currently open or is open on a different
  67484. ** index, then fall through into OP_OpenRead to force a reopen */
  67485. }
  67486. case OP_OpenRead:
  67487. case OP_OpenWrite: {
  67488. int nField;
  67489. KeyInfo *pKeyInfo;
  67490. int p2;
  67491. int iDb;
  67492. int wrFlag;
  67493. Btree *pX;
  67494. VdbeCursor *pCur;
  67495. Db *pDb;
  67496. assert( (pOp->p5&(OPFLAG_P2ISREG|OPFLAG_BULKCSR))==pOp->p5 );
  67497. assert( pOp->opcode==OP_OpenWrite || pOp->p5==0 );
  67498. assert( p->bIsReader );
  67499. assert( pOp->opcode==OP_OpenRead || pOp->opcode==OP_ReopenIdx
  67500. || p->readOnly==0 );
  67501. if( p->expired ){
  67502. rc = SQLITE_ABORT_ROLLBACK;
  67503. break;
  67504. }
  67505. nField = 0;
  67506. pKeyInfo = 0;
  67507. p2 = pOp->p2;
  67508. iDb = pOp->p3;
  67509. assert( iDb>=0 && iDb<db->nDb );
  67510. assert( DbMaskTest(p->btreeMask, iDb) );
  67511. pDb = &db->aDb[iDb];
  67512. pX = pDb->pBt;
  67513. assert( pX!=0 );
  67514. if( pOp->opcode==OP_OpenWrite ){
  67515. wrFlag = 1;
  67516. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  67517. if( pDb->pSchema->file_format < p->minWriteFileFormat ){
  67518. p->minWriteFileFormat = pDb->pSchema->file_format;
  67519. }
  67520. }else{
  67521. wrFlag = 0;
  67522. }
  67523. if( pOp->p5 & OPFLAG_P2ISREG ){
  67524. assert( p2>0 );
  67525. assert( p2<=(p->nMem-p->nCursor) );
  67526. pIn2 = &aMem[p2];
  67527. assert( memIsValid(pIn2) );
  67528. assert( (pIn2->flags & MEM_Int)!=0 );
  67529. sqlite3VdbeMemIntegerify(pIn2);
  67530. p2 = (int)pIn2->u.i;
  67531. /* The p2 value always comes from a prior OP_CreateTable opcode and
  67532. ** that opcode will always set the p2 value to 2 or more or else fail.
  67533. ** If there were a failure, the prepared statement would have halted
  67534. ** before reaching this instruction. */
  67535. if( NEVER(p2<2) ) {
  67536. rc = SQLITE_CORRUPT_BKPT;
  67537. goto abort_due_to_error;
  67538. }
  67539. }
  67540. if( pOp->p4type==P4_KEYINFO ){
  67541. pKeyInfo = pOp->p4.pKeyInfo;
  67542. assert( pKeyInfo->enc==ENC(db) );
  67543. assert( pKeyInfo->db==db );
  67544. nField = pKeyInfo->nField+pKeyInfo->nXField;
  67545. }else if( pOp->p4type==P4_INT32 ){
  67546. nField = pOp->p4.i;
  67547. }
  67548. assert( pOp->p1>=0 );
  67549. assert( nField>=0 );
  67550. testcase( nField==0 ); /* Table with INTEGER PRIMARY KEY and nothing else */
  67551. pCur = allocateCursor(p, pOp->p1, nField, iDb, 1);
  67552. if( pCur==0 ) goto no_mem;
  67553. pCur->nullRow = 1;
  67554. pCur->isOrdered = 1;
  67555. pCur->pgnoRoot = p2;
  67556. rc = sqlite3BtreeCursor(pX, p2, wrFlag, pKeyInfo, pCur->pCursor);
  67557. pCur->pKeyInfo = pKeyInfo;
  67558. assert( OPFLAG_BULKCSR==BTREE_BULKLOAD );
  67559. sqlite3BtreeCursorHints(pCur->pCursor, (pOp->p5 & OPFLAG_BULKCSR));
  67560. /* Set the VdbeCursor.isTable variable. Previous versions of
  67561. ** SQLite used to check if the root-page flags were sane at this point
  67562. ** and report database corruption if they were not, but this check has
  67563. ** since moved into the btree layer. */
  67564. pCur->isTable = pOp->p4type!=P4_KEYINFO;
  67565. break;
  67566. }
  67567. /* Opcode: OpenEphemeral P1 P2 * P4 P5
  67568. ** Synopsis: nColumn=P2
  67569. **
  67570. ** Open a new cursor P1 to a transient table.
  67571. ** The cursor is always opened read/write even if
  67572. ** the main database is read-only. The ephemeral
  67573. ** table is deleted automatically when the cursor is closed.
  67574. **
  67575. ** P2 is the number of columns in the ephemeral table.
  67576. ** The cursor points to a BTree table if P4==0 and to a BTree index
  67577. ** if P4 is not 0. If P4 is not NULL, it points to a KeyInfo structure
  67578. ** that defines the format of keys in the index.
  67579. **
  67580. ** The P5 parameter can be a mask of the BTREE_* flags defined
  67581. ** in btree.h. These flags control aspects of the operation of
  67582. ** the btree. The BTREE_OMIT_JOURNAL and BTREE_SINGLE flags are
  67583. ** added automatically.
  67584. */
  67585. /* Opcode: OpenAutoindex P1 P2 * P4 *
  67586. ** Synopsis: nColumn=P2
  67587. **
  67588. ** This opcode works the same as OP_OpenEphemeral. It has a
  67589. ** different name to distinguish its use. Tables created using
  67590. ** by this opcode will be used for automatically created transient
  67591. ** indices in joins.
  67592. */
  67593. case OP_OpenAutoindex:
  67594. case OP_OpenEphemeral: {
  67595. VdbeCursor *pCx;
  67596. KeyInfo *pKeyInfo;
  67597. static const int vfsFlags =
  67598. SQLITE_OPEN_READWRITE |
  67599. SQLITE_OPEN_CREATE |
  67600. SQLITE_OPEN_EXCLUSIVE |
  67601. SQLITE_OPEN_DELETEONCLOSE |
  67602. SQLITE_OPEN_TRANSIENT_DB;
  67603. assert( pOp->p1>=0 );
  67604. assert( pOp->p2>=0 );
  67605. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  67606. if( pCx==0 ) goto no_mem;
  67607. pCx->nullRow = 1;
  67608. pCx->isEphemeral = 1;
  67609. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pCx->pBt,
  67610. BTREE_OMIT_JOURNAL | BTREE_SINGLE | pOp->p5, vfsFlags);
  67611. if( rc==SQLITE_OK ){
  67612. rc = sqlite3BtreeBeginTrans(pCx->pBt, 1);
  67613. }
  67614. if( rc==SQLITE_OK ){
  67615. /* If a transient index is required, create it by calling
  67616. ** sqlite3BtreeCreateTable() with the BTREE_BLOBKEY flag before
  67617. ** opening it. If a transient table is required, just use the
  67618. ** automatically created table with root-page 1 (an BLOB_INTKEY table).
  67619. */
  67620. if( (pKeyInfo = pOp->p4.pKeyInfo)!=0 ){
  67621. int pgno;
  67622. assert( pOp->p4type==P4_KEYINFO );
  67623. rc = sqlite3BtreeCreateTable(pCx->pBt, &pgno, BTREE_BLOBKEY | pOp->p5);
  67624. if( rc==SQLITE_OK ){
  67625. assert( pgno==MASTER_ROOT+1 );
  67626. assert( pKeyInfo->db==db );
  67627. assert( pKeyInfo->enc==ENC(db) );
  67628. pCx->pKeyInfo = pKeyInfo;
  67629. rc = sqlite3BtreeCursor(pCx->pBt, pgno, 1, pKeyInfo, pCx->pCursor);
  67630. }
  67631. pCx->isTable = 0;
  67632. }else{
  67633. rc = sqlite3BtreeCursor(pCx->pBt, MASTER_ROOT, 1, 0, pCx->pCursor);
  67634. pCx->isTable = 1;
  67635. }
  67636. }
  67637. pCx->isOrdered = (pOp->p5!=BTREE_UNORDERED);
  67638. break;
  67639. }
  67640. /* Opcode: SorterOpen P1 P2 P3 P4 *
  67641. **
  67642. ** This opcode works like OP_OpenEphemeral except that it opens
  67643. ** a transient index that is specifically designed to sort large
  67644. ** tables using an external merge-sort algorithm.
  67645. **
  67646. ** If argument P3 is non-zero, then it indicates that the sorter may
  67647. ** assume that a stable sort considering the first P3 fields of each
  67648. ** key is sufficient to produce the required results.
  67649. */
  67650. case OP_SorterOpen: {
  67651. VdbeCursor *pCx;
  67652. assert( pOp->p1>=0 );
  67653. assert( pOp->p2>=0 );
  67654. pCx = allocateCursor(p, pOp->p1, pOp->p2, -1, 1);
  67655. if( pCx==0 ) goto no_mem;
  67656. pCx->pKeyInfo = pOp->p4.pKeyInfo;
  67657. assert( pCx->pKeyInfo->db==db );
  67658. assert( pCx->pKeyInfo->enc==ENC(db) );
  67659. rc = sqlite3VdbeSorterInit(db, pOp->p3, pCx);
  67660. break;
  67661. }
  67662. /* Opcode: SequenceTest P1 P2 * * *
  67663. ** Synopsis: if( cursor[P1].ctr++ ) pc = P2
  67664. **
  67665. ** P1 is a sorter cursor. If the sequence counter is currently zero, jump
  67666. ** to P2. Regardless of whether or not the jump is taken, increment the
  67667. ** the sequence value.
  67668. */
  67669. case OP_SequenceTest: {
  67670. VdbeCursor *pC;
  67671. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67672. pC = p->apCsr[pOp->p1];
  67673. assert( pC->pSorter );
  67674. if( (pC->seqCount++)==0 ){
  67675. pc = pOp->p2 - 1;
  67676. }
  67677. break;
  67678. }
  67679. /* Opcode: OpenPseudo P1 P2 P3 * *
  67680. ** Synopsis: P3 columns in r[P2]
  67681. **
  67682. ** Open a new cursor that points to a fake table that contains a single
  67683. ** row of data. The content of that one row is the content of memory
  67684. ** register P2. In other words, cursor P1 becomes an alias for the
  67685. ** MEM_Blob content contained in register P2.
  67686. **
  67687. ** A pseudo-table created by this opcode is used to hold a single
  67688. ** row output from the sorter so that the row can be decomposed into
  67689. ** individual columns using the OP_Column opcode. The OP_Column opcode
  67690. ** is the only cursor opcode that works with a pseudo-table.
  67691. **
  67692. ** P3 is the number of fields in the records that will be stored by
  67693. ** the pseudo-table.
  67694. */
  67695. case OP_OpenPseudo: {
  67696. VdbeCursor *pCx;
  67697. assert( pOp->p1>=0 );
  67698. assert( pOp->p3>=0 );
  67699. pCx = allocateCursor(p, pOp->p1, pOp->p3, -1, 0);
  67700. if( pCx==0 ) goto no_mem;
  67701. pCx->nullRow = 1;
  67702. pCx->pseudoTableReg = pOp->p2;
  67703. pCx->isTable = 1;
  67704. assert( pOp->p5==0 );
  67705. break;
  67706. }
  67707. /* Opcode: Close P1 * * * *
  67708. **
  67709. ** Close a cursor previously opened as P1. If P1 is not
  67710. ** currently open, this instruction is a no-op.
  67711. */
  67712. case OP_Close: {
  67713. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67714. sqlite3VdbeFreeCursor(p, p->apCsr[pOp->p1]);
  67715. p->apCsr[pOp->p1] = 0;
  67716. break;
  67717. }
  67718. /* Opcode: SeekGE P1 P2 P3 P4 *
  67719. ** Synopsis: key=r[P3@P4]
  67720. **
  67721. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67722. ** use the value in register P3 as the key. If cursor P1 refers
  67723. ** to an SQL index, then P3 is the first in an array of P4 registers
  67724. ** that are used as an unpacked index key.
  67725. **
  67726. ** Reposition cursor P1 so that it points to the smallest entry that
  67727. ** is greater than or equal to the key value. If there are no records
  67728. ** greater than or equal to the key and P2 is not zero, then jump to P2.
  67729. **
  67730. ** This opcode leaves the cursor configured to move in forward order,
  67731. ** from the beginning toward the end. In other words, the cursor is
  67732. ** configured to use Next, not Prev.
  67733. **
  67734. ** See also: Found, NotFound, SeekLt, SeekGt, SeekLe
  67735. */
  67736. /* Opcode: SeekGT P1 P2 P3 P4 *
  67737. ** Synopsis: key=r[P3@P4]
  67738. **
  67739. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67740. ** use the value in register P3 as a key. If cursor P1 refers
  67741. ** to an SQL index, then P3 is the first in an array of P4 registers
  67742. ** that are used as an unpacked index key.
  67743. **
  67744. ** Reposition cursor P1 so that it points to the smallest entry that
  67745. ** is greater than the key value. If there are no records greater than
  67746. ** the key and P2 is not zero, then jump to P2.
  67747. **
  67748. ** This opcode leaves the cursor configured to move in forward order,
  67749. ** from the beginning toward the end. In other words, the cursor is
  67750. ** configured to use Next, not Prev.
  67751. **
  67752. ** See also: Found, NotFound, SeekLt, SeekGe, SeekLe
  67753. */
  67754. /* Opcode: SeekLT P1 P2 P3 P4 *
  67755. ** Synopsis: key=r[P3@P4]
  67756. **
  67757. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67758. ** use the value in register P3 as a key. If cursor P1 refers
  67759. ** to an SQL index, then P3 is the first in an array of P4 registers
  67760. ** that are used as an unpacked index key.
  67761. **
  67762. ** Reposition cursor P1 so that it points to the largest entry that
  67763. ** is less than the key value. If there are no records less than
  67764. ** the key and P2 is not zero, then jump to P2.
  67765. **
  67766. ** This opcode leaves the cursor configured to move in reverse order,
  67767. ** from the end toward the beginning. In other words, the cursor is
  67768. ** configured to use Prev, not Next.
  67769. **
  67770. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLe
  67771. */
  67772. /* Opcode: SeekLE P1 P2 P3 P4 *
  67773. ** Synopsis: key=r[P3@P4]
  67774. **
  67775. ** If cursor P1 refers to an SQL table (B-Tree that uses integer keys),
  67776. ** use the value in register P3 as a key. If cursor P1 refers
  67777. ** to an SQL index, then P3 is the first in an array of P4 registers
  67778. ** that are used as an unpacked index key.
  67779. **
  67780. ** Reposition cursor P1 so that it points to the largest entry that
  67781. ** is less than or equal to the key value. If there are no records
  67782. ** less than or equal to the key and P2 is not zero, then jump to P2.
  67783. **
  67784. ** This opcode leaves the cursor configured to move in reverse order,
  67785. ** from the end toward the beginning. In other words, the cursor is
  67786. ** configured to use Prev, not Next.
  67787. **
  67788. ** See also: Found, NotFound, SeekGt, SeekGe, SeekLt
  67789. */
  67790. case OP_SeekLT: /* jump, in3 */
  67791. case OP_SeekLE: /* jump, in3 */
  67792. case OP_SeekGE: /* jump, in3 */
  67793. case OP_SeekGT: { /* jump, in3 */
  67794. int res;
  67795. int oc;
  67796. VdbeCursor *pC;
  67797. UnpackedRecord r;
  67798. int nField;
  67799. i64 iKey; /* The rowid we are to seek to */
  67800. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67801. assert( pOp->p2!=0 );
  67802. pC = p->apCsr[pOp->p1];
  67803. assert( pC!=0 );
  67804. assert( pC->pseudoTableReg==0 );
  67805. assert( OP_SeekLE == OP_SeekLT+1 );
  67806. assert( OP_SeekGE == OP_SeekLT+2 );
  67807. assert( OP_SeekGT == OP_SeekLT+3 );
  67808. assert( pC->isOrdered );
  67809. assert( pC->pCursor!=0 );
  67810. oc = pOp->opcode;
  67811. pC->nullRow = 0;
  67812. #ifdef SQLITE_DEBUG
  67813. pC->seekOp = pOp->opcode;
  67814. #endif
  67815. if( pC->isTable ){
  67816. /* The input value in P3 might be of any type: integer, real, string,
  67817. ** blob, or NULL. But it needs to be an integer before we can do
  67818. ** the seek, so convert it. */
  67819. pIn3 = &aMem[pOp->p3];
  67820. if( (pIn3->flags & (MEM_Int|MEM_Real|MEM_Str))==MEM_Str ){
  67821. applyNumericAffinity(pIn3, 0);
  67822. }
  67823. iKey = sqlite3VdbeIntValue(pIn3);
  67824. /* If the P3 value could not be converted into an integer without
  67825. ** loss of information, then special processing is required... */
  67826. if( (pIn3->flags & MEM_Int)==0 ){
  67827. if( (pIn3->flags & MEM_Real)==0 ){
  67828. /* If the P3 value cannot be converted into any kind of a number,
  67829. ** then the seek is not possible, so jump to P2 */
  67830. pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
  67831. break;
  67832. }
  67833. /* If the approximation iKey is larger than the actual real search
  67834. ** term, substitute >= for > and < for <=. e.g. if the search term
  67835. ** is 4.9 and the integer approximation 5:
  67836. **
  67837. ** (x > 4.9) -> (x >= 5)
  67838. ** (x <= 4.9) -> (x < 5)
  67839. */
  67840. if( pIn3->u.r<(double)iKey ){
  67841. assert( OP_SeekGE==(OP_SeekGT-1) );
  67842. assert( OP_SeekLT==(OP_SeekLE-1) );
  67843. assert( (OP_SeekLE & 0x0001)==(OP_SeekGT & 0x0001) );
  67844. if( (oc & 0x0001)==(OP_SeekGT & 0x0001) ) oc--;
  67845. }
  67846. /* If the approximation iKey is smaller than the actual real search
  67847. ** term, substitute <= for < and > for >=. */
  67848. else if( pIn3->u.r>(double)iKey ){
  67849. assert( OP_SeekLE==(OP_SeekLT+1) );
  67850. assert( OP_SeekGT==(OP_SeekGE+1) );
  67851. assert( (OP_SeekLT & 0x0001)==(OP_SeekGE & 0x0001) );
  67852. if( (oc & 0x0001)==(OP_SeekLT & 0x0001) ) oc++;
  67853. }
  67854. }
  67855. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)iKey, 0, &res);
  67856. pC->movetoTarget = iKey; /* Used by OP_Delete */
  67857. if( rc!=SQLITE_OK ){
  67858. goto abort_due_to_error;
  67859. }
  67860. }else{
  67861. nField = pOp->p4.i;
  67862. assert( pOp->p4type==P4_INT32 );
  67863. assert( nField>0 );
  67864. r.pKeyInfo = pC->pKeyInfo;
  67865. r.nField = (u16)nField;
  67866. /* The next line of code computes as follows, only faster:
  67867. ** if( oc==OP_SeekGT || oc==OP_SeekLE ){
  67868. ** r.default_rc = -1;
  67869. ** }else{
  67870. ** r.default_rc = +1;
  67871. ** }
  67872. */
  67873. r.default_rc = ((1 & (oc - OP_SeekLT)) ? -1 : +1);
  67874. assert( oc!=OP_SeekGT || r.default_rc==-1 );
  67875. assert( oc!=OP_SeekLE || r.default_rc==-1 );
  67876. assert( oc!=OP_SeekGE || r.default_rc==+1 );
  67877. assert( oc!=OP_SeekLT || r.default_rc==+1 );
  67878. r.aMem = &aMem[pOp->p3];
  67879. #ifdef SQLITE_DEBUG
  67880. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  67881. #endif
  67882. ExpandBlob(r.aMem);
  67883. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, &r, 0, 0, &res);
  67884. if( rc!=SQLITE_OK ){
  67885. goto abort_due_to_error;
  67886. }
  67887. }
  67888. pC->deferredMoveto = 0;
  67889. pC->cacheStatus = CACHE_STALE;
  67890. #ifdef SQLITE_TEST
  67891. sqlite3_search_count++;
  67892. #endif
  67893. if( oc>=OP_SeekGE ){ assert( oc==OP_SeekGE || oc==OP_SeekGT );
  67894. if( res<0 || (res==0 && oc==OP_SeekGT) ){
  67895. res = 0;
  67896. rc = sqlite3BtreeNext(pC->pCursor, &res);
  67897. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67898. }else{
  67899. res = 0;
  67900. }
  67901. }else{
  67902. assert( oc==OP_SeekLT || oc==OP_SeekLE );
  67903. if( res>0 || (res==0 && oc==OP_SeekLT) ){
  67904. res = 0;
  67905. rc = sqlite3BtreePrevious(pC->pCursor, &res);
  67906. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  67907. }else{
  67908. /* res might be negative because the table is empty. Check to
  67909. ** see if this is the case.
  67910. */
  67911. res = sqlite3BtreeEof(pC->pCursor);
  67912. }
  67913. }
  67914. assert( pOp->p2>0 );
  67915. VdbeBranchTaken(res!=0,2);
  67916. if( res ){
  67917. pc = pOp->p2 - 1;
  67918. }
  67919. break;
  67920. }
  67921. /* Opcode: Seek P1 P2 * * *
  67922. ** Synopsis: intkey=r[P2]
  67923. **
  67924. ** P1 is an open table cursor and P2 is a rowid integer. Arrange
  67925. ** for P1 to move so that it points to the rowid given by P2.
  67926. **
  67927. ** This is actually a deferred seek. Nothing actually happens until
  67928. ** the cursor is used to read a record. That way, if no reads
  67929. ** occur, no unnecessary I/O happens.
  67930. */
  67931. case OP_Seek: { /* in2 */
  67932. VdbeCursor *pC;
  67933. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  67934. pC = p->apCsr[pOp->p1];
  67935. assert( pC!=0 );
  67936. assert( pC->pCursor!=0 );
  67937. assert( pC->isTable );
  67938. pC->nullRow = 0;
  67939. pIn2 = &aMem[pOp->p2];
  67940. pC->movetoTarget = sqlite3VdbeIntValue(pIn2);
  67941. pC->deferredMoveto = 1;
  67942. break;
  67943. }
  67944. /* Opcode: Found P1 P2 P3 P4 *
  67945. ** Synopsis: key=r[P3@P4]
  67946. **
  67947. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  67948. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  67949. ** record.
  67950. **
  67951. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  67952. ** is a prefix of any entry in P1 then a jump is made to P2 and
  67953. ** P1 is left pointing at the matching entry.
  67954. **
  67955. ** This operation leaves the cursor in a state where it can be
  67956. ** advanced in the forward direction. The Next instruction will work,
  67957. ** but not the Prev instruction.
  67958. **
  67959. ** See also: NotFound, NoConflict, NotExists. SeekGe
  67960. */
  67961. /* Opcode: NotFound P1 P2 P3 P4 *
  67962. ** Synopsis: key=r[P3@P4]
  67963. **
  67964. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  67965. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  67966. ** record.
  67967. **
  67968. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  67969. ** is not the prefix of any entry in P1 then a jump is made to P2. If P1
  67970. ** does contain an entry whose prefix matches the P3/P4 record then control
  67971. ** falls through to the next instruction and P1 is left pointing at the
  67972. ** matching entry.
  67973. **
  67974. ** This operation leaves the cursor in a state where it cannot be
  67975. ** advanced in either direction. In other words, the Next and Prev
  67976. ** opcodes do not work after this operation.
  67977. **
  67978. ** See also: Found, NotExists, NoConflict
  67979. */
  67980. /* Opcode: NoConflict P1 P2 P3 P4 *
  67981. ** Synopsis: key=r[P3@P4]
  67982. **
  67983. ** If P4==0 then register P3 holds a blob constructed by MakeRecord. If
  67984. ** P4>0 then register P3 is the first of P4 registers that form an unpacked
  67985. ** record.
  67986. **
  67987. ** Cursor P1 is on an index btree. If the record identified by P3 and P4
  67988. ** contains any NULL value, jump immediately to P2. If all terms of the
  67989. ** record are not-NULL then a check is done to determine if any row in the
  67990. ** P1 index btree has a matching key prefix. If there are no matches, jump
  67991. ** immediately to P2. If there is a match, fall through and leave the P1
  67992. ** cursor pointing to the matching row.
  67993. **
  67994. ** This opcode is similar to OP_NotFound with the exceptions that the
  67995. ** branch is always taken if any part of the search key input is NULL.
  67996. **
  67997. ** This operation leaves the cursor in a state where it cannot be
  67998. ** advanced in either direction. In other words, the Next and Prev
  67999. ** opcodes do not work after this operation.
  68000. **
  68001. ** See also: NotFound, Found, NotExists
  68002. */
  68003. case OP_NoConflict: /* jump, in3 */
  68004. case OP_NotFound: /* jump, in3 */
  68005. case OP_Found: { /* jump, in3 */
  68006. int alreadyExists;
  68007. int ii;
  68008. VdbeCursor *pC;
  68009. int res;
  68010. char *pFree;
  68011. UnpackedRecord *pIdxKey;
  68012. UnpackedRecord r;
  68013. char aTempRec[ROUND8(sizeof(UnpackedRecord)) + sizeof(Mem)*4 + 7];
  68014. #ifdef SQLITE_TEST
  68015. if( pOp->opcode!=OP_NoConflict ) sqlite3_found_count++;
  68016. #endif
  68017. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68018. assert( pOp->p4type==P4_INT32 );
  68019. pC = p->apCsr[pOp->p1];
  68020. assert( pC!=0 );
  68021. #ifdef SQLITE_DEBUG
  68022. pC->seekOp = pOp->opcode;
  68023. #endif
  68024. pIn3 = &aMem[pOp->p3];
  68025. assert( pC->pCursor!=0 );
  68026. assert( pC->isTable==0 );
  68027. pFree = 0; /* Not needed. Only used to suppress a compiler warning. */
  68028. if( pOp->p4.i>0 ){
  68029. r.pKeyInfo = pC->pKeyInfo;
  68030. r.nField = (u16)pOp->p4.i;
  68031. r.aMem = pIn3;
  68032. for(ii=0; ii<r.nField; ii++){
  68033. assert( memIsValid(&r.aMem[ii]) );
  68034. ExpandBlob(&r.aMem[ii]);
  68035. #ifdef SQLITE_DEBUG
  68036. if( ii ) REGISTER_TRACE(pOp->p3+ii, &r.aMem[ii]);
  68037. #endif
  68038. }
  68039. pIdxKey = &r;
  68040. }else{
  68041. pIdxKey = sqlite3VdbeAllocUnpackedRecord(
  68042. pC->pKeyInfo, aTempRec, sizeof(aTempRec), &pFree
  68043. );
  68044. if( pIdxKey==0 ) goto no_mem;
  68045. assert( pIn3->flags & MEM_Blob );
  68046. assert( (pIn3->flags & MEM_Zero)==0 ); /* zeroblobs already expanded */
  68047. sqlite3VdbeRecordUnpack(pC->pKeyInfo, pIn3->n, pIn3->z, pIdxKey);
  68048. }
  68049. pIdxKey->default_rc = 0;
  68050. if( pOp->opcode==OP_NoConflict ){
  68051. /* For the OP_NoConflict opcode, take the jump if any of the
  68052. ** input fields are NULL, since any key with a NULL will not
  68053. ** conflict */
  68054. for(ii=0; ii<r.nField; ii++){
  68055. if( r.aMem[ii].flags & MEM_Null ){
  68056. pc = pOp->p2 - 1; VdbeBranchTaken(1,2);
  68057. break;
  68058. }
  68059. }
  68060. }
  68061. rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, pIdxKey, 0, 0, &res);
  68062. if( pOp->p4.i==0 ){
  68063. sqlite3DbFree(db, pFree);
  68064. }
  68065. if( rc!=SQLITE_OK ){
  68066. break;
  68067. }
  68068. pC->seekResult = res;
  68069. alreadyExists = (res==0);
  68070. pC->nullRow = 1-alreadyExists;
  68071. pC->deferredMoveto = 0;
  68072. pC->cacheStatus = CACHE_STALE;
  68073. if( pOp->opcode==OP_Found ){
  68074. VdbeBranchTaken(alreadyExists!=0,2);
  68075. if( alreadyExists ) pc = pOp->p2 - 1;
  68076. }else{
  68077. VdbeBranchTaken(alreadyExists==0,2);
  68078. if( !alreadyExists ) pc = pOp->p2 - 1;
  68079. }
  68080. break;
  68081. }
  68082. /* Opcode: NotExists P1 P2 P3 * *
  68083. ** Synopsis: intkey=r[P3]
  68084. **
  68085. ** P1 is the index of a cursor open on an SQL table btree (with integer
  68086. ** keys). P3 is an integer rowid. If P1 does not contain a record with
  68087. ** rowid P3 then jump immediately to P2. If P1 does contain a record
  68088. ** with rowid P3 then leave the cursor pointing at that record and fall
  68089. ** through to the next instruction.
  68090. **
  68091. ** The OP_NotFound opcode performs the same operation on index btrees
  68092. ** (with arbitrary multi-value keys).
  68093. **
  68094. ** This opcode leaves the cursor in a state where it cannot be advanced
  68095. ** in either direction. In other words, the Next and Prev opcodes will
  68096. ** not work following this opcode.
  68097. **
  68098. ** See also: Found, NotFound, NoConflict
  68099. */
  68100. case OP_NotExists: { /* jump, in3 */
  68101. VdbeCursor *pC;
  68102. BtCursor *pCrsr;
  68103. int res;
  68104. u64 iKey;
  68105. pIn3 = &aMem[pOp->p3];
  68106. assert( pIn3->flags & MEM_Int );
  68107. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68108. pC = p->apCsr[pOp->p1];
  68109. assert( pC!=0 );
  68110. #ifdef SQLITE_DEBUG
  68111. pC->seekOp = 0;
  68112. #endif
  68113. assert( pC->isTable );
  68114. assert( pC->pseudoTableReg==0 );
  68115. pCrsr = pC->pCursor;
  68116. assert( pCrsr!=0 );
  68117. res = 0;
  68118. iKey = pIn3->u.i;
  68119. rc = sqlite3BtreeMovetoUnpacked(pCrsr, 0, iKey, 0, &res);
  68120. pC->movetoTarget = iKey; /* Used by OP_Delete */
  68121. pC->nullRow = 0;
  68122. pC->cacheStatus = CACHE_STALE;
  68123. pC->deferredMoveto = 0;
  68124. VdbeBranchTaken(res!=0,2);
  68125. if( res!=0 ){
  68126. pc = pOp->p2 - 1;
  68127. }
  68128. pC->seekResult = res;
  68129. break;
  68130. }
  68131. /* Opcode: Sequence P1 P2 * * *
  68132. ** Synopsis: r[P2]=cursor[P1].ctr++
  68133. **
  68134. ** Find the next available sequence number for cursor P1.
  68135. ** Write the sequence number into register P2.
  68136. ** The sequence number on the cursor is incremented after this
  68137. ** instruction.
  68138. */
  68139. case OP_Sequence: { /* out2-prerelease */
  68140. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68141. assert( p->apCsr[pOp->p1]!=0 );
  68142. pOut->u.i = p->apCsr[pOp->p1]->seqCount++;
  68143. break;
  68144. }
  68145. /* Opcode: NewRowid P1 P2 P3 * *
  68146. ** Synopsis: r[P2]=rowid
  68147. **
  68148. ** Get a new integer record number (a.k.a "rowid") used as the key to a table.
  68149. ** The record number is not previously used as a key in the database
  68150. ** table that cursor P1 points to. The new record number is written
  68151. ** written to register P2.
  68152. **
  68153. ** If P3>0 then P3 is a register in the root frame of this VDBE that holds
  68154. ** the largest previously generated record number. No new record numbers are
  68155. ** allowed to be less than this value. When this value reaches its maximum,
  68156. ** an SQLITE_FULL error is generated. The P3 register is updated with the '
  68157. ** generated record number. This P3 mechanism is used to help implement the
  68158. ** AUTOINCREMENT feature.
  68159. */
  68160. case OP_NewRowid: { /* out2-prerelease */
  68161. i64 v; /* The new rowid */
  68162. VdbeCursor *pC; /* Cursor of table to get the new rowid */
  68163. int res; /* Result of an sqlite3BtreeLast() */
  68164. int cnt; /* Counter to limit the number of searches */
  68165. Mem *pMem; /* Register holding largest rowid for AUTOINCREMENT */
  68166. VdbeFrame *pFrame; /* Root frame of VDBE */
  68167. v = 0;
  68168. res = 0;
  68169. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68170. pC = p->apCsr[pOp->p1];
  68171. assert( pC!=0 );
  68172. if( NEVER(pC->pCursor==0) ){
  68173. /* The zero initialization above is all that is needed */
  68174. }else{
  68175. /* The next rowid or record number (different terms for the same
  68176. ** thing) is obtained in a two-step algorithm.
  68177. **
  68178. ** First we attempt to find the largest existing rowid and add one
  68179. ** to that. But if the largest existing rowid is already the maximum
  68180. ** positive integer, we have to fall through to the second
  68181. ** probabilistic algorithm
  68182. **
  68183. ** The second algorithm is to select a rowid at random and see if
  68184. ** it already exists in the table. If it does not exist, we have
  68185. ** succeeded. If the random rowid does exist, we select a new one
  68186. ** and try again, up to 100 times.
  68187. */
  68188. assert( pC->isTable );
  68189. #ifdef SQLITE_32BIT_ROWID
  68190. # define MAX_ROWID 0x7fffffff
  68191. #else
  68192. /* Some compilers complain about constants of the form 0x7fffffffffffffff.
  68193. ** Others complain about 0x7ffffffffffffffffLL. The following macro seems
  68194. ** to provide the constant while making all compilers happy.
  68195. */
  68196. # define MAX_ROWID (i64)( (((u64)0x7fffffff)<<32) | (u64)0xffffffff )
  68197. #endif
  68198. if( !pC->useRandomRowid ){
  68199. rc = sqlite3BtreeLast(pC->pCursor, &res);
  68200. if( rc!=SQLITE_OK ){
  68201. goto abort_due_to_error;
  68202. }
  68203. if( res ){
  68204. v = 1; /* IMP: R-61914-48074 */
  68205. }else{
  68206. assert( sqlite3BtreeCursorIsValid(pC->pCursor) );
  68207. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  68208. assert( rc==SQLITE_OK ); /* Cannot fail following BtreeLast() */
  68209. if( v>=MAX_ROWID ){
  68210. pC->useRandomRowid = 1;
  68211. }else{
  68212. v++; /* IMP: R-29538-34987 */
  68213. }
  68214. }
  68215. }
  68216. #ifndef SQLITE_OMIT_AUTOINCREMENT
  68217. if( pOp->p3 ){
  68218. /* Assert that P3 is a valid memory cell. */
  68219. assert( pOp->p3>0 );
  68220. if( p->pFrame ){
  68221. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  68222. /* Assert that P3 is a valid memory cell. */
  68223. assert( pOp->p3<=pFrame->nMem );
  68224. pMem = &pFrame->aMem[pOp->p3];
  68225. }else{
  68226. /* Assert that P3 is a valid memory cell. */
  68227. assert( pOp->p3<=(p->nMem-p->nCursor) );
  68228. pMem = &aMem[pOp->p3];
  68229. memAboutToChange(p, pMem);
  68230. }
  68231. assert( memIsValid(pMem) );
  68232. REGISTER_TRACE(pOp->p3, pMem);
  68233. sqlite3VdbeMemIntegerify(pMem);
  68234. assert( (pMem->flags & MEM_Int)!=0 ); /* mem(P3) holds an integer */
  68235. if( pMem->u.i==MAX_ROWID || pC->useRandomRowid ){
  68236. rc = SQLITE_FULL; /* IMP: R-12275-61338 */
  68237. goto abort_due_to_error;
  68238. }
  68239. if( v<pMem->u.i+1 ){
  68240. v = pMem->u.i + 1;
  68241. }
  68242. pMem->u.i = v;
  68243. }
  68244. #endif
  68245. if( pC->useRandomRowid ){
  68246. /* IMPLEMENTATION-OF: R-07677-41881 If the largest ROWID is equal to the
  68247. ** largest possible integer (9223372036854775807) then the database
  68248. ** engine starts picking positive candidate ROWIDs at random until
  68249. ** it finds one that is not previously used. */
  68250. assert( pOp->p3==0 ); /* We cannot be in random rowid mode if this is
  68251. ** an AUTOINCREMENT table. */
  68252. cnt = 0;
  68253. do{
  68254. sqlite3_randomness(sizeof(v), &v);
  68255. v &= (MAX_ROWID>>1); v++; /* Ensure that v is greater than zero */
  68256. }while( ((rc = sqlite3BtreeMovetoUnpacked(pC->pCursor, 0, (u64)v,
  68257. 0, &res))==SQLITE_OK)
  68258. && (res==0)
  68259. && (++cnt<100));
  68260. if( rc==SQLITE_OK && res==0 ){
  68261. rc = SQLITE_FULL; /* IMP: R-38219-53002 */
  68262. goto abort_due_to_error;
  68263. }
  68264. assert( v>0 ); /* EV: R-40812-03570 */
  68265. }
  68266. pC->deferredMoveto = 0;
  68267. pC->cacheStatus = CACHE_STALE;
  68268. }
  68269. pOut->u.i = v;
  68270. break;
  68271. }
  68272. /* Opcode: Insert P1 P2 P3 P4 P5
  68273. ** Synopsis: intkey=r[P3] data=r[P2]
  68274. **
  68275. ** Write an entry into the table of cursor P1. A new entry is
  68276. ** created if it doesn't already exist or the data for an existing
  68277. ** entry is overwritten. The data is the value MEM_Blob stored in register
  68278. ** number P2. The key is stored in register P3. The key must
  68279. ** be a MEM_Int.
  68280. **
  68281. ** If the OPFLAG_NCHANGE flag of P5 is set, then the row change count is
  68282. ** incremented (otherwise not). If the OPFLAG_LASTROWID flag of P5 is set,
  68283. ** then rowid is stored for subsequent return by the
  68284. ** sqlite3_last_insert_rowid() function (otherwise it is unmodified).
  68285. **
  68286. ** If the OPFLAG_USESEEKRESULT flag of P5 is set and if the result of
  68287. ** the last seek operation (OP_NotExists) was a success, then this
  68288. ** operation will not attempt to find the appropriate row before doing
  68289. ** the insert but will instead overwrite the row that the cursor is
  68290. ** currently pointing to. Presumably, the prior OP_NotExists opcode
  68291. ** has already positioned the cursor correctly. This is an optimization
  68292. ** that boosts performance by avoiding redundant seeks.
  68293. **
  68294. ** If the OPFLAG_ISUPDATE flag is set, then this opcode is part of an
  68295. ** UPDATE operation. Otherwise (if the flag is clear) then this opcode
  68296. ** is part of an INSERT operation. The difference is only important to
  68297. ** the update hook.
  68298. **
  68299. ** Parameter P4 may point to a string containing the table-name, or
  68300. ** may be NULL. If it is not NULL, then the update-hook
  68301. ** (sqlite3.xUpdateCallback) is invoked following a successful insert.
  68302. **
  68303. ** (WARNING/TODO: If P1 is a pseudo-cursor and P2 is dynamically
  68304. ** allocated, then ownership of P2 is transferred to the pseudo-cursor
  68305. ** and register P2 becomes ephemeral. If the cursor is changed, the
  68306. ** value of register P2 will then change. Make sure this does not
  68307. ** cause any problems.)
  68308. **
  68309. ** This instruction only works on tables. The equivalent instruction
  68310. ** for indices is OP_IdxInsert.
  68311. */
  68312. /* Opcode: InsertInt P1 P2 P3 P4 P5
  68313. ** Synopsis: intkey=P3 data=r[P2]
  68314. **
  68315. ** This works exactly like OP_Insert except that the key is the
  68316. ** integer value P3, not the value of the integer stored in register P3.
  68317. */
  68318. case OP_Insert:
  68319. case OP_InsertInt: {
  68320. Mem *pData; /* MEM cell holding data for the record to be inserted */
  68321. Mem *pKey; /* MEM cell holding key for the record */
  68322. i64 iKey; /* The integer ROWID or key for the record to be inserted */
  68323. VdbeCursor *pC; /* Cursor to table into which insert is written */
  68324. int nZero; /* Number of zero-bytes to append */
  68325. int seekResult; /* Result of prior seek or 0 if no USESEEKRESULT flag */
  68326. const char *zDb; /* database name - used by the update hook */
  68327. const char *zTbl; /* Table name - used by the opdate hook */
  68328. int op; /* Opcode for update hook: SQLITE_UPDATE or SQLITE_INSERT */
  68329. pData = &aMem[pOp->p2];
  68330. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68331. assert( memIsValid(pData) );
  68332. pC = p->apCsr[pOp->p1];
  68333. assert( pC!=0 );
  68334. assert( pC->pCursor!=0 );
  68335. assert( pC->pseudoTableReg==0 );
  68336. assert( pC->isTable );
  68337. REGISTER_TRACE(pOp->p2, pData);
  68338. if( pOp->opcode==OP_Insert ){
  68339. pKey = &aMem[pOp->p3];
  68340. assert( pKey->flags & MEM_Int );
  68341. assert( memIsValid(pKey) );
  68342. REGISTER_TRACE(pOp->p3, pKey);
  68343. iKey = pKey->u.i;
  68344. }else{
  68345. assert( pOp->opcode==OP_InsertInt );
  68346. iKey = pOp->p3;
  68347. }
  68348. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  68349. if( pOp->p5 & OPFLAG_LASTROWID ) db->lastRowid = lastRowid = iKey;
  68350. if( pData->flags & MEM_Null ){
  68351. pData->z = 0;
  68352. pData->n = 0;
  68353. }else{
  68354. assert( pData->flags & (MEM_Blob|MEM_Str) );
  68355. }
  68356. seekResult = ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0);
  68357. if( pData->flags & MEM_Zero ){
  68358. nZero = pData->u.nZero;
  68359. }else{
  68360. nZero = 0;
  68361. }
  68362. rc = sqlite3BtreeInsert(pC->pCursor, 0, iKey,
  68363. pData->z, pData->n, nZero,
  68364. (pOp->p5 & OPFLAG_APPEND)!=0, seekResult
  68365. );
  68366. pC->deferredMoveto = 0;
  68367. pC->cacheStatus = CACHE_STALE;
  68368. /* Invoke the update-hook if required. */
  68369. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z ){
  68370. zDb = db->aDb[pC->iDb].zName;
  68371. zTbl = pOp->p4.z;
  68372. op = ((pOp->p5 & OPFLAG_ISUPDATE) ? SQLITE_UPDATE : SQLITE_INSERT);
  68373. assert( pC->isTable );
  68374. db->xUpdateCallback(db->pUpdateArg, op, zDb, zTbl, iKey);
  68375. assert( pC->iDb>=0 );
  68376. }
  68377. break;
  68378. }
  68379. /* Opcode: Delete P1 P2 * P4 *
  68380. **
  68381. ** Delete the record at which the P1 cursor is currently pointing.
  68382. **
  68383. ** The cursor will be left pointing at either the next or the previous
  68384. ** record in the table. If it is left pointing at the next record, then
  68385. ** the next Next instruction will be a no-op. Hence it is OK to delete
  68386. ** a record from within a Next loop.
  68387. **
  68388. ** If the OPFLAG_NCHANGE flag of P2 is set, then the row change count is
  68389. ** incremented (otherwise not).
  68390. **
  68391. ** P1 must not be pseudo-table. It has to be a real table with
  68392. ** multiple rows.
  68393. **
  68394. ** If P4 is not NULL, then it is the name of the table that P1 is
  68395. ** pointing to. The update hook will be invoked, if it exists.
  68396. ** If P4 is not NULL then the P1 cursor must have been positioned
  68397. ** using OP_NotFound prior to invoking this opcode.
  68398. */
  68399. case OP_Delete: {
  68400. VdbeCursor *pC;
  68401. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68402. pC = p->apCsr[pOp->p1];
  68403. assert( pC!=0 );
  68404. assert( pC->pCursor!=0 ); /* Only valid for real tables, no pseudotables */
  68405. assert( pC->deferredMoveto==0 );
  68406. #ifdef SQLITE_DEBUG
  68407. /* The seek operation that positioned the cursor prior to OP_Delete will
  68408. ** have also set the pC->movetoTarget field to the rowid of the row that
  68409. ** is being deleted */
  68410. if( pOp->p4.z && pC->isTable ){
  68411. i64 iKey = 0;
  68412. sqlite3BtreeKeySize(pC->pCursor, &iKey);
  68413. assert( pC->movetoTarget==iKey );
  68414. }
  68415. #endif
  68416. rc = sqlite3BtreeDelete(pC->pCursor);
  68417. pC->cacheStatus = CACHE_STALE;
  68418. /* Invoke the update-hook if required. */
  68419. if( rc==SQLITE_OK && db->xUpdateCallback && pOp->p4.z && pC->isTable ){
  68420. db->xUpdateCallback(db->pUpdateArg, SQLITE_DELETE,
  68421. db->aDb[pC->iDb].zName, pOp->p4.z, pC->movetoTarget);
  68422. assert( pC->iDb>=0 );
  68423. }
  68424. if( pOp->p2 & OPFLAG_NCHANGE ) p->nChange++;
  68425. break;
  68426. }
  68427. /* Opcode: ResetCount * * * * *
  68428. **
  68429. ** The value of the change counter is copied to the database handle
  68430. ** change counter (returned by subsequent calls to sqlite3_changes()).
  68431. ** Then the VMs internal change counter resets to 0.
  68432. ** This is used by trigger programs.
  68433. */
  68434. case OP_ResetCount: {
  68435. sqlite3VdbeSetChanges(db, p->nChange);
  68436. p->nChange = 0;
  68437. break;
  68438. }
  68439. /* Opcode: SorterCompare P1 P2 P3 P4
  68440. ** Synopsis: if key(P1)!=trim(r[P3],P4) goto P2
  68441. **
  68442. ** P1 is a sorter cursor. This instruction compares a prefix of the
  68443. ** record blob in register P3 against a prefix of the entry that
  68444. ** the sorter cursor currently points to. Only the first P4 fields
  68445. ** of r[P3] and the sorter record are compared.
  68446. **
  68447. ** If either P3 or the sorter contains a NULL in one of their significant
  68448. ** fields (not counting the P4 fields at the end which are ignored) then
  68449. ** the comparison is assumed to be equal.
  68450. **
  68451. ** Fall through to next instruction if the two records compare equal to
  68452. ** each other. Jump to P2 if they are different.
  68453. */
  68454. case OP_SorterCompare: {
  68455. VdbeCursor *pC;
  68456. int res;
  68457. int nKeyCol;
  68458. pC = p->apCsr[pOp->p1];
  68459. assert( isSorter(pC) );
  68460. assert( pOp->p4type==P4_INT32 );
  68461. pIn3 = &aMem[pOp->p3];
  68462. nKeyCol = pOp->p4.i;
  68463. res = 0;
  68464. rc = sqlite3VdbeSorterCompare(pC, pIn3, nKeyCol, &res);
  68465. VdbeBranchTaken(res!=0,2);
  68466. if( res ){
  68467. pc = pOp->p2-1;
  68468. }
  68469. break;
  68470. };
  68471. /* Opcode: SorterData P1 P2 P3 * *
  68472. ** Synopsis: r[P2]=data
  68473. **
  68474. ** Write into register P2 the current sorter data for sorter cursor P1.
  68475. ** Then clear the column header cache on cursor P3.
  68476. **
  68477. ** This opcode is normally use to move a record out of the sorter and into
  68478. ** a register that is the source for a pseudo-table cursor created using
  68479. ** OpenPseudo. That pseudo-table cursor is the one that is identified by
  68480. ** parameter P3. Clearing the P3 column cache as part of this opcode saves
  68481. ** us from having to issue a separate NullRow instruction to clear that cache.
  68482. */
  68483. case OP_SorterData: {
  68484. VdbeCursor *pC;
  68485. pOut = &aMem[pOp->p2];
  68486. pC = p->apCsr[pOp->p1];
  68487. assert( isSorter(pC) );
  68488. rc = sqlite3VdbeSorterRowkey(pC, pOut);
  68489. assert( rc!=SQLITE_OK || (pOut->flags & MEM_Blob) );
  68490. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68491. p->apCsr[pOp->p3]->cacheStatus = CACHE_STALE;
  68492. break;
  68493. }
  68494. /* Opcode: RowData P1 P2 * * *
  68495. ** Synopsis: r[P2]=data
  68496. **
  68497. ** Write into register P2 the complete row data for cursor P1.
  68498. ** There is no interpretation of the data.
  68499. ** It is just copied onto the P2 register exactly as
  68500. ** it is found in the database file.
  68501. **
  68502. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  68503. ** of a real table, not a pseudo-table.
  68504. */
  68505. /* Opcode: RowKey P1 P2 * * *
  68506. ** Synopsis: r[P2]=key
  68507. **
  68508. ** Write into register P2 the complete row key for cursor P1.
  68509. ** There is no interpretation of the data.
  68510. ** The key is copied onto the P2 register exactly as
  68511. ** it is found in the database file.
  68512. **
  68513. ** If the P1 cursor must be pointing to a valid row (not a NULL row)
  68514. ** of a real table, not a pseudo-table.
  68515. */
  68516. case OP_RowKey:
  68517. case OP_RowData: {
  68518. VdbeCursor *pC;
  68519. BtCursor *pCrsr;
  68520. u32 n;
  68521. i64 n64;
  68522. pOut = &aMem[pOp->p2];
  68523. memAboutToChange(p, pOut);
  68524. /* Note that RowKey and RowData are really exactly the same instruction */
  68525. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68526. pC = p->apCsr[pOp->p1];
  68527. assert( isSorter(pC)==0 );
  68528. assert( pC->isTable || pOp->opcode!=OP_RowData );
  68529. assert( pC->isTable==0 || pOp->opcode==OP_RowData );
  68530. assert( pC!=0 );
  68531. assert( pC->nullRow==0 );
  68532. assert( pC->pseudoTableReg==0 );
  68533. assert( pC->pCursor!=0 );
  68534. pCrsr = pC->pCursor;
  68535. /* The OP_RowKey and OP_RowData opcodes always follow OP_NotExists or
  68536. ** OP_Rewind/Op_Next with no intervening instructions that might invalidate
  68537. ** the cursor. If this where not the case, on of the following assert()s
  68538. ** would fail. Should this ever change (because of changes in the code
  68539. ** generator) then the fix would be to insert a call to
  68540. ** sqlite3VdbeCursorMoveto().
  68541. */
  68542. assert( pC->deferredMoveto==0 );
  68543. assert( sqlite3BtreeCursorIsValid(pCrsr) );
  68544. #if 0 /* Not required due to the previous to assert() statements */
  68545. rc = sqlite3VdbeCursorMoveto(pC);
  68546. if( rc!=SQLITE_OK ) goto abort_due_to_error;
  68547. #endif
  68548. if( pC->isTable==0 ){
  68549. assert( !pC->isTable );
  68550. VVA_ONLY(rc =) sqlite3BtreeKeySize(pCrsr, &n64);
  68551. assert( rc==SQLITE_OK ); /* True because of CursorMoveto() call above */
  68552. if( n64>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68553. goto too_big;
  68554. }
  68555. n = (u32)n64;
  68556. }else{
  68557. VVA_ONLY(rc =) sqlite3BtreeDataSize(pCrsr, &n);
  68558. assert( rc==SQLITE_OK ); /* DataSize() cannot fail */
  68559. if( n>(u32)db->aLimit[SQLITE_LIMIT_LENGTH] ){
  68560. goto too_big;
  68561. }
  68562. }
  68563. testcase( n==0 );
  68564. if( sqlite3VdbeMemClearAndResize(pOut, MAX(n,32)) ){
  68565. goto no_mem;
  68566. }
  68567. pOut->n = n;
  68568. MemSetTypeFlag(pOut, MEM_Blob);
  68569. if( pC->isTable==0 ){
  68570. rc = sqlite3BtreeKey(pCrsr, 0, n, pOut->z);
  68571. }else{
  68572. rc = sqlite3BtreeData(pCrsr, 0, n, pOut->z);
  68573. }
  68574. pOut->enc = SQLITE_UTF8; /* In case the blob is ever cast to text */
  68575. UPDATE_MAX_BLOBSIZE(pOut);
  68576. REGISTER_TRACE(pOp->p2, pOut);
  68577. break;
  68578. }
  68579. /* Opcode: Rowid P1 P2 * * *
  68580. ** Synopsis: r[P2]=rowid
  68581. **
  68582. ** Store in register P2 an integer which is the key of the table entry that
  68583. ** P1 is currently point to.
  68584. **
  68585. ** P1 can be either an ordinary table or a virtual table. There used to
  68586. ** be a separate OP_VRowid opcode for use with virtual tables, but this
  68587. ** one opcode now works for both table types.
  68588. */
  68589. case OP_Rowid: { /* out2-prerelease */
  68590. VdbeCursor *pC;
  68591. i64 v;
  68592. sqlite3_vtab *pVtab;
  68593. const sqlite3_module *pModule;
  68594. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68595. pC = p->apCsr[pOp->p1];
  68596. assert( pC!=0 );
  68597. assert( pC->pseudoTableReg==0 || pC->nullRow );
  68598. if( pC->nullRow ){
  68599. pOut->flags = MEM_Null;
  68600. break;
  68601. }else if( pC->deferredMoveto ){
  68602. v = pC->movetoTarget;
  68603. #ifndef SQLITE_OMIT_VIRTUALTABLE
  68604. }else if( pC->pVtabCursor ){
  68605. pVtab = pC->pVtabCursor->pVtab;
  68606. pModule = pVtab->pModule;
  68607. assert( pModule->xRowid );
  68608. rc = pModule->xRowid(pC->pVtabCursor, &v);
  68609. sqlite3VtabImportErrmsg(p, pVtab);
  68610. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  68611. }else{
  68612. assert( pC->pCursor!=0 );
  68613. rc = sqlite3VdbeCursorRestore(pC);
  68614. if( rc ) goto abort_due_to_error;
  68615. if( pC->nullRow ){
  68616. pOut->flags = MEM_Null;
  68617. break;
  68618. }
  68619. rc = sqlite3BtreeKeySize(pC->pCursor, &v);
  68620. assert( rc==SQLITE_OK ); /* Always so because of CursorRestore() above */
  68621. }
  68622. pOut->u.i = v;
  68623. break;
  68624. }
  68625. /* Opcode: NullRow P1 * * * *
  68626. **
  68627. ** Move the cursor P1 to a null row. Any OP_Column operations
  68628. ** that occur while the cursor is on the null row will always
  68629. ** write a NULL.
  68630. */
  68631. case OP_NullRow: {
  68632. VdbeCursor *pC;
  68633. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68634. pC = p->apCsr[pOp->p1];
  68635. assert( pC!=0 );
  68636. pC->nullRow = 1;
  68637. pC->cacheStatus = CACHE_STALE;
  68638. if( pC->pCursor ){
  68639. sqlite3BtreeClearCursor(pC->pCursor);
  68640. }
  68641. break;
  68642. }
  68643. /* Opcode: Last P1 P2 * * *
  68644. **
  68645. ** The next use of the Rowid or Column or Prev instruction for P1
  68646. ** will refer to the last entry in the database table or index.
  68647. ** If the table or index is empty and P2>0, then jump immediately to P2.
  68648. ** If P2 is 0 or if the table or index is not empty, fall through
  68649. ** to the following instruction.
  68650. **
  68651. ** This opcode leaves the cursor configured to move in reverse order,
  68652. ** from the end toward the beginning. In other words, the cursor is
  68653. ** configured to use Prev, not Next.
  68654. */
  68655. case OP_Last: { /* jump */
  68656. VdbeCursor *pC;
  68657. BtCursor *pCrsr;
  68658. int res;
  68659. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68660. pC = p->apCsr[pOp->p1];
  68661. assert( pC!=0 );
  68662. pCrsr = pC->pCursor;
  68663. res = 0;
  68664. assert( pCrsr!=0 );
  68665. rc = sqlite3BtreeLast(pCrsr, &res);
  68666. pC->nullRow = (u8)res;
  68667. pC->deferredMoveto = 0;
  68668. pC->cacheStatus = CACHE_STALE;
  68669. #ifdef SQLITE_DEBUG
  68670. pC->seekOp = OP_Last;
  68671. #endif
  68672. if( pOp->p2>0 ){
  68673. VdbeBranchTaken(res!=0,2);
  68674. if( res ) pc = pOp->p2 - 1;
  68675. }
  68676. break;
  68677. }
  68678. /* Opcode: Sort P1 P2 * * *
  68679. **
  68680. ** This opcode does exactly the same thing as OP_Rewind except that
  68681. ** it increments an undocumented global variable used for testing.
  68682. **
  68683. ** Sorting is accomplished by writing records into a sorting index,
  68684. ** then rewinding that index and playing it back from beginning to
  68685. ** end. We use the OP_Sort opcode instead of OP_Rewind to do the
  68686. ** rewinding so that the global variable will be incremented and
  68687. ** regression tests can determine whether or not the optimizer is
  68688. ** correctly optimizing out sorts.
  68689. */
  68690. case OP_SorterSort: /* jump */
  68691. case OP_Sort: { /* jump */
  68692. #ifdef SQLITE_TEST
  68693. sqlite3_sort_count++;
  68694. sqlite3_search_count--;
  68695. #endif
  68696. p->aCounter[SQLITE_STMTSTATUS_SORT]++;
  68697. /* Fall through into OP_Rewind */
  68698. }
  68699. /* Opcode: Rewind P1 P2 * * *
  68700. **
  68701. ** The next use of the Rowid or Column or Next instruction for P1
  68702. ** will refer to the first entry in the database table or index.
  68703. ** If the table or index is empty and P2>0, then jump immediately to P2.
  68704. ** If P2 is 0 or if the table or index is not empty, fall through
  68705. ** to the following instruction.
  68706. **
  68707. ** This opcode leaves the cursor configured to move in forward order,
  68708. ** from the beginning toward the end. In other words, the cursor is
  68709. ** configured to use Next, not Prev.
  68710. */
  68711. case OP_Rewind: { /* jump */
  68712. VdbeCursor *pC;
  68713. BtCursor *pCrsr;
  68714. int res;
  68715. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68716. pC = p->apCsr[pOp->p1];
  68717. assert( pC!=0 );
  68718. assert( isSorter(pC)==(pOp->opcode==OP_SorterSort) );
  68719. res = 1;
  68720. #ifdef SQLITE_DEBUG
  68721. pC->seekOp = OP_Rewind;
  68722. #endif
  68723. if( isSorter(pC) ){
  68724. rc = sqlite3VdbeSorterRewind(pC, &res);
  68725. }else{
  68726. pCrsr = pC->pCursor;
  68727. assert( pCrsr );
  68728. rc = sqlite3BtreeFirst(pCrsr, &res);
  68729. pC->deferredMoveto = 0;
  68730. pC->cacheStatus = CACHE_STALE;
  68731. }
  68732. pC->nullRow = (u8)res;
  68733. assert( pOp->p2>0 && pOp->p2<p->nOp );
  68734. VdbeBranchTaken(res!=0,2);
  68735. if( res ){
  68736. pc = pOp->p2 - 1;
  68737. }
  68738. break;
  68739. }
  68740. /* Opcode: Next P1 P2 P3 P4 P5
  68741. **
  68742. ** Advance cursor P1 so that it points to the next key/data pair in its
  68743. ** table or index. If there are no more key/value pairs then fall through
  68744. ** to the following instruction. But if the cursor advance was successful,
  68745. ** jump immediately to P2.
  68746. **
  68747. ** The Next opcode is only valid following an SeekGT, SeekGE, or
  68748. ** OP_Rewind opcode used to position the cursor. Next is not allowed
  68749. ** to follow SeekLT, SeekLE, or OP_Last.
  68750. **
  68751. ** The P1 cursor must be for a real table, not a pseudo-table. P1 must have
  68752. ** been opened prior to this opcode or the program will segfault.
  68753. **
  68754. ** The P3 value is a hint to the btree implementation. If P3==1, that
  68755. ** means P1 is an SQL index and that this instruction could have been
  68756. ** omitted if that index had been unique. P3 is usually 0. P3 is
  68757. ** always either 0 or 1.
  68758. **
  68759. ** P4 is always of type P4_ADVANCE. The function pointer points to
  68760. ** sqlite3BtreeNext().
  68761. **
  68762. ** If P5 is positive and the jump is taken, then event counter
  68763. ** number P5-1 in the prepared statement is incremented.
  68764. **
  68765. ** See also: Prev, NextIfOpen
  68766. */
  68767. /* Opcode: NextIfOpen P1 P2 P3 P4 P5
  68768. **
  68769. ** This opcode works just like Next except that if cursor P1 is not
  68770. ** open it behaves a no-op.
  68771. */
  68772. /* Opcode: Prev P1 P2 P3 P4 P5
  68773. **
  68774. ** Back up cursor P1 so that it points to the previous key/data pair in its
  68775. ** table or index. If there is no previous key/value pairs then fall through
  68776. ** to the following instruction. But if the cursor backup was successful,
  68777. ** jump immediately to P2.
  68778. **
  68779. **
  68780. ** The Prev opcode is only valid following an SeekLT, SeekLE, or
  68781. ** OP_Last opcode used to position the cursor. Prev is not allowed
  68782. ** to follow SeekGT, SeekGE, or OP_Rewind.
  68783. **
  68784. ** The P1 cursor must be for a real table, not a pseudo-table. If P1 is
  68785. ** not open then the behavior is undefined.
  68786. **
  68787. ** The P3 value is a hint to the btree implementation. If P3==1, that
  68788. ** means P1 is an SQL index and that this instruction could have been
  68789. ** omitted if that index had been unique. P3 is usually 0. P3 is
  68790. ** always either 0 or 1.
  68791. **
  68792. ** P4 is always of type P4_ADVANCE. The function pointer points to
  68793. ** sqlite3BtreePrevious().
  68794. **
  68795. ** If P5 is positive and the jump is taken, then event counter
  68796. ** number P5-1 in the prepared statement is incremented.
  68797. */
  68798. /* Opcode: PrevIfOpen P1 P2 P3 P4 P5
  68799. **
  68800. ** This opcode works just like Prev except that if cursor P1 is not
  68801. ** open it behaves a no-op.
  68802. */
  68803. case OP_SorterNext: { /* jump */
  68804. VdbeCursor *pC;
  68805. int res;
  68806. pC = p->apCsr[pOp->p1];
  68807. assert( isSorter(pC) );
  68808. res = 0;
  68809. rc = sqlite3VdbeSorterNext(db, pC, &res);
  68810. goto next_tail;
  68811. case OP_PrevIfOpen: /* jump */
  68812. case OP_NextIfOpen: /* jump */
  68813. if( p->apCsr[pOp->p1]==0 ) break;
  68814. /* Fall through */
  68815. case OP_Prev: /* jump */
  68816. case OP_Next: /* jump */
  68817. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68818. assert( pOp->p5<ArraySize(p->aCounter) );
  68819. pC = p->apCsr[pOp->p1];
  68820. res = pOp->p3;
  68821. assert( pC!=0 );
  68822. assert( pC->deferredMoveto==0 );
  68823. assert( pC->pCursor );
  68824. assert( res==0 || (res==1 && pC->isTable==0) );
  68825. testcase( res==1 );
  68826. assert( pOp->opcode!=OP_Next || pOp->p4.xAdvance==sqlite3BtreeNext );
  68827. assert( pOp->opcode!=OP_Prev || pOp->p4.xAdvance==sqlite3BtreePrevious );
  68828. assert( pOp->opcode!=OP_NextIfOpen || pOp->p4.xAdvance==sqlite3BtreeNext );
  68829. assert( pOp->opcode!=OP_PrevIfOpen || pOp->p4.xAdvance==sqlite3BtreePrevious);
  68830. /* The Next opcode is only used after SeekGT, SeekGE, and Rewind.
  68831. ** The Prev opcode is only used after SeekLT, SeekLE, and Last. */
  68832. assert( pOp->opcode!=OP_Next || pOp->opcode!=OP_NextIfOpen
  68833. || pC->seekOp==OP_SeekGT || pC->seekOp==OP_SeekGE
  68834. || pC->seekOp==OP_Rewind || pC->seekOp==OP_Found);
  68835. assert( pOp->opcode!=OP_Prev || pOp->opcode!=OP_PrevIfOpen
  68836. || pC->seekOp==OP_SeekLT || pC->seekOp==OP_SeekLE
  68837. || pC->seekOp==OP_Last );
  68838. rc = pOp->p4.xAdvance(pC->pCursor, &res);
  68839. next_tail:
  68840. pC->cacheStatus = CACHE_STALE;
  68841. VdbeBranchTaken(res==0,2);
  68842. if( res==0 ){
  68843. pC->nullRow = 0;
  68844. pc = pOp->p2 - 1;
  68845. p->aCounter[pOp->p5]++;
  68846. #ifdef SQLITE_TEST
  68847. sqlite3_search_count++;
  68848. #endif
  68849. }else{
  68850. pC->nullRow = 1;
  68851. }
  68852. goto check_for_interrupt;
  68853. }
  68854. /* Opcode: IdxInsert P1 P2 P3 * P5
  68855. ** Synopsis: key=r[P2]
  68856. **
  68857. ** Register P2 holds an SQL index key made using the
  68858. ** MakeRecord instructions. This opcode writes that key
  68859. ** into the index P1. Data for the entry is nil.
  68860. **
  68861. ** P3 is a flag that provides a hint to the b-tree layer that this
  68862. ** insert is likely to be an append.
  68863. **
  68864. ** If P5 has the OPFLAG_NCHANGE bit set, then the change counter is
  68865. ** incremented by this instruction. If the OPFLAG_NCHANGE bit is clear,
  68866. ** then the change counter is unchanged.
  68867. **
  68868. ** If P5 has the OPFLAG_USESEEKRESULT bit set, then the cursor must have
  68869. ** just done a seek to the spot where the new entry is to be inserted.
  68870. ** This flag avoids doing an extra seek.
  68871. **
  68872. ** This instruction only works for indices. The equivalent instruction
  68873. ** for tables is OP_Insert.
  68874. */
  68875. case OP_SorterInsert: /* in2 */
  68876. case OP_IdxInsert: { /* in2 */
  68877. VdbeCursor *pC;
  68878. BtCursor *pCrsr;
  68879. int nKey;
  68880. const char *zKey;
  68881. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68882. pC = p->apCsr[pOp->p1];
  68883. assert( pC!=0 );
  68884. assert( isSorter(pC)==(pOp->opcode==OP_SorterInsert) );
  68885. pIn2 = &aMem[pOp->p2];
  68886. assert( pIn2->flags & MEM_Blob );
  68887. pCrsr = pC->pCursor;
  68888. if( pOp->p5 & OPFLAG_NCHANGE ) p->nChange++;
  68889. assert( pCrsr!=0 );
  68890. assert( pC->isTable==0 );
  68891. rc = ExpandBlob(pIn2);
  68892. if( rc==SQLITE_OK ){
  68893. if( isSorter(pC) ){
  68894. rc = sqlite3VdbeSorterWrite(pC, pIn2);
  68895. }else{
  68896. nKey = pIn2->n;
  68897. zKey = pIn2->z;
  68898. rc = sqlite3BtreeInsert(pCrsr, zKey, nKey, "", 0, 0, pOp->p3,
  68899. ((pOp->p5 & OPFLAG_USESEEKRESULT) ? pC->seekResult : 0)
  68900. );
  68901. assert( pC->deferredMoveto==0 );
  68902. pC->cacheStatus = CACHE_STALE;
  68903. }
  68904. }
  68905. break;
  68906. }
  68907. /* Opcode: IdxDelete P1 P2 P3 * *
  68908. ** Synopsis: key=r[P2@P3]
  68909. **
  68910. ** The content of P3 registers starting at register P2 form
  68911. ** an unpacked index key. This opcode removes that entry from the
  68912. ** index opened by cursor P1.
  68913. */
  68914. case OP_IdxDelete: {
  68915. VdbeCursor *pC;
  68916. BtCursor *pCrsr;
  68917. int res;
  68918. UnpackedRecord r;
  68919. assert( pOp->p3>0 );
  68920. assert( pOp->p2>0 && pOp->p2+pOp->p3<=(p->nMem-p->nCursor)+1 );
  68921. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68922. pC = p->apCsr[pOp->p1];
  68923. assert( pC!=0 );
  68924. pCrsr = pC->pCursor;
  68925. assert( pCrsr!=0 );
  68926. assert( pOp->p5==0 );
  68927. r.pKeyInfo = pC->pKeyInfo;
  68928. r.nField = (u16)pOp->p3;
  68929. r.default_rc = 0;
  68930. r.aMem = &aMem[pOp->p2];
  68931. #ifdef SQLITE_DEBUG
  68932. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  68933. #endif
  68934. rc = sqlite3BtreeMovetoUnpacked(pCrsr, &r, 0, 0, &res);
  68935. if( rc==SQLITE_OK && res==0 ){
  68936. rc = sqlite3BtreeDelete(pCrsr);
  68937. }
  68938. assert( pC->deferredMoveto==0 );
  68939. pC->cacheStatus = CACHE_STALE;
  68940. break;
  68941. }
  68942. /* Opcode: IdxRowid P1 P2 * * *
  68943. ** Synopsis: r[P2]=rowid
  68944. **
  68945. ** Write into register P2 an integer which is the last entry in the record at
  68946. ** the end of the index key pointed to by cursor P1. This integer should be
  68947. ** the rowid of the table entry to which this index entry points.
  68948. **
  68949. ** See also: Rowid, MakeRecord.
  68950. */
  68951. case OP_IdxRowid: { /* out2-prerelease */
  68952. BtCursor *pCrsr;
  68953. VdbeCursor *pC;
  68954. i64 rowid;
  68955. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  68956. pC = p->apCsr[pOp->p1];
  68957. assert( pC!=0 );
  68958. pCrsr = pC->pCursor;
  68959. assert( pCrsr!=0 );
  68960. pOut->flags = MEM_Null;
  68961. assert( pC->isTable==0 );
  68962. assert( pC->deferredMoveto==0 );
  68963. /* sqlite3VbeCursorRestore() can only fail if the record has been deleted
  68964. ** out from under the cursor. That will never happend for an IdxRowid
  68965. ** opcode, hence the NEVER() arround the check of the return value.
  68966. */
  68967. rc = sqlite3VdbeCursorRestore(pC);
  68968. if( NEVER(rc!=SQLITE_OK) ) goto abort_due_to_error;
  68969. if( !pC->nullRow ){
  68970. rowid = 0; /* Not needed. Only used to silence a warning. */
  68971. rc = sqlite3VdbeIdxRowid(db, pCrsr, &rowid);
  68972. if( rc!=SQLITE_OK ){
  68973. goto abort_due_to_error;
  68974. }
  68975. pOut->u.i = rowid;
  68976. pOut->flags = MEM_Int;
  68977. }
  68978. break;
  68979. }
  68980. /* Opcode: IdxGE P1 P2 P3 P4 P5
  68981. ** Synopsis: key=r[P3@P4]
  68982. **
  68983. ** The P4 register values beginning with P3 form an unpacked index
  68984. ** key that omits the PRIMARY KEY. Compare this key value against the index
  68985. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  68986. ** fields at the end.
  68987. **
  68988. ** If the P1 index entry is greater than or equal to the key value
  68989. ** then jump to P2. Otherwise fall through to the next instruction.
  68990. */
  68991. /* Opcode: IdxGT P1 P2 P3 P4 P5
  68992. ** Synopsis: key=r[P3@P4]
  68993. **
  68994. ** The P4 register values beginning with P3 form an unpacked index
  68995. ** key that omits the PRIMARY KEY. Compare this key value against the index
  68996. ** that P1 is currently pointing to, ignoring the PRIMARY KEY or ROWID
  68997. ** fields at the end.
  68998. **
  68999. ** If the P1 index entry is greater than the key value
  69000. ** then jump to P2. Otherwise fall through to the next instruction.
  69001. */
  69002. /* Opcode: IdxLT P1 P2 P3 P4 P5
  69003. ** Synopsis: key=r[P3@P4]
  69004. **
  69005. ** The P4 register values beginning with P3 form an unpacked index
  69006. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  69007. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  69008. ** ROWID on the P1 index.
  69009. **
  69010. ** If the P1 index entry is less than the key value then jump to P2.
  69011. ** Otherwise fall through to the next instruction.
  69012. */
  69013. /* Opcode: IdxLE P1 P2 P3 P4 P5
  69014. ** Synopsis: key=r[P3@P4]
  69015. **
  69016. ** The P4 register values beginning with P3 form an unpacked index
  69017. ** key that omits the PRIMARY KEY or ROWID. Compare this key value against
  69018. ** the index that P1 is currently pointing to, ignoring the PRIMARY KEY or
  69019. ** ROWID on the P1 index.
  69020. **
  69021. ** If the P1 index entry is less than or equal to the key value then jump
  69022. ** to P2. Otherwise fall through to the next instruction.
  69023. */
  69024. case OP_IdxLE: /* jump */
  69025. case OP_IdxGT: /* jump */
  69026. case OP_IdxLT: /* jump */
  69027. case OP_IdxGE: { /* jump */
  69028. VdbeCursor *pC;
  69029. int res;
  69030. UnpackedRecord r;
  69031. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69032. pC = p->apCsr[pOp->p1];
  69033. assert( pC!=0 );
  69034. assert( pC->isOrdered );
  69035. assert( pC->pCursor!=0);
  69036. assert( pC->deferredMoveto==0 );
  69037. assert( pOp->p5==0 || pOp->p5==1 );
  69038. assert( pOp->p4type==P4_INT32 );
  69039. r.pKeyInfo = pC->pKeyInfo;
  69040. r.nField = (u16)pOp->p4.i;
  69041. if( pOp->opcode<OP_IdxLT ){
  69042. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxGT );
  69043. r.default_rc = -1;
  69044. }else{
  69045. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxLT );
  69046. r.default_rc = 0;
  69047. }
  69048. r.aMem = &aMem[pOp->p3];
  69049. #ifdef SQLITE_DEBUG
  69050. { int i; for(i=0; i<r.nField; i++) assert( memIsValid(&r.aMem[i]) ); }
  69051. #endif
  69052. res = 0; /* Not needed. Only used to silence a warning. */
  69053. rc = sqlite3VdbeIdxKeyCompare(db, pC, &r, &res);
  69054. assert( (OP_IdxLE&1)==(OP_IdxLT&1) && (OP_IdxGE&1)==(OP_IdxGT&1) );
  69055. if( (pOp->opcode&1)==(OP_IdxLT&1) ){
  69056. assert( pOp->opcode==OP_IdxLE || pOp->opcode==OP_IdxLT );
  69057. res = -res;
  69058. }else{
  69059. assert( pOp->opcode==OP_IdxGE || pOp->opcode==OP_IdxGT );
  69060. res++;
  69061. }
  69062. VdbeBranchTaken(res>0,2);
  69063. if( res>0 ){
  69064. pc = pOp->p2 - 1 ;
  69065. }
  69066. break;
  69067. }
  69068. /* Opcode: Destroy P1 P2 P3 * *
  69069. **
  69070. ** Delete an entire database table or index whose root page in the database
  69071. ** file is given by P1.
  69072. **
  69073. ** The table being destroyed is in the main database file if P3==0. If
  69074. ** P3==1 then the table to be clear is in the auxiliary database file
  69075. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  69076. **
  69077. ** If AUTOVACUUM is enabled then it is possible that another root page
  69078. ** might be moved into the newly deleted root page in order to keep all
  69079. ** root pages contiguous at the beginning of the database. The former
  69080. ** value of the root page that moved - its value before the move occurred -
  69081. ** is stored in register P2. If no page
  69082. ** movement was required (because the table being dropped was already
  69083. ** the last one in the database) then a zero is stored in register P2.
  69084. ** If AUTOVACUUM is disabled then a zero is stored in register P2.
  69085. **
  69086. ** See also: Clear
  69087. */
  69088. case OP_Destroy: { /* out2-prerelease */
  69089. int iMoved;
  69090. int iCnt;
  69091. Vdbe *pVdbe;
  69092. int iDb;
  69093. assert( p->readOnly==0 );
  69094. #ifndef SQLITE_OMIT_VIRTUALTABLE
  69095. iCnt = 0;
  69096. for(pVdbe=db->pVdbe; pVdbe; pVdbe = pVdbe->pNext){
  69097. if( pVdbe->magic==VDBE_MAGIC_RUN && pVdbe->bIsReader
  69098. && pVdbe->inVtabMethod<2 && pVdbe->pc>=0
  69099. ){
  69100. iCnt++;
  69101. }
  69102. }
  69103. #else
  69104. iCnt = db->nVdbeRead;
  69105. #endif
  69106. pOut->flags = MEM_Null;
  69107. if( iCnt>1 ){
  69108. rc = SQLITE_LOCKED;
  69109. p->errorAction = OE_Abort;
  69110. }else{
  69111. iDb = pOp->p3;
  69112. assert( iCnt==1 );
  69113. assert( DbMaskTest(p->btreeMask, iDb) );
  69114. iMoved = 0; /* Not needed. Only to silence a warning. */
  69115. rc = sqlite3BtreeDropTable(db->aDb[iDb].pBt, pOp->p1, &iMoved);
  69116. pOut->flags = MEM_Int;
  69117. pOut->u.i = iMoved;
  69118. #ifndef SQLITE_OMIT_AUTOVACUUM
  69119. if( rc==SQLITE_OK && iMoved!=0 ){
  69120. sqlite3RootPageMoved(db, iDb, iMoved, pOp->p1);
  69121. /* All OP_Destroy operations occur on the same btree */
  69122. assert( resetSchemaOnFault==0 || resetSchemaOnFault==iDb+1 );
  69123. resetSchemaOnFault = iDb+1;
  69124. }
  69125. #endif
  69126. }
  69127. break;
  69128. }
  69129. /* Opcode: Clear P1 P2 P3
  69130. **
  69131. ** Delete all contents of the database table or index whose root page
  69132. ** in the database file is given by P1. But, unlike Destroy, do not
  69133. ** remove the table or index from the database file.
  69134. **
  69135. ** The table being clear is in the main database file if P2==0. If
  69136. ** P2==1 then the table to be clear is in the auxiliary database file
  69137. ** that is used to store tables create using CREATE TEMPORARY TABLE.
  69138. **
  69139. ** If the P3 value is non-zero, then the table referred to must be an
  69140. ** intkey table (an SQL table, not an index). In this case the row change
  69141. ** count is incremented by the number of rows in the table being cleared.
  69142. ** If P3 is greater than zero, then the value stored in register P3 is
  69143. ** also incremented by the number of rows in the table being cleared.
  69144. **
  69145. ** See also: Destroy
  69146. */
  69147. case OP_Clear: {
  69148. int nChange;
  69149. nChange = 0;
  69150. assert( p->readOnly==0 );
  69151. assert( DbMaskTest(p->btreeMask, pOp->p2) );
  69152. rc = sqlite3BtreeClearTable(
  69153. db->aDb[pOp->p2].pBt, pOp->p1, (pOp->p3 ? &nChange : 0)
  69154. );
  69155. if( pOp->p3 ){
  69156. p->nChange += nChange;
  69157. if( pOp->p3>0 ){
  69158. assert( memIsValid(&aMem[pOp->p3]) );
  69159. memAboutToChange(p, &aMem[pOp->p3]);
  69160. aMem[pOp->p3].u.i += nChange;
  69161. }
  69162. }
  69163. break;
  69164. }
  69165. /* Opcode: ResetSorter P1 * * * *
  69166. **
  69167. ** Delete all contents from the ephemeral table or sorter
  69168. ** that is open on cursor P1.
  69169. **
  69170. ** This opcode only works for cursors used for sorting and
  69171. ** opened with OP_OpenEphemeral or OP_SorterOpen.
  69172. */
  69173. case OP_ResetSorter: {
  69174. VdbeCursor *pC;
  69175. assert( pOp->p1>=0 && pOp->p1<p->nCursor );
  69176. pC = p->apCsr[pOp->p1];
  69177. assert( pC!=0 );
  69178. if( pC->pSorter ){
  69179. sqlite3VdbeSorterReset(db, pC->pSorter);
  69180. }else{
  69181. assert( pC->isEphemeral );
  69182. rc = sqlite3BtreeClearTableOfCursor(pC->pCursor);
  69183. }
  69184. break;
  69185. }
  69186. /* Opcode: CreateTable P1 P2 * * *
  69187. ** Synopsis: r[P2]=root iDb=P1
  69188. **
  69189. ** Allocate a new table in the main database file if P1==0 or in the
  69190. ** auxiliary database file if P1==1 or in an attached database if
  69191. ** P1>1. Write the root page number of the new table into
  69192. ** register P2
  69193. **
  69194. ** The difference between a table and an index is this: A table must
  69195. ** have a 4-byte integer key and can have arbitrary data. An index
  69196. ** has an arbitrary key but no data.
  69197. **
  69198. ** See also: CreateIndex
  69199. */
  69200. /* Opcode: CreateIndex P1 P2 * * *
  69201. ** Synopsis: r[P2]=root iDb=P1
  69202. **
  69203. ** Allocate a new index in the main database file if P1==0 or in the
  69204. ** auxiliary database file if P1==1 or in an attached database if
  69205. ** P1>1. Write the root page number of the new table into
  69206. ** register P2.
  69207. **
  69208. ** See documentation on OP_CreateTable for additional information.
  69209. */
  69210. case OP_CreateIndex: /* out2-prerelease */
  69211. case OP_CreateTable: { /* out2-prerelease */
  69212. int pgno;
  69213. int flags;
  69214. Db *pDb;
  69215. pgno = 0;
  69216. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69217. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  69218. assert( p->readOnly==0 );
  69219. pDb = &db->aDb[pOp->p1];
  69220. assert( pDb->pBt!=0 );
  69221. if( pOp->opcode==OP_CreateTable ){
  69222. /* flags = BTREE_INTKEY; */
  69223. flags = BTREE_INTKEY;
  69224. }else{
  69225. flags = BTREE_BLOBKEY;
  69226. }
  69227. rc = sqlite3BtreeCreateTable(pDb->pBt, &pgno, flags);
  69228. pOut->u.i = pgno;
  69229. break;
  69230. }
  69231. /* Opcode: ParseSchema P1 * * P4 *
  69232. **
  69233. ** Read and parse all entries from the SQLITE_MASTER table of database P1
  69234. ** that match the WHERE clause P4.
  69235. **
  69236. ** This opcode invokes the parser to create a new virtual machine,
  69237. ** then runs the new virtual machine. It is thus a re-entrant opcode.
  69238. */
  69239. case OP_ParseSchema: {
  69240. int iDb;
  69241. const char *zMaster;
  69242. char *zSql;
  69243. InitData initData;
  69244. /* Any prepared statement that invokes this opcode will hold mutexes
  69245. ** on every btree. This is a prerequisite for invoking
  69246. ** sqlite3InitCallback().
  69247. */
  69248. #ifdef SQLITE_DEBUG
  69249. for(iDb=0; iDb<db->nDb; iDb++){
  69250. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  69251. }
  69252. #endif
  69253. iDb = pOp->p1;
  69254. assert( iDb>=0 && iDb<db->nDb );
  69255. assert( DbHasProperty(db, iDb, DB_SchemaLoaded) );
  69256. /* Used to be a conditional */ {
  69257. zMaster = SCHEMA_TABLE(iDb);
  69258. initData.db = db;
  69259. initData.iDb = pOp->p1;
  69260. initData.pzErrMsg = &p->zErrMsg;
  69261. zSql = sqlite3MPrintf(db,
  69262. "SELECT name, rootpage, sql FROM '%q'.%s WHERE %s ORDER BY rowid",
  69263. db->aDb[iDb].zName, zMaster, pOp->p4.z);
  69264. if( zSql==0 ){
  69265. rc = SQLITE_NOMEM;
  69266. }else{
  69267. assert( db->init.busy==0 );
  69268. db->init.busy = 1;
  69269. initData.rc = SQLITE_OK;
  69270. assert( !db->mallocFailed );
  69271. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  69272. if( rc==SQLITE_OK ) rc = initData.rc;
  69273. sqlite3DbFree(db, zSql);
  69274. db->init.busy = 0;
  69275. }
  69276. }
  69277. if( rc ) sqlite3ResetAllSchemasOfConnection(db);
  69278. if( rc==SQLITE_NOMEM ){
  69279. goto no_mem;
  69280. }
  69281. break;
  69282. }
  69283. #if !defined(SQLITE_OMIT_ANALYZE)
  69284. /* Opcode: LoadAnalysis P1 * * * *
  69285. **
  69286. ** Read the sqlite_stat1 table for database P1 and load the content
  69287. ** of that table into the internal index hash table. This will cause
  69288. ** the analysis to be used when preparing all subsequent queries.
  69289. */
  69290. case OP_LoadAnalysis: {
  69291. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69292. rc = sqlite3AnalysisLoad(db, pOp->p1);
  69293. break;
  69294. }
  69295. #endif /* !defined(SQLITE_OMIT_ANALYZE) */
  69296. /* Opcode: DropTable P1 * * P4 *
  69297. **
  69298. ** Remove the internal (in-memory) data structures that describe
  69299. ** the table named P4 in database P1. This is called after a table
  69300. ** is dropped from disk (using the Destroy opcode) in order to keep
  69301. ** the internal representation of the
  69302. ** schema consistent with what is on disk.
  69303. */
  69304. case OP_DropTable: {
  69305. sqlite3UnlinkAndDeleteTable(db, pOp->p1, pOp->p4.z);
  69306. break;
  69307. }
  69308. /* Opcode: DropIndex P1 * * P4 *
  69309. **
  69310. ** Remove the internal (in-memory) data structures that describe
  69311. ** the index named P4 in database P1. This is called after an index
  69312. ** is dropped from disk (using the Destroy opcode)
  69313. ** in order to keep the internal representation of the
  69314. ** schema consistent with what is on disk.
  69315. */
  69316. case OP_DropIndex: {
  69317. sqlite3UnlinkAndDeleteIndex(db, pOp->p1, pOp->p4.z);
  69318. break;
  69319. }
  69320. /* Opcode: DropTrigger P1 * * P4 *
  69321. **
  69322. ** Remove the internal (in-memory) data structures that describe
  69323. ** the trigger named P4 in database P1. This is called after a trigger
  69324. ** is dropped from disk (using the Destroy opcode) in order to keep
  69325. ** the internal representation of the
  69326. ** schema consistent with what is on disk.
  69327. */
  69328. case OP_DropTrigger: {
  69329. sqlite3UnlinkAndDeleteTrigger(db, pOp->p1, pOp->p4.z);
  69330. break;
  69331. }
  69332. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  69333. /* Opcode: IntegrityCk P1 P2 P3 * P5
  69334. **
  69335. ** Do an analysis of the currently open database. Store in
  69336. ** register P1 the text of an error message describing any problems.
  69337. ** If no problems are found, store a NULL in register P1.
  69338. **
  69339. ** The register P3 contains the maximum number of allowed errors.
  69340. ** At most reg(P3) errors will be reported.
  69341. ** In other words, the analysis stops as soon as reg(P1) errors are
  69342. ** seen. Reg(P1) is updated with the number of errors remaining.
  69343. **
  69344. ** The root page numbers of all tables in the database are integer
  69345. ** stored in reg(P1), reg(P1+1), reg(P1+2), .... There are P2 tables
  69346. ** total.
  69347. **
  69348. ** If P5 is not zero, the check is done on the auxiliary database
  69349. ** file, not the main database file.
  69350. **
  69351. ** This opcode is used to implement the integrity_check pragma.
  69352. */
  69353. case OP_IntegrityCk: {
  69354. int nRoot; /* Number of tables to check. (Number of root pages.) */
  69355. int *aRoot; /* Array of rootpage numbers for tables to be checked */
  69356. int j; /* Loop counter */
  69357. int nErr; /* Number of errors reported */
  69358. char *z; /* Text of the error report */
  69359. Mem *pnErr; /* Register keeping track of errors remaining */
  69360. assert( p->bIsReader );
  69361. nRoot = pOp->p2;
  69362. assert( nRoot>0 );
  69363. aRoot = sqlite3DbMallocRaw(db, sizeof(int)*(nRoot+1) );
  69364. if( aRoot==0 ) goto no_mem;
  69365. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69366. pnErr = &aMem[pOp->p3];
  69367. assert( (pnErr->flags & MEM_Int)!=0 );
  69368. assert( (pnErr->flags & (MEM_Str|MEM_Blob))==0 );
  69369. pIn1 = &aMem[pOp->p1];
  69370. for(j=0; j<nRoot; j++){
  69371. aRoot[j] = (int)sqlite3VdbeIntValue(&pIn1[j]);
  69372. }
  69373. aRoot[j] = 0;
  69374. assert( pOp->p5<db->nDb );
  69375. assert( DbMaskTest(p->btreeMask, pOp->p5) );
  69376. z = sqlite3BtreeIntegrityCheck(db->aDb[pOp->p5].pBt, aRoot, nRoot,
  69377. (int)pnErr->u.i, &nErr);
  69378. sqlite3DbFree(db, aRoot);
  69379. pnErr->u.i -= nErr;
  69380. sqlite3VdbeMemSetNull(pIn1);
  69381. if( nErr==0 ){
  69382. assert( z==0 );
  69383. }else if( z==0 ){
  69384. goto no_mem;
  69385. }else{
  69386. sqlite3VdbeMemSetStr(pIn1, z, -1, SQLITE_UTF8, sqlite3_free);
  69387. }
  69388. UPDATE_MAX_BLOBSIZE(pIn1);
  69389. sqlite3VdbeChangeEncoding(pIn1, encoding);
  69390. break;
  69391. }
  69392. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  69393. /* Opcode: RowSetAdd P1 P2 * * *
  69394. ** Synopsis: rowset(P1)=r[P2]
  69395. **
  69396. ** Insert the integer value held by register P2 into a boolean index
  69397. ** held in register P1.
  69398. **
  69399. ** An assertion fails if P2 is not an integer.
  69400. */
  69401. case OP_RowSetAdd: { /* in1, in2 */
  69402. pIn1 = &aMem[pOp->p1];
  69403. pIn2 = &aMem[pOp->p2];
  69404. assert( (pIn2->flags & MEM_Int)!=0 );
  69405. if( (pIn1->flags & MEM_RowSet)==0 ){
  69406. sqlite3VdbeMemSetRowSet(pIn1);
  69407. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  69408. }
  69409. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn2->u.i);
  69410. break;
  69411. }
  69412. /* Opcode: RowSetRead P1 P2 P3 * *
  69413. ** Synopsis: r[P3]=rowset(P1)
  69414. **
  69415. ** Extract the smallest value from boolean index P1 and put that value into
  69416. ** register P3. Or, if boolean index P1 is initially empty, leave P3
  69417. ** unchanged and jump to instruction P2.
  69418. */
  69419. case OP_RowSetRead: { /* jump, in1, out3 */
  69420. i64 val;
  69421. pIn1 = &aMem[pOp->p1];
  69422. if( (pIn1->flags & MEM_RowSet)==0
  69423. || sqlite3RowSetNext(pIn1->u.pRowSet, &val)==0
  69424. ){
  69425. /* The boolean index is empty */
  69426. sqlite3VdbeMemSetNull(pIn1);
  69427. pc = pOp->p2 - 1;
  69428. VdbeBranchTaken(1,2);
  69429. }else{
  69430. /* A value was pulled from the index */
  69431. sqlite3VdbeMemSetInt64(&aMem[pOp->p3], val);
  69432. VdbeBranchTaken(0,2);
  69433. }
  69434. goto check_for_interrupt;
  69435. }
  69436. /* Opcode: RowSetTest P1 P2 P3 P4
  69437. ** Synopsis: if r[P3] in rowset(P1) goto P2
  69438. **
  69439. ** Register P3 is assumed to hold a 64-bit integer value. If register P1
  69440. ** contains a RowSet object and that RowSet object contains
  69441. ** the value held in P3, jump to register P2. Otherwise, insert the
  69442. ** integer in P3 into the RowSet and continue on to the
  69443. ** next opcode.
  69444. **
  69445. ** The RowSet object is optimized for the case where successive sets
  69446. ** of integers, where each set contains no duplicates. Each set
  69447. ** of values is identified by a unique P4 value. The first set
  69448. ** must have P4==0, the final set P4=-1. P4 must be either -1 or
  69449. ** non-negative. For non-negative values of P4 only the lower 4
  69450. ** bits are significant.
  69451. **
  69452. ** This allows optimizations: (a) when P4==0 there is no need to test
  69453. ** the rowset object for P3, as it is guaranteed not to contain it,
  69454. ** (b) when P4==-1 there is no need to insert the value, as it will
  69455. ** never be tested for, and (c) when a value that is part of set X is
  69456. ** inserted, there is no need to search to see if the same value was
  69457. ** previously inserted as part of set X (only if it was previously
  69458. ** inserted as part of some other set).
  69459. */
  69460. case OP_RowSetTest: { /* jump, in1, in3 */
  69461. int iSet;
  69462. int exists;
  69463. pIn1 = &aMem[pOp->p1];
  69464. pIn3 = &aMem[pOp->p3];
  69465. iSet = pOp->p4.i;
  69466. assert( pIn3->flags&MEM_Int );
  69467. /* If there is anything other than a rowset object in memory cell P1,
  69468. ** delete it now and initialize P1 with an empty rowset
  69469. */
  69470. if( (pIn1->flags & MEM_RowSet)==0 ){
  69471. sqlite3VdbeMemSetRowSet(pIn1);
  69472. if( (pIn1->flags & MEM_RowSet)==0 ) goto no_mem;
  69473. }
  69474. assert( pOp->p4type==P4_INT32 );
  69475. assert( iSet==-1 || iSet>=0 );
  69476. if( iSet ){
  69477. exists = sqlite3RowSetTest(pIn1->u.pRowSet, iSet, pIn3->u.i);
  69478. VdbeBranchTaken(exists!=0,2);
  69479. if( exists ){
  69480. pc = pOp->p2 - 1;
  69481. break;
  69482. }
  69483. }
  69484. if( iSet>=0 ){
  69485. sqlite3RowSetInsert(pIn1->u.pRowSet, pIn3->u.i);
  69486. }
  69487. break;
  69488. }
  69489. #ifndef SQLITE_OMIT_TRIGGER
  69490. /* Opcode: Program P1 P2 P3 P4 P5
  69491. **
  69492. ** Execute the trigger program passed as P4 (type P4_SUBPROGRAM).
  69493. **
  69494. ** P1 contains the address of the memory cell that contains the first memory
  69495. ** cell in an array of values used as arguments to the sub-program. P2
  69496. ** contains the address to jump to if the sub-program throws an IGNORE
  69497. ** exception using the RAISE() function. Register P3 contains the address
  69498. ** of a memory cell in this (the parent) VM that is used to allocate the
  69499. ** memory required by the sub-vdbe at runtime.
  69500. **
  69501. ** P4 is a pointer to the VM containing the trigger program.
  69502. **
  69503. ** If P5 is non-zero, then recursive program invocation is enabled.
  69504. */
  69505. case OP_Program: { /* jump */
  69506. int nMem; /* Number of memory registers for sub-program */
  69507. int nByte; /* Bytes of runtime space required for sub-program */
  69508. Mem *pRt; /* Register to allocate runtime space */
  69509. Mem *pMem; /* Used to iterate through memory cells */
  69510. Mem *pEnd; /* Last memory cell in new array */
  69511. VdbeFrame *pFrame; /* New vdbe frame to execute in */
  69512. SubProgram *pProgram; /* Sub-program to execute */
  69513. void *t; /* Token identifying trigger */
  69514. pProgram = pOp->p4.pProgram;
  69515. pRt = &aMem[pOp->p3];
  69516. assert( pProgram->nOp>0 );
  69517. /* If the p5 flag is clear, then recursive invocation of triggers is
  69518. ** disabled for backwards compatibility (p5 is set if this sub-program
  69519. ** is really a trigger, not a foreign key action, and the flag set
  69520. ** and cleared by the "PRAGMA recursive_triggers" command is clear).
  69521. **
  69522. ** It is recursive invocation of triggers, at the SQL level, that is
  69523. ** disabled. In some cases a single trigger may generate more than one
  69524. ** SubProgram (if the trigger may be executed with more than one different
  69525. ** ON CONFLICT algorithm). SubProgram structures associated with a
  69526. ** single trigger all have the same value for the SubProgram.token
  69527. ** variable. */
  69528. if( pOp->p5 ){
  69529. t = pProgram->token;
  69530. for(pFrame=p->pFrame; pFrame && pFrame->token!=t; pFrame=pFrame->pParent);
  69531. if( pFrame ) break;
  69532. }
  69533. if( p->nFrame>=db->aLimit[SQLITE_LIMIT_TRIGGER_DEPTH] ){
  69534. rc = SQLITE_ERROR;
  69535. sqlite3SetString(&p->zErrMsg, db, "too many levels of trigger recursion");
  69536. break;
  69537. }
  69538. /* Register pRt is used to store the memory required to save the state
  69539. ** of the current program, and the memory required at runtime to execute
  69540. ** the trigger program. If this trigger has been fired before, then pRt
  69541. ** is already allocated. Otherwise, it must be initialized. */
  69542. if( (pRt->flags&MEM_Frame)==0 ){
  69543. /* SubProgram.nMem is set to the number of memory cells used by the
  69544. ** program stored in SubProgram.aOp. As well as these, one memory
  69545. ** cell is required for each cursor used by the program. Set local
  69546. ** variable nMem (and later, VdbeFrame.nChildMem) to this value.
  69547. */
  69548. nMem = pProgram->nMem + pProgram->nCsr;
  69549. nByte = ROUND8(sizeof(VdbeFrame))
  69550. + nMem * sizeof(Mem)
  69551. + pProgram->nCsr * sizeof(VdbeCursor *)
  69552. + pProgram->nOnce * sizeof(u8);
  69553. pFrame = sqlite3DbMallocZero(db, nByte);
  69554. if( !pFrame ){
  69555. goto no_mem;
  69556. }
  69557. sqlite3VdbeMemRelease(pRt);
  69558. pRt->flags = MEM_Frame;
  69559. pRt->u.pFrame = pFrame;
  69560. pFrame->v = p;
  69561. pFrame->nChildMem = nMem;
  69562. pFrame->nChildCsr = pProgram->nCsr;
  69563. pFrame->pc = pc;
  69564. pFrame->aMem = p->aMem;
  69565. pFrame->nMem = p->nMem;
  69566. pFrame->apCsr = p->apCsr;
  69567. pFrame->nCursor = p->nCursor;
  69568. pFrame->aOp = p->aOp;
  69569. pFrame->nOp = p->nOp;
  69570. pFrame->token = pProgram->token;
  69571. pFrame->aOnceFlag = p->aOnceFlag;
  69572. pFrame->nOnceFlag = p->nOnceFlag;
  69573. pEnd = &VdbeFrameMem(pFrame)[pFrame->nChildMem];
  69574. for(pMem=VdbeFrameMem(pFrame); pMem!=pEnd; pMem++){
  69575. pMem->flags = MEM_Undefined;
  69576. pMem->db = db;
  69577. }
  69578. }else{
  69579. pFrame = pRt->u.pFrame;
  69580. assert( pProgram->nMem+pProgram->nCsr==pFrame->nChildMem );
  69581. assert( pProgram->nCsr==pFrame->nChildCsr );
  69582. assert( pc==pFrame->pc );
  69583. }
  69584. p->nFrame++;
  69585. pFrame->pParent = p->pFrame;
  69586. pFrame->lastRowid = lastRowid;
  69587. pFrame->nChange = p->nChange;
  69588. p->nChange = 0;
  69589. p->pFrame = pFrame;
  69590. p->aMem = aMem = &VdbeFrameMem(pFrame)[-1];
  69591. p->nMem = pFrame->nChildMem;
  69592. p->nCursor = (u16)pFrame->nChildCsr;
  69593. p->apCsr = (VdbeCursor **)&aMem[p->nMem+1];
  69594. p->aOp = aOp = pProgram->aOp;
  69595. p->nOp = pProgram->nOp;
  69596. p->aOnceFlag = (u8 *)&p->apCsr[p->nCursor];
  69597. p->nOnceFlag = pProgram->nOnce;
  69598. pc = -1;
  69599. memset(p->aOnceFlag, 0, p->nOnceFlag);
  69600. break;
  69601. }
  69602. /* Opcode: Param P1 P2 * * *
  69603. **
  69604. ** This opcode is only ever present in sub-programs called via the
  69605. ** OP_Program instruction. Copy a value currently stored in a memory
  69606. ** cell of the calling (parent) frame to cell P2 in the current frames
  69607. ** address space. This is used by trigger programs to access the new.*
  69608. ** and old.* values.
  69609. **
  69610. ** The address of the cell in the parent frame is determined by adding
  69611. ** the value of the P1 argument to the value of the P1 argument to the
  69612. ** calling OP_Program instruction.
  69613. */
  69614. case OP_Param: { /* out2-prerelease */
  69615. VdbeFrame *pFrame;
  69616. Mem *pIn;
  69617. pFrame = p->pFrame;
  69618. pIn = &pFrame->aMem[pOp->p1 + pFrame->aOp[pFrame->pc].p1];
  69619. sqlite3VdbeMemShallowCopy(pOut, pIn, MEM_Ephem);
  69620. break;
  69621. }
  69622. #endif /* #ifndef SQLITE_OMIT_TRIGGER */
  69623. #ifndef SQLITE_OMIT_FOREIGN_KEY
  69624. /* Opcode: FkCounter P1 P2 * * *
  69625. ** Synopsis: fkctr[P1]+=P2
  69626. **
  69627. ** Increment a "constraint counter" by P2 (P2 may be negative or positive).
  69628. ** If P1 is non-zero, the database constraint counter is incremented
  69629. ** (deferred foreign key constraints). Otherwise, if P1 is zero, the
  69630. ** statement counter is incremented (immediate foreign key constraints).
  69631. */
  69632. case OP_FkCounter: {
  69633. if( db->flags & SQLITE_DeferFKs ){
  69634. db->nDeferredImmCons += pOp->p2;
  69635. }else if( pOp->p1 ){
  69636. db->nDeferredCons += pOp->p2;
  69637. }else{
  69638. p->nFkConstraint += pOp->p2;
  69639. }
  69640. break;
  69641. }
  69642. /* Opcode: FkIfZero P1 P2 * * *
  69643. ** Synopsis: if fkctr[P1]==0 goto P2
  69644. **
  69645. ** This opcode tests if a foreign key constraint-counter is currently zero.
  69646. ** If so, jump to instruction P2. Otherwise, fall through to the next
  69647. ** instruction.
  69648. **
  69649. ** If P1 is non-zero, then the jump is taken if the database constraint-counter
  69650. ** is zero (the one that counts deferred constraint violations). If P1 is
  69651. ** zero, the jump is taken if the statement constraint-counter is zero
  69652. ** (immediate foreign key constraint violations).
  69653. */
  69654. case OP_FkIfZero: { /* jump */
  69655. if( pOp->p1 ){
  69656. VdbeBranchTaken(db->nDeferredCons==0 && db->nDeferredImmCons==0, 2);
  69657. if( db->nDeferredCons==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  69658. }else{
  69659. VdbeBranchTaken(p->nFkConstraint==0 && db->nDeferredImmCons==0, 2);
  69660. if( p->nFkConstraint==0 && db->nDeferredImmCons==0 ) pc = pOp->p2-1;
  69661. }
  69662. break;
  69663. }
  69664. #endif /* #ifndef SQLITE_OMIT_FOREIGN_KEY */
  69665. #ifndef SQLITE_OMIT_AUTOINCREMENT
  69666. /* Opcode: MemMax P1 P2 * * *
  69667. ** Synopsis: r[P1]=max(r[P1],r[P2])
  69668. **
  69669. ** P1 is a register in the root frame of this VM (the root frame is
  69670. ** different from the current frame if this instruction is being executed
  69671. ** within a sub-program). Set the value of register P1 to the maximum of
  69672. ** its current value and the value in register P2.
  69673. **
  69674. ** This instruction throws an error if the memory cell is not initially
  69675. ** an integer.
  69676. */
  69677. case OP_MemMax: { /* in2 */
  69678. VdbeFrame *pFrame;
  69679. if( p->pFrame ){
  69680. for(pFrame=p->pFrame; pFrame->pParent; pFrame=pFrame->pParent);
  69681. pIn1 = &pFrame->aMem[pOp->p1];
  69682. }else{
  69683. pIn1 = &aMem[pOp->p1];
  69684. }
  69685. assert( memIsValid(pIn1) );
  69686. sqlite3VdbeMemIntegerify(pIn1);
  69687. pIn2 = &aMem[pOp->p2];
  69688. sqlite3VdbeMemIntegerify(pIn2);
  69689. if( pIn1->u.i<pIn2->u.i){
  69690. pIn1->u.i = pIn2->u.i;
  69691. }
  69692. break;
  69693. }
  69694. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  69695. /* Opcode: IfPos P1 P2 * * *
  69696. ** Synopsis: if r[P1]>0 goto P2
  69697. **
  69698. ** If the value of register P1 is 1 or greater, jump to P2.
  69699. **
  69700. ** It is illegal to use this instruction on a register that does
  69701. ** not contain an integer. An assertion fault will result if you try.
  69702. */
  69703. case OP_IfPos: { /* jump, in1 */
  69704. pIn1 = &aMem[pOp->p1];
  69705. assert( pIn1->flags&MEM_Int );
  69706. VdbeBranchTaken( pIn1->u.i>0, 2);
  69707. if( pIn1->u.i>0 ){
  69708. pc = pOp->p2 - 1;
  69709. }
  69710. break;
  69711. }
  69712. /* Opcode: IfNeg P1 P2 P3 * *
  69713. ** Synopsis: r[P1]+=P3, if r[P1]<0 goto P2
  69714. **
  69715. ** Register P1 must contain an integer. Add literal P3 to the value in
  69716. ** register P1 then if the value of register P1 is less than zero, jump to P2.
  69717. */
  69718. case OP_IfNeg: { /* jump, in1 */
  69719. pIn1 = &aMem[pOp->p1];
  69720. assert( pIn1->flags&MEM_Int );
  69721. pIn1->u.i += pOp->p3;
  69722. VdbeBranchTaken(pIn1->u.i<0, 2);
  69723. if( pIn1->u.i<0 ){
  69724. pc = pOp->p2 - 1;
  69725. }
  69726. break;
  69727. }
  69728. /* Opcode: IfZero P1 P2 P3 * *
  69729. ** Synopsis: r[P1]+=P3, if r[P1]==0 goto P2
  69730. **
  69731. ** The register P1 must contain an integer. Add literal P3 to the
  69732. ** value in register P1. If the result is exactly 0, jump to P2.
  69733. */
  69734. case OP_IfZero: { /* jump, in1 */
  69735. pIn1 = &aMem[pOp->p1];
  69736. assert( pIn1->flags&MEM_Int );
  69737. pIn1->u.i += pOp->p3;
  69738. VdbeBranchTaken(pIn1->u.i==0, 2);
  69739. if( pIn1->u.i==0 ){
  69740. pc = pOp->p2 - 1;
  69741. }
  69742. break;
  69743. }
  69744. /* Opcode: AggStep * P2 P3 P4 P5
  69745. ** Synopsis: accum=r[P3] step(r[P2@P5])
  69746. **
  69747. ** Execute the step function for an aggregate. The
  69748. ** function has P5 arguments. P4 is a pointer to the FuncDef
  69749. ** structure that specifies the function. Use register
  69750. ** P3 as the accumulator.
  69751. **
  69752. ** The P5 arguments are taken from register P2 and its
  69753. ** successors.
  69754. */
  69755. case OP_AggStep: {
  69756. int n;
  69757. int i;
  69758. Mem *pMem;
  69759. Mem *pRec;
  69760. Mem t;
  69761. sqlite3_context ctx;
  69762. sqlite3_value **apVal;
  69763. n = pOp->p5;
  69764. assert( n>=0 );
  69765. pRec = &aMem[pOp->p2];
  69766. apVal = p->apArg;
  69767. assert( apVal || n==0 );
  69768. for(i=0; i<n; i++, pRec++){
  69769. assert( memIsValid(pRec) );
  69770. apVal[i] = pRec;
  69771. memAboutToChange(p, pRec);
  69772. }
  69773. ctx.pFunc = pOp->p4.pFunc;
  69774. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  69775. ctx.pMem = pMem = &aMem[pOp->p3];
  69776. pMem->n++;
  69777. sqlite3VdbeMemInit(&t, db, MEM_Null);
  69778. ctx.pOut = &t;
  69779. ctx.isError = 0;
  69780. ctx.pVdbe = p;
  69781. ctx.iOp = pc;
  69782. ctx.skipFlag = 0;
  69783. (ctx.pFunc->xStep)(&ctx, n, apVal); /* IMP: R-24505-23230 */
  69784. if( ctx.isError ){
  69785. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(&t));
  69786. rc = ctx.isError;
  69787. }
  69788. if( ctx.skipFlag ){
  69789. assert( pOp[-1].opcode==OP_CollSeq );
  69790. i = pOp[-1].p1;
  69791. if( i ) sqlite3VdbeMemSetInt64(&aMem[i], 1);
  69792. }
  69793. sqlite3VdbeMemRelease(&t);
  69794. break;
  69795. }
  69796. /* Opcode: AggFinal P1 P2 * P4 *
  69797. ** Synopsis: accum=r[P1] N=P2
  69798. **
  69799. ** Execute the finalizer function for an aggregate. P1 is
  69800. ** the memory location that is the accumulator for the aggregate.
  69801. **
  69802. ** P2 is the number of arguments that the step function takes and
  69803. ** P4 is a pointer to the FuncDef for this function. The P2
  69804. ** argument is not used by this opcode. It is only there to disambiguate
  69805. ** functions that can take varying numbers of arguments. The
  69806. ** P4 argument is only needed for the degenerate case where
  69807. ** the step function was not previously called.
  69808. */
  69809. case OP_AggFinal: {
  69810. Mem *pMem;
  69811. assert( pOp->p1>0 && pOp->p1<=(p->nMem-p->nCursor) );
  69812. pMem = &aMem[pOp->p1];
  69813. assert( (pMem->flags & ~(MEM_Null|MEM_Agg))==0 );
  69814. rc = sqlite3VdbeMemFinalize(pMem, pOp->p4.pFunc);
  69815. if( rc ){
  69816. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3_value_text(pMem));
  69817. }
  69818. sqlite3VdbeChangeEncoding(pMem, encoding);
  69819. UPDATE_MAX_BLOBSIZE(pMem);
  69820. if( sqlite3VdbeMemTooBig(pMem) ){
  69821. goto too_big;
  69822. }
  69823. break;
  69824. }
  69825. #ifndef SQLITE_OMIT_WAL
  69826. /* Opcode: Checkpoint P1 P2 P3 * *
  69827. **
  69828. ** Checkpoint database P1. This is a no-op if P1 is not currently in
  69829. ** WAL mode. Parameter P2 is one of SQLITE_CHECKPOINT_PASSIVE, FULL
  69830. ** or RESTART. Write 1 or 0 into mem[P3] if the checkpoint returns
  69831. ** SQLITE_BUSY or not, respectively. Write the number of pages in the
  69832. ** WAL after the checkpoint into mem[P3+1] and the number of pages
  69833. ** in the WAL that have been checkpointed after the checkpoint
  69834. ** completes into mem[P3+2]. However on an error, mem[P3+1] and
  69835. ** mem[P3+2] are initialized to -1.
  69836. */
  69837. case OP_Checkpoint: {
  69838. int i; /* Loop counter */
  69839. int aRes[3]; /* Results */
  69840. Mem *pMem; /* Write results here */
  69841. assert( p->readOnly==0 );
  69842. aRes[0] = 0;
  69843. aRes[1] = aRes[2] = -1;
  69844. assert( pOp->p2==SQLITE_CHECKPOINT_PASSIVE
  69845. || pOp->p2==SQLITE_CHECKPOINT_FULL
  69846. || pOp->p2==SQLITE_CHECKPOINT_RESTART
  69847. );
  69848. rc = sqlite3Checkpoint(db, pOp->p1, pOp->p2, &aRes[1], &aRes[2]);
  69849. if( rc==SQLITE_BUSY ){
  69850. rc = SQLITE_OK;
  69851. aRes[0] = 1;
  69852. }
  69853. for(i=0, pMem = &aMem[pOp->p3]; i<3; i++, pMem++){
  69854. sqlite3VdbeMemSetInt64(pMem, (i64)aRes[i]);
  69855. }
  69856. break;
  69857. };
  69858. #endif
  69859. #ifndef SQLITE_OMIT_PRAGMA
  69860. /* Opcode: JournalMode P1 P2 P3 * *
  69861. **
  69862. ** Change the journal mode of database P1 to P3. P3 must be one of the
  69863. ** PAGER_JOURNALMODE_XXX values. If changing between the various rollback
  69864. ** modes (delete, truncate, persist, off and memory), this is a simple
  69865. ** operation. No IO is required.
  69866. **
  69867. ** If changing into or out of WAL mode the procedure is more complicated.
  69868. **
  69869. ** Write a string containing the final journal-mode to register P2.
  69870. */
  69871. case OP_JournalMode: { /* out2-prerelease */
  69872. Btree *pBt; /* Btree to change journal mode of */
  69873. Pager *pPager; /* Pager associated with pBt */
  69874. int eNew; /* New journal mode */
  69875. int eOld; /* The old journal mode */
  69876. #ifndef SQLITE_OMIT_WAL
  69877. const char *zFilename; /* Name of database file for pPager */
  69878. #endif
  69879. eNew = pOp->p3;
  69880. assert( eNew==PAGER_JOURNALMODE_DELETE
  69881. || eNew==PAGER_JOURNALMODE_TRUNCATE
  69882. || eNew==PAGER_JOURNALMODE_PERSIST
  69883. || eNew==PAGER_JOURNALMODE_OFF
  69884. || eNew==PAGER_JOURNALMODE_MEMORY
  69885. || eNew==PAGER_JOURNALMODE_WAL
  69886. || eNew==PAGER_JOURNALMODE_QUERY
  69887. );
  69888. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69889. assert( p->readOnly==0 );
  69890. pBt = db->aDb[pOp->p1].pBt;
  69891. pPager = sqlite3BtreePager(pBt);
  69892. eOld = sqlite3PagerGetJournalMode(pPager);
  69893. if( eNew==PAGER_JOURNALMODE_QUERY ) eNew = eOld;
  69894. if( !sqlite3PagerOkToChangeJournalMode(pPager) ) eNew = eOld;
  69895. #ifndef SQLITE_OMIT_WAL
  69896. zFilename = sqlite3PagerFilename(pPager, 1);
  69897. /* Do not allow a transition to journal_mode=WAL for a database
  69898. ** in temporary storage or if the VFS does not support shared memory
  69899. */
  69900. if( eNew==PAGER_JOURNALMODE_WAL
  69901. && (sqlite3Strlen30(zFilename)==0 /* Temp file */
  69902. || !sqlite3PagerWalSupported(pPager)) /* No shared-memory support */
  69903. ){
  69904. eNew = eOld;
  69905. }
  69906. if( (eNew!=eOld)
  69907. && (eOld==PAGER_JOURNALMODE_WAL || eNew==PAGER_JOURNALMODE_WAL)
  69908. ){
  69909. if( !db->autoCommit || db->nVdbeRead>1 ){
  69910. rc = SQLITE_ERROR;
  69911. sqlite3SetString(&p->zErrMsg, db,
  69912. "cannot change %s wal mode from within a transaction",
  69913. (eNew==PAGER_JOURNALMODE_WAL ? "into" : "out of")
  69914. );
  69915. break;
  69916. }else{
  69917. if( eOld==PAGER_JOURNALMODE_WAL ){
  69918. /* If leaving WAL mode, close the log file. If successful, the call
  69919. ** to PagerCloseWal() checkpoints and deletes the write-ahead-log
  69920. ** file. An EXCLUSIVE lock may still be held on the database file
  69921. ** after a successful return.
  69922. */
  69923. rc = sqlite3PagerCloseWal(pPager);
  69924. if( rc==SQLITE_OK ){
  69925. sqlite3PagerSetJournalMode(pPager, eNew);
  69926. }
  69927. }else if( eOld==PAGER_JOURNALMODE_MEMORY ){
  69928. /* Cannot transition directly from MEMORY to WAL. Use mode OFF
  69929. ** as an intermediate */
  69930. sqlite3PagerSetJournalMode(pPager, PAGER_JOURNALMODE_OFF);
  69931. }
  69932. /* Open a transaction on the database file. Regardless of the journal
  69933. ** mode, this transaction always uses a rollback journal.
  69934. */
  69935. assert( sqlite3BtreeIsInTrans(pBt)==0 );
  69936. if( rc==SQLITE_OK ){
  69937. rc = sqlite3BtreeSetVersion(pBt, (eNew==PAGER_JOURNALMODE_WAL ? 2 : 1));
  69938. }
  69939. }
  69940. }
  69941. #endif /* ifndef SQLITE_OMIT_WAL */
  69942. if( rc ){
  69943. eNew = eOld;
  69944. }
  69945. eNew = sqlite3PagerSetJournalMode(pPager, eNew);
  69946. pOut = &aMem[pOp->p2];
  69947. pOut->flags = MEM_Str|MEM_Static|MEM_Term;
  69948. pOut->z = (char *)sqlite3JournalModename(eNew);
  69949. pOut->n = sqlite3Strlen30(pOut->z);
  69950. pOut->enc = SQLITE_UTF8;
  69951. sqlite3VdbeChangeEncoding(pOut, encoding);
  69952. break;
  69953. };
  69954. #endif /* SQLITE_OMIT_PRAGMA */
  69955. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  69956. /* Opcode: Vacuum * * * * *
  69957. **
  69958. ** Vacuum the entire database. This opcode will cause other virtual
  69959. ** machines to be created and run. It may not be called from within
  69960. ** a transaction.
  69961. */
  69962. case OP_Vacuum: {
  69963. assert( p->readOnly==0 );
  69964. rc = sqlite3RunVacuum(&p->zErrMsg, db);
  69965. break;
  69966. }
  69967. #endif
  69968. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  69969. /* Opcode: IncrVacuum P1 P2 * * *
  69970. **
  69971. ** Perform a single step of the incremental vacuum procedure on
  69972. ** the P1 database. If the vacuum has finished, jump to instruction
  69973. ** P2. Otherwise, fall through to the next instruction.
  69974. */
  69975. case OP_IncrVacuum: { /* jump */
  69976. Btree *pBt;
  69977. assert( pOp->p1>=0 && pOp->p1<db->nDb );
  69978. assert( DbMaskTest(p->btreeMask, pOp->p1) );
  69979. assert( p->readOnly==0 );
  69980. pBt = db->aDb[pOp->p1].pBt;
  69981. rc = sqlite3BtreeIncrVacuum(pBt);
  69982. VdbeBranchTaken(rc==SQLITE_DONE,2);
  69983. if( rc==SQLITE_DONE ){
  69984. pc = pOp->p2 - 1;
  69985. rc = SQLITE_OK;
  69986. }
  69987. break;
  69988. }
  69989. #endif
  69990. /* Opcode: Expire P1 * * * *
  69991. **
  69992. ** Cause precompiled statements to expire. When an expired statement
  69993. ** is executed using sqlite3_step() it will either automatically
  69994. ** reprepare itself (if it was originally created using sqlite3_prepare_v2())
  69995. ** or it will fail with SQLITE_SCHEMA.
  69996. **
  69997. ** If P1 is 0, then all SQL statements become expired. If P1 is non-zero,
  69998. ** then only the currently executing statement is expired.
  69999. */
  70000. case OP_Expire: {
  70001. if( !pOp->p1 ){
  70002. sqlite3ExpirePreparedStatements(db);
  70003. }else{
  70004. p->expired = 1;
  70005. }
  70006. break;
  70007. }
  70008. #ifndef SQLITE_OMIT_SHARED_CACHE
  70009. /* Opcode: TableLock P1 P2 P3 P4 *
  70010. ** Synopsis: iDb=P1 root=P2 write=P3
  70011. **
  70012. ** Obtain a lock on a particular table. This instruction is only used when
  70013. ** the shared-cache feature is enabled.
  70014. **
  70015. ** P1 is the index of the database in sqlite3.aDb[] of the database
  70016. ** on which the lock is acquired. A readlock is obtained if P3==0 or
  70017. ** a write lock if P3==1.
  70018. **
  70019. ** P2 contains the root-page of the table to lock.
  70020. **
  70021. ** P4 contains a pointer to the name of the table being locked. This is only
  70022. ** used to generate an error message if the lock cannot be obtained.
  70023. */
  70024. case OP_TableLock: {
  70025. u8 isWriteLock = (u8)pOp->p3;
  70026. if( isWriteLock || 0==(db->flags&SQLITE_ReadUncommitted) ){
  70027. int p1 = pOp->p1;
  70028. assert( p1>=0 && p1<db->nDb );
  70029. assert( DbMaskTest(p->btreeMask, p1) );
  70030. assert( isWriteLock==0 || isWriteLock==1 );
  70031. rc = sqlite3BtreeLockTable(db->aDb[p1].pBt, pOp->p2, isWriteLock);
  70032. if( (rc&0xFF)==SQLITE_LOCKED ){
  70033. const char *z = pOp->p4.z;
  70034. sqlite3SetString(&p->zErrMsg, db, "database table is locked: %s", z);
  70035. }
  70036. }
  70037. break;
  70038. }
  70039. #endif /* SQLITE_OMIT_SHARED_CACHE */
  70040. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70041. /* Opcode: VBegin * * * P4 *
  70042. **
  70043. ** P4 may be a pointer to an sqlite3_vtab structure. If so, call the
  70044. ** xBegin method for that table.
  70045. **
  70046. ** Also, whether or not P4 is set, check that this is not being called from
  70047. ** within a callback to a virtual table xSync() method. If it is, the error
  70048. ** code will be set to SQLITE_LOCKED.
  70049. */
  70050. case OP_VBegin: {
  70051. VTable *pVTab;
  70052. pVTab = pOp->p4.pVtab;
  70053. rc = sqlite3VtabBegin(db, pVTab);
  70054. if( pVTab ) sqlite3VtabImportErrmsg(p, pVTab->pVtab);
  70055. break;
  70056. }
  70057. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70058. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70059. /* Opcode: VCreate P1 * * P4 *
  70060. **
  70061. ** P4 is the name of a virtual table in database P1. Call the xCreate method
  70062. ** for that table.
  70063. */
  70064. case OP_VCreate: {
  70065. rc = sqlite3VtabCallCreate(db, pOp->p1, pOp->p4.z, &p->zErrMsg);
  70066. break;
  70067. }
  70068. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70069. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70070. /* Opcode: VDestroy P1 * * P4 *
  70071. **
  70072. ** P4 is the name of a virtual table in database P1. Call the xDestroy method
  70073. ** of that table.
  70074. */
  70075. case OP_VDestroy: {
  70076. p->inVtabMethod = 2;
  70077. rc = sqlite3VtabCallDestroy(db, pOp->p1, pOp->p4.z);
  70078. p->inVtabMethod = 0;
  70079. break;
  70080. }
  70081. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70082. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70083. /* Opcode: VOpen P1 * * P4 *
  70084. **
  70085. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70086. ** P1 is a cursor number. This opcode opens a cursor to the virtual
  70087. ** table and stores that cursor in P1.
  70088. */
  70089. case OP_VOpen: {
  70090. VdbeCursor *pCur;
  70091. sqlite3_vtab_cursor *pVtabCursor;
  70092. sqlite3_vtab *pVtab;
  70093. sqlite3_module *pModule;
  70094. assert( p->bIsReader );
  70095. pCur = 0;
  70096. pVtabCursor = 0;
  70097. pVtab = pOp->p4.pVtab->pVtab;
  70098. pModule = (sqlite3_module *)pVtab->pModule;
  70099. assert(pVtab && pModule);
  70100. rc = pModule->xOpen(pVtab, &pVtabCursor);
  70101. sqlite3VtabImportErrmsg(p, pVtab);
  70102. if( SQLITE_OK==rc ){
  70103. /* Initialize sqlite3_vtab_cursor base class */
  70104. pVtabCursor->pVtab = pVtab;
  70105. /* Initialize vdbe cursor object */
  70106. pCur = allocateCursor(p, pOp->p1, 0, -1, 0);
  70107. if( pCur ){
  70108. pCur->pVtabCursor = pVtabCursor;
  70109. }else{
  70110. db->mallocFailed = 1;
  70111. pModule->xClose(pVtabCursor);
  70112. }
  70113. }
  70114. break;
  70115. }
  70116. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70117. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70118. /* Opcode: VFilter P1 P2 P3 P4 *
  70119. ** Synopsis: iplan=r[P3] zplan='P4'
  70120. **
  70121. ** P1 is a cursor opened using VOpen. P2 is an address to jump to if
  70122. ** the filtered result set is empty.
  70123. **
  70124. ** P4 is either NULL or a string that was generated by the xBestIndex
  70125. ** method of the module. The interpretation of the P4 string is left
  70126. ** to the module implementation.
  70127. **
  70128. ** This opcode invokes the xFilter method on the virtual table specified
  70129. ** by P1. The integer query plan parameter to xFilter is stored in register
  70130. ** P3. Register P3+1 stores the argc parameter to be passed to the
  70131. ** xFilter method. Registers P3+2..P3+1+argc are the argc
  70132. ** additional parameters which are passed to
  70133. ** xFilter as argv. Register P3+2 becomes argv[0] when passed to xFilter.
  70134. **
  70135. ** A jump is made to P2 if the result set after filtering would be empty.
  70136. */
  70137. case OP_VFilter: { /* jump */
  70138. int nArg;
  70139. int iQuery;
  70140. const sqlite3_module *pModule;
  70141. Mem *pQuery;
  70142. Mem *pArgc;
  70143. sqlite3_vtab_cursor *pVtabCursor;
  70144. sqlite3_vtab *pVtab;
  70145. VdbeCursor *pCur;
  70146. int res;
  70147. int i;
  70148. Mem **apArg;
  70149. pQuery = &aMem[pOp->p3];
  70150. pArgc = &pQuery[1];
  70151. pCur = p->apCsr[pOp->p1];
  70152. assert( memIsValid(pQuery) );
  70153. REGISTER_TRACE(pOp->p3, pQuery);
  70154. assert( pCur->pVtabCursor );
  70155. pVtabCursor = pCur->pVtabCursor;
  70156. pVtab = pVtabCursor->pVtab;
  70157. pModule = pVtab->pModule;
  70158. /* Grab the index number and argc parameters */
  70159. assert( (pQuery->flags&MEM_Int)!=0 && pArgc->flags==MEM_Int );
  70160. nArg = (int)pArgc->u.i;
  70161. iQuery = (int)pQuery->u.i;
  70162. /* Invoke the xFilter method */
  70163. {
  70164. res = 0;
  70165. apArg = p->apArg;
  70166. for(i = 0; i<nArg; i++){
  70167. apArg[i] = &pArgc[i+1];
  70168. }
  70169. p->inVtabMethod = 1;
  70170. rc = pModule->xFilter(pVtabCursor, iQuery, pOp->p4.z, nArg, apArg);
  70171. p->inVtabMethod = 0;
  70172. sqlite3VtabImportErrmsg(p, pVtab);
  70173. if( rc==SQLITE_OK ){
  70174. res = pModule->xEof(pVtabCursor);
  70175. }
  70176. VdbeBranchTaken(res!=0,2);
  70177. if( res ){
  70178. pc = pOp->p2 - 1;
  70179. }
  70180. }
  70181. pCur->nullRow = 0;
  70182. break;
  70183. }
  70184. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70185. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70186. /* Opcode: VColumn P1 P2 P3 * *
  70187. ** Synopsis: r[P3]=vcolumn(P2)
  70188. **
  70189. ** Store the value of the P2-th column of
  70190. ** the row of the virtual-table that the
  70191. ** P1 cursor is pointing to into register P3.
  70192. */
  70193. case OP_VColumn: {
  70194. sqlite3_vtab *pVtab;
  70195. const sqlite3_module *pModule;
  70196. Mem *pDest;
  70197. sqlite3_context sContext;
  70198. VdbeCursor *pCur = p->apCsr[pOp->p1];
  70199. assert( pCur->pVtabCursor );
  70200. assert( pOp->p3>0 && pOp->p3<=(p->nMem-p->nCursor) );
  70201. pDest = &aMem[pOp->p3];
  70202. memAboutToChange(p, pDest);
  70203. if( pCur->nullRow ){
  70204. sqlite3VdbeMemSetNull(pDest);
  70205. break;
  70206. }
  70207. pVtab = pCur->pVtabCursor->pVtab;
  70208. pModule = pVtab->pModule;
  70209. assert( pModule->xColumn );
  70210. memset(&sContext, 0, sizeof(sContext));
  70211. sContext.pOut = pDest;
  70212. MemSetTypeFlag(pDest, MEM_Null);
  70213. rc = pModule->xColumn(pCur->pVtabCursor, &sContext, pOp->p2);
  70214. sqlite3VtabImportErrmsg(p, pVtab);
  70215. if( sContext.isError ){
  70216. rc = sContext.isError;
  70217. }
  70218. sqlite3VdbeChangeEncoding(pDest, encoding);
  70219. REGISTER_TRACE(pOp->p3, pDest);
  70220. UPDATE_MAX_BLOBSIZE(pDest);
  70221. if( sqlite3VdbeMemTooBig(pDest) ){
  70222. goto too_big;
  70223. }
  70224. break;
  70225. }
  70226. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70227. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70228. /* Opcode: VNext P1 P2 * * *
  70229. **
  70230. ** Advance virtual table P1 to the next row in its result set and
  70231. ** jump to instruction P2. Or, if the virtual table has reached
  70232. ** the end of its result set, then fall through to the next instruction.
  70233. */
  70234. case OP_VNext: { /* jump */
  70235. sqlite3_vtab *pVtab;
  70236. const sqlite3_module *pModule;
  70237. int res;
  70238. VdbeCursor *pCur;
  70239. res = 0;
  70240. pCur = p->apCsr[pOp->p1];
  70241. assert( pCur->pVtabCursor );
  70242. if( pCur->nullRow ){
  70243. break;
  70244. }
  70245. pVtab = pCur->pVtabCursor->pVtab;
  70246. pModule = pVtab->pModule;
  70247. assert( pModule->xNext );
  70248. /* Invoke the xNext() method of the module. There is no way for the
  70249. ** underlying implementation to return an error if one occurs during
  70250. ** xNext(). Instead, if an error occurs, true is returned (indicating that
  70251. ** data is available) and the error code returned when xColumn or
  70252. ** some other method is next invoked on the save virtual table cursor.
  70253. */
  70254. p->inVtabMethod = 1;
  70255. rc = pModule->xNext(pCur->pVtabCursor);
  70256. p->inVtabMethod = 0;
  70257. sqlite3VtabImportErrmsg(p, pVtab);
  70258. if( rc==SQLITE_OK ){
  70259. res = pModule->xEof(pCur->pVtabCursor);
  70260. }
  70261. VdbeBranchTaken(!res,2);
  70262. if( !res ){
  70263. /* If there is data, jump to P2 */
  70264. pc = pOp->p2 - 1;
  70265. }
  70266. goto check_for_interrupt;
  70267. }
  70268. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70269. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70270. /* Opcode: VRename P1 * * P4 *
  70271. **
  70272. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70273. ** This opcode invokes the corresponding xRename method. The value
  70274. ** in register P1 is passed as the zName argument to the xRename method.
  70275. */
  70276. case OP_VRename: {
  70277. sqlite3_vtab *pVtab;
  70278. Mem *pName;
  70279. pVtab = pOp->p4.pVtab->pVtab;
  70280. pName = &aMem[pOp->p1];
  70281. assert( pVtab->pModule->xRename );
  70282. assert( memIsValid(pName) );
  70283. assert( p->readOnly==0 );
  70284. REGISTER_TRACE(pOp->p1, pName);
  70285. assert( pName->flags & MEM_Str );
  70286. testcase( pName->enc==SQLITE_UTF8 );
  70287. testcase( pName->enc==SQLITE_UTF16BE );
  70288. testcase( pName->enc==SQLITE_UTF16LE );
  70289. rc = sqlite3VdbeChangeEncoding(pName, SQLITE_UTF8);
  70290. if( rc==SQLITE_OK ){
  70291. rc = pVtab->pModule->xRename(pVtab, pName->z);
  70292. sqlite3VtabImportErrmsg(p, pVtab);
  70293. p->expired = 0;
  70294. }
  70295. break;
  70296. }
  70297. #endif
  70298. #ifndef SQLITE_OMIT_VIRTUALTABLE
  70299. /* Opcode: VUpdate P1 P2 P3 P4 P5
  70300. ** Synopsis: data=r[P3@P2]
  70301. **
  70302. ** P4 is a pointer to a virtual table object, an sqlite3_vtab structure.
  70303. ** This opcode invokes the corresponding xUpdate method. P2 values
  70304. ** are contiguous memory cells starting at P3 to pass to the xUpdate
  70305. ** invocation. The value in register (P3+P2-1) corresponds to the
  70306. ** p2th element of the argv array passed to xUpdate.
  70307. **
  70308. ** The xUpdate method will do a DELETE or an INSERT or both.
  70309. ** The argv[0] element (which corresponds to memory cell P3)
  70310. ** is the rowid of a row to delete. If argv[0] is NULL then no
  70311. ** deletion occurs. The argv[1] element is the rowid of the new
  70312. ** row. This can be NULL to have the virtual table select the new
  70313. ** rowid for itself. The subsequent elements in the array are
  70314. ** the values of columns in the new row.
  70315. **
  70316. ** If P2==1 then no insert is performed. argv[0] is the rowid of
  70317. ** a row to delete.
  70318. **
  70319. ** P1 is a boolean flag. If it is set to true and the xUpdate call
  70320. ** is successful, then the value returned by sqlite3_last_insert_rowid()
  70321. ** is set to the value of the rowid for the row just inserted.
  70322. **
  70323. ** P5 is the error actions (OE_Replace, OE_Fail, OE_Ignore, etc) to
  70324. ** apply in the case of a constraint failure on an insert or update.
  70325. */
  70326. case OP_VUpdate: {
  70327. sqlite3_vtab *pVtab;
  70328. sqlite3_module *pModule;
  70329. int nArg;
  70330. int i;
  70331. sqlite_int64 rowid;
  70332. Mem **apArg;
  70333. Mem *pX;
  70334. assert( pOp->p2==1 || pOp->p5==OE_Fail || pOp->p5==OE_Rollback
  70335. || pOp->p5==OE_Abort || pOp->p5==OE_Ignore || pOp->p5==OE_Replace
  70336. );
  70337. assert( p->readOnly==0 );
  70338. pVtab = pOp->p4.pVtab->pVtab;
  70339. pModule = (sqlite3_module *)pVtab->pModule;
  70340. nArg = pOp->p2;
  70341. assert( pOp->p4type==P4_VTAB );
  70342. if( ALWAYS(pModule->xUpdate) ){
  70343. u8 vtabOnConflict = db->vtabOnConflict;
  70344. apArg = p->apArg;
  70345. pX = &aMem[pOp->p3];
  70346. for(i=0; i<nArg; i++){
  70347. assert( memIsValid(pX) );
  70348. memAboutToChange(p, pX);
  70349. apArg[i] = pX;
  70350. pX++;
  70351. }
  70352. db->vtabOnConflict = pOp->p5;
  70353. rc = pModule->xUpdate(pVtab, nArg, apArg, &rowid);
  70354. db->vtabOnConflict = vtabOnConflict;
  70355. sqlite3VtabImportErrmsg(p, pVtab);
  70356. if( rc==SQLITE_OK && pOp->p1 ){
  70357. assert( nArg>1 && apArg[0] && (apArg[0]->flags&MEM_Null) );
  70358. db->lastRowid = lastRowid = rowid;
  70359. }
  70360. if( (rc&0xff)==SQLITE_CONSTRAINT && pOp->p4.pVtab->bConstraint ){
  70361. if( pOp->p5==OE_Ignore ){
  70362. rc = SQLITE_OK;
  70363. }else{
  70364. p->errorAction = ((pOp->p5==OE_Replace) ? OE_Abort : pOp->p5);
  70365. }
  70366. }else{
  70367. p->nChange++;
  70368. }
  70369. }
  70370. break;
  70371. }
  70372. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  70373. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  70374. /* Opcode: Pagecount P1 P2 * * *
  70375. **
  70376. ** Write the current number of pages in database P1 to memory cell P2.
  70377. */
  70378. case OP_Pagecount: { /* out2-prerelease */
  70379. pOut->u.i = sqlite3BtreeLastPage(db->aDb[pOp->p1].pBt);
  70380. break;
  70381. }
  70382. #endif
  70383. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  70384. /* Opcode: MaxPgcnt P1 P2 P3 * *
  70385. **
  70386. ** Try to set the maximum page count for database P1 to the value in P3.
  70387. ** Do not let the maximum page count fall below the current page count and
  70388. ** do not change the maximum page count value if P3==0.
  70389. **
  70390. ** Store the maximum page count after the change in register P2.
  70391. */
  70392. case OP_MaxPgcnt: { /* out2-prerelease */
  70393. unsigned int newMax;
  70394. Btree *pBt;
  70395. pBt = db->aDb[pOp->p1].pBt;
  70396. newMax = 0;
  70397. if( pOp->p3 ){
  70398. newMax = sqlite3BtreeLastPage(pBt);
  70399. if( newMax < (unsigned)pOp->p3 ) newMax = (unsigned)pOp->p3;
  70400. }
  70401. pOut->u.i = sqlite3BtreeMaxPageCount(pBt, newMax);
  70402. break;
  70403. }
  70404. #endif
  70405. /* Opcode: Init * P2 * P4 *
  70406. ** Synopsis: Start at P2
  70407. **
  70408. ** Programs contain a single instance of this opcode as the very first
  70409. ** opcode.
  70410. **
  70411. ** If tracing is enabled (by the sqlite3_trace()) interface, then
  70412. ** the UTF-8 string contained in P4 is emitted on the trace callback.
  70413. ** Or if P4 is blank, use the string returned by sqlite3_sql().
  70414. **
  70415. ** If P2 is not zero, jump to instruction P2.
  70416. */
  70417. case OP_Init: { /* jump */
  70418. char *zTrace;
  70419. char *z;
  70420. if( pOp->p2 ){
  70421. pc = pOp->p2 - 1;
  70422. }
  70423. #ifndef SQLITE_OMIT_TRACE
  70424. if( db->xTrace
  70425. && !p->doingRerun
  70426. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  70427. ){
  70428. z = sqlite3VdbeExpandSql(p, zTrace);
  70429. db->xTrace(db->pTraceArg, z);
  70430. sqlite3DbFree(db, z);
  70431. }
  70432. #ifdef SQLITE_USE_FCNTL_TRACE
  70433. zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql);
  70434. if( zTrace ){
  70435. int i;
  70436. for(i=0; i<db->nDb; i++){
  70437. if( DbMaskTest(p->btreeMask, i)==0 ) continue;
  70438. sqlite3_file_control(db, db->aDb[i].zName, SQLITE_FCNTL_TRACE, zTrace);
  70439. }
  70440. }
  70441. #endif /* SQLITE_USE_FCNTL_TRACE */
  70442. #ifdef SQLITE_DEBUG
  70443. if( (db->flags & SQLITE_SqlTrace)!=0
  70444. && (zTrace = (pOp->p4.z ? pOp->p4.z : p->zSql))!=0
  70445. ){
  70446. sqlite3DebugPrintf("SQL-trace: %s\n", zTrace);
  70447. }
  70448. #endif /* SQLITE_DEBUG */
  70449. #endif /* SQLITE_OMIT_TRACE */
  70450. break;
  70451. }
  70452. /* Opcode: Noop * * * * *
  70453. **
  70454. ** Do nothing. This instruction is often useful as a jump
  70455. ** destination.
  70456. */
  70457. /*
  70458. ** The magic Explain opcode are only inserted when explain==2 (which
  70459. ** is to say when the EXPLAIN QUERY PLAN syntax is used.)
  70460. ** This opcode records information from the optimizer. It is the
  70461. ** the same as a no-op. This opcodesnever appears in a real VM program.
  70462. */
  70463. default: { /* This is really OP_Noop and OP_Explain */
  70464. assert( pOp->opcode==OP_Noop || pOp->opcode==OP_Explain );
  70465. break;
  70466. }
  70467. /*****************************************************************************
  70468. ** The cases of the switch statement above this line should all be indented
  70469. ** by 6 spaces. But the left-most 6 spaces have been removed to improve the
  70470. ** readability. From this point on down, the normal indentation rules are
  70471. ** restored.
  70472. *****************************************************************************/
  70473. }
  70474. #ifdef VDBE_PROFILE
  70475. {
  70476. u64 endTime = sqlite3Hwtime();
  70477. if( endTime>start ) pOp->cycles += endTime - start;
  70478. pOp->cnt++;
  70479. }
  70480. #endif
  70481. /* The following code adds nothing to the actual functionality
  70482. ** of the program. It is only here for testing and debugging.
  70483. ** On the other hand, it does burn CPU cycles every time through
  70484. ** the evaluator loop. So we can leave it out when NDEBUG is defined.
  70485. */
  70486. #ifndef NDEBUG
  70487. assert( pc>=-1 && pc<p->nOp );
  70488. #ifdef SQLITE_DEBUG
  70489. if( db->flags & SQLITE_VdbeTrace ){
  70490. if( rc!=0 ) printf("rc=%d\n",rc);
  70491. if( pOp->opflags & (OPFLG_OUT2_PRERELEASE|OPFLG_OUT2) ){
  70492. registerTrace(pOp->p2, &aMem[pOp->p2]);
  70493. }
  70494. if( pOp->opflags & OPFLG_OUT3 ){
  70495. registerTrace(pOp->p3, &aMem[pOp->p3]);
  70496. }
  70497. }
  70498. #endif /* SQLITE_DEBUG */
  70499. #endif /* NDEBUG */
  70500. } /* The end of the for(;;) loop the loops through opcodes */
  70501. /* If we reach this point, it means that execution is finished with
  70502. ** an error of some kind.
  70503. */
  70504. vdbe_error_halt:
  70505. assert( rc );
  70506. p->rc = rc;
  70507. testcase( sqlite3GlobalConfig.xLog!=0 );
  70508. sqlite3_log(rc, "statement aborts at %d: [%s] %s",
  70509. pc, p->zSql, p->zErrMsg);
  70510. sqlite3VdbeHalt(p);
  70511. if( rc==SQLITE_IOERR_NOMEM ) db->mallocFailed = 1;
  70512. rc = SQLITE_ERROR;
  70513. if( resetSchemaOnFault>0 ){
  70514. sqlite3ResetOneSchema(db, resetSchemaOnFault-1);
  70515. }
  70516. /* This is the only way out of this procedure. We have to
  70517. ** release the mutexes on btrees that were acquired at the
  70518. ** top. */
  70519. vdbe_return:
  70520. db->lastRowid = lastRowid;
  70521. testcase( nVmStep>0 );
  70522. p->aCounter[SQLITE_STMTSTATUS_VM_STEP] += (int)nVmStep;
  70523. sqlite3VdbeLeave(p);
  70524. return rc;
  70525. /* Jump to here if a string or blob larger than SQLITE_MAX_LENGTH
  70526. ** is encountered.
  70527. */
  70528. too_big:
  70529. sqlite3SetString(&p->zErrMsg, db, "string or blob too big");
  70530. rc = SQLITE_TOOBIG;
  70531. goto vdbe_error_halt;
  70532. /* Jump to here if a malloc() fails.
  70533. */
  70534. no_mem:
  70535. db->mallocFailed = 1;
  70536. sqlite3SetString(&p->zErrMsg, db, "out of memory");
  70537. rc = SQLITE_NOMEM;
  70538. goto vdbe_error_halt;
  70539. /* Jump to here for any other kind of fatal error. The "rc" variable
  70540. ** should hold the error number.
  70541. */
  70542. abort_due_to_error:
  70543. assert( p->zErrMsg==0 );
  70544. if( db->mallocFailed ) rc = SQLITE_NOMEM;
  70545. if( rc!=SQLITE_IOERR_NOMEM ){
  70546. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  70547. }
  70548. goto vdbe_error_halt;
  70549. /* Jump to here if the sqlite3_interrupt() API sets the interrupt
  70550. ** flag.
  70551. */
  70552. abort_due_to_interrupt:
  70553. assert( db->u1.isInterrupted );
  70554. rc = SQLITE_INTERRUPT;
  70555. p->rc = rc;
  70556. sqlite3SetString(&p->zErrMsg, db, "%s", sqlite3ErrStr(rc));
  70557. goto vdbe_error_halt;
  70558. }
  70559. /************** End of vdbe.c ************************************************/
  70560. /************** Begin file vdbeblob.c ****************************************/
  70561. /*
  70562. ** 2007 May 1
  70563. **
  70564. ** The author disclaims copyright to this source code. In place of
  70565. ** a legal notice, here is a blessing:
  70566. **
  70567. ** May you do good and not evil.
  70568. ** May you find forgiveness for yourself and forgive others.
  70569. ** May you share freely, never taking more than you give.
  70570. **
  70571. *************************************************************************
  70572. **
  70573. ** This file contains code used to implement incremental BLOB I/O.
  70574. */
  70575. #ifndef SQLITE_OMIT_INCRBLOB
  70576. /*
  70577. ** Valid sqlite3_blob* handles point to Incrblob structures.
  70578. */
  70579. typedef struct Incrblob Incrblob;
  70580. struct Incrblob {
  70581. int flags; /* Copy of "flags" passed to sqlite3_blob_open() */
  70582. int nByte; /* Size of open blob, in bytes */
  70583. int iOffset; /* Byte offset of blob in cursor data */
  70584. int iCol; /* Table column this handle is open on */
  70585. BtCursor *pCsr; /* Cursor pointing at blob row */
  70586. sqlite3_stmt *pStmt; /* Statement holding cursor open */
  70587. sqlite3 *db; /* The associated database */
  70588. };
  70589. /*
  70590. ** This function is used by both blob_open() and blob_reopen(). It seeks
  70591. ** the b-tree cursor associated with blob handle p to point to row iRow.
  70592. ** If successful, SQLITE_OK is returned and subsequent calls to
  70593. ** sqlite3_blob_read() or sqlite3_blob_write() access the specified row.
  70594. **
  70595. ** If an error occurs, or if the specified row does not exist or does not
  70596. ** contain a value of type TEXT or BLOB in the column nominated when the
  70597. ** blob handle was opened, then an error code is returned and *pzErr may
  70598. ** be set to point to a buffer containing an error message. It is the
  70599. ** responsibility of the caller to free the error message buffer using
  70600. ** sqlite3DbFree().
  70601. **
  70602. ** If an error does occur, then the b-tree cursor is closed. All subsequent
  70603. ** calls to sqlite3_blob_read(), blob_write() or blob_reopen() will
  70604. ** immediately return SQLITE_ABORT.
  70605. */
  70606. static int blobSeekToRow(Incrblob *p, sqlite3_int64 iRow, char **pzErr){
  70607. int rc; /* Error code */
  70608. char *zErr = 0; /* Error message */
  70609. Vdbe *v = (Vdbe *)p->pStmt;
  70610. /* Set the value of the SQL statements only variable to integer iRow.
  70611. ** This is done directly instead of using sqlite3_bind_int64() to avoid
  70612. ** triggering asserts related to mutexes.
  70613. */
  70614. assert( v->aVar[0].flags&MEM_Int );
  70615. v->aVar[0].u.i = iRow;
  70616. rc = sqlite3_step(p->pStmt);
  70617. if( rc==SQLITE_ROW ){
  70618. VdbeCursor *pC = v->apCsr[0];
  70619. u32 type = pC->aType[p->iCol];
  70620. if( type<12 ){
  70621. zErr = sqlite3MPrintf(p->db, "cannot open value of type %s",
  70622. type==0?"null": type==7?"real": "integer"
  70623. );
  70624. rc = SQLITE_ERROR;
  70625. sqlite3_finalize(p->pStmt);
  70626. p->pStmt = 0;
  70627. }else{
  70628. p->iOffset = pC->aType[p->iCol + pC->nField];
  70629. p->nByte = sqlite3VdbeSerialTypeLen(type);
  70630. p->pCsr = pC->pCursor;
  70631. sqlite3BtreeIncrblobCursor(p->pCsr);
  70632. }
  70633. }
  70634. if( rc==SQLITE_ROW ){
  70635. rc = SQLITE_OK;
  70636. }else if( p->pStmt ){
  70637. rc = sqlite3_finalize(p->pStmt);
  70638. p->pStmt = 0;
  70639. if( rc==SQLITE_OK ){
  70640. zErr = sqlite3MPrintf(p->db, "no such rowid: %lld", iRow);
  70641. rc = SQLITE_ERROR;
  70642. }else{
  70643. zErr = sqlite3MPrintf(p->db, "%s", sqlite3_errmsg(p->db));
  70644. }
  70645. }
  70646. assert( rc!=SQLITE_OK || zErr==0 );
  70647. assert( rc!=SQLITE_ROW && rc!=SQLITE_DONE );
  70648. *pzErr = zErr;
  70649. return rc;
  70650. }
  70651. /*
  70652. ** Open a blob handle.
  70653. */
  70654. SQLITE_API int sqlite3_blob_open(
  70655. sqlite3* db, /* The database connection */
  70656. const char *zDb, /* The attached database containing the blob */
  70657. const char *zTable, /* The table containing the blob */
  70658. const char *zColumn, /* The column containing the blob */
  70659. sqlite_int64 iRow, /* The row containing the glob */
  70660. int flags, /* True -> read/write access, false -> read-only */
  70661. sqlite3_blob **ppBlob /* Handle for accessing the blob returned here */
  70662. ){
  70663. int nAttempt = 0;
  70664. int iCol; /* Index of zColumn in row-record */
  70665. /* This VDBE program seeks a btree cursor to the identified
  70666. ** db/table/row entry. The reason for using a vdbe program instead
  70667. ** of writing code to use the b-tree layer directly is that the
  70668. ** vdbe program will take advantage of the various transaction,
  70669. ** locking and error handling infrastructure built into the vdbe.
  70670. **
  70671. ** After seeking the cursor, the vdbe executes an OP_ResultRow.
  70672. ** Code external to the Vdbe then "borrows" the b-tree cursor and
  70673. ** uses it to implement the blob_read(), blob_write() and
  70674. ** blob_bytes() functions.
  70675. **
  70676. ** The sqlite3_blob_close() function finalizes the vdbe program,
  70677. ** which closes the b-tree cursor and (possibly) commits the
  70678. ** transaction.
  70679. */
  70680. static const int iLn = VDBE_OFFSET_LINENO(4);
  70681. static const VdbeOpList openBlob[] = {
  70682. /* {OP_Transaction, 0, 0, 0}, // 0: Inserted separately */
  70683. {OP_TableLock, 0, 0, 0}, /* 1: Acquire a read or write lock */
  70684. /* One of the following two instructions is replaced by an OP_Noop. */
  70685. {OP_OpenRead, 0, 0, 0}, /* 2: Open cursor 0 for reading */
  70686. {OP_OpenWrite, 0, 0, 0}, /* 3: Open cursor 0 for read/write */
  70687. {OP_Variable, 1, 1, 1}, /* 4: Push the rowid to the stack */
  70688. {OP_NotExists, 0, 10, 1}, /* 5: Seek the cursor */
  70689. {OP_Column, 0, 0, 1}, /* 6 */
  70690. {OP_ResultRow, 1, 0, 0}, /* 7 */
  70691. {OP_Goto, 0, 4, 0}, /* 8 */
  70692. {OP_Close, 0, 0, 0}, /* 9 */
  70693. {OP_Halt, 0, 0, 0}, /* 10 */
  70694. };
  70695. int rc = SQLITE_OK;
  70696. char *zErr = 0;
  70697. Table *pTab;
  70698. Parse *pParse = 0;
  70699. Incrblob *pBlob = 0;
  70700. flags = !!flags; /* flags = (flags ? 1 : 0); */
  70701. *ppBlob = 0;
  70702. sqlite3_mutex_enter(db->mutex);
  70703. pBlob = (Incrblob *)sqlite3DbMallocZero(db, sizeof(Incrblob));
  70704. if( !pBlob ) goto blob_open_out;
  70705. pParse = sqlite3StackAllocRaw(db, sizeof(*pParse));
  70706. if( !pParse ) goto blob_open_out;
  70707. do {
  70708. memset(pParse, 0, sizeof(Parse));
  70709. pParse->db = db;
  70710. sqlite3DbFree(db, zErr);
  70711. zErr = 0;
  70712. sqlite3BtreeEnterAll(db);
  70713. pTab = sqlite3LocateTable(pParse, 0, zTable, zDb);
  70714. if( pTab && IsVirtual(pTab) ){
  70715. pTab = 0;
  70716. sqlite3ErrorMsg(pParse, "cannot open virtual table: %s", zTable);
  70717. }
  70718. if( pTab && !HasRowid(pTab) ){
  70719. pTab = 0;
  70720. sqlite3ErrorMsg(pParse, "cannot open table without rowid: %s", zTable);
  70721. }
  70722. #ifndef SQLITE_OMIT_VIEW
  70723. if( pTab && pTab->pSelect ){
  70724. pTab = 0;
  70725. sqlite3ErrorMsg(pParse, "cannot open view: %s", zTable);
  70726. }
  70727. #endif
  70728. if( !pTab ){
  70729. if( pParse->zErrMsg ){
  70730. sqlite3DbFree(db, zErr);
  70731. zErr = pParse->zErrMsg;
  70732. pParse->zErrMsg = 0;
  70733. }
  70734. rc = SQLITE_ERROR;
  70735. sqlite3BtreeLeaveAll(db);
  70736. goto blob_open_out;
  70737. }
  70738. /* Now search pTab for the exact column. */
  70739. for(iCol=0; iCol<pTab->nCol; iCol++) {
  70740. if( sqlite3StrICmp(pTab->aCol[iCol].zName, zColumn)==0 ){
  70741. break;
  70742. }
  70743. }
  70744. if( iCol==pTab->nCol ){
  70745. sqlite3DbFree(db, zErr);
  70746. zErr = sqlite3MPrintf(db, "no such column: \"%s\"", zColumn);
  70747. rc = SQLITE_ERROR;
  70748. sqlite3BtreeLeaveAll(db);
  70749. goto blob_open_out;
  70750. }
  70751. /* If the value is being opened for writing, check that the
  70752. ** column is not indexed, and that it is not part of a foreign key.
  70753. ** It is against the rules to open a column to which either of these
  70754. ** descriptions applies for writing. */
  70755. if( flags ){
  70756. const char *zFault = 0;
  70757. Index *pIdx;
  70758. #ifndef SQLITE_OMIT_FOREIGN_KEY
  70759. if( db->flags&SQLITE_ForeignKeys ){
  70760. /* Check that the column is not part of an FK child key definition. It
  70761. ** is not necessary to check if it is part of a parent key, as parent
  70762. ** key columns must be indexed. The check below will pick up this
  70763. ** case. */
  70764. FKey *pFKey;
  70765. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  70766. int j;
  70767. for(j=0; j<pFKey->nCol; j++){
  70768. if( pFKey->aCol[j].iFrom==iCol ){
  70769. zFault = "foreign key";
  70770. }
  70771. }
  70772. }
  70773. }
  70774. #endif
  70775. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  70776. int j;
  70777. for(j=0; j<pIdx->nKeyCol; j++){
  70778. if( pIdx->aiColumn[j]==iCol ){
  70779. zFault = "indexed";
  70780. }
  70781. }
  70782. }
  70783. if( zFault ){
  70784. sqlite3DbFree(db, zErr);
  70785. zErr = sqlite3MPrintf(db, "cannot open %s column for writing", zFault);
  70786. rc = SQLITE_ERROR;
  70787. sqlite3BtreeLeaveAll(db);
  70788. goto blob_open_out;
  70789. }
  70790. }
  70791. pBlob->pStmt = (sqlite3_stmt *)sqlite3VdbeCreate(pParse);
  70792. assert( pBlob->pStmt || db->mallocFailed );
  70793. if( pBlob->pStmt ){
  70794. Vdbe *v = (Vdbe *)pBlob->pStmt;
  70795. int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  70796. sqlite3VdbeAddOp4Int(v, OP_Transaction, iDb, flags,
  70797. pTab->pSchema->schema_cookie,
  70798. pTab->pSchema->iGeneration);
  70799. sqlite3VdbeChangeP5(v, 1);
  70800. sqlite3VdbeAddOpList(v, ArraySize(openBlob), openBlob, iLn);
  70801. /* Make sure a mutex is held on the table to be accessed */
  70802. sqlite3VdbeUsesBtree(v, iDb);
  70803. /* Configure the OP_TableLock instruction */
  70804. #ifdef SQLITE_OMIT_SHARED_CACHE
  70805. sqlite3VdbeChangeToNoop(v, 1);
  70806. #else
  70807. sqlite3VdbeChangeP1(v, 1, iDb);
  70808. sqlite3VdbeChangeP2(v, 1, pTab->tnum);
  70809. sqlite3VdbeChangeP3(v, 1, flags);
  70810. sqlite3VdbeChangeP4(v, 1, pTab->zName, P4_TRANSIENT);
  70811. #endif
  70812. /* Remove either the OP_OpenWrite or OpenRead. Set the P2
  70813. ** parameter of the other to pTab->tnum. */
  70814. sqlite3VdbeChangeToNoop(v, 3 - flags);
  70815. sqlite3VdbeChangeP2(v, 2 + flags, pTab->tnum);
  70816. sqlite3VdbeChangeP3(v, 2 + flags, iDb);
  70817. /* Configure the number of columns. Configure the cursor to
  70818. ** think that the table has one more column than it really
  70819. ** does. An OP_Column to retrieve this imaginary column will
  70820. ** always return an SQL NULL. This is useful because it means
  70821. ** we can invoke OP_Column to fill in the vdbe cursors type
  70822. ** and offset cache without causing any IO.
  70823. */
  70824. sqlite3VdbeChangeP4(v, 2+flags, SQLITE_INT_TO_PTR(pTab->nCol+1),P4_INT32);
  70825. sqlite3VdbeChangeP2(v, 6, pTab->nCol);
  70826. if( !db->mallocFailed ){
  70827. pParse->nVar = 1;
  70828. pParse->nMem = 1;
  70829. pParse->nTab = 1;
  70830. sqlite3VdbeMakeReady(v, pParse);
  70831. }
  70832. }
  70833. pBlob->flags = flags;
  70834. pBlob->iCol = iCol;
  70835. pBlob->db = db;
  70836. sqlite3BtreeLeaveAll(db);
  70837. if( db->mallocFailed ){
  70838. goto blob_open_out;
  70839. }
  70840. sqlite3_bind_int64(pBlob->pStmt, 1, iRow);
  70841. rc = blobSeekToRow(pBlob, iRow, &zErr);
  70842. } while( (++nAttempt)<SQLITE_MAX_SCHEMA_RETRY && rc==SQLITE_SCHEMA );
  70843. blob_open_out:
  70844. if( rc==SQLITE_OK && db->mallocFailed==0 ){
  70845. *ppBlob = (sqlite3_blob *)pBlob;
  70846. }else{
  70847. if( pBlob && pBlob->pStmt ) sqlite3VdbeFinalize((Vdbe *)pBlob->pStmt);
  70848. sqlite3DbFree(db, pBlob);
  70849. }
  70850. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  70851. sqlite3DbFree(db, zErr);
  70852. sqlite3ParserReset(pParse);
  70853. sqlite3StackFree(db, pParse);
  70854. rc = sqlite3ApiExit(db, rc);
  70855. sqlite3_mutex_leave(db->mutex);
  70856. return rc;
  70857. }
  70858. /*
  70859. ** Close a blob handle that was previously created using
  70860. ** sqlite3_blob_open().
  70861. */
  70862. SQLITE_API int sqlite3_blob_close(sqlite3_blob *pBlob){
  70863. Incrblob *p = (Incrblob *)pBlob;
  70864. int rc;
  70865. sqlite3 *db;
  70866. if( p ){
  70867. db = p->db;
  70868. sqlite3_mutex_enter(db->mutex);
  70869. rc = sqlite3_finalize(p->pStmt);
  70870. sqlite3DbFree(db, p);
  70871. sqlite3_mutex_leave(db->mutex);
  70872. }else{
  70873. rc = SQLITE_OK;
  70874. }
  70875. return rc;
  70876. }
  70877. /*
  70878. ** Perform a read or write operation on a blob
  70879. */
  70880. static int blobReadWrite(
  70881. sqlite3_blob *pBlob,
  70882. void *z,
  70883. int n,
  70884. int iOffset,
  70885. int (*xCall)(BtCursor*, u32, u32, void*)
  70886. ){
  70887. int rc;
  70888. Incrblob *p = (Incrblob *)pBlob;
  70889. Vdbe *v;
  70890. sqlite3 *db;
  70891. if( p==0 ) return SQLITE_MISUSE_BKPT;
  70892. db = p->db;
  70893. sqlite3_mutex_enter(db->mutex);
  70894. v = (Vdbe*)p->pStmt;
  70895. if( n<0 || iOffset<0 || (iOffset+n)>p->nByte ){
  70896. /* Request is out of range. Return a transient error. */
  70897. rc = SQLITE_ERROR;
  70898. sqlite3Error(db, SQLITE_ERROR);
  70899. }else if( v==0 ){
  70900. /* If there is no statement handle, then the blob-handle has
  70901. ** already been invalidated. Return SQLITE_ABORT in this case.
  70902. */
  70903. rc = SQLITE_ABORT;
  70904. }else{
  70905. /* Call either BtreeData() or BtreePutData(). If SQLITE_ABORT is
  70906. ** returned, clean-up the statement handle.
  70907. */
  70908. assert( db == v->db );
  70909. sqlite3BtreeEnterCursor(p->pCsr);
  70910. rc = xCall(p->pCsr, iOffset+p->iOffset, n, z);
  70911. sqlite3BtreeLeaveCursor(p->pCsr);
  70912. if( rc==SQLITE_ABORT ){
  70913. sqlite3VdbeFinalize(v);
  70914. p->pStmt = 0;
  70915. }else{
  70916. db->errCode = rc;
  70917. v->rc = rc;
  70918. }
  70919. }
  70920. rc = sqlite3ApiExit(db, rc);
  70921. sqlite3_mutex_leave(db->mutex);
  70922. return rc;
  70923. }
  70924. /*
  70925. ** Read data from a blob handle.
  70926. */
  70927. SQLITE_API int sqlite3_blob_read(sqlite3_blob *pBlob, void *z, int n, int iOffset){
  70928. return blobReadWrite(pBlob, z, n, iOffset, sqlite3BtreeData);
  70929. }
  70930. /*
  70931. ** Write data to a blob handle.
  70932. */
  70933. SQLITE_API int sqlite3_blob_write(sqlite3_blob *pBlob, const void *z, int n, int iOffset){
  70934. return blobReadWrite(pBlob, (void *)z, n, iOffset, sqlite3BtreePutData);
  70935. }
  70936. /*
  70937. ** Query a blob handle for the size of the data.
  70938. **
  70939. ** The Incrblob.nByte field is fixed for the lifetime of the Incrblob
  70940. ** so no mutex is required for access.
  70941. */
  70942. SQLITE_API int sqlite3_blob_bytes(sqlite3_blob *pBlob){
  70943. Incrblob *p = (Incrblob *)pBlob;
  70944. return (p && p->pStmt) ? p->nByte : 0;
  70945. }
  70946. /*
  70947. ** Move an existing blob handle to point to a different row of the same
  70948. ** database table.
  70949. **
  70950. ** If an error occurs, or if the specified row does not exist or does not
  70951. ** contain a blob or text value, then an error code is returned and the
  70952. ** database handle error code and message set. If this happens, then all
  70953. ** subsequent calls to sqlite3_blob_xxx() functions (except blob_close())
  70954. ** immediately return SQLITE_ABORT.
  70955. */
  70956. SQLITE_API int sqlite3_blob_reopen(sqlite3_blob *pBlob, sqlite3_int64 iRow){
  70957. int rc;
  70958. Incrblob *p = (Incrblob *)pBlob;
  70959. sqlite3 *db;
  70960. if( p==0 ) return SQLITE_MISUSE_BKPT;
  70961. db = p->db;
  70962. sqlite3_mutex_enter(db->mutex);
  70963. if( p->pStmt==0 ){
  70964. /* If there is no statement handle, then the blob-handle has
  70965. ** already been invalidated. Return SQLITE_ABORT in this case.
  70966. */
  70967. rc = SQLITE_ABORT;
  70968. }else{
  70969. char *zErr;
  70970. rc = blobSeekToRow(p, iRow, &zErr);
  70971. if( rc!=SQLITE_OK ){
  70972. sqlite3ErrorWithMsg(db, rc, (zErr ? "%s" : 0), zErr);
  70973. sqlite3DbFree(db, zErr);
  70974. }
  70975. assert( rc!=SQLITE_SCHEMA );
  70976. }
  70977. rc = sqlite3ApiExit(db, rc);
  70978. assert( rc==SQLITE_OK || p->pStmt==0 );
  70979. sqlite3_mutex_leave(db->mutex);
  70980. return rc;
  70981. }
  70982. #endif /* #ifndef SQLITE_OMIT_INCRBLOB */
  70983. /************** End of vdbeblob.c ********************************************/
  70984. /************** Begin file vdbesort.c ****************************************/
  70985. /*
  70986. ** 2011-07-09
  70987. **
  70988. ** The author disclaims copyright to this source code. In place of
  70989. ** a legal notice, here is a blessing:
  70990. **
  70991. ** May you do good and not evil.
  70992. ** May you find forgiveness for yourself and forgive others.
  70993. ** May you share freely, never taking more than you give.
  70994. **
  70995. *************************************************************************
  70996. ** This file contains code for the VdbeSorter object, used in concert with
  70997. ** a VdbeCursor to sort large numbers of keys for CREATE INDEX statements
  70998. ** or by SELECT statements with ORDER BY clauses that cannot be satisfied
  70999. ** using indexes and without LIMIT clauses.
  71000. **
  71001. ** The VdbeSorter object implements a multi-threaded external merge sort
  71002. ** algorithm that is efficient even if the number of elements being sorted
  71003. ** exceeds the available memory.
  71004. **
  71005. ** Here is the (internal, non-API) interface between this module and the
  71006. ** rest of the SQLite system:
  71007. **
  71008. ** sqlite3VdbeSorterInit() Create a new VdbeSorter object.
  71009. **
  71010. ** sqlite3VdbeSorterWrite() Add a single new row to the VdbeSorter
  71011. ** object. The row is a binary blob in the
  71012. ** OP_MakeRecord format that contains both
  71013. ** the ORDER BY key columns and result columns
  71014. ** in the case of a SELECT w/ ORDER BY, or
  71015. ** the complete record for an index entry
  71016. ** in the case of a CREATE INDEX.
  71017. **
  71018. ** sqlite3VdbeSorterRewind() Sort all content previously added.
  71019. ** Position the read cursor on the
  71020. ** first sorted element.
  71021. **
  71022. ** sqlite3VdbeSorterNext() Advance the read cursor to the next sorted
  71023. ** element.
  71024. **
  71025. ** sqlite3VdbeSorterRowkey() Return the complete binary blob for the
  71026. ** row currently under the read cursor.
  71027. **
  71028. ** sqlite3VdbeSorterCompare() Compare the binary blob for the row
  71029. ** currently under the read cursor against
  71030. ** another binary blob X and report if
  71031. ** X is strictly less than the read cursor.
  71032. ** Used to enforce uniqueness in a
  71033. ** CREATE UNIQUE INDEX statement.
  71034. **
  71035. ** sqlite3VdbeSorterClose() Close the VdbeSorter object and reclaim
  71036. ** all resources.
  71037. **
  71038. ** sqlite3VdbeSorterReset() Refurbish the VdbeSorter for reuse. This
  71039. ** is like Close() followed by Init() only
  71040. ** much faster.
  71041. **
  71042. ** The interfaces above must be called in a particular order. Write() can
  71043. ** only occur in between Init()/Reset() and Rewind(). Next(), Rowkey(), and
  71044. ** Compare() can only occur in between Rewind() and Close()/Reset(). i.e.
  71045. **
  71046. ** Init()
  71047. ** for each record: Write()
  71048. ** Rewind()
  71049. ** Rowkey()/Compare()
  71050. ** Next()
  71051. ** Close()
  71052. **
  71053. ** Algorithm:
  71054. **
  71055. ** Records passed to the sorter via calls to Write() are initially held
  71056. ** unsorted in main memory. Assuming the amount of memory used never exceeds
  71057. ** a threshold, when Rewind() is called the set of records is sorted using
  71058. ** an in-memory merge sort. In this case, no temporary files are required
  71059. ** and subsequent calls to Rowkey(), Next() and Compare() read records
  71060. ** directly from main memory.
  71061. **
  71062. ** If the amount of space used to store records in main memory exceeds the
  71063. ** threshold, then the set of records currently in memory are sorted and
  71064. ** written to a temporary file in "Packed Memory Array" (PMA) format.
  71065. ** A PMA created at this point is known as a "level-0 PMA". Higher levels
  71066. ** of PMAs may be created by merging existing PMAs together - for example
  71067. ** merging two or more level-0 PMAs together creates a level-1 PMA.
  71068. **
  71069. ** The threshold for the amount of main memory to use before flushing
  71070. ** records to a PMA is roughly the same as the limit configured for the
  71071. ** page-cache of the main database. Specifically, the threshold is set to
  71072. ** the value returned by "PRAGMA main.page_size" multipled by
  71073. ** that returned by "PRAGMA main.cache_size", in bytes.
  71074. **
  71075. ** If the sorter is running in single-threaded mode, then all PMAs generated
  71076. ** are appended to a single temporary file. Or, if the sorter is running in
  71077. ** multi-threaded mode then up to (N+1) temporary files may be opened, where
  71078. ** N is the configured number of worker threads. In this case, instead of
  71079. ** sorting the records and writing the PMA to a temporary file itself, the
  71080. ** calling thread usually launches a worker thread to do so. Except, if
  71081. ** there are already N worker threads running, the main thread does the work
  71082. ** itself.
  71083. **
  71084. ** The sorter is running in multi-threaded mode if (a) the library was built
  71085. ** with pre-processor symbol SQLITE_MAX_WORKER_THREADS set to a value greater
  71086. ** than zero, and (b) worker threads have been enabled at runtime by calling
  71087. ** sqlite3_config(SQLITE_CONFIG_WORKER_THREADS, ...).
  71088. **
  71089. ** When Rewind() is called, any data remaining in memory is flushed to a
  71090. ** final PMA. So at this point the data is stored in some number of sorted
  71091. ** PMAs within temporary files on disk.
  71092. **
  71093. ** If there are fewer than SORTER_MAX_MERGE_COUNT PMAs in total and the
  71094. ** sorter is running in single-threaded mode, then these PMAs are merged
  71095. ** incrementally as keys are retreived from the sorter by the VDBE. The
  71096. ** MergeEngine object, described in further detail below, performs this
  71097. ** merge.
  71098. **
  71099. ** Or, if running in multi-threaded mode, then a background thread is
  71100. ** launched to merge the existing PMAs. Once the background thread has
  71101. ** merged T bytes of data into a single sorted PMA, the main thread
  71102. ** begins reading keys from that PMA while the background thread proceeds
  71103. ** with merging the next T bytes of data. And so on.
  71104. **
  71105. ** Parameter T is set to half the value of the memory threshold used
  71106. ** by Write() above to determine when to create a new PMA.
  71107. **
  71108. ** If there are more than SORTER_MAX_MERGE_COUNT PMAs in total when
  71109. ** Rewind() is called, then a hierarchy of incremental-merges is used.
  71110. ** First, T bytes of data from the first SORTER_MAX_MERGE_COUNT PMAs on
  71111. ** disk are merged together. Then T bytes of data from the second set, and
  71112. ** so on, such that no operation ever merges more than SORTER_MAX_MERGE_COUNT
  71113. ** PMAs at a time. This done is to improve locality.
  71114. **
  71115. ** If running in multi-threaded mode and there are more than
  71116. ** SORTER_MAX_MERGE_COUNT PMAs on disk when Rewind() is called, then more
  71117. ** than one background thread may be created. Specifically, there may be
  71118. ** one background thread for each temporary file on disk, and one background
  71119. ** thread to merge the output of each of the others to a single PMA for
  71120. ** the main thread to read from.
  71121. */
  71122. /*
  71123. ** If SQLITE_DEBUG_SORTER_THREADS is defined, this module outputs various
  71124. ** messages to stderr that may be helpful in understanding the performance
  71125. ** characteristics of the sorter in multi-threaded mode.
  71126. */
  71127. #if 0
  71128. # define SQLITE_DEBUG_SORTER_THREADS 1
  71129. #endif
  71130. /*
  71131. ** Private objects used by the sorter
  71132. */
  71133. typedef struct MergeEngine MergeEngine; /* Merge PMAs together */
  71134. typedef struct PmaReader PmaReader; /* Incrementally read one PMA */
  71135. typedef struct PmaWriter PmaWriter; /* Incrementally write one PMA */
  71136. typedef struct SorterRecord SorterRecord; /* A record being sorted */
  71137. typedef struct SortSubtask SortSubtask; /* A sub-task in the sort process */
  71138. typedef struct SorterFile SorterFile; /* Temporary file object wrapper */
  71139. typedef struct SorterList SorterList; /* In-memory list of records */
  71140. typedef struct IncrMerger IncrMerger; /* Read & merge multiple PMAs */
  71141. /*
  71142. ** A container for a temp file handle and the current amount of data
  71143. ** stored in the file.
  71144. */
  71145. struct SorterFile {
  71146. sqlite3_file *pFd; /* File handle */
  71147. i64 iEof; /* Bytes of data stored in pFd */
  71148. };
  71149. /*
  71150. ** An in-memory list of objects to be sorted.
  71151. **
  71152. ** If aMemory==0 then each object is allocated separately and the objects
  71153. ** are connected using SorterRecord.u.pNext. If aMemory!=0 then all objects
  71154. ** are stored in the aMemory[] bulk memory, one right after the other, and
  71155. ** are connected using SorterRecord.u.iNext.
  71156. */
  71157. struct SorterList {
  71158. SorterRecord *pList; /* Linked list of records */
  71159. u8 *aMemory; /* If non-NULL, bulk memory to hold pList */
  71160. int szPMA; /* Size of pList as PMA in bytes */
  71161. };
  71162. /*
  71163. ** The MergeEngine object is used to combine two or more smaller PMAs into
  71164. ** one big PMA using a merge operation. Separate PMAs all need to be
  71165. ** combined into one big PMA in order to be able to step through the sorted
  71166. ** records in order.
  71167. **
  71168. ** The aReadr[] array contains a PmaReader object for each of the PMAs being
  71169. ** merged. An aReadr[] object either points to a valid key or else is at EOF.
  71170. ** ("EOF" means "End Of File". When aReadr[] is at EOF there is no more data.)
  71171. ** For the purposes of the paragraphs below, we assume that the array is
  71172. ** actually N elements in size, where N is the smallest power of 2 greater
  71173. ** to or equal to the number of PMAs being merged. The extra aReadr[] elements
  71174. ** are treated as if they are empty (always at EOF).
  71175. **
  71176. ** The aTree[] array is also N elements in size. The value of N is stored in
  71177. ** the MergeEngine.nTree variable.
  71178. **
  71179. ** The final (N/2) elements of aTree[] contain the results of comparing
  71180. ** pairs of PMA keys together. Element i contains the result of
  71181. ** comparing aReadr[2*i-N] and aReadr[2*i-N+1]. Whichever key is smaller, the
  71182. ** aTree element is set to the index of it.
  71183. **
  71184. ** For the purposes of this comparison, EOF is considered greater than any
  71185. ** other key value. If the keys are equal (only possible with two EOF
  71186. ** values), it doesn't matter which index is stored.
  71187. **
  71188. ** The (N/4) elements of aTree[] that precede the final (N/2) described
  71189. ** above contains the index of the smallest of each block of 4 PmaReaders
  71190. ** And so on. So that aTree[1] contains the index of the PmaReader that
  71191. ** currently points to the smallest key value. aTree[0] is unused.
  71192. **
  71193. ** Example:
  71194. **
  71195. ** aReadr[0] -> Banana
  71196. ** aReadr[1] -> Feijoa
  71197. ** aReadr[2] -> Elderberry
  71198. ** aReadr[3] -> Currant
  71199. ** aReadr[4] -> Grapefruit
  71200. ** aReadr[5] -> Apple
  71201. ** aReadr[6] -> Durian
  71202. ** aReadr[7] -> EOF
  71203. **
  71204. ** aTree[] = { X, 5 0, 5 0, 3, 5, 6 }
  71205. **
  71206. ** The current element is "Apple" (the value of the key indicated by
  71207. ** PmaReader 5). When the Next() operation is invoked, PmaReader 5 will
  71208. ** be advanced to the next key in its segment. Say the next key is
  71209. ** "Eggplant":
  71210. **
  71211. ** aReadr[5] -> Eggplant
  71212. **
  71213. ** The contents of aTree[] are updated first by comparing the new PmaReader
  71214. ** 5 key to the current key of PmaReader 4 (still "Grapefruit"). The PmaReader
  71215. ** 5 value is still smaller, so aTree[6] is set to 5. And so on up the tree.
  71216. ** The value of PmaReader 6 - "Durian" - is now smaller than that of PmaReader
  71217. ** 5, so aTree[3] is set to 6. Key 0 is smaller than key 6 (Banana<Durian),
  71218. ** so the value written into element 1 of the array is 0. As follows:
  71219. **
  71220. ** aTree[] = { X, 0 0, 6 0, 3, 5, 6 }
  71221. **
  71222. ** In other words, each time we advance to the next sorter element, log2(N)
  71223. ** key comparison operations are required, where N is the number of segments
  71224. ** being merged (rounded up to the next power of 2).
  71225. */
  71226. struct MergeEngine {
  71227. int nTree; /* Used size of aTree/aReadr (power of 2) */
  71228. SortSubtask *pTask; /* Used by this thread only */
  71229. int *aTree; /* Current state of incremental merge */
  71230. PmaReader *aReadr; /* Array of PmaReaders to merge data from */
  71231. };
  71232. /*
  71233. ** This object represents a single thread of control in a sort operation.
  71234. ** Exactly VdbeSorter.nTask instances of this object are allocated
  71235. ** as part of each VdbeSorter object. Instances are never allocated any
  71236. ** other way. VdbeSorter.nTask is set to the number of worker threads allowed
  71237. ** (see SQLITE_CONFIG_WORKER_THREADS) plus one (the main thread). Thus for
  71238. ** single-threaded operation, there is exactly one instance of this object
  71239. ** and for multi-threaded operation there are two or more instances.
  71240. **
  71241. ** Essentially, this structure contains all those fields of the VdbeSorter
  71242. ** structure for which each thread requires a separate instance. For example,
  71243. ** each thread requries its own UnpackedRecord object to unpack records in
  71244. ** as part of comparison operations.
  71245. **
  71246. ** Before a background thread is launched, variable bDone is set to 0. Then,
  71247. ** right before it exits, the thread itself sets bDone to 1. This is used for
  71248. ** two purposes:
  71249. **
  71250. ** 1. When flushing the contents of memory to a level-0 PMA on disk, to
  71251. ** attempt to select a SortSubtask for which there is not already an
  71252. ** active background thread (since doing so causes the main thread
  71253. ** to block until it finishes).
  71254. **
  71255. ** 2. If SQLITE_DEBUG_SORTER_THREADS is defined, to determine if a call
  71256. ** to sqlite3ThreadJoin() is likely to block. Cases that are likely to
  71257. ** block provoke debugging output.
  71258. **
  71259. ** In both cases, the effects of the main thread seeing (bDone==0) even
  71260. ** after the thread has finished are not dire. So we don't worry about
  71261. ** memory barriers and such here.
  71262. */
  71263. struct SortSubtask {
  71264. SQLiteThread *pThread; /* Background thread, if any */
  71265. int bDone; /* Set if thread is finished but not joined */
  71266. VdbeSorter *pSorter; /* Sorter that owns this sub-task */
  71267. UnpackedRecord *pUnpacked; /* Space to unpack a record */
  71268. SorterList list; /* List for thread to write to a PMA */
  71269. int nPMA; /* Number of PMAs currently in file */
  71270. SorterFile file; /* Temp file for level-0 PMAs */
  71271. SorterFile file2; /* Space for other PMAs */
  71272. };
  71273. /*
  71274. ** Main sorter structure. A single instance of this is allocated for each
  71275. ** sorter cursor created by the VDBE.
  71276. **
  71277. ** mxKeysize:
  71278. ** As records are added to the sorter by calls to sqlite3VdbeSorterWrite(),
  71279. ** this variable is updated so as to be set to the size on disk of the
  71280. ** largest record in the sorter.
  71281. */
  71282. struct VdbeSorter {
  71283. int mnPmaSize; /* Minimum PMA size, in bytes */
  71284. int mxPmaSize; /* Maximum PMA size, in bytes. 0==no limit */
  71285. int mxKeysize; /* Largest serialized key seen so far */
  71286. int pgsz; /* Main database page size */
  71287. PmaReader *pReader; /* Readr data from here after Rewind() */
  71288. MergeEngine *pMerger; /* Or here, if bUseThreads==0 */
  71289. sqlite3 *db; /* Database connection */
  71290. KeyInfo *pKeyInfo; /* How to compare records */
  71291. UnpackedRecord *pUnpacked; /* Used by VdbeSorterCompare() */
  71292. SorterList list; /* List of in-memory records */
  71293. int iMemory; /* Offset of free space in list.aMemory */
  71294. int nMemory; /* Size of list.aMemory allocation in bytes */
  71295. u8 bUsePMA; /* True if one or more PMAs created */
  71296. u8 bUseThreads; /* True to use background threads */
  71297. u8 iPrev; /* Previous thread used to flush PMA */
  71298. u8 nTask; /* Size of aTask[] array */
  71299. SortSubtask aTask[1]; /* One or more subtasks */
  71300. };
  71301. /*
  71302. ** An instance of the following object is used to read records out of a
  71303. ** PMA, in sorted order. The next key to be read is cached in nKey/aKey.
  71304. ** aKey might point into aMap or into aBuffer. If neither of those locations
  71305. ** contain a contiguous representation of the key, then aAlloc is allocated
  71306. ** and the key is copied into aAlloc and aKey is made to poitn to aAlloc.
  71307. **
  71308. ** pFd==0 at EOF.
  71309. */
  71310. struct PmaReader {
  71311. i64 iReadOff; /* Current read offset */
  71312. i64 iEof; /* 1 byte past EOF for this PmaReader */
  71313. int nAlloc; /* Bytes of space at aAlloc */
  71314. int nKey; /* Number of bytes in key */
  71315. sqlite3_file *pFd; /* File handle we are reading from */
  71316. u8 *aAlloc; /* Space for aKey if aBuffer and pMap wont work */
  71317. u8 *aKey; /* Pointer to current key */
  71318. u8 *aBuffer; /* Current read buffer */
  71319. int nBuffer; /* Size of read buffer in bytes */
  71320. u8 *aMap; /* Pointer to mapping of entire file */
  71321. IncrMerger *pIncr; /* Incremental merger */
  71322. };
  71323. /*
  71324. ** Normally, a PmaReader object iterates through an existing PMA stored
  71325. ** within a temp file. However, if the PmaReader.pIncr variable points to
  71326. ** an object of the following type, it may be used to iterate/merge through
  71327. ** multiple PMAs simultaneously.
  71328. **
  71329. ** There are two types of IncrMerger object - single (bUseThread==0) and
  71330. ** multi-threaded (bUseThread==1).
  71331. **
  71332. ** A multi-threaded IncrMerger object uses two temporary files - aFile[0]
  71333. ** and aFile[1]. Neither file is allowed to grow to more than mxSz bytes in
  71334. ** size. When the IncrMerger is initialized, it reads enough data from
  71335. ** pMerger to populate aFile[0]. It then sets variables within the
  71336. ** corresponding PmaReader object to read from that file and kicks off
  71337. ** a background thread to populate aFile[1] with the next mxSz bytes of
  71338. ** sorted record data from pMerger.
  71339. **
  71340. ** When the PmaReader reaches the end of aFile[0], it blocks until the
  71341. ** background thread has finished populating aFile[1]. It then exchanges
  71342. ** the contents of the aFile[0] and aFile[1] variables within this structure,
  71343. ** sets the PmaReader fields to read from the new aFile[0] and kicks off
  71344. ** another background thread to populate the new aFile[1]. And so on, until
  71345. ** the contents of pMerger are exhausted.
  71346. **
  71347. ** A single-threaded IncrMerger does not open any temporary files of its
  71348. ** own. Instead, it has exclusive access to mxSz bytes of space beginning
  71349. ** at offset iStartOff of file pTask->file2. And instead of using a
  71350. ** background thread to prepare data for the PmaReader, with a single
  71351. ** threaded IncrMerger the allocate part of pTask->file2 is "refilled" with
  71352. ** keys from pMerger by the calling thread whenever the PmaReader runs out
  71353. ** of data.
  71354. */
  71355. struct IncrMerger {
  71356. SortSubtask *pTask; /* Task that owns this merger */
  71357. MergeEngine *pMerger; /* Merge engine thread reads data from */
  71358. i64 iStartOff; /* Offset to start writing file at */
  71359. int mxSz; /* Maximum bytes of data to store */
  71360. int bEof; /* Set to true when merge is finished */
  71361. int bUseThread; /* True to use a bg thread for this object */
  71362. SorterFile aFile[2]; /* aFile[0] for reading, [1] for writing */
  71363. };
  71364. /*
  71365. ** An instance of this object is used for writing a PMA.
  71366. **
  71367. ** The PMA is written one record at a time. Each record is of an arbitrary
  71368. ** size. But I/O is more efficient if it occurs in page-sized blocks where
  71369. ** each block is aligned on a page boundary. This object caches writes to
  71370. ** the PMA so that aligned, page-size blocks are written.
  71371. */
  71372. struct PmaWriter {
  71373. int eFWErr; /* Non-zero if in an error state */
  71374. u8 *aBuffer; /* Pointer to write buffer */
  71375. int nBuffer; /* Size of write buffer in bytes */
  71376. int iBufStart; /* First byte of buffer to write */
  71377. int iBufEnd; /* Last byte of buffer to write */
  71378. i64 iWriteOff; /* Offset of start of buffer in file */
  71379. sqlite3_file *pFd; /* File handle to write to */
  71380. };
  71381. /*
  71382. ** This object is the header on a single record while that record is being
  71383. ** held in memory and prior to being written out as part of a PMA.
  71384. **
  71385. ** How the linked list is connected depends on how memory is being managed
  71386. ** by this module. If using a separate allocation for each in-memory record
  71387. ** (VdbeSorter.list.aMemory==0), then the list is always connected using the
  71388. ** SorterRecord.u.pNext pointers.
  71389. **
  71390. ** Or, if using the single large allocation method (VdbeSorter.list.aMemory!=0),
  71391. ** then while records are being accumulated the list is linked using the
  71392. ** SorterRecord.u.iNext offset. This is because the aMemory[] array may
  71393. ** be sqlite3Realloc()ed while records are being accumulated. Once the VM
  71394. ** has finished passing records to the sorter, or when the in-memory buffer
  71395. ** is full, the list is sorted. As part of the sorting process, it is
  71396. ** converted to use the SorterRecord.u.pNext pointers. See function
  71397. ** vdbeSorterSort() for details.
  71398. */
  71399. struct SorterRecord {
  71400. int nVal; /* Size of the record in bytes */
  71401. union {
  71402. SorterRecord *pNext; /* Pointer to next record in list */
  71403. int iNext; /* Offset within aMemory of next record */
  71404. } u;
  71405. /* The data for the record immediately follows this header */
  71406. };
  71407. /* Return a pointer to the buffer containing the record data for SorterRecord
  71408. ** object p. Should be used as if:
  71409. **
  71410. ** void *SRVAL(SorterRecord *p) { return (void*)&p[1]; }
  71411. */
  71412. #define SRVAL(p) ((void*)((SorterRecord*)(p) + 1))
  71413. /* The minimum PMA size is set to this value multiplied by the database
  71414. ** page size in bytes. */
  71415. #define SORTER_MIN_WORKING 10
  71416. /* Maximum number of PMAs that a single MergeEngine can merge */
  71417. #define SORTER_MAX_MERGE_COUNT 16
  71418. static int vdbeIncrSwap(IncrMerger*);
  71419. static void vdbeIncrFree(IncrMerger *);
  71420. /*
  71421. ** Free all memory belonging to the PmaReader object passed as the
  71422. ** argument. All structure fields are set to zero before returning.
  71423. */
  71424. static void vdbePmaReaderClear(PmaReader *pReadr){
  71425. sqlite3_free(pReadr->aAlloc);
  71426. sqlite3_free(pReadr->aBuffer);
  71427. if( pReadr->aMap ) sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  71428. vdbeIncrFree(pReadr->pIncr);
  71429. memset(pReadr, 0, sizeof(PmaReader));
  71430. }
  71431. /*
  71432. ** Read the next nByte bytes of data from the PMA p.
  71433. ** If successful, set *ppOut to point to a buffer containing the data
  71434. ** and return SQLITE_OK. Otherwise, if an error occurs, return an SQLite
  71435. ** error code.
  71436. **
  71437. ** The buffer returned in *ppOut is only valid until the
  71438. ** next call to this function.
  71439. */
  71440. static int vdbePmaReadBlob(
  71441. PmaReader *p, /* PmaReader from which to take the blob */
  71442. int nByte, /* Bytes of data to read */
  71443. u8 **ppOut /* OUT: Pointer to buffer containing data */
  71444. ){
  71445. int iBuf; /* Offset within buffer to read from */
  71446. int nAvail; /* Bytes of data available in buffer */
  71447. if( p->aMap ){
  71448. *ppOut = &p->aMap[p->iReadOff];
  71449. p->iReadOff += nByte;
  71450. return SQLITE_OK;
  71451. }
  71452. assert( p->aBuffer );
  71453. /* If there is no more data to be read from the buffer, read the next
  71454. ** p->nBuffer bytes of data from the file into it. Or, if there are less
  71455. ** than p->nBuffer bytes remaining in the PMA, read all remaining data. */
  71456. iBuf = p->iReadOff % p->nBuffer;
  71457. if( iBuf==0 ){
  71458. int nRead; /* Bytes to read from disk */
  71459. int rc; /* sqlite3OsRead() return code */
  71460. /* Determine how many bytes of data to read. */
  71461. if( (p->iEof - p->iReadOff) > (i64)p->nBuffer ){
  71462. nRead = p->nBuffer;
  71463. }else{
  71464. nRead = (int)(p->iEof - p->iReadOff);
  71465. }
  71466. assert( nRead>0 );
  71467. /* Readr data from the file. Return early if an error occurs. */
  71468. rc = sqlite3OsRead(p->pFd, p->aBuffer, nRead, p->iReadOff);
  71469. assert( rc!=SQLITE_IOERR_SHORT_READ );
  71470. if( rc!=SQLITE_OK ) return rc;
  71471. }
  71472. nAvail = p->nBuffer - iBuf;
  71473. if( nByte<=nAvail ){
  71474. /* The requested data is available in the in-memory buffer. In this
  71475. ** case there is no need to make a copy of the data, just return a
  71476. ** pointer into the buffer to the caller. */
  71477. *ppOut = &p->aBuffer[iBuf];
  71478. p->iReadOff += nByte;
  71479. }else{
  71480. /* The requested data is not all available in the in-memory buffer.
  71481. ** In this case, allocate space at p->aAlloc[] to copy the requested
  71482. ** range into. Then return a copy of pointer p->aAlloc to the caller. */
  71483. int nRem; /* Bytes remaining to copy */
  71484. /* Extend the p->aAlloc[] allocation if required. */
  71485. if( p->nAlloc<nByte ){
  71486. u8 *aNew;
  71487. int nNew = MAX(128, p->nAlloc*2);
  71488. while( nByte>nNew ) nNew = nNew*2;
  71489. aNew = sqlite3Realloc(p->aAlloc, nNew);
  71490. if( !aNew ) return SQLITE_NOMEM;
  71491. p->nAlloc = nNew;
  71492. p->aAlloc = aNew;
  71493. }
  71494. /* Copy as much data as is available in the buffer into the start of
  71495. ** p->aAlloc[]. */
  71496. memcpy(p->aAlloc, &p->aBuffer[iBuf], nAvail);
  71497. p->iReadOff += nAvail;
  71498. nRem = nByte - nAvail;
  71499. /* The following loop copies up to p->nBuffer bytes per iteration into
  71500. ** the p->aAlloc[] buffer. */
  71501. while( nRem>0 ){
  71502. int rc; /* vdbePmaReadBlob() return code */
  71503. int nCopy; /* Number of bytes to copy */
  71504. u8 *aNext; /* Pointer to buffer to copy data from */
  71505. nCopy = nRem;
  71506. if( nRem>p->nBuffer ) nCopy = p->nBuffer;
  71507. rc = vdbePmaReadBlob(p, nCopy, &aNext);
  71508. if( rc!=SQLITE_OK ) return rc;
  71509. assert( aNext!=p->aAlloc );
  71510. memcpy(&p->aAlloc[nByte - nRem], aNext, nCopy);
  71511. nRem -= nCopy;
  71512. }
  71513. *ppOut = p->aAlloc;
  71514. }
  71515. return SQLITE_OK;
  71516. }
  71517. /*
  71518. ** Read a varint from the stream of data accessed by p. Set *pnOut to
  71519. ** the value read.
  71520. */
  71521. static int vdbePmaReadVarint(PmaReader *p, u64 *pnOut){
  71522. int iBuf;
  71523. if( p->aMap ){
  71524. p->iReadOff += sqlite3GetVarint(&p->aMap[p->iReadOff], pnOut);
  71525. }else{
  71526. iBuf = p->iReadOff % p->nBuffer;
  71527. if( iBuf && (p->nBuffer-iBuf)>=9 ){
  71528. p->iReadOff += sqlite3GetVarint(&p->aBuffer[iBuf], pnOut);
  71529. }else{
  71530. u8 aVarint[16], *a;
  71531. int i = 0, rc;
  71532. do{
  71533. rc = vdbePmaReadBlob(p, 1, &a);
  71534. if( rc ) return rc;
  71535. aVarint[(i++)&0xf] = a[0];
  71536. }while( (a[0]&0x80)!=0 );
  71537. sqlite3GetVarint(aVarint, pnOut);
  71538. }
  71539. }
  71540. return SQLITE_OK;
  71541. }
  71542. /*
  71543. ** Attempt to memory map file pFile. If successful, set *pp to point to the
  71544. ** new mapping and return SQLITE_OK. If the mapping is not attempted
  71545. ** (because the file is too large or the VFS layer is configured not to use
  71546. ** mmap), return SQLITE_OK and set *pp to NULL.
  71547. **
  71548. ** Or, if an error occurs, return an SQLite error code. The final value of
  71549. ** *pp is undefined in this case.
  71550. */
  71551. static int vdbeSorterMapFile(SortSubtask *pTask, SorterFile *pFile, u8 **pp){
  71552. int rc = SQLITE_OK;
  71553. if( pFile->iEof<=(i64)(pTask->pSorter->db->nMaxSorterMmap) ){
  71554. sqlite3_file *pFd = pFile->pFd;
  71555. if( pFd->pMethods->iVersion>=3 ){
  71556. rc = sqlite3OsFetch(pFd, 0, (int)pFile->iEof, (void**)pp);
  71557. testcase( rc!=SQLITE_OK );
  71558. }
  71559. }
  71560. return rc;
  71561. }
  71562. /*
  71563. ** Attach PmaReader pReadr to file pFile (if it is not already attached to
  71564. ** that file) and seek it to offset iOff within the file. Return SQLITE_OK
  71565. ** if successful, or an SQLite error code if an error occurs.
  71566. */
  71567. static int vdbePmaReaderSeek(
  71568. SortSubtask *pTask, /* Task context */
  71569. PmaReader *pReadr, /* Reader whose cursor is to be moved */
  71570. SorterFile *pFile, /* Sorter file to read from */
  71571. i64 iOff /* Offset in pFile */
  71572. ){
  71573. int rc = SQLITE_OK;
  71574. assert( pReadr->pIncr==0 || pReadr->pIncr->bEof==0 );
  71575. if( sqlite3FaultSim(201) ) return SQLITE_IOERR_READ;
  71576. if( pReadr->aMap ){
  71577. sqlite3OsUnfetch(pReadr->pFd, 0, pReadr->aMap);
  71578. pReadr->aMap = 0;
  71579. }
  71580. pReadr->iReadOff = iOff;
  71581. pReadr->iEof = pFile->iEof;
  71582. pReadr->pFd = pFile->pFd;
  71583. rc = vdbeSorterMapFile(pTask, pFile, &pReadr->aMap);
  71584. if( rc==SQLITE_OK && pReadr->aMap==0 ){
  71585. int pgsz = pTask->pSorter->pgsz;
  71586. int iBuf = pReadr->iReadOff % pgsz;
  71587. if( pReadr->aBuffer==0 ){
  71588. pReadr->aBuffer = (u8*)sqlite3Malloc(pgsz);
  71589. if( pReadr->aBuffer==0 ) rc = SQLITE_NOMEM;
  71590. pReadr->nBuffer = pgsz;
  71591. }
  71592. if( rc==SQLITE_OK && iBuf ){
  71593. int nRead = pgsz - iBuf;
  71594. if( (pReadr->iReadOff + nRead) > pReadr->iEof ){
  71595. nRead = (int)(pReadr->iEof - pReadr->iReadOff);
  71596. }
  71597. rc = sqlite3OsRead(
  71598. pReadr->pFd, &pReadr->aBuffer[iBuf], nRead, pReadr->iReadOff
  71599. );
  71600. testcase( rc!=SQLITE_OK );
  71601. }
  71602. }
  71603. return rc;
  71604. }
  71605. /*
  71606. ** Advance PmaReader pReadr to the next key in its PMA. Return SQLITE_OK if
  71607. ** no error occurs, or an SQLite error code if one does.
  71608. */
  71609. static int vdbePmaReaderNext(PmaReader *pReadr){
  71610. int rc = SQLITE_OK; /* Return Code */
  71611. u64 nRec = 0; /* Size of record in bytes */
  71612. if( pReadr->iReadOff>=pReadr->iEof ){
  71613. IncrMerger *pIncr = pReadr->pIncr;
  71614. int bEof = 1;
  71615. if( pIncr ){
  71616. rc = vdbeIncrSwap(pIncr);
  71617. if( rc==SQLITE_OK && pIncr->bEof==0 ){
  71618. rc = vdbePmaReaderSeek(
  71619. pIncr->pTask, pReadr, &pIncr->aFile[0], pIncr->iStartOff
  71620. );
  71621. bEof = 0;
  71622. }
  71623. }
  71624. if( bEof ){
  71625. /* This is an EOF condition */
  71626. vdbePmaReaderClear(pReadr);
  71627. testcase( rc!=SQLITE_OK );
  71628. return rc;
  71629. }
  71630. }
  71631. if( rc==SQLITE_OK ){
  71632. rc = vdbePmaReadVarint(pReadr, &nRec);
  71633. }
  71634. if( rc==SQLITE_OK ){
  71635. pReadr->nKey = (int)nRec;
  71636. rc = vdbePmaReadBlob(pReadr, (int)nRec, &pReadr->aKey);
  71637. testcase( rc!=SQLITE_OK );
  71638. }
  71639. return rc;
  71640. }
  71641. /*
  71642. ** Initialize PmaReader pReadr to scan through the PMA stored in file pFile
  71643. ** starting at offset iStart and ending at offset iEof-1. This function
  71644. ** leaves the PmaReader pointing to the first key in the PMA (or EOF if the
  71645. ** PMA is empty).
  71646. **
  71647. ** If the pnByte parameter is NULL, then it is assumed that the file
  71648. ** contains a single PMA, and that that PMA omits the initial length varint.
  71649. */
  71650. static int vdbePmaReaderInit(
  71651. SortSubtask *pTask, /* Task context */
  71652. SorterFile *pFile, /* Sorter file to read from */
  71653. i64 iStart, /* Start offset in pFile */
  71654. PmaReader *pReadr, /* PmaReader to populate */
  71655. i64 *pnByte /* IN/OUT: Increment this value by PMA size */
  71656. ){
  71657. int rc;
  71658. assert( pFile->iEof>iStart );
  71659. assert( pReadr->aAlloc==0 && pReadr->nAlloc==0 );
  71660. assert( pReadr->aBuffer==0 );
  71661. assert( pReadr->aMap==0 );
  71662. rc = vdbePmaReaderSeek(pTask, pReadr, pFile, iStart);
  71663. if( rc==SQLITE_OK ){
  71664. u64 nByte; /* Size of PMA in bytes */
  71665. rc = vdbePmaReadVarint(pReadr, &nByte);
  71666. pReadr->iEof = pReadr->iReadOff + nByte;
  71667. *pnByte += nByte;
  71668. }
  71669. if( rc==SQLITE_OK ){
  71670. rc = vdbePmaReaderNext(pReadr);
  71671. }
  71672. return rc;
  71673. }
  71674. /*
  71675. ** Compare key1 (buffer pKey1, size nKey1 bytes) with key2 (buffer pKey2,
  71676. ** size nKey2 bytes). Use (pTask->pKeyInfo) for the collation sequences
  71677. ** used by the comparison. Return the result of the comparison.
  71678. **
  71679. ** Before returning, object (pTask->pUnpacked) is populated with the
  71680. ** unpacked version of key2. Or, if pKey2 is passed a NULL pointer, then it
  71681. ** is assumed that the (pTask->pUnpacked) structure already contains the
  71682. ** unpacked key to use as key2.
  71683. **
  71684. ** If an OOM error is encountered, (pTask->pUnpacked->error_rc) is set
  71685. ** to SQLITE_NOMEM.
  71686. */
  71687. static int vdbeSorterCompare(
  71688. SortSubtask *pTask, /* Subtask context (for pKeyInfo) */
  71689. const void *pKey1, int nKey1, /* Left side of comparison */
  71690. const void *pKey2, int nKey2 /* Right side of comparison */
  71691. ){
  71692. UnpackedRecord *r2 = pTask->pUnpacked;
  71693. if( pKey2 ){
  71694. sqlite3VdbeRecordUnpack(pTask->pSorter->pKeyInfo, nKey2, pKey2, r2);
  71695. }
  71696. return sqlite3VdbeRecordCompare(nKey1, pKey1, r2);
  71697. }
  71698. /*
  71699. ** Initialize the temporary index cursor just opened as a sorter cursor.
  71700. **
  71701. ** Usually, the sorter module uses the value of (pCsr->pKeyInfo->nField)
  71702. ** to determine the number of fields that should be compared from the
  71703. ** records being sorted. However, if the value passed as argument nField
  71704. ** is non-zero and the sorter is able to guarantee a stable sort, nField
  71705. ** is used instead. This is used when sorting records for a CREATE INDEX
  71706. ** statement. In this case, keys are always delivered to the sorter in
  71707. ** order of the primary key, which happens to be make up the final part
  71708. ** of the records being sorted. So if the sort is stable, there is never
  71709. ** any reason to compare PK fields and they can be ignored for a small
  71710. ** performance boost.
  71711. **
  71712. ** The sorter can guarantee a stable sort when running in single-threaded
  71713. ** mode, but not in multi-threaded mode.
  71714. **
  71715. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  71716. */
  71717. SQLITE_PRIVATE int sqlite3VdbeSorterInit(
  71718. sqlite3 *db, /* Database connection (for malloc()) */
  71719. int nField, /* Number of key fields in each record */
  71720. VdbeCursor *pCsr /* Cursor that holds the new sorter */
  71721. ){
  71722. int pgsz; /* Page size of main database */
  71723. int i; /* Used to iterate through aTask[] */
  71724. int mxCache; /* Cache size */
  71725. VdbeSorter *pSorter; /* The new sorter */
  71726. KeyInfo *pKeyInfo; /* Copy of pCsr->pKeyInfo with db==0 */
  71727. int szKeyInfo; /* Size of pCsr->pKeyInfo in bytes */
  71728. int sz; /* Size of pSorter in bytes */
  71729. int rc = SQLITE_OK;
  71730. #if SQLITE_MAX_WORKER_THREADS==0
  71731. # define nWorker 0
  71732. #else
  71733. int nWorker;
  71734. #endif
  71735. /* Initialize the upper limit on the number of worker threads */
  71736. #if SQLITE_MAX_WORKER_THREADS>0
  71737. if( sqlite3TempInMemory(db) || sqlite3GlobalConfig.bCoreMutex==0 ){
  71738. nWorker = 0;
  71739. }else{
  71740. nWorker = db->aLimit[SQLITE_LIMIT_WORKER_THREADS];
  71741. }
  71742. #endif
  71743. /* Do not allow the total number of threads (main thread + all workers)
  71744. ** to exceed the maximum merge count */
  71745. #if SQLITE_MAX_WORKER_THREADS>=SORTER_MAX_MERGE_COUNT
  71746. if( nWorker>=SORTER_MAX_MERGE_COUNT ){
  71747. nWorker = SORTER_MAX_MERGE_COUNT-1;
  71748. }
  71749. #endif
  71750. assert( pCsr->pKeyInfo && pCsr->pBt==0 );
  71751. szKeyInfo = sizeof(KeyInfo) + (pCsr->pKeyInfo->nField-1)*sizeof(CollSeq*);
  71752. sz = sizeof(VdbeSorter) + nWorker * sizeof(SortSubtask);
  71753. pSorter = (VdbeSorter*)sqlite3DbMallocZero(db, sz + szKeyInfo);
  71754. pCsr->pSorter = pSorter;
  71755. if( pSorter==0 ){
  71756. rc = SQLITE_NOMEM;
  71757. }else{
  71758. pSorter->pKeyInfo = pKeyInfo = (KeyInfo*)((u8*)pSorter + sz);
  71759. memcpy(pKeyInfo, pCsr->pKeyInfo, szKeyInfo);
  71760. pKeyInfo->db = 0;
  71761. if( nField && nWorker==0 ) pKeyInfo->nField = nField;
  71762. pSorter->pgsz = pgsz = sqlite3BtreeGetPageSize(db->aDb[0].pBt);
  71763. pSorter->nTask = nWorker + 1;
  71764. pSorter->bUseThreads = (pSorter->nTask>1);
  71765. pSorter->db = db;
  71766. for(i=0; i<pSorter->nTask; i++){
  71767. SortSubtask *pTask = &pSorter->aTask[i];
  71768. pTask->pSorter = pSorter;
  71769. }
  71770. if( !sqlite3TempInMemory(db) ){
  71771. pSorter->mnPmaSize = SORTER_MIN_WORKING * pgsz;
  71772. mxCache = db->aDb[0].pSchema->cache_size;
  71773. if( mxCache<SORTER_MIN_WORKING ) mxCache = SORTER_MIN_WORKING;
  71774. pSorter->mxPmaSize = mxCache * pgsz;
  71775. /* If the application has not configure scratch memory using
  71776. ** SQLITE_CONFIG_SCRATCH then we assume it is OK to do large memory
  71777. ** allocations. If scratch memory has been configured, then assume
  71778. ** large memory allocations should be avoided to prevent heap
  71779. ** fragmentation.
  71780. */
  71781. if( sqlite3GlobalConfig.pScratch==0 ){
  71782. assert( pSorter->iMemory==0 );
  71783. pSorter->nMemory = pgsz;
  71784. pSorter->list.aMemory = (u8*)sqlite3Malloc(pgsz);
  71785. if( !pSorter->list.aMemory ) rc = SQLITE_NOMEM;
  71786. }
  71787. }
  71788. }
  71789. return rc;
  71790. }
  71791. #undef nWorker /* Defined at the top of this function */
  71792. /*
  71793. ** Free the list of sorted records starting at pRecord.
  71794. */
  71795. static void vdbeSorterRecordFree(sqlite3 *db, SorterRecord *pRecord){
  71796. SorterRecord *p;
  71797. SorterRecord *pNext;
  71798. for(p=pRecord; p; p=pNext){
  71799. pNext = p->u.pNext;
  71800. sqlite3DbFree(db, p);
  71801. }
  71802. }
  71803. /*
  71804. ** Free all resources owned by the object indicated by argument pTask. All
  71805. ** fields of *pTask are zeroed before returning.
  71806. */
  71807. static void vdbeSortSubtaskCleanup(sqlite3 *db, SortSubtask *pTask){
  71808. sqlite3DbFree(db, pTask->pUnpacked);
  71809. pTask->pUnpacked = 0;
  71810. #if SQLITE_MAX_WORKER_THREADS>0
  71811. /* pTask->list.aMemory can only be non-zero if it was handed memory
  71812. ** from the main thread. That only occurs SQLITE_MAX_WORKER_THREADS>0 */
  71813. if( pTask->list.aMemory ){
  71814. sqlite3_free(pTask->list.aMemory);
  71815. pTask->list.aMemory = 0;
  71816. }else
  71817. #endif
  71818. {
  71819. assert( pTask->list.aMemory==0 );
  71820. vdbeSorterRecordFree(0, pTask->list.pList);
  71821. }
  71822. pTask->list.pList = 0;
  71823. if( pTask->file.pFd ){
  71824. sqlite3OsCloseFree(pTask->file.pFd);
  71825. pTask->file.pFd = 0;
  71826. pTask->file.iEof = 0;
  71827. }
  71828. if( pTask->file2.pFd ){
  71829. sqlite3OsCloseFree(pTask->file2.pFd);
  71830. pTask->file2.pFd = 0;
  71831. pTask->file2.iEof = 0;
  71832. }
  71833. }
  71834. #ifdef SQLITE_DEBUG_SORTER_THREADS
  71835. static void vdbeSorterWorkDebug(SortSubtask *pTask, const char *zEvent){
  71836. i64 t;
  71837. int iTask = (pTask - pTask->pSorter->aTask);
  71838. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  71839. fprintf(stderr, "%lld:%d %s\n", t, iTask, zEvent);
  71840. }
  71841. static void vdbeSorterRewindDebug(const char *zEvent){
  71842. i64 t;
  71843. sqlite3OsCurrentTimeInt64(sqlite3_vfs_find(0), &t);
  71844. fprintf(stderr, "%lld:X %s\n", t, zEvent);
  71845. }
  71846. static void vdbeSorterPopulateDebug(
  71847. SortSubtask *pTask,
  71848. const char *zEvent
  71849. ){
  71850. i64 t;
  71851. int iTask = (pTask - pTask->pSorter->aTask);
  71852. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  71853. fprintf(stderr, "%lld:bg%d %s\n", t, iTask, zEvent);
  71854. }
  71855. static void vdbeSorterBlockDebug(
  71856. SortSubtask *pTask,
  71857. int bBlocked,
  71858. const char *zEvent
  71859. ){
  71860. if( bBlocked ){
  71861. i64 t;
  71862. sqlite3OsCurrentTimeInt64(pTask->pSorter->db->pVfs, &t);
  71863. fprintf(stderr, "%lld:main %s\n", t, zEvent);
  71864. }
  71865. }
  71866. #else
  71867. # define vdbeSorterWorkDebug(x,y)
  71868. # define vdbeSorterRewindDebug(y)
  71869. # define vdbeSorterPopulateDebug(x,y)
  71870. # define vdbeSorterBlockDebug(x,y,z)
  71871. #endif
  71872. #if SQLITE_MAX_WORKER_THREADS>0
  71873. /*
  71874. ** Join thread pTask->thread.
  71875. */
  71876. static int vdbeSorterJoinThread(SortSubtask *pTask){
  71877. int rc = SQLITE_OK;
  71878. if( pTask->pThread ){
  71879. #ifdef SQLITE_DEBUG_SORTER_THREADS
  71880. int bDone = pTask->bDone;
  71881. #endif
  71882. void *pRet = SQLITE_INT_TO_PTR(SQLITE_ERROR);
  71883. vdbeSorterBlockDebug(pTask, !bDone, "enter");
  71884. (void)sqlite3ThreadJoin(pTask->pThread, &pRet);
  71885. vdbeSorterBlockDebug(pTask, !bDone, "exit");
  71886. rc = SQLITE_PTR_TO_INT(pRet);
  71887. assert( pTask->bDone==1 );
  71888. pTask->bDone = 0;
  71889. pTask->pThread = 0;
  71890. }
  71891. return rc;
  71892. }
  71893. /*
  71894. ** Launch a background thread to run xTask(pIn).
  71895. */
  71896. static int vdbeSorterCreateThread(
  71897. SortSubtask *pTask, /* Thread will use this task object */
  71898. void *(*xTask)(void*), /* Routine to run in a separate thread */
  71899. void *pIn /* Argument passed into xTask() */
  71900. ){
  71901. assert( pTask->pThread==0 && pTask->bDone==0 );
  71902. return sqlite3ThreadCreate(&pTask->pThread, xTask, pIn);
  71903. }
  71904. /*
  71905. ** Join all outstanding threads launched by SorterWrite() to create
  71906. ** level-0 PMAs.
  71907. */
  71908. static int vdbeSorterJoinAll(VdbeSorter *pSorter, int rcin){
  71909. int rc = rcin;
  71910. int i;
  71911. /* This function is always called by the main user thread.
  71912. **
  71913. ** If this function is being called after SorterRewind() has been called,
  71914. ** it is possible that thread pSorter->aTask[pSorter->nTask-1].pThread
  71915. ** is currently attempt to join one of the other threads. To avoid a race
  71916. ** condition where this thread also attempts to join the same object, join
  71917. ** thread pSorter->aTask[pSorter->nTask-1].pThread first. */
  71918. for(i=pSorter->nTask-1; i>=0; i--){
  71919. SortSubtask *pTask = &pSorter->aTask[i];
  71920. int rc2 = vdbeSorterJoinThread(pTask);
  71921. if( rc==SQLITE_OK ) rc = rc2;
  71922. }
  71923. return rc;
  71924. }
  71925. #else
  71926. # define vdbeSorterJoinAll(x,rcin) (rcin)
  71927. # define vdbeSorterJoinThread(pTask) SQLITE_OK
  71928. #endif
  71929. /*
  71930. ** Allocate a new MergeEngine object capable of handling up to
  71931. ** nReader PmaReader inputs.
  71932. **
  71933. ** nReader is automatically rounded up to the next power of two.
  71934. ** nReader may not exceed SORTER_MAX_MERGE_COUNT even after rounding up.
  71935. */
  71936. static MergeEngine *vdbeMergeEngineNew(int nReader){
  71937. int N = 2; /* Smallest power of two >= nReader */
  71938. int nByte; /* Total bytes of space to allocate */
  71939. MergeEngine *pNew; /* Pointer to allocated object to return */
  71940. assert( nReader<=SORTER_MAX_MERGE_COUNT );
  71941. while( N<nReader ) N += N;
  71942. nByte = sizeof(MergeEngine) + N * (sizeof(int) + sizeof(PmaReader));
  71943. pNew = sqlite3FaultSim(100) ? 0 : (MergeEngine*)sqlite3MallocZero(nByte);
  71944. if( pNew ){
  71945. pNew->nTree = N;
  71946. pNew->pTask = 0;
  71947. pNew->aReadr = (PmaReader*)&pNew[1];
  71948. pNew->aTree = (int*)&pNew->aReadr[N];
  71949. }
  71950. return pNew;
  71951. }
  71952. /*
  71953. ** Free the MergeEngine object passed as the only argument.
  71954. */
  71955. static void vdbeMergeEngineFree(MergeEngine *pMerger){
  71956. int i;
  71957. if( pMerger ){
  71958. for(i=0; i<pMerger->nTree; i++){
  71959. vdbePmaReaderClear(&pMerger->aReadr[i]);
  71960. }
  71961. }
  71962. sqlite3_free(pMerger);
  71963. }
  71964. /*
  71965. ** Free all resources associated with the IncrMerger object indicated by
  71966. ** the first argument.
  71967. */
  71968. static void vdbeIncrFree(IncrMerger *pIncr){
  71969. if( pIncr ){
  71970. #if SQLITE_MAX_WORKER_THREADS>0
  71971. if( pIncr->bUseThread ){
  71972. vdbeSorterJoinThread(pIncr->pTask);
  71973. if( pIncr->aFile[0].pFd ) sqlite3OsCloseFree(pIncr->aFile[0].pFd);
  71974. if( pIncr->aFile[1].pFd ) sqlite3OsCloseFree(pIncr->aFile[1].pFd);
  71975. }
  71976. #endif
  71977. vdbeMergeEngineFree(pIncr->pMerger);
  71978. sqlite3_free(pIncr);
  71979. }
  71980. }
  71981. /*
  71982. ** Reset a sorting cursor back to its original empty state.
  71983. */
  71984. SQLITE_PRIVATE void sqlite3VdbeSorterReset(sqlite3 *db, VdbeSorter *pSorter){
  71985. int i;
  71986. (void)vdbeSorterJoinAll(pSorter, SQLITE_OK);
  71987. assert( pSorter->bUseThreads || pSorter->pReader==0 );
  71988. #if SQLITE_MAX_WORKER_THREADS>0
  71989. if( pSorter->pReader ){
  71990. vdbePmaReaderClear(pSorter->pReader);
  71991. sqlite3DbFree(db, pSorter->pReader);
  71992. pSorter->pReader = 0;
  71993. }
  71994. #endif
  71995. vdbeMergeEngineFree(pSorter->pMerger);
  71996. pSorter->pMerger = 0;
  71997. for(i=0; i<pSorter->nTask; i++){
  71998. SortSubtask *pTask = &pSorter->aTask[i];
  71999. vdbeSortSubtaskCleanup(db, pTask);
  72000. }
  72001. if( pSorter->list.aMemory==0 ){
  72002. vdbeSorterRecordFree(0, pSorter->list.pList);
  72003. }
  72004. pSorter->list.pList = 0;
  72005. pSorter->list.szPMA = 0;
  72006. pSorter->bUsePMA = 0;
  72007. pSorter->iMemory = 0;
  72008. pSorter->mxKeysize = 0;
  72009. sqlite3DbFree(db, pSorter->pUnpacked);
  72010. pSorter->pUnpacked = 0;
  72011. }
  72012. /*
  72013. ** Free any cursor components allocated by sqlite3VdbeSorterXXX routines.
  72014. */
  72015. SQLITE_PRIVATE void sqlite3VdbeSorterClose(sqlite3 *db, VdbeCursor *pCsr){
  72016. VdbeSorter *pSorter = pCsr->pSorter;
  72017. if( pSorter ){
  72018. sqlite3VdbeSorterReset(db, pSorter);
  72019. sqlite3_free(pSorter->list.aMemory);
  72020. sqlite3DbFree(db, pSorter);
  72021. pCsr->pSorter = 0;
  72022. }
  72023. }
  72024. #if SQLITE_MAX_MMAP_SIZE>0
  72025. /*
  72026. ** The first argument is a file-handle open on a temporary file. The file
  72027. ** is guaranteed to be nByte bytes or smaller in size. This function
  72028. ** attempts to extend the file to nByte bytes in size and to ensure that
  72029. ** the VFS has memory mapped it.
  72030. **
  72031. ** Whether or not the file does end up memory mapped of course depends on
  72032. ** the specific VFS implementation.
  72033. */
  72034. static void vdbeSorterExtendFile(sqlite3 *db, sqlite3_file *pFd, i64 nByte){
  72035. if( nByte<=(i64)(db->nMaxSorterMmap) && pFd->pMethods->iVersion>=3 ){
  72036. int rc = sqlite3OsTruncate(pFd, nByte);
  72037. if( rc==SQLITE_OK ){
  72038. void *p = 0;
  72039. sqlite3OsFetch(pFd, 0, (int)nByte, &p);
  72040. sqlite3OsUnfetch(pFd, 0, p);
  72041. }
  72042. }
  72043. }
  72044. #else
  72045. # define vdbeSorterExtendFile(x,y,z)
  72046. #endif
  72047. /*
  72048. ** Allocate space for a file-handle and open a temporary file. If successful,
  72049. ** set *ppFd to point to the malloc'd file-handle and return SQLITE_OK.
  72050. ** Otherwise, set *ppFd to 0 and return an SQLite error code.
  72051. */
  72052. static int vdbeSorterOpenTempFile(
  72053. sqlite3 *db, /* Database handle doing sort */
  72054. i64 nExtend, /* Attempt to extend file to this size */
  72055. sqlite3_file **ppFd
  72056. ){
  72057. int rc;
  72058. rc = sqlite3OsOpenMalloc(db->pVfs, 0, ppFd,
  72059. SQLITE_OPEN_TEMP_JOURNAL |
  72060. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE |
  72061. SQLITE_OPEN_EXCLUSIVE | SQLITE_OPEN_DELETEONCLOSE, &rc
  72062. );
  72063. if( rc==SQLITE_OK ){
  72064. i64 max = SQLITE_MAX_MMAP_SIZE;
  72065. sqlite3OsFileControlHint(*ppFd, SQLITE_FCNTL_MMAP_SIZE, (void*)&max);
  72066. if( nExtend>0 ){
  72067. vdbeSorterExtendFile(db, *ppFd, nExtend);
  72068. }
  72069. }
  72070. return rc;
  72071. }
  72072. /*
  72073. ** If it has not already been allocated, allocate the UnpackedRecord
  72074. ** structure at pTask->pUnpacked. Return SQLITE_OK if successful (or
  72075. ** if no allocation was required), or SQLITE_NOMEM otherwise.
  72076. */
  72077. static int vdbeSortAllocUnpacked(SortSubtask *pTask){
  72078. if( pTask->pUnpacked==0 ){
  72079. char *pFree;
  72080. pTask->pUnpacked = sqlite3VdbeAllocUnpackedRecord(
  72081. pTask->pSorter->pKeyInfo, 0, 0, &pFree
  72082. );
  72083. assert( pTask->pUnpacked==(UnpackedRecord*)pFree );
  72084. if( pFree==0 ) return SQLITE_NOMEM;
  72085. pTask->pUnpacked->nField = pTask->pSorter->pKeyInfo->nField;
  72086. pTask->pUnpacked->errCode = 0;
  72087. }
  72088. return SQLITE_OK;
  72089. }
  72090. /*
  72091. ** Merge the two sorted lists p1 and p2 into a single list.
  72092. ** Set *ppOut to the head of the new list.
  72093. */
  72094. static void vdbeSorterMerge(
  72095. SortSubtask *pTask, /* Calling thread context */
  72096. SorterRecord *p1, /* First list to merge */
  72097. SorterRecord *p2, /* Second list to merge */
  72098. SorterRecord **ppOut /* OUT: Head of merged list */
  72099. ){
  72100. SorterRecord *pFinal = 0;
  72101. SorterRecord **pp = &pFinal;
  72102. void *pVal2 = p2 ? SRVAL(p2) : 0;
  72103. while( p1 && p2 ){
  72104. int res;
  72105. res = vdbeSorterCompare(pTask, SRVAL(p1), p1->nVal, pVal2, p2->nVal);
  72106. if( res<=0 ){
  72107. *pp = p1;
  72108. pp = &p1->u.pNext;
  72109. p1 = p1->u.pNext;
  72110. pVal2 = 0;
  72111. }else{
  72112. *pp = p2;
  72113. pp = &p2->u.pNext;
  72114. p2 = p2->u.pNext;
  72115. if( p2==0 ) break;
  72116. pVal2 = SRVAL(p2);
  72117. }
  72118. }
  72119. *pp = p1 ? p1 : p2;
  72120. *ppOut = pFinal;
  72121. }
  72122. /*
  72123. ** Sort the linked list of records headed at pTask->pList. Return
  72124. ** SQLITE_OK if successful, or an SQLite error code (i.e. SQLITE_NOMEM) if
  72125. ** an error occurs.
  72126. */
  72127. static int vdbeSorterSort(SortSubtask *pTask, SorterList *pList){
  72128. int i;
  72129. SorterRecord **aSlot;
  72130. SorterRecord *p;
  72131. int rc;
  72132. rc = vdbeSortAllocUnpacked(pTask);
  72133. if( rc!=SQLITE_OK ) return rc;
  72134. aSlot = (SorterRecord **)sqlite3MallocZero(64 * sizeof(SorterRecord *));
  72135. if( !aSlot ){
  72136. return SQLITE_NOMEM;
  72137. }
  72138. p = pList->pList;
  72139. while( p ){
  72140. SorterRecord *pNext;
  72141. if( pList->aMemory ){
  72142. if( (u8*)p==pList->aMemory ){
  72143. pNext = 0;
  72144. }else{
  72145. assert( p->u.iNext<sqlite3MallocSize(pList->aMemory) );
  72146. pNext = (SorterRecord*)&pList->aMemory[p->u.iNext];
  72147. }
  72148. }else{
  72149. pNext = p->u.pNext;
  72150. }
  72151. p->u.pNext = 0;
  72152. for(i=0; aSlot[i]; i++){
  72153. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  72154. aSlot[i] = 0;
  72155. }
  72156. aSlot[i] = p;
  72157. p = pNext;
  72158. }
  72159. p = 0;
  72160. for(i=0; i<64; i++){
  72161. vdbeSorterMerge(pTask, p, aSlot[i], &p);
  72162. }
  72163. pList->pList = p;
  72164. sqlite3_free(aSlot);
  72165. assert( pTask->pUnpacked->errCode==SQLITE_OK
  72166. || pTask->pUnpacked->errCode==SQLITE_NOMEM
  72167. );
  72168. return pTask->pUnpacked->errCode;
  72169. }
  72170. /*
  72171. ** Initialize a PMA-writer object.
  72172. */
  72173. static void vdbePmaWriterInit(
  72174. sqlite3_file *pFd, /* File handle to write to */
  72175. PmaWriter *p, /* Object to populate */
  72176. int nBuf, /* Buffer size */
  72177. i64 iStart /* Offset of pFd to begin writing at */
  72178. ){
  72179. memset(p, 0, sizeof(PmaWriter));
  72180. p->aBuffer = (u8*)sqlite3Malloc(nBuf);
  72181. if( !p->aBuffer ){
  72182. p->eFWErr = SQLITE_NOMEM;
  72183. }else{
  72184. p->iBufEnd = p->iBufStart = (iStart % nBuf);
  72185. p->iWriteOff = iStart - p->iBufStart;
  72186. p->nBuffer = nBuf;
  72187. p->pFd = pFd;
  72188. }
  72189. }
  72190. /*
  72191. ** Write nData bytes of data to the PMA. Return SQLITE_OK
  72192. ** if successful, or an SQLite error code if an error occurs.
  72193. */
  72194. static void vdbePmaWriteBlob(PmaWriter *p, u8 *pData, int nData){
  72195. int nRem = nData;
  72196. while( nRem>0 && p->eFWErr==0 ){
  72197. int nCopy = nRem;
  72198. if( nCopy>(p->nBuffer - p->iBufEnd) ){
  72199. nCopy = p->nBuffer - p->iBufEnd;
  72200. }
  72201. memcpy(&p->aBuffer[p->iBufEnd], &pData[nData-nRem], nCopy);
  72202. p->iBufEnd += nCopy;
  72203. if( p->iBufEnd==p->nBuffer ){
  72204. p->eFWErr = sqlite3OsWrite(p->pFd,
  72205. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  72206. p->iWriteOff + p->iBufStart
  72207. );
  72208. p->iBufStart = p->iBufEnd = 0;
  72209. p->iWriteOff += p->nBuffer;
  72210. }
  72211. assert( p->iBufEnd<p->nBuffer );
  72212. nRem -= nCopy;
  72213. }
  72214. }
  72215. /*
  72216. ** Flush any buffered data to disk and clean up the PMA-writer object.
  72217. ** The results of using the PMA-writer after this call are undefined.
  72218. ** Return SQLITE_OK if flushing the buffered data succeeds or is not
  72219. ** required. Otherwise, return an SQLite error code.
  72220. **
  72221. ** Before returning, set *piEof to the offset immediately following the
  72222. ** last byte written to the file.
  72223. */
  72224. static int vdbePmaWriterFinish(PmaWriter *p, i64 *piEof){
  72225. int rc;
  72226. if( p->eFWErr==0 && ALWAYS(p->aBuffer) && p->iBufEnd>p->iBufStart ){
  72227. p->eFWErr = sqlite3OsWrite(p->pFd,
  72228. &p->aBuffer[p->iBufStart], p->iBufEnd - p->iBufStart,
  72229. p->iWriteOff + p->iBufStart
  72230. );
  72231. }
  72232. *piEof = (p->iWriteOff + p->iBufEnd);
  72233. sqlite3_free(p->aBuffer);
  72234. rc = p->eFWErr;
  72235. memset(p, 0, sizeof(PmaWriter));
  72236. return rc;
  72237. }
  72238. /*
  72239. ** Write value iVal encoded as a varint to the PMA. Return
  72240. ** SQLITE_OK if successful, or an SQLite error code if an error occurs.
  72241. */
  72242. static void vdbePmaWriteVarint(PmaWriter *p, u64 iVal){
  72243. int nByte;
  72244. u8 aByte[10];
  72245. nByte = sqlite3PutVarint(aByte, iVal);
  72246. vdbePmaWriteBlob(p, aByte, nByte);
  72247. }
  72248. /*
  72249. ** Write the current contents of in-memory linked-list pList to a level-0
  72250. ** PMA in the temp file belonging to sub-task pTask. Return SQLITE_OK if
  72251. ** successful, or an SQLite error code otherwise.
  72252. **
  72253. ** The format of a PMA is:
  72254. **
  72255. ** * A varint. This varint contains the total number of bytes of content
  72256. ** in the PMA (not including the varint itself).
  72257. **
  72258. ** * One or more records packed end-to-end in order of ascending keys.
  72259. ** Each record consists of a varint followed by a blob of data (the
  72260. ** key). The varint is the number of bytes in the blob of data.
  72261. */
  72262. static int vdbeSorterListToPMA(SortSubtask *pTask, SorterList *pList){
  72263. sqlite3 *db = pTask->pSorter->db;
  72264. int rc = SQLITE_OK; /* Return code */
  72265. PmaWriter writer; /* Object used to write to the file */
  72266. #ifdef SQLITE_DEBUG
  72267. /* Set iSz to the expected size of file pTask->file after writing the PMA.
  72268. ** This is used by an assert() statement at the end of this function. */
  72269. i64 iSz = pList->szPMA + sqlite3VarintLen(pList->szPMA) + pTask->file.iEof;
  72270. #endif
  72271. vdbeSorterWorkDebug(pTask, "enter");
  72272. memset(&writer, 0, sizeof(PmaWriter));
  72273. assert( pList->szPMA>0 );
  72274. /* If the first temporary PMA file has not been opened, open it now. */
  72275. if( pTask->file.pFd==0 ){
  72276. rc = vdbeSorterOpenTempFile(db, 0, &pTask->file.pFd);
  72277. assert( rc!=SQLITE_OK || pTask->file.pFd );
  72278. assert( pTask->file.iEof==0 );
  72279. assert( pTask->nPMA==0 );
  72280. }
  72281. /* Try to get the file to memory map */
  72282. if( rc==SQLITE_OK ){
  72283. vdbeSorterExtendFile(db, pTask->file.pFd, pTask->file.iEof+pList->szPMA+9);
  72284. }
  72285. /* Sort the list */
  72286. if( rc==SQLITE_OK ){
  72287. rc = vdbeSorterSort(pTask, pList);
  72288. }
  72289. if( rc==SQLITE_OK ){
  72290. SorterRecord *p;
  72291. SorterRecord *pNext = 0;
  72292. vdbePmaWriterInit(pTask->file.pFd, &writer, pTask->pSorter->pgsz,
  72293. pTask->file.iEof);
  72294. pTask->nPMA++;
  72295. vdbePmaWriteVarint(&writer, pList->szPMA);
  72296. for(p=pList->pList; p; p=pNext){
  72297. pNext = p->u.pNext;
  72298. vdbePmaWriteVarint(&writer, p->nVal);
  72299. vdbePmaWriteBlob(&writer, SRVAL(p), p->nVal);
  72300. if( pList->aMemory==0 ) sqlite3_free(p);
  72301. }
  72302. pList->pList = p;
  72303. rc = vdbePmaWriterFinish(&writer, &pTask->file.iEof);
  72304. }
  72305. vdbeSorterWorkDebug(pTask, "exit");
  72306. assert( rc!=SQLITE_OK || pList->pList==0 );
  72307. assert( rc!=SQLITE_OK || pTask->file.iEof==iSz );
  72308. return rc;
  72309. }
  72310. /*
  72311. ** Advance the MergeEngine to its next entry.
  72312. ** Set *pbEof to true there is no next entry because
  72313. ** the MergeEngine has reached the end of all its inputs.
  72314. **
  72315. ** Return SQLITE_OK if successful or an error code if an error occurs.
  72316. */
  72317. static int vdbeMergeEngineStep(
  72318. MergeEngine *pMerger, /* The merge engine to advance to the next row */
  72319. int *pbEof /* Set TRUE at EOF. Set false for more content */
  72320. ){
  72321. int rc;
  72322. int iPrev = pMerger->aTree[1];/* Index of PmaReader to advance */
  72323. SortSubtask *pTask = pMerger->pTask;
  72324. /* Advance the current PmaReader */
  72325. rc = vdbePmaReaderNext(&pMerger->aReadr[iPrev]);
  72326. /* Update contents of aTree[] */
  72327. if( rc==SQLITE_OK ){
  72328. int i; /* Index of aTree[] to recalculate */
  72329. PmaReader *pReadr1; /* First PmaReader to compare */
  72330. PmaReader *pReadr2; /* Second PmaReader to compare */
  72331. u8 *pKey2; /* To pReadr2->aKey, or 0 if record cached */
  72332. /* Find the first two PmaReaders to compare. The one that was just
  72333. ** advanced (iPrev) and the one next to it in the array. */
  72334. pReadr1 = &pMerger->aReadr[(iPrev & 0xFFFE)];
  72335. pReadr2 = &pMerger->aReadr[(iPrev | 0x0001)];
  72336. pKey2 = pReadr2->aKey;
  72337. for(i=(pMerger->nTree+iPrev)/2; i>0; i=i/2){
  72338. /* Compare pReadr1 and pReadr2. Store the result in variable iRes. */
  72339. int iRes;
  72340. if( pReadr1->pFd==0 ){
  72341. iRes = +1;
  72342. }else if( pReadr2->pFd==0 ){
  72343. iRes = -1;
  72344. }else{
  72345. iRes = vdbeSorterCompare(pTask,
  72346. pReadr1->aKey, pReadr1->nKey, pKey2, pReadr2->nKey
  72347. );
  72348. }
  72349. /* If pReadr1 contained the smaller value, set aTree[i] to its index.
  72350. ** Then set pReadr2 to the next PmaReader to compare to pReadr1. In this
  72351. ** case there is no cache of pReadr2 in pTask->pUnpacked, so set
  72352. ** pKey2 to point to the record belonging to pReadr2.
  72353. **
  72354. ** Alternatively, if pReadr2 contains the smaller of the two values,
  72355. ** set aTree[i] to its index and update pReadr1. If vdbeSorterCompare()
  72356. ** was actually called above, then pTask->pUnpacked now contains
  72357. ** a value equivalent to pReadr2. So set pKey2 to NULL to prevent
  72358. ** vdbeSorterCompare() from decoding pReadr2 again.
  72359. **
  72360. ** If the two values were equal, then the value from the oldest
  72361. ** PMA should be considered smaller. The VdbeSorter.aReadr[] array
  72362. ** is sorted from oldest to newest, so pReadr1 contains older values
  72363. ** than pReadr2 iff (pReadr1<pReadr2). */
  72364. if( iRes<0 || (iRes==0 && pReadr1<pReadr2) ){
  72365. pMerger->aTree[i] = (int)(pReadr1 - pMerger->aReadr);
  72366. pReadr2 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  72367. pKey2 = pReadr2->aKey;
  72368. }else{
  72369. if( pReadr1->pFd ) pKey2 = 0;
  72370. pMerger->aTree[i] = (int)(pReadr2 - pMerger->aReadr);
  72371. pReadr1 = &pMerger->aReadr[ pMerger->aTree[i ^ 0x0001] ];
  72372. }
  72373. }
  72374. *pbEof = (pMerger->aReadr[pMerger->aTree[1]].pFd==0);
  72375. }
  72376. return (rc==SQLITE_OK ? pTask->pUnpacked->errCode : rc);
  72377. }
  72378. #if SQLITE_MAX_WORKER_THREADS>0
  72379. /*
  72380. ** The main routine for background threads that write level-0 PMAs.
  72381. */
  72382. static void *vdbeSorterFlushThread(void *pCtx){
  72383. SortSubtask *pTask = (SortSubtask*)pCtx;
  72384. int rc; /* Return code */
  72385. assert( pTask->bDone==0 );
  72386. rc = vdbeSorterListToPMA(pTask, &pTask->list);
  72387. pTask->bDone = 1;
  72388. return SQLITE_INT_TO_PTR(rc);
  72389. }
  72390. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  72391. /*
  72392. ** Flush the current contents of VdbeSorter.list to a new PMA, possibly
  72393. ** using a background thread.
  72394. */
  72395. static int vdbeSorterFlushPMA(VdbeSorter *pSorter){
  72396. #if SQLITE_MAX_WORKER_THREADS==0
  72397. pSorter->bUsePMA = 1;
  72398. return vdbeSorterListToPMA(&pSorter->aTask[0], &pSorter->list);
  72399. #else
  72400. int rc = SQLITE_OK;
  72401. int i;
  72402. SortSubtask *pTask = 0; /* Thread context used to create new PMA */
  72403. int nWorker = (pSorter->nTask-1);
  72404. /* Set the flag to indicate that at least one PMA has been written.
  72405. ** Or will be, anyhow. */
  72406. pSorter->bUsePMA = 1;
  72407. /* Select a sub-task to sort and flush the current list of in-memory
  72408. ** records to disk. If the sorter is running in multi-threaded mode,
  72409. ** round-robin between the first (pSorter->nTask-1) tasks. Except, if
  72410. ** the background thread from a sub-tasks previous turn is still running,
  72411. ** skip it. If the first (pSorter->nTask-1) sub-tasks are all still busy,
  72412. ** fall back to using the final sub-task. The first (pSorter->nTask-1)
  72413. ** sub-tasks are prefered as they use background threads - the final
  72414. ** sub-task uses the main thread. */
  72415. for(i=0; i<nWorker; i++){
  72416. int iTest = (pSorter->iPrev + i + 1) % nWorker;
  72417. pTask = &pSorter->aTask[iTest];
  72418. if( pTask->bDone ){
  72419. rc = vdbeSorterJoinThread(pTask);
  72420. }
  72421. if( rc!=SQLITE_OK || pTask->pThread==0 ) break;
  72422. }
  72423. if( rc==SQLITE_OK ){
  72424. if( i==nWorker ){
  72425. /* Use the foreground thread for this operation */
  72426. rc = vdbeSorterListToPMA(&pSorter->aTask[nWorker], &pSorter->list);
  72427. }else{
  72428. /* Launch a background thread for this operation */
  72429. u8 *aMem = pTask->list.aMemory;
  72430. void *pCtx = (void*)pTask;
  72431. assert( pTask->pThread==0 && pTask->bDone==0 );
  72432. assert( pTask->list.pList==0 );
  72433. assert( pTask->list.aMemory==0 || pSorter->list.aMemory!=0 );
  72434. pSorter->iPrev = (u8)(pTask - pSorter->aTask);
  72435. pTask->list = pSorter->list;
  72436. pSorter->list.pList = 0;
  72437. pSorter->list.szPMA = 0;
  72438. if( aMem ){
  72439. pSorter->list.aMemory = aMem;
  72440. pSorter->nMemory = sqlite3MallocSize(aMem);
  72441. }else if( pSorter->list.aMemory ){
  72442. pSorter->list.aMemory = sqlite3Malloc(pSorter->nMemory);
  72443. if( !pSorter->list.aMemory ) return SQLITE_NOMEM;
  72444. }
  72445. rc = vdbeSorterCreateThread(pTask, vdbeSorterFlushThread, pCtx);
  72446. }
  72447. }
  72448. return rc;
  72449. #endif /* SQLITE_MAX_WORKER_THREADS!=0 */
  72450. }
  72451. /*
  72452. ** Add a record to the sorter.
  72453. */
  72454. SQLITE_PRIVATE int sqlite3VdbeSorterWrite(
  72455. const VdbeCursor *pCsr, /* Sorter cursor */
  72456. Mem *pVal /* Memory cell containing record */
  72457. ){
  72458. VdbeSorter *pSorter = pCsr->pSorter;
  72459. int rc = SQLITE_OK; /* Return Code */
  72460. SorterRecord *pNew; /* New list element */
  72461. int bFlush; /* True to flush contents of memory to PMA */
  72462. int nReq; /* Bytes of memory required */
  72463. int nPMA; /* Bytes of PMA space required */
  72464. assert( pSorter );
  72465. /* Figure out whether or not the current contents of memory should be
  72466. ** flushed to a PMA before continuing. If so, do so.
  72467. **
  72468. ** If using the single large allocation mode (pSorter->aMemory!=0), then
  72469. ** flush the contents of memory to a new PMA if (a) at least one value is
  72470. ** already in memory and (b) the new value will not fit in memory.
  72471. **
  72472. ** Or, if using separate allocations for each record, flush the contents
  72473. ** of memory to a PMA if either of the following are true:
  72474. **
  72475. ** * The total memory allocated for the in-memory list is greater
  72476. ** than (page-size * cache-size), or
  72477. **
  72478. ** * The total memory allocated for the in-memory list is greater
  72479. ** than (page-size * 10) and sqlite3HeapNearlyFull() returns true.
  72480. */
  72481. nReq = pVal->n + sizeof(SorterRecord);
  72482. nPMA = pVal->n + sqlite3VarintLen(pVal->n);
  72483. if( pSorter->mxPmaSize ){
  72484. if( pSorter->list.aMemory ){
  72485. bFlush = pSorter->iMemory && (pSorter->iMemory+nReq) > pSorter->mxPmaSize;
  72486. }else{
  72487. bFlush = (
  72488. (pSorter->list.szPMA > pSorter->mxPmaSize)
  72489. || (pSorter->list.szPMA > pSorter->mnPmaSize && sqlite3HeapNearlyFull())
  72490. );
  72491. }
  72492. if( bFlush ){
  72493. rc = vdbeSorterFlushPMA(pSorter);
  72494. pSorter->list.szPMA = 0;
  72495. pSorter->iMemory = 0;
  72496. assert( rc!=SQLITE_OK || pSorter->list.pList==0 );
  72497. }
  72498. }
  72499. pSorter->list.szPMA += nPMA;
  72500. if( nPMA>pSorter->mxKeysize ){
  72501. pSorter->mxKeysize = nPMA;
  72502. }
  72503. if( pSorter->list.aMemory ){
  72504. int nMin = pSorter->iMemory + nReq;
  72505. if( nMin>pSorter->nMemory ){
  72506. u8 *aNew;
  72507. int nNew = pSorter->nMemory * 2;
  72508. while( nNew < nMin ) nNew = nNew*2;
  72509. if( nNew > pSorter->mxPmaSize ) nNew = pSorter->mxPmaSize;
  72510. if( nNew < nMin ) nNew = nMin;
  72511. aNew = sqlite3Realloc(pSorter->list.aMemory, nNew);
  72512. if( !aNew ) return SQLITE_NOMEM;
  72513. pSorter->list.pList = (SorterRecord*)(
  72514. aNew + ((u8*)pSorter->list.pList - pSorter->list.aMemory)
  72515. );
  72516. pSorter->list.aMemory = aNew;
  72517. pSorter->nMemory = nNew;
  72518. }
  72519. pNew = (SorterRecord*)&pSorter->list.aMemory[pSorter->iMemory];
  72520. pSorter->iMemory += ROUND8(nReq);
  72521. pNew->u.iNext = (int)((u8*)(pSorter->list.pList) - pSorter->list.aMemory);
  72522. }else{
  72523. pNew = (SorterRecord *)sqlite3Malloc(nReq);
  72524. if( pNew==0 ){
  72525. return SQLITE_NOMEM;
  72526. }
  72527. pNew->u.pNext = pSorter->list.pList;
  72528. }
  72529. memcpy(SRVAL(pNew), pVal->z, pVal->n);
  72530. pNew->nVal = pVal->n;
  72531. pSorter->list.pList = pNew;
  72532. return rc;
  72533. }
  72534. /*
  72535. ** Read keys from pIncr->pMerger and populate pIncr->aFile[1]. The format
  72536. ** of the data stored in aFile[1] is the same as that used by regular PMAs,
  72537. ** except that the number-of-bytes varint is omitted from the start.
  72538. */
  72539. static int vdbeIncrPopulate(IncrMerger *pIncr){
  72540. int rc = SQLITE_OK;
  72541. int rc2;
  72542. i64 iStart = pIncr->iStartOff;
  72543. SorterFile *pOut = &pIncr->aFile[1];
  72544. SortSubtask *pTask = pIncr->pTask;
  72545. MergeEngine *pMerger = pIncr->pMerger;
  72546. PmaWriter writer;
  72547. assert( pIncr->bEof==0 );
  72548. vdbeSorterPopulateDebug(pTask, "enter");
  72549. vdbePmaWriterInit(pOut->pFd, &writer, pTask->pSorter->pgsz, iStart);
  72550. while( rc==SQLITE_OK ){
  72551. int dummy;
  72552. PmaReader *pReader = &pMerger->aReadr[ pMerger->aTree[1] ];
  72553. int nKey = pReader->nKey;
  72554. i64 iEof = writer.iWriteOff + writer.iBufEnd;
  72555. /* Check if the output file is full or if the input has been exhausted.
  72556. ** In either case exit the loop. */
  72557. if( pReader->pFd==0 ) break;
  72558. if( (iEof + nKey + sqlite3VarintLen(nKey))>(iStart + pIncr->mxSz) ) break;
  72559. /* Write the next key to the output. */
  72560. vdbePmaWriteVarint(&writer, nKey);
  72561. vdbePmaWriteBlob(&writer, pReader->aKey, nKey);
  72562. assert( pIncr->pMerger->pTask==pTask );
  72563. rc = vdbeMergeEngineStep(pIncr->pMerger, &dummy);
  72564. }
  72565. rc2 = vdbePmaWriterFinish(&writer, &pOut->iEof);
  72566. if( rc==SQLITE_OK ) rc = rc2;
  72567. vdbeSorterPopulateDebug(pTask, "exit");
  72568. return rc;
  72569. }
  72570. #if SQLITE_MAX_WORKER_THREADS>0
  72571. /*
  72572. ** The main routine for background threads that populate aFile[1] of
  72573. ** multi-threaded IncrMerger objects.
  72574. */
  72575. static void *vdbeIncrPopulateThread(void *pCtx){
  72576. IncrMerger *pIncr = (IncrMerger*)pCtx;
  72577. void *pRet = SQLITE_INT_TO_PTR( vdbeIncrPopulate(pIncr) );
  72578. pIncr->pTask->bDone = 1;
  72579. return pRet;
  72580. }
  72581. /*
  72582. ** Launch a background thread to populate aFile[1] of pIncr.
  72583. */
  72584. static int vdbeIncrBgPopulate(IncrMerger *pIncr){
  72585. void *p = (void*)pIncr;
  72586. assert( pIncr->bUseThread );
  72587. return vdbeSorterCreateThread(pIncr->pTask, vdbeIncrPopulateThread, p);
  72588. }
  72589. #endif
  72590. /*
  72591. ** This function is called when the PmaReader corresponding to pIncr has
  72592. ** finished reading the contents of aFile[0]. Its purpose is to "refill"
  72593. ** aFile[0] such that the PmaReader should start rereading it from the
  72594. ** beginning.
  72595. **
  72596. ** For single-threaded objects, this is accomplished by literally reading
  72597. ** keys from pIncr->pMerger and repopulating aFile[0].
  72598. **
  72599. ** For multi-threaded objects, all that is required is to wait until the
  72600. ** background thread is finished (if it is not already) and then swap
  72601. ** aFile[0] and aFile[1] in place. If the contents of pMerger have not
  72602. ** been exhausted, this function also launches a new background thread
  72603. ** to populate the new aFile[1].
  72604. **
  72605. ** SQLITE_OK is returned on success, or an SQLite error code otherwise.
  72606. */
  72607. static int vdbeIncrSwap(IncrMerger *pIncr){
  72608. int rc = SQLITE_OK;
  72609. #if SQLITE_MAX_WORKER_THREADS>0
  72610. if( pIncr->bUseThread ){
  72611. rc = vdbeSorterJoinThread(pIncr->pTask);
  72612. if( rc==SQLITE_OK ){
  72613. SorterFile f0 = pIncr->aFile[0];
  72614. pIncr->aFile[0] = pIncr->aFile[1];
  72615. pIncr->aFile[1] = f0;
  72616. }
  72617. if( rc==SQLITE_OK ){
  72618. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  72619. pIncr->bEof = 1;
  72620. }else{
  72621. rc = vdbeIncrBgPopulate(pIncr);
  72622. }
  72623. }
  72624. }else
  72625. #endif
  72626. {
  72627. rc = vdbeIncrPopulate(pIncr);
  72628. pIncr->aFile[0] = pIncr->aFile[1];
  72629. if( pIncr->aFile[0].iEof==pIncr->iStartOff ){
  72630. pIncr->bEof = 1;
  72631. }
  72632. }
  72633. return rc;
  72634. }
  72635. /*
  72636. ** Allocate and return a new IncrMerger object to read data from pMerger.
  72637. **
  72638. ** If an OOM condition is encountered, return NULL. In this case free the
  72639. ** pMerger argument before returning.
  72640. */
  72641. static int vdbeIncrMergerNew(
  72642. SortSubtask *pTask, /* The thread that will be using the new IncrMerger */
  72643. MergeEngine *pMerger, /* The MergeEngine that the IncrMerger will control */
  72644. IncrMerger **ppOut /* Write the new IncrMerger here */
  72645. ){
  72646. int rc = SQLITE_OK;
  72647. IncrMerger *pIncr = *ppOut = (IncrMerger*)
  72648. (sqlite3FaultSim(100) ? 0 : sqlite3MallocZero(sizeof(*pIncr)));
  72649. if( pIncr ){
  72650. pIncr->pMerger = pMerger;
  72651. pIncr->pTask = pTask;
  72652. pIncr->mxSz = MAX(pTask->pSorter->mxKeysize+9,pTask->pSorter->mxPmaSize/2);
  72653. pTask->file2.iEof += pIncr->mxSz;
  72654. }else{
  72655. vdbeMergeEngineFree(pMerger);
  72656. rc = SQLITE_NOMEM;
  72657. }
  72658. return rc;
  72659. }
  72660. #if SQLITE_MAX_WORKER_THREADS>0
  72661. /*
  72662. ** Set the "use-threads" flag on object pIncr.
  72663. */
  72664. static void vdbeIncrMergerSetThreads(IncrMerger *pIncr){
  72665. pIncr->bUseThread = 1;
  72666. pIncr->pTask->file2.iEof -= pIncr->mxSz;
  72667. }
  72668. #endif /* SQLITE_MAX_WORKER_THREADS>0 */
  72669. /*
  72670. ** Recompute pMerger->aTree[iOut] by comparing the next keys on the
  72671. ** two PmaReaders that feed that entry. Neither of the PmaReaders
  72672. ** are advanced. This routine merely does the comparison.
  72673. */
  72674. static void vdbeMergeEngineCompare(
  72675. MergeEngine *pMerger, /* Merge engine containing PmaReaders to compare */
  72676. int iOut /* Store the result in pMerger->aTree[iOut] */
  72677. ){
  72678. int i1;
  72679. int i2;
  72680. int iRes;
  72681. PmaReader *p1;
  72682. PmaReader *p2;
  72683. assert( iOut<pMerger->nTree && iOut>0 );
  72684. if( iOut>=(pMerger->nTree/2) ){
  72685. i1 = (iOut - pMerger->nTree/2) * 2;
  72686. i2 = i1 + 1;
  72687. }else{
  72688. i1 = pMerger->aTree[iOut*2];
  72689. i2 = pMerger->aTree[iOut*2+1];
  72690. }
  72691. p1 = &pMerger->aReadr[i1];
  72692. p2 = &pMerger->aReadr[i2];
  72693. if( p1->pFd==0 ){
  72694. iRes = i2;
  72695. }else if( p2->pFd==0 ){
  72696. iRes = i1;
  72697. }else{
  72698. int res;
  72699. assert( pMerger->pTask->pUnpacked!=0 ); /* from vdbeSortSubtaskMain() */
  72700. res = vdbeSorterCompare(
  72701. pMerger->pTask, p1->aKey, p1->nKey, p2->aKey, p2->nKey
  72702. );
  72703. if( res<=0 ){
  72704. iRes = i1;
  72705. }else{
  72706. iRes = i2;
  72707. }
  72708. }
  72709. pMerger->aTree[iOut] = iRes;
  72710. }
  72711. /*
  72712. ** Allowed values for the eMode parameter to vdbeMergeEngineInit()
  72713. ** and vdbePmaReaderIncrMergeInit().
  72714. **
  72715. ** Only INCRINIT_NORMAL is valid in single-threaded builds (when
  72716. ** SQLITE_MAX_WORKER_THREADS==0). The other values are only used
  72717. ** when there exists one or more separate worker threads.
  72718. */
  72719. #define INCRINIT_NORMAL 0
  72720. #define INCRINIT_TASK 1
  72721. #define INCRINIT_ROOT 2
  72722. /* Forward reference.
  72723. ** The vdbeIncrMergeInit() and vdbePmaReaderIncrMergeInit() routines call each
  72724. ** other (when building a merge tree).
  72725. */
  72726. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode);
  72727. /*
  72728. ** Initialize the MergeEngine object passed as the second argument. Once this
  72729. ** function returns, the first key of merged data may be read from the
  72730. ** MergeEngine object in the usual fashion.
  72731. **
  72732. ** If argument eMode is INCRINIT_ROOT, then it is assumed that any IncrMerge
  72733. ** objects attached to the PmaReader objects that the merger reads from have
  72734. ** already been populated, but that they have not yet populated aFile[0] and
  72735. ** set the PmaReader objects up to read from it. In this case all that is
  72736. ** required is to call vdbePmaReaderNext() on each PmaReader to point it at
  72737. ** its first key.
  72738. **
  72739. ** Otherwise, if eMode is any value other than INCRINIT_ROOT, then use
  72740. ** vdbePmaReaderIncrMergeInit() to initialize each PmaReader that feeds data
  72741. ** to pMerger.
  72742. **
  72743. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  72744. */
  72745. static int vdbeMergeEngineInit(
  72746. SortSubtask *pTask, /* Thread that will run pMerger */
  72747. MergeEngine *pMerger, /* MergeEngine to initialize */
  72748. int eMode /* One of the INCRINIT_XXX constants */
  72749. ){
  72750. int rc = SQLITE_OK; /* Return code */
  72751. int i; /* For looping over PmaReader objects */
  72752. int nTree = pMerger->nTree;
  72753. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  72754. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  72755. /* Verify that the MergeEngine is assigned to a single thread */
  72756. assert( pMerger->pTask==0 );
  72757. pMerger->pTask = pTask;
  72758. for(i=0; i<nTree; i++){
  72759. if( SQLITE_MAX_WORKER_THREADS>0 && eMode==INCRINIT_ROOT ){
  72760. /* PmaReaders should be normally initialized in order, as if they are
  72761. ** reading from the same temp file this makes for more linear file IO.
  72762. ** However, in the INCRINIT_ROOT case, if PmaReader aReadr[nTask-1] is
  72763. ** in use it will block the vdbePmaReaderNext() call while it uses
  72764. ** the main thread to fill its buffer. So calling PmaReaderNext()
  72765. ** on this PmaReader before any of the multi-threaded PmaReaders takes
  72766. ** better advantage of multi-processor hardware. */
  72767. rc = vdbePmaReaderNext(&pMerger->aReadr[nTree-i-1]);
  72768. }else{
  72769. rc = vdbePmaReaderIncrMergeInit(&pMerger->aReadr[i], INCRINIT_NORMAL);
  72770. }
  72771. if( rc!=SQLITE_OK ) return rc;
  72772. }
  72773. for(i=pMerger->nTree-1; i>0; i--){
  72774. vdbeMergeEngineCompare(pMerger, i);
  72775. }
  72776. return pTask->pUnpacked->errCode;
  72777. }
  72778. /*
  72779. ** Initialize the IncrMerge field of a PmaReader.
  72780. **
  72781. ** If the PmaReader passed as the first argument is not an incremental-reader
  72782. ** (if pReadr->pIncr==0), then this function is a no-op. Otherwise, it serves
  72783. ** to open and/or initialize the temp file related fields of the IncrMerge
  72784. ** object at (pReadr->pIncr).
  72785. **
  72786. ** If argument eMode is set to INCRINIT_NORMAL, then all PmaReaders
  72787. ** in the sub-tree headed by pReadr are also initialized. Data is then loaded
  72788. ** into the buffers belonging to pReadr and it is set to
  72789. ** point to the first key in its range.
  72790. **
  72791. ** If argument eMode is set to INCRINIT_TASK, then pReadr is guaranteed
  72792. ** to be a multi-threaded PmaReader and this function is being called in a
  72793. ** background thread. In this case all PmaReaders in the sub-tree are
  72794. ** initialized as for INCRINIT_NORMAL and the aFile[1] buffer belonging to
  72795. ** pReadr is populated. However, pReadr itself is not set up to point
  72796. ** to its first key. A call to vdbePmaReaderNext() is still required to do
  72797. ** that.
  72798. **
  72799. ** The reason this function does not call vdbePmaReaderNext() immediately
  72800. ** in the INCRINIT_TASK case is that vdbePmaReaderNext() assumes that it has
  72801. ** to block on thread (pTask->thread) before accessing aFile[1]. But, since
  72802. ** this entire function is being run by thread (pTask->thread), that will
  72803. ** lead to the current background thread attempting to join itself.
  72804. **
  72805. ** Finally, if argument eMode is set to INCRINIT_ROOT, it may be assumed
  72806. ** that pReadr->pIncr is a multi-threaded IncrMerge objects, and that all
  72807. ** child-trees have already been initialized using IncrInit(INCRINIT_TASK).
  72808. ** In this case vdbePmaReaderNext() is called on all child PmaReaders and
  72809. ** the current PmaReader set to point to the first key in its range.
  72810. **
  72811. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  72812. */
  72813. static int vdbePmaReaderIncrMergeInit(PmaReader *pReadr, int eMode){
  72814. int rc = SQLITE_OK;
  72815. IncrMerger *pIncr = pReadr->pIncr;
  72816. /* eMode is always INCRINIT_NORMAL in single-threaded mode */
  72817. assert( SQLITE_MAX_WORKER_THREADS>0 || eMode==INCRINIT_NORMAL );
  72818. if( pIncr ){
  72819. SortSubtask *pTask = pIncr->pTask;
  72820. sqlite3 *db = pTask->pSorter->db;
  72821. rc = vdbeMergeEngineInit(pTask, pIncr->pMerger, eMode);
  72822. /* Set up the required files for pIncr. A multi-theaded IncrMerge object
  72823. ** requires two temp files to itself, whereas a single-threaded object
  72824. ** only requires a region of pTask->file2. */
  72825. if( rc==SQLITE_OK ){
  72826. int mxSz = pIncr->mxSz;
  72827. #if SQLITE_MAX_WORKER_THREADS>0
  72828. if( pIncr->bUseThread ){
  72829. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[0].pFd);
  72830. if( rc==SQLITE_OK ){
  72831. rc = vdbeSorterOpenTempFile(db, mxSz, &pIncr->aFile[1].pFd);
  72832. }
  72833. }else
  72834. #endif
  72835. /*if( !pIncr->bUseThread )*/{
  72836. if( pTask->file2.pFd==0 ){
  72837. assert( pTask->file2.iEof>0 );
  72838. rc = vdbeSorterOpenTempFile(db, pTask->file2.iEof, &pTask->file2.pFd);
  72839. pTask->file2.iEof = 0;
  72840. }
  72841. if( rc==SQLITE_OK ){
  72842. pIncr->aFile[1].pFd = pTask->file2.pFd;
  72843. pIncr->iStartOff = pTask->file2.iEof;
  72844. pTask->file2.iEof += mxSz;
  72845. }
  72846. }
  72847. }
  72848. #if SQLITE_MAX_WORKER_THREADS>0
  72849. if( rc==SQLITE_OK && pIncr->bUseThread ){
  72850. /* Use the current thread to populate aFile[1], even though this
  72851. ** PmaReader is multi-threaded. The reason being that this function
  72852. ** is already running in background thread pIncr->pTask->thread. */
  72853. assert( eMode==INCRINIT_ROOT || eMode==INCRINIT_TASK );
  72854. rc = vdbeIncrPopulate(pIncr);
  72855. }
  72856. #endif
  72857. if( rc==SQLITE_OK
  72858. && (SQLITE_MAX_WORKER_THREADS==0 || eMode!=INCRINIT_TASK)
  72859. ){
  72860. rc = vdbePmaReaderNext(pReadr);
  72861. }
  72862. }
  72863. return rc;
  72864. }
  72865. #if SQLITE_MAX_WORKER_THREADS>0
  72866. /*
  72867. ** The main routine for vdbePmaReaderIncrMergeInit() operations run in
  72868. ** background threads.
  72869. */
  72870. static void *vdbePmaReaderBgInit(void *pCtx){
  72871. PmaReader *pReader = (PmaReader*)pCtx;
  72872. void *pRet = SQLITE_INT_TO_PTR(
  72873. vdbePmaReaderIncrMergeInit(pReader,INCRINIT_TASK)
  72874. );
  72875. pReader->pIncr->pTask->bDone = 1;
  72876. return pRet;
  72877. }
  72878. /*
  72879. ** Use a background thread to invoke vdbePmaReaderIncrMergeInit(INCRINIT_TASK)
  72880. ** on the PmaReader object passed as the first argument.
  72881. **
  72882. ** This call will initialize the various fields of the pReadr->pIncr
  72883. ** structure and, if it is a multi-threaded IncrMerger, launch a
  72884. ** background thread to populate aFile[1].
  72885. */
  72886. static int vdbePmaReaderBgIncrInit(PmaReader *pReadr){
  72887. void *pCtx = (void*)pReadr;
  72888. return vdbeSorterCreateThread(pReadr->pIncr->pTask, vdbePmaReaderBgInit, pCtx);
  72889. }
  72890. #endif
  72891. /*
  72892. ** Allocate a new MergeEngine object to merge the contents of nPMA level-0
  72893. ** PMAs from pTask->file. If no error occurs, set *ppOut to point to
  72894. ** the new object and return SQLITE_OK. Or, if an error does occur, set *ppOut
  72895. ** to NULL and return an SQLite error code.
  72896. **
  72897. ** When this function is called, *piOffset is set to the offset of the
  72898. ** first PMA to read from pTask->file. Assuming no error occurs, it is
  72899. ** set to the offset immediately following the last byte of the last
  72900. ** PMA before returning. If an error does occur, then the final value of
  72901. ** *piOffset is undefined.
  72902. */
  72903. static int vdbeMergeEngineLevel0(
  72904. SortSubtask *pTask, /* Sorter task to read from */
  72905. int nPMA, /* Number of PMAs to read */
  72906. i64 *piOffset, /* IN/OUT: Readr offset in pTask->file */
  72907. MergeEngine **ppOut /* OUT: New merge-engine */
  72908. ){
  72909. MergeEngine *pNew; /* Merge engine to return */
  72910. i64 iOff = *piOffset;
  72911. int i;
  72912. int rc = SQLITE_OK;
  72913. *ppOut = pNew = vdbeMergeEngineNew(nPMA);
  72914. if( pNew==0 ) rc = SQLITE_NOMEM;
  72915. for(i=0; i<nPMA && rc==SQLITE_OK; i++){
  72916. i64 nDummy;
  72917. PmaReader *pReadr = &pNew->aReadr[i];
  72918. rc = vdbePmaReaderInit(pTask, &pTask->file, iOff, pReadr, &nDummy);
  72919. iOff = pReadr->iEof;
  72920. }
  72921. if( rc!=SQLITE_OK ){
  72922. vdbeMergeEngineFree(pNew);
  72923. *ppOut = 0;
  72924. }
  72925. *piOffset = iOff;
  72926. return rc;
  72927. }
  72928. /*
  72929. ** Return the depth of a tree comprising nPMA PMAs, assuming a fanout of
  72930. ** SORTER_MAX_MERGE_COUNT. The returned value does not include leaf nodes.
  72931. **
  72932. ** i.e.
  72933. **
  72934. ** nPMA<=16 -> TreeDepth() == 0
  72935. ** nPMA<=256 -> TreeDepth() == 1
  72936. ** nPMA<=65536 -> TreeDepth() == 2
  72937. */
  72938. static int vdbeSorterTreeDepth(int nPMA){
  72939. int nDepth = 0;
  72940. i64 nDiv = SORTER_MAX_MERGE_COUNT;
  72941. while( nDiv < (i64)nPMA ){
  72942. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  72943. nDepth++;
  72944. }
  72945. return nDepth;
  72946. }
  72947. /*
  72948. ** pRoot is the root of an incremental merge-tree with depth nDepth (according
  72949. ** to vdbeSorterTreeDepth()). pLeaf is the iSeq'th leaf to be added to the
  72950. ** tree, counting from zero. This function adds pLeaf to the tree.
  72951. **
  72952. ** If successful, SQLITE_OK is returned. If an error occurs, an SQLite error
  72953. ** code is returned and pLeaf is freed.
  72954. */
  72955. static int vdbeSorterAddToTree(
  72956. SortSubtask *pTask, /* Task context */
  72957. int nDepth, /* Depth of tree according to TreeDepth() */
  72958. int iSeq, /* Sequence number of leaf within tree */
  72959. MergeEngine *pRoot, /* Root of tree */
  72960. MergeEngine *pLeaf /* Leaf to add to tree */
  72961. ){
  72962. int rc = SQLITE_OK;
  72963. int nDiv = 1;
  72964. int i;
  72965. MergeEngine *p = pRoot;
  72966. IncrMerger *pIncr;
  72967. rc = vdbeIncrMergerNew(pTask, pLeaf, &pIncr);
  72968. for(i=1; i<nDepth; i++){
  72969. nDiv = nDiv * SORTER_MAX_MERGE_COUNT;
  72970. }
  72971. for(i=1; i<nDepth && rc==SQLITE_OK; i++){
  72972. int iIter = (iSeq / nDiv) % SORTER_MAX_MERGE_COUNT;
  72973. PmaReader *pReadr = &p->aReadr[iIter];
  72974. if( pReadr->pIncr==0 ){
  72975. MergeEngine *pNew = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  72976. if( pNew==0 ){
  72977. rc = SQLITE_NOMEM;
  72978. }else{
  72979. rc = vdbeIncrMergerNew(pTask, pNew, &pReadr->pIncr);
  72980. }
  72981. }
  72982. if( rc==SQLITE_OK ){
  72983. p = pReadr->pIncr->pMerger;
  72984. nDiv = nDiv / SORTER_MAX_MERGE_COUNT;
  72985. }
  72986. }
  72987. if( rc==SQLITE_OK ){
  72988. p->aReadr[iSeq % SORTER_MAX_MERGE_COUNT].pIncr = pIncr;
  72989. }else{
  72990. vdbeIncrFree(pIncr);
  72991. }
  72992. return rc;
  72993. }
  72994. /*
  72995. ** This function is called as part of a SorterRewind() operation on a sorter
  72996. ** that has already written two or more level-0 PMAs to one or more temp
  72997. ** files. It builds a tree of MergeEngine/IncrMerger/PmaReader objects that
  72998. ** can be used to incrementally merge all PMAs on disk.
  72999. **
  73000. ** If successful, SQLITE_OK is returned and *ppOut set to point to the
  73001. ** MergeEngine object at the root of the tree before returning. Or, if an
  73002. ** error occurs, an SQLite error code is returned and the final value
  73003. ** of *ppOut is undefined.
  73004. */
  73005. static int vdbeSorterMergeTreeBuild(
  73006. VdbeSorter *pSorter, /* The VDBE cursor that implements the sort */
  73007. MergeEngine **ppOut /* Write the MergeEngine here */
  73008. ){
  73009. MergeEngine *pMain = 0;
  73010. int rc = SQLITE_OK;
  73011. int iTask;
  73012. #if SQLITE_MAX_WORKER_THREADS>0
  73013. /* If the sorter uses more than one task, then create the top-level
  73014. ** MergeEngine here. This MergeEngine will read data from exactly
  73015. ** one PmaReader per sub-task. */
  73016. assert( pSorter->bUseThreads || pSorter->nTask==1 );
  73017. if( pSorter->nTask>1 ){
  73018. pMain = vdbeMergeEngineNew(pSorter->nTask);
  73019. if( pMain==0 ) rc = SQLITE_NOMEM;
  73020. }
  73021. #endif
  73022. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  73023. SortSubtask *pTask = &pSorter->aTask[iTask];
  73024. assert( pTask->nPMA>0 || SQLITE_MAX_WORKER_THREADS>0 );
  73025. if( SQLITE_MAX_WORKER_THREADS==0 || pTask->nPMA ){
  73026. MergeEngine *pRoot = 0; /* Root node of tree for this task */
  73027. int nDepth = vdbeSorterTreeDepth(pTask->nPMA);
  73028. i64 iReadOff = 0;
  73029. if( pTask->nPMA<=SORTER_MAX_MERGE_COUNT ){
  73030. rc = vdbeMergeEngineLevel0(pTask, pTask->nPMA, &iReadOff, &pRoot);
  73031. }else{
  73032. int i;
  73033. int iSeq = 0;
  73034. pRoot = vdbeMergeEngineNew(SORTER_MAX_MERGE_COUNT);
  73035. if( pRoot==0 ) rc = SQLITE_NOMEM;
  73036. for(i=0; i<pTask->nPMA && rc==SQLITE_OK; i += SORTER_MAX_MERGE_COUNT){
  73037. MergeEngine *pMerger = 0; /* New level-0 PMA merger */
  73038. int nReader; /* Number of level-0 PMAs to merge */
  73039. nReader = MIN(pTask->nPMA - i, SORTER_MAX_MERGE_COUNT);
  73040. rc = vdbeMergeEngineLevel0(pTask, nReader, &iReadOff, &pMerger);
  73041. if( rc==SQLITE_OK ){
  73042. rc = vdbeSorterAddToTree(pTask, nDepth, iSeq++, pRoot, pMerger);
  73043. }
  73044. }
  73045. }
  73046. if( rc==SQLITE_OK ){
  73047. #if SQLITE_MAX_WORKER_THREADS>0
  73048. if( pMain!=0 ){
  73049. rc = vdbeIncrMergerNew(pTask, pRoot, &pMain->aReadr[iTask].pIncr);
  73050. }else
  73051. #endif
  73052. {
  73053. assert( pMain==0 );
  73054. pMain = pRoot;
  73055. }
  73056. }else{
  73057. vdbeMergeEngineFree(pRoot);
  73058. }
  73059. }
  73060. }
  73061. if( rc!=SQLITE_OK ){
  73062. vdbeMergeEngineFree(pMain);
  73063. pMain = 0;
  73064. }
  73065. *ppOut = pMain;
  73066. return rc;
  73067. }
  73068. /*
  73069. ** This function is called as part of an sqlite3VdbeSorterRewind() operation
  73070. ** on a sorter that has written two or more PMAs to temporary files. It sets
  73071. ** up either VdbeSorter.pMerger (for single threaded sorters) or pReader
  73072. ** (for multi-threaded sorters) so that it can be used to iterate through
  73073. ** all records stored in the sorter.
  73074. **
  73075. ** SQLITE_OK is returned if successful, or an SQLite error code otherwise.
  73076. */
  73077. static int vdbeSorterSetupMerge(VdbeSorter *pSorter){
  73078. int rc; /* Return code */
  73079. SortSubtask *pTask0 = &pSorter->aTask[0];
  73080. MergeEngine *pMain = 0;
  73081. #if SQLITE_MAX_WORKER_THREADS
  73082. sqlite3 *db = pTask0->pSorter->db;
  73083. #endif
  73084. rc = vdbeSorterMergeTreeBuild(pSorter, &pMain);
  73085. if( rc==SQLITE_OK ){
  73086. #if SQLITE_MAX_WORKER_THREADS
  73087. assert( pSorter->bUseThreads==0 || pSorter->nTask>1 );
  73088. if( pSorter->bUseThreads ){
  73089. int iTask;
  73090. PmaReader *pReadr = 0;
  73091. SortSubtask *pLast = &pSorter->aTask[pSorter->nTask-1];
  73092. rc = vdbeSortAllocUnpacked(pLast);
  73093. if( rc==SQLITE_OK ){
  73094. pReadr = (PmaReader*)sqlite3DbMallocZero(db, sizeof(PmaReader));
  73095. pSorter->pReader = pReadr;
  73096. if( pReadr==0 ) rc = SQLITE_NOMEM;
  73097. }
  73098. if( rc==SQLITE_OK ){
  73099. rc = vdbeIncrMergerNew(pLast, pMain, &pReadr->pIncr);
  73100. if( rc==SQLITE_OK ){
  73101. vdbeIncrMergerSetThreads(pReadr->pIncr);
  73102. for(iTask=0; iTask<(pSorter->nTask-1); iTask++){
  73103. IncrMerger *pIncr;
  73104. if( (pIncr = pMain->aReadr[iTask].pIncr) ){
  73105. vdbeIncrMergerSetThreads(pIncr);
  73106. assert( pIncr->pTask!=pLast );
  73107. }
  73108. }
  73109. for(iTask=0; rc==SQLITE_OK && iTask<pSorter->nTask; iTask++){
  73110. PmaReader *p = &pMain->aReadr[iTask];
  73111. assert( p->pIncr==0 || p->pIncr->pTask==&pSorter->aTask[iTask] );
  73112. if( p->pIncr ){
  73113. if( iTask==pSorter->nTask-1 ){
  73114. rc = vdbePmaReaderIncrMergeInit(p, INCRINIT_TASK);
  73115. }else{
  73116. rc = vdbePmaReaderBgIncrInit(p);
  73117. }
  73118. }
  73119. }
  73120. }
  73121. pMain = 0;
  73122. }
  73123. if( rc==SQLITE_OK ){
  73124. rc = vdbePmaReaderIncrMergeInit(pReadr, INCRINIT_ROOT);
  73125. }
  73126. }else
  73127. #endif
  73128. {
  73129. rc = vdbeMergeEngineInit(pTask0, pMain, INCRINIT_NORMAL);
  73130. pSorter->pMerger = pMain;
  73131. pMain = 0;
  73132. }
  73133. }
  73134. if( rc!=SQLITE_OK ){
  73135. vdbeMergeEngineFree(pMain);
  73136. }
  73137. return rc;
  73138. }
  73139. /*
  73140. ** Once the sorter has been populated by calls to sqlite3VdbeSorterWrite,
  73141. ** this function is called to prepare for iterating through the records
  73142. ** in sorted order.
  73143. */
  73144. SQLITE_PRIVATE int sqlite3VdbeSorterRewind(const VdbeCursor *pCsr, int *pbEof){
  73145. VdbeSorter *pSorter = pCsr->pSorter;
  73146. int rc = SQLITE_OK; /* Return code */
  73147. assert( pSorter );
  73148. /* If no data has been written to disk, then do not do so now. Instead,
  73149. ** sort the VdbeSorter.pRecord list. The vdbe layer will read data directly
  73150. ** from the in-memory list. */
  73151. if( pSorter->bUsePMA==0 ){
  73152. if( pSorter->list.pList ){
  73153. *pbEof = 0;
  73154. rc = vdbeSorterSort(&pSorter->aTask[0], &pSorter->list);
  73155. }else{
  73156. *pbEof = 1;
  73157. }
  73158. return rc;
  73159. }
  73160. /* Write the current in-memory list to a PMA. When the VdbeSorterWrite()
  73161. ** function flushes the contents of memory to disk, it immediately always
  73162. ** creates a new list consisting of a single key immediately afterwards.
  73163. ** So the list is never empty at this point. */
  73164. assert( pSorter->list.pList );
  73165. rc = vdbeSorterFlushPMA(pSorter);
  73166. /* Join all threads */
  73167. rc = vdbeSorterJoinAll(pSorter, rc);
  73168. vdbeSorterRewindDebug("rewind");
  73169. /* Assuming no errors have occurred, set up a merger structure to
  73170. ** incrementally read and merge all remaining PMAs. */
  73171. assert( pSorter->pReader==0 );
  73172. if( rc==SQLITE_OK ){
  73173. rc = vdbeSorterSetupMerge(pSorter);
  73174. *pbEof = 0;
  73175. }
  73176. vdbeSorterRewindDebug("rewinddone");
  73177. return rc;
  73178. }
  73179. /*
  73180. ** Advance to the next element in the sorter.
  73181. */
  73182. SQLITE_PRIVATE int sqlite3VdbeSorterNext(sqlite3 *db, const VdbeCursor *pCsr, int *pbEof){
  73183. VdbeSorter *pSorter = pCsr->pSorter;
  73184. int rc; /* Return code */
  73185. assert( pSorter->bUsePMA || (pSorter->pReader==0 && pSorter->pMerger==0) );
  73186. if( pSorter->bUsePMA ){
  73187. assert( pSorter->pReader==0 || pSorter->pMerger==0 );
  73188. assert( pSorter->bUseThreads==0 || pSorter->pReader );
  73189. assert( pSorter->bUseThreads==1 || pSorter->pMerger );
  73190. #if SQLITE_MAX_WORKER_THREADS>0
  73191. if( pSorter->bUseThreads ){
  73192. rc = vdbePmaReaderNext(pSorter->pReader);
  73193. *pbEof = (pSorter->pReader->pFd==0);
  73194. }else
  73195. #endif
  73196. /*if( !pSorter->bUseThreads )*/ {
  73197. assert( pSorter->pMerger->pTask==(&pSorter->aTask[0]) );
  73198. rc = vdbeMergeEngineStep(pSorter->pMerger, pbEof);
  73199. }
  73200. }else{
  73201. SorterRecord *pFree = pSorter->list.pList;
  73202. pSorter->list.pList = pFree->u.pNext;
  73203. pFree->u.pNext = 0;
  73204. if( pSorter->list.aMemory==0 ) vdbeSorterRecordFree(db, pFree);
  73205. *pbEof = !pSorter->list.pList;
  73206. rc = SQLITE_OK;
  73207. }
  73208. return rc;
  73209. }
  73210. /*
  73211. ** Return a pointer to a buffer owned by the sorter that contains the
  73212. ** current key.
  73213. */
  73214. static void *vdbeSorterRowkey(
  73215. const VdbeSorter *pSorter, /* Sorter object */
  73216. int *pnKey /* OUT: Size of current key in bytes */
  73217. ){
  73218. void *pKey;
  73219. if( pSorter->bUsePMA ){
  73220. PmaReader *pReader;
  73221. #if SQLITE_MAX_WORKER_THREADS>0
  73222. if( pSorter->bUseThreads ){
  73223. pReader = pSorter->pReader;
  73224. }else
  73225. #endif
  73226. /*if( !pSorter->bUseThreads )*/{
  73227. pReader = &pSorter->pMerger->aReadr[pSorter->pMerger->aTree[1]];
  73228. }
  73229. *pnKey = pReader->nKey;
  73230. pKey = pReader->aKey;
  73231. }else{
  73232. *pnKey = pSorter->list.pList->nVal;
  73233. pKey = SRVAL(pSorter->list.pList);
  73234. }
  73235. return pKey;
  73236. }
  73237. /*
  73238. ** Copy the current sorter key into the memory cell pOut.
  73239. */
  73240. SQLITE_PRIVATE int sqlite3VdbeSorterRowkey(const VdbeCursor *pCsr, Mem *pOut){
  73241. VdbeSorter *pSorter = pCsr->pSorter;
  73242. void *pKey; int nKey; /* Sorter key to copy into pOut */
  73243. pKey = vdbeSorterRowkey(pSorter, &nKey);
  73244. if( sqlite3VdbeMemClearAndResize(pOut, nKey) ){
  73245. return SQLITE_NOMEM;
  73246. }
  73247. pOut->n = nKey;
  73248. MemSetTypeFlag(pOut, MEM_Blob);
  73249. memcpy(pOut->z, pKey, nKey);
  73250. return SQLITE_OK;
  73251. }
  73252. /*
  73253. ** Compare the key in memory cell pVal with the key that the sorter cursor
  73254. ** passed as the first argument currently points to. For the purposes of
  73255. ** the comparison, ignore the rowid field at the end of each record.
  73256. **
  73257. ** If the sorter cursor key contains any NULL values, consider it to be
  73258. ** less than pVal. Even if pVal also contains NULL values.
  73259. **
  73260. ** If an error occurs, return an SQLite error code (i.e. SQLITE_NOMEM).
  73261. ** Otherwise, set *pRes to a negative, zero or positive value if the
  73262. ** key in pVal is smaller than, equal to or larger than the current sorter
  73263. ** key.
  73264. **
  73265. ** This routine forms the core of the OP_SorterCompare opcode, which in
  73266. ** turn is used to verify uniqueness when constructing a UNIQUE INDEX.
  73267. */
  73268. SQLITE_PRIVATE int sqlite3VdbeSorterCompare(
  73269. const VdbeCursor *pCsr, /* Sorter cursor */
  73270. Mem *pVal, /* Value to compare to current sorter key */
  73271. int nKeyCol, /* Compare this many columns */
  73272. int *pRes /* OUT: Result of comparison */
  73273. ){
  73274. VdbeSorter *pSorter = pCsr->pSorter;
  73275. UnpackedRecord *r2 = pSorter->pUnpacked;
  73276. KeyInfo *pKeyInfo = pCsr->pKeyInfo;
  73277. int i;
  73278. void *pKey; int nKey; /* Sorter key to compare pVal with */
  73279. if( r2==0 ){
  73280. char *p;
  73281. r2 = pSorter->pUnpacked = sqlite3VdbeAllocUnpackedRecord(pKeyInfo,0,0,&p);
  73282. assert( pSorter->pUnpacked==(UnpackedRecord*)p );
  73283. if( r2==0 ) return SQLITE_NOMEM;
  73284. r2->nField = nKeyCol;
  73285. }
  73286. assert( r2->nField==nKeyCol );
  73287. pKey = vdbeSorterRowkey(pSorter, &nKey);
  73288. sqlite3VdbeRecordUnpack(pKeyInfo, nKey, pKey, r2);
  73289. for(i=0; i<nKeyCol; i++){
  73290. if( r2->aMem[i].flags & MEM_Null ){
  73291. *pRes = -1;
  73292. return SQLITE_OK;
  73293. }
  73294. }
  73295. *pRes = sqlite3VdbeRecordCompare(pVal->n, pVal->z, r2);
  73296. return SQLITE_OK;
  73297. }
  73298. /************** End of vdbesort.c ********************************************/
  73299. /************** Begin file journal.c *****************************************/
  73300. /*
  73301. ** 2007 August 22
  73302. **
  73303. ** The author disclaims copyright to this source code. In place of
  73304. ** a legal notice, here is a blessing:
  73305. **
  73306. ** May you do good and not evil.
  73307. ** May you find forgiveness for yourself and forgive others.
  73308. ** May you share freely, never taking more than you give.
  73309. **
  73310. *************************************************************************
  73311. **
  73312. ** This file implements a special kind of sqlite3_file object used
  73313. ** by SQLite to create journal files if the atomic-write optimization
  73314. ** is enabled.
  73315. **
  73316. ** The distinctive characteristic of this sqlite3_file is that the
  73317. ** actual on disk file is created lazily. When the file is created,
  73318. ** the caller specifies a buffer size for an in-memory buffer to
  73319. ** be used to service read() and write() requests. The actual file
  73320. ** on disk is not created or populated until either:
  73321. **
  73322. ** 1) The in-memory representation grows too large for the allocated
  73323. ** buffer, or
  73324. ** 2) The sqlite3JournalCreate() function is called.
  73325. */
  73326. #ifdef SQLITE_ENABLE_ATOMIC_WRITE
  73327. /*
  73328. ** A JournalFile object is a subclass of sqlite3_file used by
  73329. ** as an open file handle for journal files.
  73330. */
  73331. struct JournalFile {
  73332. sqlite3_io_methods *pMethod; /* I/O methods on journal files */
  73333. int nBuf; /* Size of zBuf[] in bytes */
  73334. char *zBuf; /* Space to buffer journal writes */
  73335. int iSize; /* Amount of zBuf[] currently used */
  73336. int flags; /* xOpen flags */
  73337. sqlite3_vfs *pVfs; /* The "real" underlying VFS */
  73338. sqlite3_file *pReal; /* The "real" underlying file descriptor */
  73339. const char *zJournal; /* Name of the journal file */
  73340. };
  73341. typedef struct JournalFile JournalFile;
  73342. /*
  73343. ** If it does not already exists, create and populate the on-disk file
  73344. ** for JournalFile p.
  73345. */
  73346. static int createFile(JournalFile *p){
  73347. int rc = SQLITE_OK;
  73348. if( !p->pReal ){
  73349. sqlite3_file *pReal = (sqlite3_file *)&p[1];
  73350. rc = sqlite3OsOpen(p->pVfs, p->zJournal, pReal, p->flags, 0);
  73351. if( rc==SQLITE_OK ){
  73352. p->pReal = pReal;
  73353. if( p->iSize>0 ){
  73354. assert(p->iSize<=p->nBuf);
  73355. rc = sqlite3OsWrite(p->pReal, p->zBuf, p->iSize, 0);
  73356. }
  73357. if( rc!=SQLITE_OK ){
  73358. /* If an error occurred while writing to the file, close it before
  73359. ** returning. This way, SQLite uses the in-memory journal data to
  73360. ** roll back changes made to the internal page-cache before this
  73361. ** function was called. */
  73362. sqlite3OsClose(pReal);
  73363. p->pReal = 0;
  73364. }
  73365. }
  73366. }
  73367. return rc;
  73368. }
  73369. /*
  73370. ** Close the file.
  73371. */
  73372. static int jrnlClose(sqlite3_file *pJfd){
  73373. JournalFile *p = (JournalFile *)pJfd;
  73374. if( p->pReal ){
  73375. sqlite3OsClose(p->pReal);
  73376. }
  73377. sqlite3_free(p->zBuf);
  73378. return SQLITE_OK;
  73379. }
  73380. /*
  73381. ** Read data from the file.
  73382. */
  73383. static int jrnlRead(
  73384. sqlite3_file *pJfd, /* The journal file from which to read */
  73385. void *zBuf, /* Put the results here */
  73386. int iAmt, /* Number of bytes to read */
  73387. sqlite_int64 iOfst /* Begin reading at this offset */
  73388. ){
  73389. int rc = SQLITE_OK;
  73390. JournalFile *p = (JournalFile *)pJfd;
  73391. if( p->pReal ){
  73392. rc = sqlite3OsRead(p->pReal, zBuf, iAmt, iOfst);
  73393. }else if( (iAmt+iOfst)>p->iSize ){
  73394. rc = SQLITE_IOERR_SHORT_READ;
  73395. }else{
  73396. memcpy(zBuf, &p->zBuf[iOfst], iAmt);
  73397. }
  73398. return rc;
  73399. }
  73400. /*
  73401. ** Write data to the file.
  73402. */
  73403. static int jrnlWrite(
  73404. sqlite3_file *pJfd, /* The journal file into which to write */
  73405. const void *zBuf, /* Take data to be written from here */
  73406. int iAmt, /* Number of bytes to write */
  73407. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  73408. ){
  73409. int rc = SQLITE_OK;
  73410. JournalFile *p = (JournalFile *)pJfd;
  73411. if( !p->pReal && (iOfst+iAmt)>p->nBuf ){
  73412. rc = createFile(p);
  73413. }
  73414. if( rc==SQLITE_OK ){
  73415. if( p->pReal ){
  73416. rc = sqlite3OsWrite(p->pReal, zBuf, iAmt, iOfst);
  73417. }else{
  73418. memcpy(&p->zBuf[iOfst], zBuf, iAmt);
  73419. if( p->iSize<(iOfst+iAmt) ){
  73420. p->iSize = (iOfst+iAmt);
  73421. }
  73422. }
  73423. }
  73424. return rc;
  73425. }
  73426. /*
  73427. ** Truncate the file.
  73428. */
  73429. static int jrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  73430. int rc = SQLITE_OK;
  73431. JournalFile *p = (JournalFile *)pJfd;
  73432. if( p->pReal ){
  73433. rc = sqlite3OsTruncate(p->pReal, size);
  73434. }else if( size<p->iSize ){
  73435. p->iSize = size;
  73436. }
  73437. return rc;
  73438. }
  73439. /*
  73440. ** Sync the file.
  73441. */
  73442. static int jrnlSync(sqlite3_file *pJfd, int flags){
  73443. int rc;
  73444. JournalFile *p = (JournalFile *)pJfd;
  73445. if( p->pReal ){
  73446. rc = sqlite3OsSync(p->pReal, flags);
  73447. }else{
  73448. rc = SQLITE_OK;
  73449. }
  73450. return rc;
  73451. }
  73452. /*
  73453. ** Query the size of the file in bytes.
  73454. */
  73455. static int jrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  73456. int rc = SQLITE_OK;
  73457. JournalFile *p = (JournalFile *)pJfd;
  73458. if( p->pReal ){
  73459. rc = sqlite3OsFileSize(p->pReal, pSize);
  73460. }else{
  73461. *pSize = (sqlite_int64) p->iSize;
  73462. }
  73463. return rc;
  73464. }
  73465. /*
  73466. ** Table of methods for JournalFile sqlite3_file object.
  73467. */
  73468. static struct sqlite3_io_methods JournalFileMethods = {
  73469. 1, /* iVersion */
  73470. jrnlClose, /* xClose */
  73471. jrnlRead, /* xRead */
  73472. jrnlWrite, /* xWrite */
  73473. jrnlTruncate, /* xTruncate */
  73474. jrnlSync, /* xSync */
  73475. jrnlFileSize, /* xFileSize */
  73476. 0, /* xLock */
  73477. 0, /* xUnlock */
  73478. 0, /* xCheckReservedLock */
  73479. 0, /* xFileControl */
  73480. 0, /* xSectorSize */
  73481. 0, /* xDeviceCharacteristics */
  73482. 0, /* xShmMap */
  73483. 0, /* xShmLock */
  73484. 0, /* xShmBarrier */
  73485. 0 /* xShmUnmap */
  73486. };
  73487. /*
  73488. ** Open a journal file.
  73489. */
  73490. SQLITE_PRIVATE int sqlite3JournalOpen(
  73491. sqlite3_vfs *pVfs, /* The VFS to use for actual file I/O */
  73492. const char *zName, /* Name of the journal file */
  73493. sqlite3_file *pJfd, /* Preallocated, blank file handle */
  73494. int flags, /* Opening flags */
  73495. int nBuf /* Bytes buffered before opening the file */
  73496. ){
  73497. JournalFile *p = (JournalFile *)pJfd;
  73498. memset(p, 0, sqlite3JournalSize(pVfs));
  73499. if( nBuf>0 ){
  73500. p->zBuf = sqlite3MallocZero(nBuf);
  73501. if( !p->zBuf ){
  73502. return SQLITE_NOMEM;
  73503. }
  73504. }else{
  73505. return sqlite3OsOpen(pVfs, zName, pJfd, flags, 0);
  73506. }
  73507. p->pMethod = &JournalFileMethods;
  73508. p->nBuf = nBuf;
  73509. p->flags = flags;
  73510. p->zJournal = zName;
  73511. p->pVfs = pVfs;
  73512. return SQLITE_OK;
  73513. }
  73514. /*
  73515. ** If the argument p points to a JournalFile structure, and the underlying
  73516. ** file has not yet been created, create it now.
  73517. */
  73518. SQLITE_PRIVATE int sqlite3JournalCreate(sqlite3_file *p){
  73519. if( p->pMethods!=&JournalFileMethods ){
  73520. return SQLITE_OK;
  73521. }
  73522. return createFile((JournalFile *)p);
  73523. }
  73524. /*
  73525. ** The file-handle passed as the only argument is guaranteed to be an open
  73526. ** file. It may or may not be of class JournalFile. If the file is a
  73527. ** JournalFile, and the underlying file on disk has not yet been opened,
  73528. ** return 0. Otherwise, return 1.
  73529. */
  73530. SQLITE_PRIVATE int sqlite3JournalExists(sqlite3_file *p){
  73531. return (p->pMethods!=&JournalFileMethods || ((JournalFile *)p)->pReal!=0);
  73532. }
  73533. /*
  73534. ** Return the number of bytes required to store a JournalFile that uses vfs
  73535. ** pVfs to create the underlying on-disk files.
  73536. */
  73537. SQLITE_PRIVATE int sqlite3JournalSize(sqlite3_vfs *pVfs){
  73538. return (pVfs->szOsFile+sizeof(JournalFile));
  73539. }
  73540. #endif
  73541. /************** End of journal.c *********************************************/
  73542. /************** Begin file memjournal.c **************************************/
  73543. /*
  73544. ** 2008 October 7
  73545. **
  73546. ** The author disclaims copyright to this source code. In place of
  73547. ** a legal notice, here is a blessing:
  73548. **
  73549. ** May you do good and not evil.
  73550. ** May you find forgiveness for yourself and forgive others.
  73551. ** May you share freely, never taking more than you give.
  73552. **
  73553. *************************************************************************
  73554. **
  73555. ** This file contains code use to implement an in-memory rollback journal.
  73556. ** The in-memory rollback journal is used to journal transactions for
  73557. ** ":memory:" databases and when the journal_mode=MEMORY pragma is used.
  73558. */
  73559. /* Forward references to internal structures */
  73560. typedef struct MemJournal MemJournal;
  73561. typedef struct FilePoint FilePoint;
  73562. typedef struct FileChunk FileChunk;
  73563. /* Space to hold the rollback journal is allocated in increments of
  73564. ** this many bytes.
  73565. **
  73566. ** The size chosen is a little less than a power of two. That way,
  73567. ** the FileChunk object will have a size that almost exactly fills
  73568. ** a power-of-two allocation. This minimizes wasted space in power-of-two
  73569. ** memory allocators.
  73570. */
  73571. #define JOURNAL_CHUNKSIZE ((int)(1024-sizeof(FileChunk*)))
  73572. /*
  73573. ** The rollback journal is composed of a linked list of these structures.
  73574. */
  73575. struct FileChunk {
  73576. FileChunk *pNext; /* Next chunk in the journal */
  73577. u8 zChunk[JOURNAL_CHUNKSIZE]; /* Content of this chunk */
  73578. };
  73579. /*
  73580. ** An instance of this object serves as a cursor into the rollback journal.
  73581. ** The cursor can be either for reading or writing.
  73582. */
  73583. struct FilePoint {
  73584. sqlite3_int64 iOffset; /* Offset from the beginning of the file */
  73585. FileChunk *pChunk; /* Specific chunk into which cursor points */
  73586. };
  73587. /*
  73588. ** This subclass is a subclass of sqlite3_file. Each open memory-journal
  73589. ** is an instance of this class.
  73590. */
  73591. struct MemJournal {
  73592. sqlite3_io_methods *pMethod; /* Parent class. MUST BE FIRST */
  73593. FileChunk *pFirst; /* Head of in-memory chunk-list */
  73594. FilePoint endpoint; /* Pointer to the end of the file */
  73595. FilePoint readpoint; /* Pointer to the end of the last xRead() */
  73596. };
  73597. /*
  73598. ** Read data from the in-memory journal file. This is the implementation
  73599. ** of the sqlite3_vfs.xRead method.
  73600. */
  73601. static int memjrnlRead(
  73602. sqlite3_file *pJfd, /* The journal file from which to read */
  73603. void *zBuf, /* Put the results here */
  73604. int iAmt, /* Number of bytes to read */
  73605. sqlite_int64 iOfst /* Begin reading at this offset */
  73606. ){
  73607. MemJournal *p = (MemJournal *)pJfd;
  73608. u8 *zOut = zBuf;
  73609. int nRead = iAmt;
  73610. int iChunkOffset;
  73611. FileChunk *pChunk;
  73612. /* SQLite never tries to read past the end of a rollback journal file */
  73613. assert( iOfst+iAmt<=p->endpoint.iOffset );
  73614. if( p->readpoint.iOffset!=iOfst || iOfst==0 ){
  73615. sqlite3_int64 iOff = 0;
  73616. for(pChunk=p->pFirst;
  73617. ALWAYS(pChunk) && (iOff+JOURNAL_CHUNKSIZE)<=iOfst;
  73618. pChunk=pChunk->pNext
  73619. ){
  73620. iOff += JOURNAL_CHUNKSIZE;
  73621. }
  73622. }else{
  73623. pChunk = p->readpoint.pChunk;
  73624. }
  73625. iChunkOffset = (int)(iOfst%JOURNAL_CHUNKSIZE);
  73626. do {
  73627. int iSpace = JOURNAL_CHUNKSIZE - iChunkOffset;
  73628. int nCopy = MIN(nRead, (JOURNAL_CHUNKSIZE - iChunkOffset));
  73629. memcpy(zOut, &pChunk->zChunk[iChunkOffset], nCopy);
  73630. zOut += nCopy;
  73631. nRead -= iSpace;
  73632. iChunkOffset = 0;
  73633. } while( nRead>=0 && (pChunk=pChunk->pNext)!=0 && nRead>0 );
  73634. p->readpoint.iOffset = iOfst+iAmt;
  73635. p->readpoint.pChunk = pChunk;
  73636. return SQLITE_OK;
  73637. }
  73638. /*
  73639. ** Write data to the file.
  73640. */
  73641. static int memjrnlWrite(
  73642. sqlite3_file *pJfd, /* The journal file into which to write */
  73643. const void *zBuf, /* Take data to be written from here */
  73644. int iAmt, /* Number of bytes to write */
  73645. sqlite_int64 iOfst /* Begin writing at this offset into the file */
  73646. ){
  73647. MemJournal *p = (MemJournal *)pJfd;
  73648. int nWrite = iAmt;
  73649. u8 *zWrite = (u8 *)zBuf;
  73650. /* An in-memory journal file should only ever be appended to. Random
  73651. ** access writes are not required by sqlite.
  73652. */
  73653. assert( iOfst==p->endpoint.iOffset );
  73654. UNUSED_PARAMETER(iOfst);
  73655. while( nWrite>0 ){
  73656. FileChunk *pChunk = p->endpoint.pChunk;
  73657. int iChunkOffset = (int)(p->endpoint.iOffset%JOURNAL_CHUNKSIZE);
  73658. int iSpace = MIN(nWrite, JOURNAL_CHUNKSIZE - iChunkOffset);
  73659. if( iChunkOffset==0 ){
  73660. /* New chunk is required to extend the file. */
  73661. FileChunk *pNew = sqlite3_malloc(sizeof(FileChunk));
  73662. if( !pNew ){
  73663. return SQLITE_IOERR_NOMEM;
  73664. }
  73665. pNew->pNext = 0;
  73666. if( pChunk ){
  73667. assert( p->pFirst );
  73668. pChunk->pNext = pNew;
  73669. }else{
  73670. assert( !p->pFirst );
  73671. p->pFirst = pNew;
  73672. }
  73673. p->endpoint.pChunk = pNew;
  73674. }
  73675. memcpy(&p->endpoint.pChunk->zChunk[iChunkOffset], zWrite, iSpace);
  73676. zWrite += iSpace;
  73677. nWrite -= iSpace;
  73678. p->endpoint.iOffset += iSpace;
  73679. }
  73680. return SQLITE_OK;
  73681. }
  73682. /*
  73683. ** Truncate the file.
  73684. */
  73685. static int memjrnlTruncate(sqlite3_file *pJfd, sqlite_int64 size){
  73686. MemJournal *p = (MemJournal *)pJfd;
  73687. FileChunk *pChunk;
  73688. assert(size==0);
  73689. UNUSED_PARAMETER(size);
  73690. pChunk = p->pFirst;
  73691. while( pChunk ){
  73692. FileChunk *pTmp = pChunk;
  73693. pChunk = pChunk->pNext;
  73694. sqlite3_free(pTmp);
  73695. }
  73696. sqlite3MemJournalOpen(pJfd);
  73697. return SQLITE_OK;
  73698. }
  73699. /*
  73700. ** Close the file.
  73701. */
  73702. static int memjrnlClose(sqlite3_file *pJfd){
  73703. memjrnlTruncate(pJfd, 0);
  73704. return SQLITE_OK;
  73705. }
  73706. /*
  73707. ** Sync the file.
  73708. **
  73709. ** Syncing an in-memory journal is a no-op. And, in fact, this routine
  73710. ** is never called in a working implementation. This implementation
  73711. ** exists purely as a contingency, in case some malfunction in some other
  73712. ** part of SQLite causes Sync to be called by mistake.
  73713. */
  73714. static int memjrnlSync(sqlite3_file *NotUsed, int NotUsed2){
  73715. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  73716. return SQLITE_OK;
  73717. }
  73718. /*
  73719. ** Query the size of the file in bytes.
  73720. */
  73721. static int memjrnlFileSize(sqlite3_file *pJfd, sqlite_int64 *pSize){
  73722. MemJournal *p = (MemJournal *)pJfd;
  73723. *pSize = (sqlite_int64) p->endpoint.iOffset;
  73724. return SQLITE_OK;
  73725. }
  73726. /*
  73727. ** Table of methods for MemJournal sqlite3_file object.
  73728. */
  73729. static const struct sqlite3_io_methods MemJournalMethods = {
  73730. 1, /* iVersion */
  73731. memjrnlClose, /* xClose */
  73732. memjrnlRead, /* xRead */
  73733. memjrnlWrite, /* xWrite */
  73734. memjrnlTruncate, /* xTruncate */
  73735. memjrnlSync, /* xSync */
  73736. memjrnlFileSize, /* xFileSize */
  73737. 0, /* xLock */
  73738. 0, /* xUnlock */
  73739. 0, /* xCheckReservedLock */
  73740. 0, /* xFileControl */
  73741. 0, /* xSectorSize */
  73742. 0, /* xDeviceCharacteristics */
  73743. 0, /* xShmMap */
  73744. 0, /* xShmLock */
  73745. 0, /* xShmBarrier */
  73746. 0, /* xShmUnmap */
  73747. 0, /* xFetch */
  73748. 0 /* xUnfetch */
  73749. };
  73750. /*
  73751. ** Open a journal file.
  73752. */
  73753. SQLITE_PRIVATE void sqlite3MemJournalOpen(sqlite3_file *pJfd){
  73754. MemJournal *p = (MemJournal *)pJfd;
  73755. assert( EIGHT_BYTE_ALIGNMENT(p) );
  73756. memset(p, 0, sqlite3MemJournalSize());
  73757. p->pMethod = (sqlite3_io_methods*)&MemJournalMethods;
  73758. }
  73759. /*
  73760. ** Return true if the file-handle passed as an argument is
  73761. ** an in-memory journal
  73762. */
  73763. SQLITE_PRIVATE int sqlite3IsMemJournal(sqlite3_file *pJfd){
  73764. return pJfd->pMethods==&MemJournalMethods;
  73765. }
  73766. /*
  73767. ** Return the number of bytes required to store a MemJournal file descriptor.
  73768. */
  73769. SQLITE_PRIVATE int sqlite3MemJournalSize(void){
  73770. return sizeof(MemJournal);
  73771. }
  73772. /************** End of memjournal.c ******************************************/
  73773. /************** Begin file walker.c ******************************************/
  73774. /*
  73775. ** 2008 August 16
  73776. **
  73777. ** The author disclaims copyright to this source code. In place of
  73778. ** a legal notice, here is a blessing:
  73779. **
  73780. ** May you do good and not evil.
  73781. ** May you find forgiveness for yourself and forgive others.
  73782. ** May you share freely, never taking more than you give.
  73783. **
  73784. *************************************************************************
  73785. ** This file contains routines used for walking the parser tree for
  73786. ** an SQL statement.
  73787. */
  73788. /* #include <stdlib.h> */
  73789. /* #include <string.h> */
  73790. /*
  73791. ** Walk an expression tree. Invoke the callback once for each node
  73792. ** of the expression, while descending. (In other words, the callback
  73793. ** is invoked before visiting children.)
  73794. **
  73795. ** The return value from the callback should be one of the WRC_*
  73796. ** constants to specify how to proceed with the walk.
  73797. **
  73798. ** WRC_Continue Continue descending down the tree.
  73799. **
  73800. ** WRC_Prune Do not descend into child nodes. But allow
  73801. ** the walk to continue with sibling nodes.
  73802. **
  73803. ** WRC_Abort Do no more callbacks. Unwind the stack and
  73804. ** return the top-level walk call.
  73805. **
  73806. ** The return value from this routine is WRC_Abort to abandon the tree walk
  73807. ** and WRC_Continue to continue.
  73808. */
  73809. SQLITE_PRIVATE int sqlite3WalkExpr(Walker *pWalker, Expr *pExpr){
  73810. int rc;
  73811. if( pExpr==0 ) return WRC_Continue;
  73812. testcase( ExprHasProperty(pExpr, EP_TokenOnly) );
  73813. testcase( ExprHasProperty(pExpr, EP_Reduced) );
  73814. rc = pWalker->xExprCallback(pWalker, pExpr);
  73815. if( rc==WRC_Continue
  73816. && !ExprHasProperty(pExpr,EP_TokenOnly) ){
  73817. if( sqlite3WalkExpr(pWalker, pExpr->pLeft) ) return WRC_Abort;
  73818. if( sqlite3WalkExpr(pWalker, pExpr->pRight) ) return WRC_Abort;
  73819. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  73820. if( sqlite3WalkSelect(pWalker, pExpr->x.pSelect) ) return WRC_Abort;
  73821. }else{
  73822. if( sqlite3WalkExprList(pWalker, pExpr->x.pList) ) return WRC_Abort;
  73823. }
  73824. }
  73825. return rc & WRC_Abort;
  73826. }
  73827. /*
  73828. ** Call sqlite3WalkExpr() for every expression in list p or until
  73829. ** an abort request is seen.
  73830. */
  73831. SQLITE_PRIVATE int sqlite3WalkExprList(Walker *pWalker, ExprList *p){
  73832. int i;
  73833. struct ExprList_item *pItem;
  73834. if( p ){
  73835. for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
  73836. if( sqlite3WalkExpr(pWalker, pItem->pExpr) ) return WRC_Abort;
  73837. }
  73838. }
  73839. return WRC_Continue;
  73840. }
  73841. /*
  73842. ** Walk all expressions associated with SELECT statement p. Do
  73843. ** not invoke the SELECT callback on p, but do (of course) invoke
  73844. ** any expr callbacks and SELECT callbacks that come from subqueries.
  73845. ** Return WRC_Abort or WRC_Continue.
  73846. */
  73847. SQLITE_PRIVATE int sqlite3WalkSelectExpr(Walker *pWalker, Select *p){
  73848. if( sqlite3WalkExprList(pWalker, p->pEList) ) return WRC_Abort;
  73849. if( sqlite3WalkExpr(pWalker, p->pWhere) ) return WRC_Abort;
  73850. if( sqlite3WalkExprList(pWalker, p->pGroupBy) ) return WRC_Abort;
  73851. if( sqlite3WalkExpr(pWalker, p->pHaving) ) return WRC_Abort;
  73852. if( sqlite3WalkExprList(pWalker, p->pOrderBy) ) return WRC_Abort;
  73853. if( sqlite3WalkExpr(pWalker, p->pLimit) ) return WRC_Abort;
  73854. if( sqlite3WalkExpr(pWalker, p->pOffset) ) return WRC_Abort;
  73855. return WRC_Continue;
  73856. }
  73857. /*
  73858. ** Walk the parse trees associated with all subqueries in the
  73859. ** FROM clause of SELECT statement p. Do not invoke the select
  73860. ** callback on p, but do invoke it on each FROM clause subquery
  73861. ** and on any subqueries further down in the tree. Return
  73862. ** WRC_Abort or WRC_Continue;
  73863. */
  73864. SQLITE_PRIVATE int sqlite3WalkSelectFrom(Walker *pWalker, Select *p){
  73865. SrcList *pSrc;
  73866. int i;
  73867. struct SrcList_item *pItem;
  73868. pSrc = p->pSrc;
  73869. if( ALWAYS(pSrc) ){
  73870. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  73871. if( sqlite3WalkSelect(pWalker, pItem->pSelect) ){
  73872. return WRC_Abort;
  73873. }
  73874. }
  73875. }
  73876. return WRC_Continue;
  73877. }
  73878. /*
  73879. ** Call sqlite3WalkExpr() for every expression in Select statement p.
  73880. ** Invoke sqlite3WalkSelect() for subqueries in the FROM clause and
  73881. ** on the compound select chain, p->pPrior.
  73882. **
  73883. ** If it is not NULL, the xSelectCallback() callback is invoked before
  73884. ** the walk of the expressions and FROM clause. The xSelectCallback2()
  73885. ** method, if it is not NULL, is invoked following the walk of the
  73886. ** expressions and FROM clause.
  73887. **
  73888. ** Return WRC_Continue under normal conditions. Return WRC_Abort if
  73889. ** there is an abort request.
  73890. **
  73891. ** If the Walker does not have an xSelectCallback() then this routine
  73892. ** is a no-op returning WRC_Continue.
  73893. */
  73894. SQLITE_PRIVATE int sqlite3WalkSelect(Walker *pWalker, Select *p){
  73895. int rc;
  73896. if( p==0 || (pWalker->xSelectCallback==0 && pWalker->xSelectCallback2==0) ){
  73897. return WRC_Continue;
  73898. }
  73899. rc = WRC_Continue;
  73900. pWalker->walkerDepth++;
  73901. while( p ){
  73902. if( pWalker->xSelectCallback ){
  73903. rc = pWalker->xSelectCallback(pWalker, p);
  73904. if( rc ) break;
  73905. }
  73906. if( sqlite3WalkSelectExpr(pWalker, p)
  73907. || sqlite3WalkSelectFrom(pWalker, p)
  73908. ){
  73909. pWalker->walkerDepth--;
  73910. return WRC_Abort;
  73911. }
  73912. if( pWalker->xSelectCallback2 ){
  73913. pWalker->xSelectCallback2(pWalker, p);
  73914. }
  73915. p = p->pPrior;
  73916. }
  73917. pWalker->walkerDepth--;
  73918. return rc & WRC_Abort;
  73919. }
  73920. /************** End of walker.c **********************************************/
  73921. /************** Begin file resolve.c *****************************************/
  73922. /*
  73923. ** 2008 August 18
  73924. **
  73925. ** The author disclaims copyright to this source code. In place of
  73926. ** a legal notice, here is a blessing:
  73927. **
  73928. ** May you do good and not evil.
  73929. ** May you find forgiveness for yourself and forgive others.
  73930. ** May you share freely, never taking more than you give.
  73931. **
  73932. *************************************************************************
  73933. **
  73934. ** This file contains routines used for walking the parser tree and
  73935. ** resolve all identifiers by associating them with a particular
  73936. ** table and column.
  73937. */
  73938. /* #include <stdlib.h> */
  73939. /* #include <string.h> */
  73940. /*
  73941. ** Walk the expression tree pExpr and increase the aggregate function
  73942. ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
  73943. ** This needs to occur when copying a TK_AGG_FUNCTION node from an
  73944. ** outer query into an inner subquery.
  73945. **
  73946. ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
  73947. ** is a helper function - a callback for the tree walker.
  73948. */
  73949. static int incrAggDepth(Walker *pWalker, Expr *pExpr){
  73950. if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
  73951. return WRC_Continue;
  73952. }
  73953. static void incrAggFunctionDepth(Expr *pExpr, int N){
  73954. if( N>0 ){
  73955. Walker w;
  73956. memset(&w, 0, sizeof(w));
  73957. w.xExprCallback = incrAggDepth;
  73958. w.u.i = N;
  73959. sqlite3WalkExpr(&w, pExpr);
  73960. }
  73961. }
  73962. /*
  73963. ** Turn the pExpr expression into an alias for the iCol-th column of the
  73964. ** result set in pEList.
  73965. **
  73966. ** If the result set column is a simple column reference, then this routine
  73967. ** makes an exact copy. But for any other kind of expression, this
  73968. ** routine make a copy of the result set column as the argument to the
  73969. ** TK_AS operator. The TK_AS operator causes the expression to be
  73970. ** evaluated just once and then reused for each alias.
  73971. **
  73972. ** The reason for suppressing the TK_AS term when the expression is a simple
  73973. ** column reference is so that the column reference will be recognized as
  73974. ** usable by indices within the WHERE clause processing logic.
  73975. **
  73976. ** The TK_AS operator is inhibited if zType[0]=='G'. This means
  73977. ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
  73978. **
  73979. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
  73980. **
  73981. ** Is equivalent to:
  73982. **
  73983. ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
  73984. **
  73985. ** The result of random()%5 in the GROUP BY clause is probably different
  73986. ** from the result in the result-set. On the other hand Standard SQL does
  73987. ** not allow the GROUP BY clause to contain references to result-set columns.
  73988. ** So this should never come up in well-formed queries.
  73989. **
  73990. ** If the reference is followed by a COLLATE operator, then make sure
  73991. ** the COLLATE operator is preserved. For example:
  73992. **
  73993. ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
  73994. **
  73995. ** Should be transformed into:
  73996. **
  73997. ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
  73998. **
  73999. ** The nSubquery parameter specifies how many levels of subquery the
  74000. ** alias is removed from the original expression. The usually value is
  74001. ** zero but it might be more if the alias is contained within a subquery
  74002. ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
  74003. ** structures must be increased by the nSubquery amount.
  74004. */
  74005. static void resolveAlias(
  74006. Parse *pParse, /* Parsing context */
  74007. ExprList *pEList, /* A result set */
  74008. int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
  74009. Expr *pExpr, /* Transform this into an alias to the result set */
  74010. const char *zType, /* "GROUP" or "ORDER" or "" */
  74011. int nSubquery /* Number of subqueries that the label is moving */
  74012. ){
  74013. Expr *pOrig; /* The iCol-th column of the result set */
  74014. Expr *pDup; /* Copy of pOrig */
  74015. sqlite3 *db; /* The database connection */
  74016. assert( iCol>=0 && iCol<pEList->nExpr );
  74017. pOrig = pEList->a[iCol].pExpr;
  74018. assert( pOrig!=0 );
  74019. assert( pOrig->flags & EP_Resolved );
  74020. db = pParse->db;
  74021. pDup = sqlite3ExprDup(db, pOrig, 0);
  74022. if( pDup==0 ) return;
  74023. if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
  74024. incrAggFunctionDepth(pDup, nSubquery);
  74025. pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
  74026. if( pDup==0 ) return;
  74027. ExprSetProperty(pDup, EP_Skip);
  74028. if( pEList->a[iCol].u.x.iAlias==0 ){
  74029. pEList->a[iCol].u.x.iAlias = (u16)(++pParse->nAlias);
  74030. }
  74031. pDup->iTable = pEList->a[iCol].u.x.iAlias;
  74032. }
  74033. if( pExpr->op==TK_COLLATE ){
  74034. pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
  74035. }
  74036. /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
  74037. ** prevents ExprDelete() from deleting the Expr structure itself,
  74038. ** allowing it to be repopulated by the memcpy() on the following line.
  74039. ** The pExpr->u.zToken might point into memory that will be freed by the
  74040. ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
  74041. ** make a copy of the token before doing the sqlite3DbFree().
  74042. */
  74043. ExprSetProperty(pExpr, EP_Static);
  74044. sqlite3ExprDelete(db, pExpr);
  74045. memcpy(pExpr, pDup, sizeof(*pExpr));
  74046. if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
  74047. assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
  74048. pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
  74049. pExpr->flags |= EP_MemToken;
  74050. }
  74051. sqlite3DbFree(db, pDup);
  74052. }
  74053. /*
  74054. ** Return TRUE if the name zCol occurs anywhere in the USING clause.
  74055. **
  74056. ** Return FALSE if the USING clause is NULL or if it does not contain
  74057. ** zCol.
  74058. */
  74059. static int nameInUsingClause(IdList *pUsing, const char *zCol){
  74060. if( pUsing ){
  74061. int k;
  74062. for(k=0; k<pUsing->nId; k++){
  74063. if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
  74064. }
  74065. }
  74066. return 0;
  74067. }
  74068. /*
  74069. ** Subqueries stores the original database, table and column names for their
  74070. ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
  74071. ** Check to see if the zSpan given to this routine matches the zDb, zTab,
  74072. ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
  74073. ** match anything.
  74074. */
  74075. SQLITE_PRIVATE int sqlite3MatchSpanName(
  74076. const char *zSpan,
  74077. const char *zCol,
  74078. const char *zTab,
  74079. const char *zDb
  74080. ){
  74081. int n;
  74082. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  74083. if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
  74084. return 0;
  74085. }
  74086. zSpan += n+1;
  74087. for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
  74088. if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
  74089. return 0;
  74090. }
  74091. zSpan += n+1;
  74092. if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
  74093. return 0;
  74094. }
  74095. return 1;
  74096. }
  74097. /*
  74098. ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
  74099. ** that name in the set of source tables in pSrcList and make the pExpr
  74100. ** expression node refer back to that source column. The following changes
  74101. ** are made to pExpr:
  74102. **
  74103. ** pExpr->iDb Set the index in db->aDb[] of the database X
  74104. ** (even if X is implied).
  74105. ** pExpr->iTable Set to the cursor number for the table obtained
  74106. ** from pSrcList.
  74107. ** pExpr->pTab Points to the Table structure of X.Y (even if
  74108. ** X and/or Y are implied.)
  74109. ** pExpr->iColumn Set to the column number within the table.
  74110. ** pExpr->op Set to TK_COLUMN.
  74111. ** pExpr->pLeft Any expression this points to is deleted
  74112. ** pExpr->pRight Any expression this points to is deleted.
  74113. **
  74114. ** The zDb variable is the name of the database (the "X"). This value may be
  74115. ** NULL meaning that name is of the form Y.Z or Z. Any available database
  74116. ** can be used. The zTable variable is the name of the table (the "Y"). This
  74117. ** value can be NULL if zDb is also NULL. If zTable is NULL it
  74118. ** means that the form of the name is Z and that columns from any table
  74119. ** can be used.
  74120. **
  74121. ** If the name cannot be resolved unambiguously, leave an error message
  74122. ** in pParse and return WRC_Abort. Return WRC_Prune on success.
  74123. */
  74124. static int lookupName(
  74125. Parse *pParse, /* The parsing context */
  74126. const char *zDb, /* Name of the database containing table, or NULL */
  74127. const char *zTab, /* Name of table containing column, or NULL */
  74128. const char *zCol, /* Name of the column. */
  74129. NameContext *pNC, /* The name context used to resolve the name */
  74130. Expr *pExpr /* Make this EXPR node point to the selected column */
  74131. ){
  74132. int i, j; /* Loop counters */
  74133. int cnt = 0; /* Number of matching column names */
  74134. int cntTab = 0; /* Number of matching table names */
  74135. int nSubquery = 0; /* How many levels of subquery */
  74136. sqlite3 *db = pParse->db; /* The database connection */
  74137. struct SrcList_item *pItem; /* Use for looping over pSrcList items */
  74138. struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
  74139. NameContext *pTopNC = pNC; /* First namecontext in the list */
  74140. Schema *pSchema = 0; /* Schema of the expression */
  74141. int isTrigger = 0; /* True if resolved to a trigger column */
  74142. Table *pTab = 0; /* Table hold the row */
  74143. Column *pCol; /* A column of pTab */
  74144. assert( pNC ); /* the name context cannot be NULL. */
  74145. assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
  74146. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  74147. /* Initialize the node to no-match */
  74148. pExpr->iTable = -1;
  74149. pExpr->pTab = 0;
  74150. ExprSetVVAProperty(pExpr, EP_NoReduce);
  74151. /* Translate the schema name in zDb into a pointer to the corresponding
  74152. ** schema. If not found, pSchema will remain NULL and nothing will match
  74153. ** resulting in an appropriate error message toward the end of this routine
  74154. */
  74155. if( zDb ){
  74156. testcase( pNC->ncFlags & NC_PartIdx );
  74157. testcase( pNC->ncFlags & NC_IsCheck );
  74158. if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
  74159. /* Silently ignore database qualifiers inside CHECK constraints and partial
  74160. ** indices. Do not raise errors because that might break legacy and
  74161. ** because it does not hurt anything to just ignore the database name. */
  74162. zDb = 0;
  74163. }else{
  74164. for(i=0; i<db->nDb; i++){
  74165. assert( db->aDb[i].zName );
  74166. if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
  74167. pSchema = db->aDb[i].pSchema;
  74168. break;
  74169. }
  74170. }
  74171. }
  74172. }
  74173. /* Start at the inner-most context and move outward until a match is found */
  74174. while( pNC && cnt==0 ){
  74175. ExprList *pEList;
  74176. SrcList *pSrcList = pNC->pSrcList;
  74177. if( pSrcList ){
  74178. for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
  74179. pTab = pItem->pTab;
  74180. assert( pTab!=0 && pTab->zName!=0 );
  74181. assert( pTab->nCol>0 );
  74182. if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
  74183. int hit = 0;
  74184. pEList = pItem->pSelect->pEList;
  74185. for(j=0; j<pEList->nExpr; j++){
  74186. if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
  74187. cnt++;
  74188. cntTab = 2;
  74189. pMatch = pItem;
  74190. pExpr->iColumn = j;
  74191. hit = 1;
  74192. }
  74193. }
  74194. if( hit || zTab==0 ) continue;
  74195. }
  74196. if( zDb && pTab->pSchema!=pSchema ){
  74197. continue;
  74198. }
  74199. if( zTab ){
  74200. const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
  74201. assert( zTabName!=0 );
  74202. if( sqlite3StrICmp(zTabName, zTab)!=0 ){
  74203. continue;
  74204. }
  74205. }
  74206. if( 0==(cntTab++) ){
  74207. pMatch = pItem;
  74208. }
  74209. for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
  74210. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  74211. /* If there has been exactly one prior match and this match
  74212. ** is for the right-hand table of a NATURAL JOIN or is in a
  74213. ** USING clause, then skip this match.
  74214. */
  74215. if( cnt==1 ){
  74216. if( pItem->jointype & JT_NATURAL ) continue;
  74217. if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
  74218. }
  74219. cnt++;
  74220. pMatch = pItem;
  74221. /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
  74222. pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
  74223. break;
  74224. }
  74225. }
  74226. }
  74227. if( pMatch ){
  74228. pExpr->iTable = pMatch->iCursor;
  74229. pExpr->pTab = pMatch->pTab;
  74230. assert( (pMatch->jointype & JT_RIGHT)==0 ); /* RIGHT JOIN not (yet) supported */
  74231. if( (pMatch->jointype & JT_LEFT)!=0 ){
  74232. ExprSetProperty(pExpr, EP_CanBeNull);
  74233. }
  74234. pSchema = pExpr->pTab->pSchema;
  74235. }
  74236. } /* if( pSrcList ) */
  74237. #ifndef SQLITE_OMIT_TRIGGER
  74238. /* If we have not already resolved the name, then maybe
  74239. ** it is a new.* or old.* trigger argument reference
  74240. */
  74241. if( zDb==0 && zTab!=0 && cntTab==0 && pParse->pTriggerTab!=0 ){
  74242. int op = pParse->eTriggerOp;
  74243. assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
  74244. if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
  74245. pExpr->iTable = 1;
  74246. pTab = pParse->pTriggerTab;
  74247. }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
  74248. pExpr->iTable = 0;
  74249. pTab = pParse->pTriggerTab;
  74250. }else{
  74251. pTab = 0;
  74252. }
  74253. if( pTab ){
  74254. int iCol;
  74255. pSchema = pTab->pSchema;
  74256. cntTab++;
  74257. for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
  74258. if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
  74259. if( iCol==pTab->iPKey ){
  74260. iCol = -1;
  74261. }
  74262. break;
  74263. }
  74264. }
  74265. if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && HasRowid(pTab) ){
  74266. /* IMP: R-51414-32910 */
  74267. /* IMP: R-44911-55124 */
  74268. iCol = -1;
  74269. }
  74270. if( iCol<pTab->nCol ){
  74271. cnt++;
  74272. if( iCol<0 ){
  74273. pExpr->affinity = SQLITE_AFF_INTEGER;
  74274. }else if( pExpr->iTable==0 ){
  74275. testcase( iCol==31 );
  74276. testcase( iCol==32 );
  74277. pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  74278. }else{
  74279. testcase( iCol==31 );
  74280. testcase( iCol==32 );
  74281. pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
  74282. }
  74283. pExpr->iColumn = (i16)iCol;
  74284. pExpr->pTab = pTab;
  74285. isTrigger = 1;
  74286. }
  74287. }
  74288. }
  74289. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  74290. /*
  74291. ** Perhaps the name is a reference to the ROWID
  74292. */
  74293. if( cnt==0 && cntTab==1 && pMatch && sqlite3IsRowid(zCol)
  74294. && HasRowid(pMatch->pTab) ){
  74295. cnt = 1;
  74296. pExpr->iColumn = -1; /* IMP: R-44911-55124 */
  74297. pExpr->affinity = SQLITE_AFF_INTEGER;
  74298. }
  74299. /*
  74300. ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
  74301. ** might refer to an result-set alias. This happens, for example, when
  74302. ** we are resolving names in the WHERE clause of the following command:
  74303. **
  74304. ** SELECT a+b AS x FROM table WHERE x<10;
  74305. **
  74306. ** In cases like this, replace pExpr with a copy of the expression that
  74307. ** forms the result set entry ("a+b" in the example) and return immediately.
  74308. ** Note that the expression in the result set should have already been
  74309. ** resolved by the time the WHERE clause is resolved.
  74310. **
  74311. ** The ability to use an output result-set column in the WHERE, GROUP BY,
  74312. ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
  74313. ** clause is not standard SQL. This is a (goofy) SQLite extension, that
  74314. ** is supported for backwards compatibility only. TO DO: Issue a warning
  74315. ** on sqlite3_log() whenever the capability is used.
  74316. */
  74317. if( (pEList = pNC->pEList)!=0
  74318. && zTab==0
  74319. && cnt==0
  74320. ){
  74321. for(j=0; j<pEList->nExpr; j++){
  74322. char *zAs = pEList->a[j].zName;
  74323. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  74324. Expr *pOrig;
  74325. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  74326. assert( pExpr->x.pList==0 );
  74327. assert( pExpr->x.pSelect==0 );
  74328. pOrig = pEList->a[j].pExpr;
  74329. if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
  74330. sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
  74331. return WRC_Abort;
  74332. }
  74333. resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
  74334. cnt = 1;
  74335. pMatch = 0;
  74336. assert( zTab==0 && zDb==0 );
  74337. goto lookupname_end;
  74338. }
  74339. }
  74340. }
  74341. /* Advance to the next name context. The loop will exit when either
  74342. ** we have a match (cnt>0) or when we run out of name contexts.
  74343. */
  74344. if( cnt==0 ){
  74345. pNC = pNC->pNext;
  74346. nSubquery++;
  74347. }
  74348. }
  74349. /*
  74350. ** If X and Y are NULL (in other words if only the column name Z is
  74351. ** supplied) and the value of Z is enclosed in double-quotes, then
  74352. ** Z is a string literal if it doesn't match any column names. In that
  74353. ** case, we need to return right away and not make any changes to
  74354. ** pExpr.
  74355. **
  74356. ** Because no reference was made to outer contexts, the pNC->nRef
  74357. ** fields are not changed in any context.
  74358. */
  74359. if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
  74360. pExpr->op = TK_STRING;
  74361. pExpr->pTab = 0;
  74362. return WRC_Prune;
  74363. }
  74364. /*
  74365. ** cnt==0 means there was not match. cnt>1 means there were two or
  74366. ** more matches. Either way, we have an error.
  74367. */
  74368. if( cnt!=1 ){
  74369. const char *zErr;
  74370. zErr = cnt==0 ? "no such column" : "ambiguous column name";
  74371. if( zDb ){
  74372. sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
  74373. }else if( zTab ){
  74374. sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
  74375. }else{
  74376. sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
  74377. }
  74378. pParse->checkSchema = 1;
  74379. pTopNC->nErr++;
  74380. }
  74381. /* If a column from a table in pSrcList is referenced, then record
  74382. ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
  74383. ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
  74384. ** column number is greater than the number of bits in the bitmask
  74385. ** then set the high-order bit of the bitmask.
  74386. */
  74387. if( pExpr->iColumn>=0 && pMatch!=0 ){
  74388. int n = pExpr->iColumn;
  74389. testcase( n==BMS-1 );
  74390. if( n>=BMS ){
  74391. n = BMS-1;
  74392. }
  74393. assert( pMatch->iCursor==pExpr->iTable );
  74394. pMatch->colUsed |= ((Bitmask)1)<<n;
  74395. }
  74396. /* Clean up and return
  74397. */
  74398. sqlite3ExprDelete(db, pExpr->pLeft);
  74399. pExpr->pLeft = 0;
  74400. sqlite3ExprDelete(db, pExpr->pRight);
  74401. pExpr->pRight = 0;
  74402. pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
  74403. lookupname_end:
  74404. if( cnt==1 ){
  74405. assert( pNC!=0 );
  74406. if( pExpr->op!=TK_AS ){
  74407. sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
  74408. }
  74409. /* Increment the nRef value on all name contexts from TopNC up to
  74410. ** the point where the name matched. */
  74411. for(;;){
  74412. assert( pTopNC!=0 );
  74413. pTopNC->nRef++;
  74414. if( pTopNC==pNC ) break;
  74415. pTopNC = pTopNC->pNext;
  74416. }
  74417. return WRC_Prune;
  74418. } else {
  74419. return WRC_Abort;
  74420. }
  74421. }
  74422. /*
  74423. ** Allocate and return a pointer to an expression to load the column iCol
  74424. ** from datasource iSrc in SrcList pSrc.
  74425. */
  74426. SQLITE_PRIVATE Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
  74427. Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
  74428. if( p ){
  74429. struct SrcList_item *pItem = &pSrc->a[iSrc];
  74430. p->pTab = pItem->pTab;
  74431. p->iTable = pItem->iCursor;
  74432. if( p->pTab->iPKey==iCol ){
  74433. p->iColumn = -1;
  74434. }else{
  74435. p->iColumn = (ynVar)iCol;
  74436. testcase( iCol==BMS );
  74437. testcase( iCol==BMS-1 );
  74438. pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
  74439. }
  74440. ExprSetProperty(p, EP_Resolved);
  74441. }
  74442. return p;
  74443. }
  74444. /*
  74445. ** Report an error that an expression is not valid for a partial index WHERE
  74446. ** clause.
  74447. */
  74448. static void notValidPartIdxWhere(
  74449. Parse *pParse, /* Leave error message here */
  74450. NameContext *pNC, /* The name context */
  74451. const char *zMsg /* Type of error */
  74452. ){
  74453. if( (pNC->ncFlags & NC_PartIdx)!=0 ){
  74454. sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
  74455. zMsg);
  74456. }
  74457. }
  74458. #ifndef SQLITE_OMIT_CHECK
  74459. /*
  74460. ** Report an error that an expression is not valid for a CHECK constraint.
  74461. */
  74462. static void notValidCheckConstraint(
  74463. Parse *pParse, /* Leave error message here */
  74464. NameContext *pNC, /* The name context */
  74465. const char *zMsg /* Type of error */
  74466. ){
  74467. if( (pNC->ncFlags & NC_IsCheck)!=0 ){
  74468. sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
  74469. }
  74470. }
  74471. #else
  74472. # define notValidCheckConstraint(P,N,M)
  74473. #endif
  74474. /*
  74475. ** Expression p should encode a floating point value between 1.0 and 0.0.
  74476. ** Return 1024 times this value. Or return -1 if p is not a floating point
  74477. ** value between 1.0 and 0.0.
  74478. */
  74479. static int exprProbability(Expr *p){
  74480. double r = -1.0;
  74481. if( p->op!=TK_FLOAT ) return -1;
  74482. sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
  74483. assert( r>=0.0 );
  74484. if( r>1.0 ) return -1;
  74485. return (int)(r*1000.0);
  74486. }
  74487. /*
  74488. ** This routine is callback for sqlite3WalkExpr().
  74489. **
  74490. ** Resolve symbolic names into TK_COLUMN operators for the current
  74491. ** node in the expression tree. Return 0 to continue the search down
  74492. ** the tree or 2 to abort the tree walk.
  74493. **
  74494. ** This routine also does error checking and name resolution for
  74495. ** function names. The operator for aggregate functions is changed
  74496. ** to TK_AGG_FUNCTION.
  74497. */
  74498. static int resolveExprStep(Walker *pWalker, Expr *pExpr){
  74499. NameContext *pNC;
  74500. Parse *pParse;
  74501. pNC = pWalker->u.pNC;
  74502. assert( pNC!=0 );
  74503. pParse = pNC->pParse;
  74504. assert( pParse==pWalker->pParse );
  74505. if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
  74506. ExprSetProperty(pExpr, EP_Resolved);
  74507. #ifndef NDEBUG
  74508. if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
  74509. SrcList *pSrcList = pNC->pSrcList;
  74510. int i;
  74511. for(i=0; i<pNC->pSrcList->nSrc; i++){
  74512. assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
  74513. }
  74514. }
  74515. #endif
  74516. switch( pExpr->op ){
  74517. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  74518. /* The special operator TK_ROW means use the rowid for the first
  74519. ** column in the FROM clause. This is used by the LIMIT and ORDER BY
  74520. ** clause processing on UPDATE and DELETE statements.
  74521. */
  74522. case TK_ROW: {
  74523. SrcList *pSrcList = pNC->pSrcList;
  74524. struct SrcList_item *pItem;
  74525. assert( pSrcList && pSrcList->nSrc==1 );
  74526. pItem = pSrcList->a;
  74527. pExpr->op = TK_COLUMN;
  74528. pExpr->pTab = pItem->pTab;
  74529. pExpr->iTable = pItem->iCursor;
  74530. pExpr->iColumn = -1;
  74531. pExpr->affinity = SQLITE_AFF_INTEGER;
  74532. break;
  74533. }
  74534. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
  74535. /* A lone identifier is the name of a column.
  74536. */
  74537. case TK_ID: {
  74538. return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
  74539. }
  74540. /* A table name and column name: ID.ID
  74541. ** Or a database, table and column: ID.ID.ID
  74542. */
  74543. case TK_DOT: {
  74544. const char *zColumn;
  74545. const char *zTable;
  74546. const char *zDb;
  74547. Expr *pRight;
  74548. /* if( pSrcList==0 ) break; */
  74549. pRight = pExpr->pRight;
  74550. if( pRight->op==TK_ID ){
  74551. zDb = 0;
  74552. zTable = pExpr->pLeft->u.zToken;
  74553. zColumn = pRight->u.zToken;
  74554. }else{
  74555. assert( pRight->op==TK_DOT );
  74556. zDb = pExpr->pLeft->u.zToken;
  74557. zTable = pRight->pLeft->u.zToken;
  74558. zColumn = pRight->pRight->u.zToken;
  74559. }
  74560. return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
  74561. }
  74562. /* Resolve function names
  74563. */
  74564. case TK_FUNCTION: {
  74565. ExprList *pList = pExpr->x.pList; /* The argument list */
  74566. int n = pList ? pList->nExpr : 0; /* Number of arguments */
  74567. int no_such_func = 0; /* True if no such function exists */
  74568. int wrong_num_args = 0; /* True if wrong number of arguments */
  74569. int is_agg = 0; /* True if is an aggregate function */
  74570. int auth; /* Authorization to use the function */
  74571. int nId; /* Number of characters in function name */
  74572. const char *zId; /* The function name. */
  74573. FuncDef *pDef; /* Information about the function */
  74574. u8 enc = ENC(pParse->db); /* The database encoding */
  74575. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  74576. notValidPartIdxWhere(pParse, pNC, "functions");
  74577. zId = pExpr->u.zToken;
  74578. nId = sqlite3Strlen30(zId);
  74579. pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
  74580. if( pDef==0 ){
  74581. pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
  74582. if( pDef==0 ){
  74583. no_such_func = 1;
  74584. }else{
  74585. wrong_num_args = 1;
  74586. }
  74587. }else{
  74588. is_agg = pDef->xFunc==0;
  74589. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  74590. ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
  74591. if( n==2 ){
  74592. pExpr->iTable = exprProbability(pList->a[1].pExpr);
  74593. if( pExpr->iTable<0 ){
  74594. sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
  74595. "constant between 0.0 and 1.0");
  74596. pNC->nErr++;
  74597. }
  74598. }else{
  74599. /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is equivalent to
  74600. ** likelihood(X, 0.0625).
  74601. ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is short-hand for
  74602. ** likelihood(X,0.0625).
  74603. ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand for
  74604. ** likelihood(X,0.9375).
  74605. ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent to
  74606. ** likelihood(X,0.9375). */
  74607. /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
  74608. pExpr->iTable = pDef->zName[0]=='u' ? 62 : 938;
  74609. }
  74610. }
  74611. #ifndef SQLITE_OMIT_AUTHORIZATION
  74612. auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
  74613. if( auth!=SQLITE_OK ){
  74614. if( auth==SQLITE_DENY ){
  74615. sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
  74616. pDef->zName);
  74617. pNC->nErr++;
  74618. }
  74619. pExpr->op = TK_NULL;
  74620. return WRC_Prune;
  74621. }
  74622. #endif
  74623. if( pDef->funcFlags & SQLITE_FUNC_CONSTANT ) ExprSetProperty(pExpr,EP_Constant);
  74624. }
  74625. if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
  74626. sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
  74627. pNC->nErr++;
  74628. is_agg = 0;
  74629. }else if( no_such_func && pParse->db->init.busy==0 ){
  74630. sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
  74631. pNC->nErr++;
  74632. }else if( wrong_num_args ){
  74633. sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
  74634. nId, zId);
  74635. pNC->nErr++;
  74636. }
  74637. if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
  74638. sqlite3WalkExprList(pWalker, pList);
  74639. if( is_agg ){
  74640. NameContext *pNC2 = pNC;
  74641. pExpr->op = TK_AGG_FUNCTION;
  74642. pExpr->op2 = 0;
  74643. while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
  74644. pExpr->op2++;
  74645. pNC2 = pNC2->pNext;
  74646. }
  74647. assert( pDef!=0 );
  74648. if( pNC2 ){
  74649. assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
  74650. testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
  74651. pNC2->ncFlags |= NC_HasAgg | (pDef->funcFlags & SQLITE_FUNC_MINMAX);
  74652. }
  74653. pNC->ncFlags |= NC_AllowAgg;
  74654. }
  74655. /* FIX ME: Compute pExpr->affinity based on the expected return
  74656. ** type of the function
  74657. */
  74658. return WRC_Prune;
  74659. }
  74660. #ifndef SQLITE_OMIT_SUBQUERY
  74661. case TK_SELECT:
  74662. case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
  74663. #endif
  74664. case TK_IN: {
  74665. testcase( pExpr->op==TK_IN );
  74666. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  74667. int nRef = pNC->nRef;
  74668. notValidCheckConstraint(pParse, pNC, "subqueries");
  74669. notValidPartIdxWhere(pParse, pNC, "subqueries");
  74670. sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
  74671. assert( pNC->nRef>=nRef );
  74672. if( nRef!=pNC->nRef ){
  74673. ExprSetProperty(pExpr, EP_VarSelect);
  74674. }
  74675. }
  74676. break;
  74677. }
  74678. case TK_VARIABLE: {
  74679. notValidCheckConstraint(pParse, pNC, "parameters");
  74680. notValidPartIdxWhere(pParse, pNC, "parameters");
  74681. break;
  74682. }
  74683. }
  74684. return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
  74685. }
  74686. /*
  74687. ** pEList is a list of expressions which are really the result set of the
  74688. ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
  74689. ** This routine checks to see if pE is a simple identifier which corresponds
  74690. ** to the AS-name of one of the terms of the expression list. If it is,
  74691. ** this routine return an integer between 1 and N where N is the number of
  74692. ** elements in pEList, corresponding to the matching entry. If there is
  74693. ** no match, or if pE is not a simple identifier, then this routine
  74694. ** return 0.
  74695. **
  74696. ** pEList has been resolved. pE has not.
  74697. */
  74698. static int resolveAsName(
  74699. Parse *pParse, /* Parsing context for error messages */
  74700. ExprList *pEList, /* List of expressions to scan */
  74701. Expr *pE /* Expression we are trying to match */
  74702. ){
  74703. int i; /* Loop counter */
  74704. UNUSED_PARAMETER(pParse);
  74705. if( pE->op==TK_ID ){
  74706. char *zCol = pE->u.zToken;
  74707. for(i=0; i<pEList->nExpr; i++){
  74708. char *zAs = pEList->a[i].zName;
  74709. if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
  74710. return i+1;
  74711. }
  74712. }
  74713. }
  74714. return 0;
  74715. }
  74716. /*
  74717. ** pE is a pointer to an expression which is a single term in the
  74718. ** ORDER BY of a compound SELECT. The expression has not been
  74719. ** name resolved.
  74720. **
  74721. ** At the point this routine is called, we already know that the
  74722. ** ORDER BY term is not an integer index into the result set. That
  74723. ** case is handled by the calling routine.
  74724. **
  74725. ** Attempt to match pE against result set columns in the left-most
  74726. ** SELECT statement. Return the index i of the matching column,
  74727. ** as an indication to the caller that it should sort by the i-th column.
  74728. ** The left-most column is 1. In other words, the value returned is the
  74729. ** same integer value that would be used in the SQL statement to indicate
  74730. ** the column.
  74731. **
  74732. ** If there is no match, return 0. Return -1 if an error occurs.
  74733. */
  74734. static int resolveOrderByTermToExprList(
  74735. Parse *pParse, /* Parsing context for error messages */
  74736. Select *pSelect, /* The SELECT statement with the ORDER BY clause */
  74737. Expr *pE /* The specific ORDER BY term */
  74738. ){
  74739. int i; /* Loop counter */
  74740. ExprList *pEList; /* The columns of the result set */
  74741. NameContext nc; /* Name context for resolving pE */
  74742. sqlite3 *db; /* Database connection */
  74743. int rc; /* Return code from subprocedures */
  74744. u8 savedSuppErr; /* Saved value of db->suppressErr */
  74745. assert( sqlite3ExprIsInteger(pE, &i)==0 );
  74746. pEList = pSelect->pEList;
  74747. /* Resolve all names in the ORDER BY term expression
  74748. */
  74749. memset(&nc, 0, sizeof(nc));
  74750. nc.pParse = pParse;
  74751. nc.pSrcList = pSelect->pSrc;
  74752. nc.pEList = pEList;
  74753. nc.ncFlags = NC_AllowAgg;
  74754. nc.nErr = 0;
  74755. db = pParse->db;
  74756. savedSuppErr = db->suppressErr;
  74757. db->suppressErr = 1;
  74758. rc = sqlite3ResolveExprNames(&nc, pE);
  74759. db->suppressErr = savedSuppErr;
  74760. if( rc ) return 0;
  74761. /* Try to match the ORDER BY expression against an expression
  74762. ** in the result set. Return an 1-based index of the matching
  74763. ** result-set entry.
  74764. */
  74765. for(i=0; i<pEList->nExpr; i++){
  74766. if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
  74767. return i+1;
  74768. }
  74769. }
  74770. /* If no match, return 0. */
  74771. return 0;
  74772. }
  74773. /*
  74774. ** Generate an ORDER BY or GROUP BY term out-of-range error.
  74775. */
  74776. static void resolveOutOfRangeError(
  74777. Parse *pParse, /* The error context into which to write the error */
  74778. const char *zType, /* "ORDER" or "GROUP" */
  74779. int i, /* The index (1-based) of the term out of range */
  74780. int mx /* Largest permissible value of i */
  74781. ){
  74782. sqlite3ErrorMsg(pParse,
  74783. "%r %s BY term out of range - should be "
  74784. "between 1 and %d", i, zType, mx);
  74785. }
  74786. /*
  74787. ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
  74788. ** each term of the ORDER BY clause is a constant integer between 1
  74789. ** and N where N is the number of columns in the compound SELECT.
  74790. **
  74791. ** ORDER BY terms that are already an integer between 1 and N are
  74792. ** unmodified. ORDER BY terms that are integers outside the range of
  74793. ** 1 through N generate an error. ORDER BY terms that are expressions
  74794. ** are matched against result set expressions of compound SELECT
  74795. ** beginning with the left-most SELECT and working toward the right.
  74796. ** At the first match, the ORDER BY expression is transformed into
  74797. ** the integer column number.
  74798. **
  74799. ** Return the number of errors seen.
  74800. */
  74801. static int resolveCompoundOrderBy(
  74802. Parse *pParse, /* Parsing context. Leave error messages here */
  74803. Select *pSelect /* The SELECT statement containing the ORDER BY */
  74804. ){
  74805. int i;
  74806. ExprList *pOrderBy;
  74807. ExprList *pEList;
  74808. sqlite3 *db;
  74809. int moreToDo = 1;
  74810. pOrderBy = pSelect->pOrderBy;
  74811. if( pOrderBy==0 ) return 0;
  74812. db = pParse->db;
  74813. #if SQLITE_MAX_COLUMN
  74814. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  74815. sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
  74816. return 1;
  74817. }
  74818. #endif
  74819. for(i=0; i<pOrderBy->nExpr; i++){
  74820. pOrderBy->a[i].done = 0;
  74821. }
  74822. pSelect->pNext = 0;
  74823. while( pSelect->pPrior ){
  74824. pSelect->pPrior->pNext = pSelect;
  74825. pSelect = pSelect->pPrior;
  74826. }
  74827. while( pSelect && moreToDo ){
  74828. struct ExprList_item *pItem;
  74829. moreToDo = 0;
  74830. pEList = pSelect->pEList;
  74831. assert( pEList!=0 );
  74832. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  74833. int iCol = -1;
  74834. Expr *pE, *pDup;
  74835. if( pItem->done ) continue;
  74836. pE = sqlite3ExprSkipCollate(pItem->pExpr);
  74837. if( sqlite3ExprIsInteger(pE, &iCol) ){
  74838. if( iCol<=0 || iCol>pEList->nExpr ){
  74839. resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
  74840. return 1;
  74841. }
  74842. }else{
  74843. iCol = resolveAsName(pParse, pEList, pE);
  74844. if( iCol==0 ){
  74845. pDup = sqlite3ExprDup(db, pE, 0);
  74846. if( !db->mallocFailed ){
  74847. assert(pDup);
  74848. iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
  74849. }
  74850. sqlite3ExprDelete(db, pDup);
  74851. }
  74852. }
  74853. if( iCol>0 ){
  74854. /* Convert the ORDER BY term into an integer column number iCol,
  74855. ** taking care to preserve the COLLATE clause if it exists */
  74856. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  74857. if( pNew==0 ) return 1;
  74858. pNew->flags |= EP_IntValue;
  74859. pNew->u.iValue = iCol;
  74860. if( pItem->pExpr==pE ){
  74861. pItem->pExpr = pNew;
  74862. }else{
  74863. assert( pItem->pExpr->op==TK_COLLATE );
  74864. assert( pItem->pExpr->pLeft==pE );
  74865. pItem->pExpr->pLeft = pNew;
  74866. }
  74867. sqlite3ExprDelete(db, pE);
  74868. pItem->u.x.iOrderByCol = (u16)iCol;
  74869. pItem->done = 1;
  74870. }else{
  74871. moreToDo = 1;
  74872. }
  74873. }
  74874. pSelect = pSelect->pNext;
  74875. }
  74876. for(i=0; i<pOrderBy->nExpr; i++){
  74877. if( pOrderBy->a[i].done==0 ){
  74878. sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
  74879. "column in the result set", i+1);
  74880. return 1;
  74881. }
  74882. }
  74883. return 0;
  74884. }
  74885. /*
  74886. ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
  74887. ** the SELECT statement pSelect. If any term is reference to a
  74888. ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
  74889. ** field) then convert that term into a copy of the corresponding result set
  74890. ** column.
  74891. **
  74892. ** If any errors are detected, add an error message to pParse and
  74893. ** return non-zero. Return zero if no errors are seen.
  74894. */
  74895. SQLITE_PRIVATE int sqlite3ResolveOrderGroupBy(
  74896. Parse *pParse, /* Parsing context. Leave error messages here */
  74897. Select *pSelect, /* The SELECT statement containing the clause */
  74898. ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
  74899. const char *zType /* "ORDER" or "GROUP" */
  74900. ){
  74901. int i;
  74902. sqlite3 *db = pParse->db;
  74903. ExprList *pEList;
  74904. struct ExprList_item *pItem;
  74905. if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
  74906. #if SQLITE_MAX_COLUMN
  74907. if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  74908. sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
  74909. return 1;
  74910. }
  74911. #endif
  74912. pEList = pSelect->pEList;
  74913. assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
  74914. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  74915. if( pItem->u.x.iOrderByCol ){
  74916. if( pItem->u.x.iOrderByCol>pEList->nExpr ){
  74917. resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
  74918. return 1;
  74919. }
  74920. resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr, zType,0);
  74921. }
  74922. }
  74923. return 0;
  74924. }
  74925. /*
  74926. ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
  74927. ** The Name context of the SELECT statement is pNC. zType is either
  74928. ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
  74929. **
  74930. ** This routine resolves each term of the clause into an expression.
  74931. ** If the order-by term is an integer I between 1 and N (where N is the
  74932. ** number of columns in the result set of the SELECT) then the expression
  74933. ** in the resolution is a copy of the I-th result-set expression. If
  74934. ** the order-by term is an identifier that corresponds to the AS-name of
  74935. ** a result-set expression, then the term resolves to a copy of the
  74936. ** result-set expression. Otherwise, the expression is resolved in
  74937. ** the usual way - using sqlite3ResolveExprNames().
  74938. **
  74939. ** This routine returns the number of errors. If errors occur, then
  74940. ** an appropriate error message might be left in pParse. (OOM errors
  74941. ** excepted.)
  74942. */
  74943. static int resolveOrderGroupBy(
  74944. NameContext *pNC, /* The name context of the SELECT statement */
  74945. Select *pSelect, /* The SELECT statement holding pOrderBy */
  74946. ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
  74947. const char *zType /* Either "ORDER" or "GROUP", as appropriate */
  74948. ){
  74949. int i, j; /* Loop counters */
  74950. int iCol; /* Column number */
  74951. struct ExprList_item *pItem; /* A term of the ORDER BY clause */
  74952. Parse *pParse; /* Parsing context */
  74953. int nResult; /* Number of terms in the result set */
  74954. if( pOrderBy==0 ) return 0;
  74955. nResult = pSelect->pEList->nExpr;
  74956. pParse = pNC->pParse;
  74957. for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
  74958. Expr *pE = pItem->pExpr;
  74959. Expr *pE2 = sqlite3ExprSkipCollate(pE);
  74960. if( zType[0]!='G' ){
  74961. iCol = resolveAsName(pParse, pSelect->pEList, pE2);
  74962. if( iCol>0 ){
  74963. /* If an AS-name match is found, mark this ORDER BY column as being
  74964. ** a copy of the iCol-th result-set column. The subsequent call to
  74965. ** sqlite3ResolveOrderGroupBy() will convert the expression to a
  74966. ** copy of the iCol-th result-set expression. */
  74967. pItem->u.x.iOrderByCol = (u16)iCol;
  74968. continue;
  74969. }
  74970. }
  74971. if( sqlite3ExprIsInteger(pE2, &iCol) ){
  74972. /* The ORDER BY term is an integer constant. Again, set the column
  74973. ** number so that sqlite3ResolveOrderGroupBy() will convert the
  74974. ** order-by term to a copy of the result-set expression */
  74975. if( iCol<1 || iCol>0xffff ){
  74976. resolveOutOfRangeError(pParse, zType, i+1, nResult);
  74977. return 1;
  74978. }
  74979. pItem->u.x.iOrderByCol = (u16)iCol;
  74980. continue;
  74981. }
  74982. /* Otherwise, treat the ORDER BY term as an ordinary expression */
  74983. pItem->u.x.iOrderByCol = 0;
  74984. if( sqlite3ResolveExprNames(pNC, pE) ){
  74985. return 1;
  74986. }
  74987. for(j=0; j<pSelect->pEList->nExpr; j++){
  74988. if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
  74989. pItem->u.x.iOrderByCol = j+1;
  74990. }
  74991. }
  74992. }
  74993. return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
  74994. }
  74995. /*
  74996. ** Resolve names in the SELECT statement p and all of its descendants.
  74997. */
  74998. static int resolveSelectStep(Walker *pWalker, Select *p){
  74999. NameContext *pOuterNC; /* Context that contains this SELECT */
  75000. NameContext sNC; /* Name context of this SELECT */
  75001. int isCompound; /* True if p is a compound select */
  75002. int nCompound; /* Number of compound terms processed so far */
  75003. Parse *pParse; /* Parsing context */
  75004. ExprList *pEList; /* Result set expression list */
  75005. int i; /* Loop counter */
  75006. ExprList *pGroupBy; /* The GROUP BY clause */
  75007. Select *pLeftmost; /* Left-most of SELECT of a compound */
  75008. sqlite3 *db; /* Database connection */
  75009. assert( p!=0 );
  75010. if( p->selFlags & SF_Resolved ){
  75011. return WRC_Prune;
  75012. }
  75013. pOuterNC = pWalker->u.pNC;
  75014. pParse = pWalker->pParse;
  75015. db = pParse->db;
  75016. /* Normally sqlite3SelectExpand() will be called first and will have
  75017. ** already expanded this SELECT. However, if this is a subquery within
  75018. ** an expression, sqlite3ResolveExprNames() will be called without a
  75019. ** prior call to sqlite3SelectExpand(). When that happens, let
  75020. ** sqlite3SelectPrep() do all of the processing for this SELECT.
  75021. ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
  75022. ** this routine in the correct order.
  75023. */
  75024. if( (p->selFlags & SF_Expanded)==0 ){
  75025. sqlite3SelectPrep(pParse, p, pOuterNC);
  75026. return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
  75027. }
  75028. isCompound = p->pPrior!=0;
  75029. nCompound = 0;
  75030. pLeftmost = p;
  75031. while( p ){
  75032. assert( (p->selFlags & SF_Expanded)!=0 );
  75033. assert( (p->selFlags & SF_Resolved)==0 );
  75034. p->selFlags |= SF_Resolved;
  75035. /* Resolve the expressions in the LIMIT and OFFSET clauses. These
  75036. ** are not allowed to refer to any names, so pass an empty NameContext.
  75037. */
  75038. memset(&sNC, 0, sizeof(sNC));
  75039. sNC.pParse = pParse;
  75040. if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
  75041. sqlite3ResolveExprNames(&sNC, p->pOffset) ){
  75042. return WRC_Abort;
  75043. }
  75044. /* Recursively resolve names in all subqueries
  75045. */
  75046. for(i=0; i<p->pSrc->nSrc; i++){
  75047. struct SrcList_item *pItem = &p->pSrc->a[i];
  75048. if( pItem->pSelect ){
  75049. NameContext *pNC; /* Used to iterate name contexts */
  75050. int nRef = 0; /* Refcount for pOuterNC and outer contexts */
  75051. const char *zSavedContext = pParse->zAuthContext;
  75052. /* Count the total number of references to pOuterNC and all of its
  75053. ** parent contexts. After resolving references to expressions in
  75054. ** pItem->pSelect, check if this value has changed. If so, then
  75055. ** SELECT statement pItem->pSelect must be correlated. Set the
  75056. ** pItem->isCorrelated flag if this is the case. */
  75057. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
  75058. if( pItem->zName ) pParse->zAuthContext = pItem->zName;
  75059. sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
  75060. pParse->zAuthContext = zSavedContext;
  75061. if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
  75062. for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
  75063. assert( pItem->isCorrelated==0 && nRef<=0 );
  75064. pItem->isCorrelated = (nRef!=0);
  75065. }
  75066. }
  75067. /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
  75068. ** resolve the result-set expression list.
  75069. */
  75070. sNC.ncFlags = NC_AllowAgg;
  75071. sNC.pSrcList = p->pSrc;
  75072. sNC.pNext = pOuterNC;
  75073. /* Resolve names in the result set. */
  75074. pEList = p->pEList;
  75075. assert( pEList!=0 );
  75076. for(i=0; i<pEList->nExpr; i++){
  75077. Expr *pX = pEList->a[i].pExpr;
  75078. if( sqlite3ResolveExprNames(&sNC, pX) ){
  75079. return WRC_Abort;
  75080. }
  75081. }
  75082. /* If there are no aggregate functions in the result-set, and no GROUP BY
  75083. ** expression, do not allow aggregates in any of the other expressions.
  75084. */
  75085. assert( (p->selFlags & SF_Aggregate)==0 );
  75086. pGroupBy = p->pGroupBy;
  75087. if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
  75088. assert( NC_MinMaxAgg==SF_MinMaxAgg );
  75089. p->selFlags |= SF_Aggregate | (sNC.ncFlags&NC_MinMaxAgg);
  75090. }else{
  75091. sNC.ncFlags &= ~NC_AllowAgg;
  75092. }
  75093. /* If a HAVING clause is present, then there must be a GROUP BY clause.
  75094. */
  75095. if( p->pHaving && !pGroupBy ){
  75096. sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
  75097. return WRC_Abort;
  75098. }
  75099. /* Add the output column list to the name-context before parsing the
  75100. ** other expressions in the SELECT statement. This is so that
  75101. ** expressions in the WHERE clause (etc.) can refer to expressions by
  75102. ** aliases in the result set.
  75103. **
  75104. ** Minor point: If this is the case, then the expression will be
  75105. ** re-evaluated for each reference to it.
  75106. */
  75107. sNC.pEList = p->pEList;
  75108. if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
  75109. if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
  75110. /* The ORDER BY and GROUP BY clauses may not refer to terms in
  75111. ** outer queries
  75112. */
  75113. sNC.pNext = 0;
  75114. sNC.ncFlags |= NC_AllowAgg;
  75115. /* Process the ORDER BY clause for singleton SELECT statements.
  75116. ** The ORDER BY clause for compounds SELECT statements is handled
  75117. ** below, after all of the result-sets for all of the elements of
  75118. ** the compound have been resolved.
  75119. */
  75120. if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
  75121. return WRC_Abort;
  75122. }
  75123. if( db->mallocFailed ){
  75124. return WRC_Abort;
  75125. }
  75126. /* Resolve the GROUP BY clause. At the same time, make sure
  75127. ** the GROUP BY clause does not contain aggregate functions.
  75128. */
  75129. if( pGroupBy ){
  75130. struct ExprList_item *pItem;
  75131. if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
  75132. return WRC_Abort;
  75133. }
  75134. for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
  75135. if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
  75136. sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
  75137. "the GROUP BY clause");
  75138. return WRC_Abort;
  75139. }
  75140. }
  75141. }
  75142. /* Advance to the next term of the compound
  75143. */
  75144. p = p->pPrior;
  75145. nCompound++;
  75146. }
  75147. /* Resolve the ORDER BY on a compound SELECT after all terms of
  75148. ** the compound have been resolved.
  75149. */
  75150. if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
  75151. return WRC_Abort;
  75152. }
  75153. return WRC_Prune;
  75154. }
  75155. /*
  75156. ** This routine walks an expression tree and resolves references to
  75157. ** table columns and result-set columns. At the same time, do error
  75158. ** checking on function usage and set a flag if any aggregate functions
  75159. ** are seen.
  75160. **
  75161. ** To resolve table columns references we look for nodes (or subtrees) of the
  75162. ** form X.Y.Z or Y.Z or just Z where
  75163. **
  75164. ** X: The name of a database. Ex: "main" or "temp" or
  75165. ** the symbolic name assigned to an ATTACH-ed database.
  75166. **
  75167. ** Y: The name of a table in a FROM clause. Or in a trigger
  75168. ** one of the special names "old" or "new".
  75169. **
  75170. ** Z: The name of a column in table Y.
  75171. **
  75172. ** The node at the root of the subtree is modified as follows:
  75173. **
  75174. ** Expr.op Changed to TK_COLUMN
  75175. ** Expr.pTab Points to the Table object for X.Y
  75176. ** Expr.iColumn The column index in X.Y. -1 for the rowid.
  75177. ** Expr.iTable The VDBE cursor number for X.Y
  75178. **
  75179. **
  75180. ** To resolve result-set references, look for expression nodes of the
  75181. ** form Z (with no X and Y prefix) where the Z matches the right-hand
  75182. ** size of an AS clause in the result-set of a SELECT. The Z expression
  75183. ** is replaced by a copy of the left-hand side of the result-set expression.
  75184. ** Table-name and function resolution occurs on the substituted expression
  75185. ** tree. For example, in:
  75186. **
  75187. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
  75188. **
  75189. ** The "x" term of the order by is replaced by "a+b" to render:
  75190. **
  75191. ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
  75192. **
  75193. ** Function calls are checked to make sure that the function is
  75194. ** defined and that the correct number of arguments are specified.
  75195. ** If the function is an aggregate function, then the NC_HasAgg flag is
  75196. ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
  75197. ** If an expression contains aggregate functions then the EP_Agg
  75198. ** property on the expression is set.
  75199. **
  75200. ** An error message is left in pParse if anything is amiss. The number
  75201. ** if errors is returned.
  75202. */
  75203. SQLITE_PRIVATE int sqlite3ResolveExprNames(
  75204. NameContext *pNC, /* Namespace to resolve expressions in. */
  75205. Expr *pExpr /* The expression to be analyzed. */
  75206. ){
  75207. u16 savedHasAgg;
  75208. Walker w;
  75209. if( pExpr==0 ) return 0;
  75210. #if SQLITE_MAX_EXPR_DEPTH>0
  75211. {
  75212. Parse *pParse = pNC->pParse;
  75213. if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
  75214. return 1;
  75215. }
  75216. pParse->nHeight += pExpr->nHeight;
  75217. }
  75218. #endif
  75219. savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg);
  75220. pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg);
  75221. memset(&w, 0, sizeof(w));
  75222. w.xExprCallback = resolveExprStep;
  75223. w.xSelectCallback = resolveSelectStep;
  75224. w.pParse = pNC->pParse;
  75225. w.u.pNC = pNC;
  75226. sqlite3WalkExpr(&w, pExpr);
  75227. #if SQLITE_MAX_EXPR_DEPTH>0
  75228. pNC->pParse->nHeight -= pExpr->nHeight;
  75229. #endif
  75230. if( pNC->nErr>0 || w.pParse->nErr>0 ){
  75231. ExprSetProperty(pExpr, EP_Error);
  75232. }
  75233. if( pNC->ncFlags & NC_HasAgg ){
  75234. ExprSetProperty(pExpr, EP_Agg);
  75235. }
  75236. pNC->ncFlags |= savedHasAgg;
  75237. return ExprHasProperty(pExpr, EP_Error);
  75238. }
  75239. /*
  75240. ** Resolve all names in all expressions of a SELECT and in all
  75241. ** decendents of the SELECT, including compounds off of p->pPrior,
  75242. ** subqueries in expressions, and subqueries used as FROM clause
  75243. ** terms.
  75244. **
  75245. ** See sqlite3ResolveExprNames() for a description of the kinds of
  75246. ** transformations that occur.
  75247. **
  75248. ** All SELECT statements should have been expanded using
  75249. ** sqlite3SelectExpand() prior to invoking this routine.
  75250. */
  75251. SQLITE_PRIVATE void sqlite3ResolveSelectNames(
  75252. Parse *pParse, /* The parser context */
  75253. Select *p, /* The SELECT statement being coded. */
  75254. NameContext *pOuterNC /* Name context for parent SELECT statement */
  75255. ){
  75256. Walker w;
  75257. assert( p!=0 );
  75258. memset(&w, 0, sizeof(w));
  75259. w.xExprCallback = resolveExprStep;
  75260. w.xSelectCallback = resolveSelectStep;
  75261. w.pParse = pParse;
  75262. w.u.pNC = pOuterNC;
  75263. sqlite3WalkSelect(&w, p);
  75264. }
  75265. /*
  75266. ** Resolve names in expressions that can only reference a single table:
  75267. **
  75268. ** * CHECK constraints
  75269. ** * WHERE clauses on partial indices
  75270. **
  75271. ** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
  75272. ** is set to -1 and the Expr.iColumn value is set to the column number.
  75273. **
  75274. ** Any errors cause an error message to be set in pParse.
  75275. */
  75276. SQLITE_PRIVATE void sqlite3ResolveSelfReference(
  75277. Parse *pParse, /* Parsing context */
  75278. Table *pTab, /* The table being referenced */
  75279. int type, /* NC_IsCheck or NC_PartIdx */
  75280. Expr *pExpr, /* Expression to resolve. May be NULL. */
  75281. ExprList *pList /* Expression list to resolve. May be NUL. */
  75282. ){
  75283. SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
  75284. NameContext sNC; /* Name context for pParse->pNewTable */
  75285. int i; /* Loop counter */
  75286. assert( type==NC_IsCheck || type==NC_PartIdx );
  75287. memset(&sNC, 0, sizeof(sNC));
  75288. memset(&sSrc, 0, sizeof(sSrc));
  75289. sSrc.nSrc = 1;
  75290. sSrc.a[0].zName = pTab->zName;
  75291. sSrc.a[0].pTab = pTab;
  75292. sSrc.a[0].iCursor = -1;
  75293. sNC.pParse = pParse;
  75294. sNC.pSrcList = &sSrc;
  75295. sNC.ncFlags = type;
  75296. if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
  75297. if( pList ){
  75298. for(i=0; i<pList->nExpr; i++){
  75299. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  75300. return;
  75301. }
  75302. }
  75303. }
  75304. }
  75305. /************** End of resolve.c *********************************************/
  75306. /************** Begin file expr.c ********************************************/
  75307. /*
  75308. ** 2001 September 15
  75309. **
  75310. ** The author disclaims copyright to this source code. In place of
  75311. ** a legal notice, here is a blessing:
  75312. **
  75313. ** May you do good and not evil.
  75314. ** May you find forgiveness for yourself and forgive others.
  75315. ** May you share freely, never taking more than you give.
  75316. **
  75317. *************************************************************************
  75318. ** This file contains routines used for analyzing expressions and
  75319. ** for generating VDBE code that evaluates expressions in SQLite.
  75320. */
  75321. /*
  75322. ** Return the 'affinity' of the expression pExpr if any.
  75323. **
  75324. ** If pExpr is a column, a reference to a column via an 'AS' alias,
  75325. ** or a sub-select with a column as the return value, then the
  75326. ** affinity of that column is returned. Otherwise, 0x00 is returned,
  75327. ** indicating no affinity for the expression.
  75328. **
  75329. ** i.e. the WHERE clause expressions in the following statements all
  75330. ** have an affinity:
  75331. **
  75332. ** CREATE TABLE t1(a);
  75333. ** SELECT * FROM t1 WHERE a;
  75334. ** SELECT a AS b FROM t1 WHERE b;
  75335. ** SELECT * FROM t1 WHERE (select a from t1);
  75336. */
  75337. SQLITE_PRIVATE char sqlite3ExprAffinity(Expr *pExpr){
  75338. int op;
  75339. pExpr = sqlite3ExprSkipCollate(pExpr);
  75340. if( pExpr->flags & EP_Generic ) return 0;
  75341. op = pExpr->op;
  75342. if( op==TK_SELECT ){
  75343. assert( pExpr->flags&EP_xIsSelect );
  75344. return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
  75345. }
  75346. #ifndef SQLITE_OMIT_CAST
  75347. if( op==TK_CAST ){
  75348. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  75349. return sqlite3AffinityType(pExpr->u.zToken, 0);
  75350. }
  75351. #endif
  75352. if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
  75353. && pExpr->pTab!=0
  75354. ){
  75355. /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
  75356. ** a TK_COLUMN but was previously evaluated and cached in a register */
  75357. int j = pExpr->iColumn;
  75358. if( j<0 ) return SQLITE_AFF_INTEGER;
  75359. assert( pExpr->pTab && j<pExpr->pTab->nCol );
  75360. return pExpr->pTab->aCol[j].affinity;
  75361. }
  75362. return pExpr->affinity;
  75363. }
  75364. /*
  75365. ** Set the collating sequence for expression pExpr to be the collating
  75366. ** sequence named by pToken. Return a pointer to a new Expr node that
  75367. ** implements the COLLATE operator.
  75368. **
  75369. ** If a memory allocation error occurs, that fact is recorded in pParse->db
  75370. ** and the pExpr parameter is returned unchanged.
  75371. */
  75372. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateToken(
  75373. Parse *pParse, /* Parsing context */
  75374. Expr *pExpr, /* Add the "COLLATE" clause to this expression */
  75375. const Token *pCollName /* Name of collating sequence */
  75376. ){
  75377. if( pCollName->n>0 ){
  75378. Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, 1);
  75379. if( pNew ){
  75380. pNew->pLeft = pExpr;
  75381. pNew->flags |= EP_Collate|EP_Skip;
  75382. pExpr = pNew;
  75383. }
  75384. }
  75385. return pExpr;
  75386. }
  75387. SQLITE_PRIVATE Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
  75388. Token s;
  75389. assert( zC!=0 );
  75390. s.z = zC;
  75391. s.n = sqlite3Strlen30(s.z);
  75392. return sqlite3ExprAddCollateToken(pParse, pExpr, &s);
  75393. }
  75394. /*
  75395. ** Skip over any TK_COLLATE or TK_AS operators and any unlikely()
  75396. ** or likelihood() function at the root of an expression.
  75397. */
  75398. SQLITE_PRIVATE Expr *sqlite3ExprSkipCollate(Expr *pExpr){
  75399. while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
  75400. if( ExprHasProperty(pExpr, EP_Unlikely) ){
  75401. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  75402. assert( pExpr->x.pList->nExpr>0 );
  75403. assert( pExpr->op==TK_FUNCTION );
  75404. pExpr = pExpr->x.pList->a[0].pExpr;
  75405. }else{
  75406. assert( pExpr->op==TK_COLLATE || pExpr->op==TK_AS );
  75407. pExpr = pExpr->pLeft;
  75408. }
  75409. }
  75410. return pExpr;
  75411. }
  75412. /*
  75413. ** Return the collation sequence for the expression pExpr. If
  75414. ** there is no defined collating sequence, return NULL.
  75415. **
  75416. ** The collating sequence might be determined by a COLLATE operator
  75417. ** or by the presence of a column with a defined collating sequence.
  75418. ** COLLATE operators take first precedence. Left operands take
  75419. ** precedence over right operands.
  75420. */
  75421. SQLITE_PRIVATE CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
  75422. sqlite3 *db = pParse->db;
  75423. CollSeq *pColl = 0;
  75424. Expr *p = pExpr;
  75425. while( p ){
  75426. int op = p->op;
  75427. if( p->flags & EP_Generic ) break;
  75428. if( op==TK_CAST || op==TK_UPLUS ){
  75429. p = p->pLeft;
  75430. continue;
  75431. }
  75432. if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
  75433. pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
  75434. break;
  75435. }
  75436. if( p->pTab!=0
  75437. && (op==TK_AGG_COLUMN || op==TK_COLUMN
  75438. || op==TK_REGISTER || op==TK_TRIGGER)
  75439. ){
  75440. /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
  75441. ** a TK_COLUMN but was previously evaluated and cached in a register */
  75442. int j = p->iColumn;
  75443. if( j>=0 ){
  75444. const char *zColl = p->pTab->aCol[j].zColl;
  75445. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  75446. }
  75447. break;
  75448. }
  75449. if( p->flags & EP_Collate ){
  75450. if( ALWAYS(p->pLeft) && (p->pLeft->flags & EP_Collate)!=0 ){
  75451. p = p->pLeft;
  75452. }else{
  75453. p = p->pRight;
  75454. }
  75455. }else{
  75456. break;
  75457. }
  75458. }
  75459. if( sqlite3CheckCollSeq(pParse, pColl) ){
  75460. pColl = 0;
  75461. }
  75462. return pColl;
  75463. }
  75464. /*
  75465. ** pExpr is an operand of a comparison operator. aff2 is the
  75466. ** type affinity of the other operand. This routine returns the
  75467. ** type affinity that should be used for the comparison operator.
  75468. */
  75469. SQLITE_PRIVATE char sqlite3CompareAffinity(Expr *pExpr, char aff2){
  75470. char aff1 = sqlite3ExprAffinity(pExpr);
  75471. if( aff1 && aff2 ){
  75472. /* Both sides of the comparison are columns. If one has numeric
  75473. ** affinity, use that. Otherwise use no affinity.
  75474. */
  75475. if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
  75476. return SQLITE_AFF_NUMERIC;
  75477. }else{
  75478. return SQLITE_AFF_NONE;
  75479. }
  75480. }else if( !aff1 && !aff2 ){
  75481. /* Neither side of the comparison is a column. Compare the
  75482. ** results directly.
  75483. */
  75484. return SQLITE_AFF_NONE;
  75485. }else{
  75486. /* One side is a column, the other is not. Use the columns affinity. */
  75487. assert( aff1==0 || aff2==0 );
  75488. return (aff1 + aff2);
  75489. }
  75490. }
  75491. /*
  75492. ** pExpr is a comparison operator. Return the type affinity that should
  75493. ** be applied to both operands prior to doing the comparison.
  75494. */
  75495. static char comparisonAffinity(Expr *pExpr){
  75496. char aff;
  75497. assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
  75498. pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
  75499. pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
  75500. assert( pExpr->pLeft );
  75501. aff = sqlite3ExprAffinity(pExpr->pLeft);
  75502. if( pExpr->pRight ){
  75503. aff = sqlite3CompareAffinity(pExpr->pRight, aff);
  75504. }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  75505. aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
  75506. }else if( !aff ){
  75507. aff = SQLITE_AFF_NONE;
  75508. }
  75509. return aff;
  75510. }
  75511. /*
  75512. ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
  75513. ** idx_affinity is the affinity of an indexed column. Return true
  75514. ** if the index with affinity idx_affinity may be used to implement
  75515. ** the comparison in pExpr.
  75516. */
  75517. SQLITE_PRIVATE int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
  75518. char aff = comparisonAffinity(pExpr);
  75519. switch( aff ){
  75520. case SQLITE_AFF_NONE:
  75521. return 1;
  75522. case SQLITE_AFF_TEXT:
  75523. return idx_affinity==SQLITE_AFF_TEXT;
  75524. default:
  75525. return sqlite3IsNumericAffinity(idx_affinity);
  75526. }
  75527. }
  75528. /*
  75529. ** Return the P5 value that should be used for a binary comparison
  75530. ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
  75531. */
  75532. static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
  75533. u8 aff = (char)sqlite3ExprAffinity(pExpr2);
  75534. aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
  75535. return aff;
  75536. }
  75537. /*
  75538. ** Return a pointer to the collation sequence that should be used by
  75539. ** a binary comparison operator comparing pLeft and pRight.
  75540. **
  75541. ** If the left hand expression has a collating sequence type, then it is
  75542. ** used. Otherwise the collation sequence for the right hand expression
  75543. ** is used, or the default (BINARY) if neither expression has a collating
  75544. ** type.
  75545. **
  75546. ** Argument pRight (but not pLeft) may be a null pointer. In this case,
  75547. ** it is not considered.
  75548. */
  75549. SQLITE_PRIVATE CollSeq *sqlite3BinaryCompareCollSeq(
  75550. Parse *pParse,
  75551. Expr *pLeft,
  75552. Expr *pRight
  75553. ){
  75554. CollSeq *pColl;
  75555. assert( pLeft );
  75556. if( pLeft->flags & EP_Collate ){
  75557. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  75558. }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
  75559. pColl = sqlite3ExprCollSeq(pParse, pRight);
  75560. }else{
  75561. pColl = sqlite3ExprCollSeq(pParse, pLeft);
  75562. if( !pColl ){
  75563. pColl = sqlite3ExprCollSeq(pParse, pRight);
  75564. }
  75565. }
  75566. return pColl;
  75567. }
  75568. /*
  75569. ** Generate code for a comparison operator.
  75570. */
  75571. static int codeCompare(
  75572. Parse *pParse, /* The parsing (and code generating) context */
  75573. Expr *pLeft, /* The left operand */
  75574. Expr *pRight, /* The right operand */
  75575. int opcode, /* The comparison opcode */
  75576. int in1, int in2, /* Register holding operands */
  75577. int dest, /* Jump here if true. */
  75578. int jumpIfNull /* If true, jump if either operand is NULL */
  75579. ){
  75580. int p5;
  75581. int addr;
  75582. CollSeq *p4;
  75583. p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
  75584. p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
  75585. addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
  75586. (void*)p4, P4_COLLSEQ);
  75587. sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
  75588. return addr;
  75589. }
  75590. #if SQLITE_MAX_EXPR_DEPTH>0
  75591. /*
  75592. ** Check that argument nHeight is less than or equal to the maximum
  75593. ** expression depth allowed. If it is not, leave an error message in
  75594. ** pParse.
  75595. */
  75596. SQLITE_PRIVATE int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
  75597. int rc = SQLITE_OK;
  75598. int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
  75599. if( nHeight>mxHeight ){
  75600. sqlite3ErrorMsg(pParse,
  75601. "Expression tree is too large (maximum depth %d)", mxHeight
  75602. );
  75603. rc = SQLITE_ERROR;
  75604. }
  75605. return rc;
  75606. }
  75607. /* The following three functions, heightOfExpr(), heightOfExprList()
  75608. ** and heightOfSelect(), are used to determine the maximum height
  75609. ** of any expression tree referenced by the structure passed as the
  75610. ** first argument.
  75611. **
  75612. ** If this maximum height is greater than the current value pointed
  75613. ** to by pnHeight, the second parameter, then set *pnHeight to that
  75614. ** value.
  75615. */
  75616. static void heightOfExpr(Expr *p, int *pnHeight){
  75617. if( p ){
  75618. if( p->nHeight>*pnHeight ){
  75619. *pnHeight = p->nHeight;
  75620. }
  75621. }
  75622. }
  75623. static void heightOfExprList(ExprList *p, int *pnHeight){
  75624. if( p ){
  75625. int i;
  75626. for(i=0; i<p->nExpr; i++){
  75627. heightOfExpr(p->a[i].pExpr, pnHeight);
  75628. }
  75629. }
  75630. }
  75631. static void heightOfSelect(Select *p, int *pnHeight){
  75632. if( p ){
  75633. heightOfExpr(p->pWhere, pnHeight);
  75634. heightOfExpr(p->pHaving, pnHeight);
  75635. heightOfExpr(p->pLimit, pnHeight);
  75636. heightOfExpr(p->pOffset, pnHeight);
  75637. heightOfExprList(p->pEList, pnHeight);
  75638. heightOfExprList(p->pGroupBy, pnHeight);
  75639. heightOfExprList(p->pOrderBy, pnHeight);
  75640. heightOfSelect(p->pPrior, pnHeight);
  75641. }
  75642. }
  75643. /*
  75644. ** Set the Expr.nHeight variable in the structure passed as an
  75645. ** argument. An expression with no children, Expr.pList or
  75646. ** Expr.pSelect member has a height of 1. Any other expression
  75647. ** has a height equal to the maximum height of any other
  75648. ** referenced Expr plus one.
  75649. */
  75650. static void exprSetHeight(Expr *p){
  75651. int nHeight = 0;
  75652. heightOfExpr(p->pLeft, &nHeight);
  75653. heightOfExpr(p->pRight, &nHeight);
  75654. if( ExprHasProperty(p, EP_xIsSelect) ){
  75655. heightOfSelect(p->x.pSelect, &nHeight);
  75656. }else{
  75657. heightOfExprList(p->x.pList, &nHeight);
  75658. }
  75659. p->nHeight = nHeight + 1;
  75660. }
  75661. /*
  75662. ** Set the Expr.nHeight variable using the exprSetHeight() function. If
  75663. ** the height is greater than the maximum allowed expression depth,
  75664. ** leave an error in pParse.
  75665. */
  75666. SQLITE_PRIVATE void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
  75667. exprSetHeight(p);
  75668. sqlite3ExprCheckHeight(pParse, p->nHeight);
  75669. }
  75670. /*
  75671. ** Return the maximum height of any expression tree referenced
  75672. ** by the select statement passed as an argument.
  75673. */
  75674. SQLITE_PRIVATE int sqlite3SelectExprHeight(Select *p){
  75675. int nHeight = 0;
  75676. heightOfSelect(p, &nHeight);
  75677. return nHeight;
  75678. }
  75679. #else
  75680. #define exprSetHeight(y)
  75681. #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
  75682. /*
  75683. ** This routine is the core allocator for Expr nodes.
  75684. **
  75685. ** Construct a new expression node and return a pointer to it. Memory
  75686. ** for this node and for the pToken argument is a single allocation
  75687. ** obtained from sqlite3DbMalloc(). The calling function
  75688. ** is responsible for making sure the node eventually gets freed.
  75689. **
  75690. ** If dequote is true, then the token (if it exists) is dequoted.
  75691. ** If dequote is false, no dequoting is performance. The deQuote
  75692. ** parameter is ignored if pToken is NULL or if the token does not
  75693. ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
  75694. ** then the EP_DblQuoted flag is set on the expression node.
  75695. **
  75696. ** Special case: If op==TK_INTEGER and pToken points to a string that
  75697. ** can be translated into a 32-bit integer, then the token is not
  75698. ** stored in u.zToken. Instead, the integer values is written
  75699. ** into u.iValue and the EP_IntValue flag is set. No extra storage
  75700. ** is allocated to hold the integer text and the dequote flag is ignored.
  75701. */
  75702. SQLITE_PRIVATE Expr *sqlite3ExprAlloc(
  75703. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  75704. int op, /* Expression opcode */
  75705. const Token *pToken, /* Token argument. Might be NULL */
  75706. int dequote /* True to dequote */
  75707. ){
  75708. Expr *pNew;
  75709. int nExtra = 0;
  75710. int iValue = 0;
  75711. if( pToken ){
  75712. if( op!=TK_INTEGER || pToken->z==0
  75713. || sqlite3GetInt32(pToken->z, &iValue)==0 ){
  75714. nExtra = pToken->n+1;
  75715. assert( iValue>=0 );
  75716. }
  75717. }
  75718. pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
  75719. if( pNew ){
  75720. pNew->op = (u8)op;
  75721. pNew->iAgg = -1;
  75722. if( pToken ){
  75723. if( nExtra==0 ){
  75724. pNew->flags |= EP_IntValue;
  75725. pNew->u.iValue = iValue;
  75726. }else{
  75727. int c;
  75728. pNew->u.zToken = (char*)&pNew[1];
  75729. assert( pToken->z!=0 || pToken->n==0 );
  75730. if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
  75731. pNew->u.zToken[pToken->n] = 0;
  75732. if( dequote && nExtra>=3
  75733. && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
  75734. sqlite3Dequote(pNew->u.zToken);
  75735. if( c=='"' ) pNew->flags |= EP_DblQuoted;
  75736. }
  75737. }
  75738. }
  75739. #if SQLITE_MAX_EXPR_DEPTH>0
  75740. pNew->nHeight = 1;
  75741. #endif
  75742. }
  75743. return pNew;
  75744. }
  75745. /*
  75746. ** Allocate a new expression node from a zero-terminated token that has
  75747. ** already been dequoted.
  75748. */
  75749. SQLITE_PRIVATE Expr *sqlite3Expr(
  75750. sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
  75751. int op, /* Expression opcode */
  75752. const char *zToken /* Token argument. Might be NULL */
  75753. ){
  75754. Token x;
  75755. x.z = zToken;
  75756. x.n = zToken ? sqlite3Strlen30(zToken) : 0;
  75757. return sqlite3ExprAlloc(db, op, &x, 0);
  75758. }
  75759. /*
  75760. ** Attach subtrees pLeft and pRight to the Expr node pRoot.
  75761. **
  75762. ** If pRoot==NULL that means that a memory allocation error has occurred.
  75763. ** In that case, delete the subtrees pLeft and pRight.
  75764. */
  75765. SQLITE_PRIVATE void sqlite3ExprAttachSubtrees(
  75766. sqlite3 *db,
  75767. Expr *pRoot,
  75768. Expr *pLeft,
  75769. Expr *pRight
  75770. ){
  75771. if( pRoot==0 ){
  75772. assert( db->mallocFailed );
  75773. sqlite3ExprDelete(db, pLeft);
  75774. sqlite3ExprDelete(db, pRight);
  75775. }else{
  75776. if( pRight ){
  75777. pRoot->pRight = pRight;
  75778. pRoot->flags |= EP_Collate & pRight->flags;
  75779. }
  75780. if( pLeft ){
  75781. pRoot->pLeft = pLeft;
  75782. pRoot->flags |= EP_Collate & pLeft->flags;
  75783. }
  75784. exprSetHeight(pRoot);
  75785. }
  75786. }
  75787. /*
  75788. ** Allocate an Expr node which joins as many as two subtrees.
  75789. **
  75790. ** One or both of the subtrees can be NULL. Return a pointer to the new
  75791. ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
  75792. ** free the subtrees and return NULL.
  75793. */
  75794. SQLITE_PRIVATE Expr *sqlite3PExpr(
  75795. Parse *pParse, /* Parsing context */
  75796. int op, /* Expression opcode */
  75797. Expr *pLeft, /* Left operand */
  75798. Expr *pRight, /* Right operand */
  75799. const Token *pToken /* Argument token */
  75800. ){
  75801. Expr *p;
  75802. if( op==TK_AND && pLeft && pRight ){
  75803. /* Take advantage of short-circuit false optimization for AND */
  75804. p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
  75805. }else{
  75806. p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
  75807. sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
  75808. }
  75809. if( p ) {
  75810. sqlite3ExprCheckHeight(pParse, p->nHeight);
  75811. }
  75812. return p;
  75813. }
  75814. /*
  75815. ** If the expression is always either TRUE or FALSE (respectively),
  75816. ** then return 1. If one cannot determine the truth value of the
  75817. ** expression at compile-time return 0.
  75818. **
  75819. ** This is an optimization. If is OK to return 0 here even if
  75820. ** the expression really is always false or false (a false negative).
  75821. ** But it is a bug to return 1 if the expression might have different
  75822. ** boolean values in different circumstances (a false positive.)
  75823. **
  75824. ** Note that if the expression is part of conditional for a
  75825. ** LEFT JOIN, then we cannot determine at compile-time whether or not
  75826. ** is it true or false, so always return 0.
  75827. */
  75828. static int exprAlwaysTrue(Expr *p){
  75829. int v = 0;
  75830. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  75831. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  75832. return v!=0;
  75833. }
  75834. static int exprAlwaysFalse(Expr *p){
  75835. int v = 0;
  75836. if( ExprHasProperty(p, EP_FromJoin) ) return 0;
  75837. if( !sqlite3ExprIsInteger(p, &v) ) return 0;
  75838. return v==0;
  75839. }
  75840. /*
  75841. ** Join two expressions using an AND operator. If either expression is
  75842. ** NULL, then just return the other expression.
  75843. **
  75844. ** If one side or the other of the AND is known to be false, then instead
  75845. ** of returning an AND expression, just return a constant expression with
  75846. ** a value of false.
  75847. */
  75848. SQLITE_PRIVATE Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
  75849. if( pLeft==0 ){
  75850. return pRight;
  75851. }else if( pRight==0 ){
  75852. return pLeft;
  75853. }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
  75854. sqlite3ExprDelete(db, pLeft);
  75855. sqlite3ExprDelete(db, pRight);
  75856. return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
  75857. }else{
  75858. Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
  75859. sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
  75860. return pNew;
  75861. }
  75862. }
  75863. /*
  75864. ** Construct a new expression node for a function with multiple
  75865. ** arguments.
  75866. */
  75867. SQLITE_PRIVATE Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
  75868. Expr *pNew;
  75869. sqlite3 *db = pParse->db;
  75870. assert( pToken );
  75871. pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
  75872. if( pNew==0 ){
  75873. sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
  75874. return 0;
  75875. }
  75876. pNew->x.pList = pList;
  75877. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  75878. sqlite3ExprSetHeight(pParse, pNew);
  75879. return pNew;
  75880. }
  75881. /*
  75882. ** Assign a variable number to an expression that encodes a wildcard
  75883. ** in the original SQL statement.
  75884. **
  75885. ** Wildcards consisting of a single "?" are assigned the next sequential
  75886. ** variable number.
  75887. **
  75888. ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
  75889. ** sure "nnn" is not too be to avoid a denial of service attack when
  75890. ** the SQL statement comes from an external source.
  75891. **
  75892. ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
  75893. ** as the previous instance of the same wildcard. Or if this is the first
  75894. ** instance of the wildcard, the next sequential variable number is
  75895. ** assigned.
  75896. */
  75897. SQLITE_PRIVATE void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
  75898. sqlite3 *db = pParse->db;
  75899. const char *z;
  75900. if( pExpr==0 ) return;
  75901. assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
  75902. z = pExpr->u.zToken;
  75903. assert( z!=0 );
  75904. assert( z[0]!=0 );
  75905. if( z[1]==0 ){
  75906. /* Wildcard of the form "?". Assign the next variable number */
  75907. assert( z[0]=='?' );
  75908. pExpr->iColumn = (ynVar)(++pParse->nVar);
  75909. }else{
  75910. ynVar x = 0;
  75911. u32 n = sqlite3Strlen30(z);
  75912. if( z[0]=='?' ){
  75913. /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
  75914. ** use it as the variable number */
  75915. i64 i;
  75916. int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
  75917. pExpr->iColumn = x = (ynVar)i;
  75918. testcase( i==0 );
  75919. testcase( i==1 );
  75920. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
  75921. testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
  75922. if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  75923. sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
  75924. db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
  75925. x = 0;
  75926. }
  75927. if( i>pParse->nVar ){
  75928. pParse->nVar = (int)i;
  75929. }
  75930. }else{
  75931. /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
  75932. ** number as the prior appearance of the same name, or if the name
  75933. ** has never appeared before, reuse the same variable number
  75934. */
  75935. ynVar i;
  75936. for(i=0; i<pParse->nzVar; i++){
  75937. if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
  75938. pExpr->iColumn = x = (ynVar)i+1;
  75939. break;
  75940. }
  75941. }
  75942. if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
  75943. }
  75944. if( x>0 ){
  75945. if( x>pParse->nzVar ){
  75946. char **a;
  75947. a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
  75948. if( a==0 ) return; /* Error reported through db->mallocFailed */
  75949. pParse->azVar = a;
  75950. memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
  75951. pParse->nzVar = x;
  75952. }
  75953. if( z[0]!='?' || pParse->azVar[x-1]==0 ){
  75954. sqlite3DbFree(db, pParse->azVar[x-1]);
  75955. pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
  75956. }
  75957. }
  75958. }
  75959. if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
  75960. sqlite3ErrorMsg(pParse, "too many SQL variables");
  75961. }
  75962. }
  75963. /*
  75964. ** Recursively delete an expression tree.
  75965. */
  75966. SQLITE_PRIVATE void sqlite3ExprDelete(sqlite3 *db, Expr *p){
  75967. if( p==0 ) return;
  75968. /* Sanity check: Assert that the IntValue is non-negative if it exists */
  75969. assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
  75970. if( !ExprHasProperty(p, EP_TokenOnly) ){
  75971. /* The Expr.x union is never used at the same time as Expr.pRight */
  75972. assert( p->x.pList==0 || p->pRight==0 );
  75973. sqlite3ExprDelete(db, p->pLeft);
  75974. sqlite3ExprDelete(db, p->pRight);
  75975. if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
  75976. if( ExprHasProperty(p, EP_xIsSelect) ){
  75977. sqlite3SelectDelete(db, p->x.pSelect);
  75978. }else{
  75979. sqlite3ExprListDelete(db, p->x.pList);
  75980. }
  75981. }
  75982. if( !ExprHasProperty(p, EP_Static) ){
  75983. sqlite3DbFree(db, p);
  75984. }
  75985. }
  75986. /*
  75987. ** Return the number of bytes allocated for the expression structure
  75988. ** passed as the first argument. This is always one of EXPR_FULLSIZE,
  75989. ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
  75990. */
  75991. static int exprStructSize(Expr *p){
  75992. if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
  75993. if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
  75994. return EXPR_FULLSIZE;
  75995. }
  75996. /*
  75997. ** The dupedExpr*Size() routines each return the number of bytes required
  75998. ** to store a copy of an expression or expression tree. They differ in
  75999. ** how much of the tree is measured.
  76000. **
  76001. ** dupedExprStructSize() Size of only the Expr structure
  76002. ** dupedExprNodeSize() Size of Expr + space for token
  76003. ** dupedExprSize() Expr + token + subtree components
  76004. **
  76005. ***************************************************************************
  76006. **
  76007. ** The dupedExprStructSize() function returns two values OR-ed together:
  76008. ** (1) the space required for a copy of the Expr structure only and
  76009. ** (2) the EP_xxx flags that indicate what the structure size should be.
  76010. ** The return values is always one of:
  76011. **
  76012. ** EXPR_FULLSIZE
  76013. ** EXPR_REDUCEDSIZE | EP_Reduced
  76014. ** EXPR_TOKENONLYSIZE | EP_TokenOnly
  76015. **
  76016. ** The size of the structure can be found by masking the return value
  76017. ** of this routine with 0xfff. The flags can be found by masking the
  76018. ** return value with EP_Reduced|EP_TokenOnly.
  76019. **
  76020. ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
  76021. ** (unreduced) Expr objects as they or originally constructed by the parser.
  76022. ** During expression analysis, extra information is computed and moved into
  76023. ** later parts of teh Expr object and that extra information might get chopped
  76024. ** off if the expression is reduced. Note also that it does not work to
  76025. ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
  76026. ** to reduce a pristine expression tree from the parser. The implementation
  76027. ** of dupedExprStructSize() contain multiple assert() statements that attempt
  76028. ** to enforce this constraint.
  76029. */
  76030. static int dupedExprStructSize(Expr *p, int flags){
  76031. int nSize;
  76032. assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
  76033. assert( EXPR_FULLSIZE<=0xfff );
  76034. assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
  76035. if( 0==(flags&EXPRDUP_REDUCE) ){
  76036. nSize = EXPR_FULLSIZE;
  76037. }else{
  76038. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  76039. assert( !ExprHasProperty(p, EP_FromJoin) );
  76040. assert( !ExprHasProperty(p, EP_MemToken) );
  76041. assert( !ExprHasProperty(p, EP_NoReduce) );
  76042. if( p->pLeft || p->x.pList ){
  76043. nSize = EXPR_REDUCEDSIZE | EP_Reduced;
  76044. }else{
  76045. assert( p->pRight==0 );
  76046. nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
  76047. }
  76048. }
  76049. return nSize;
  76050. }
  76051. /*
  76052. ** This function returns the space in bytes required to store the copy
  76053. ** of the Expr structure and a copy of the Expr.u.zToken string (if that
  76054. ** string is defined.)
  76055. */
  76056. static int dupedExprNodeSize(Expr *p, int flags){
  76057. int nByte = dupedExprStructSize(p, flags) & 0xfff;
  76058. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  76059. nByte += sqlite3Strlen30(p->u.zToken)+1;
  76060. }
  76061. return ROUND8(nByte);
  76062. }
  76063. /*
  76064. ** Return the number of bytes required to create a duplicate of the
  76065. ** expression passed as the first argument. The second argument is a
  76066. ** mask containing EXPRDUP_XXX flags.
  76067. **
  76068. ** The value returned includes space to create a copy of the Expr struct
  76069. ** itself and the buffer referred to by Expr.u.zToken, if any.
  76070. **
  76071. ** If the EXPRDUP_REDUCE flag is set, then the return value includes
  76072. ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
  76073. ** and Expr.pRight variables (but not for any structures pointed to or
  76074. ** descended from the Expr.x.pList or Expr.x.pSelect variables).
  76075. */
  76076. static int dupedExprSize(Expr *p, int flags){
  76077. int nByte = 0;
  76078. if( p ){
  76079. nByte = dupedExprNodeSize(p, flags);
  76080. if( flags&EXPRDUP_REDUCE ){
  76081. nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
  76082. }
  76083. }
  76084. return nByte;
  76085. }
  76086. /*
  76087. ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
  76088. ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
  76089. ** to store the copy of expression p, the copies of p->u.zToken
  76090. ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
  76091. ** if any. Before returning, *pzBuffer is set to the first byte past the
  76092. ** portion of the buffer copied into by this function.
  76093. */
  76094. static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
  76095. Expr *pNew = 0; /* Value to return */
  76096. if( p ){
  76097. const int isReduced = (flags&EXPRDUP_REDUCE);
  76098. u8 *zAlloc;
  76099. u32 staticFlag = 0;
  76100. assert( pzBuffer==0 || isReduced );
  76101. /* Figure out where to write the new Expr structure. */
  76102. if( pzBuffer ){
  76103. zAlloc = *pzBuffer;
  76104. staticFlag = EP_Static;
  76105. }else{
  76106. zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
  76107. }
  76108. pNew = (Expr *)zAlloc;
  76109. if( pNew ){
  76110. /* Set nNewSize to the size allocated for the structure pointed to
  76111. ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
  76112. ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
  76113. ** by the copy of the p->u.zToken string (if any).
  76114. */
  76115. const unsigned nStructSize = dupedExprStructSize(p, flags);
  76116. const int nNewSize = nStructSize & 0xfff;
  76117. int nToken;
  76118. if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
  76119. nToken = sqlite3Strlen30(p->u.zToken) + 1;
  76120. }else{
  76121. nToken = 0;
  76122. }
  76123. if( isReduced ){
  76124. assert( ExprHasProperty(p, EP_Reduced)==0 );
  76125. memcpy(zAlloc, p, nNewSize);
  76126. }else{
  76127. int nSize = exprStructSize(p);
  76128. memcpy(zAlloc, p, nSize);
  76129. memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
  76130. }
  76131. /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
  76132. pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
  76133. pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
  76134. pNew->flags |= staticFlag;
  76135. /* Copy the p->u.zToken string, if any. */
  76136. if( nToken ){
  76137. char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
  76138. memcpy(zToken, p->u.zToken, nToken);
  76139. }
  76140. if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
  76141. /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
  76142. if( ExprHasProperty(p, EP_xIsSelect) ){
  76143. pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
  76144. }else{
  76145. pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
  76146. }
  76147. }
  76148. /* Fill in pNew->pLeft and pNew->pRight. */
  76149. if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
  76150. zAlloc += dupedExprNodeSize(p, flags);
  76151. if( ExprHasProperty(pNew, EP_Reduced) ){
  76152. pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
  76153. pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
  76154. }
  76155. if( pzBuffer ){
  76156. *pzBuffer = zAlloc;
  76157. }
  76158. }else{
  76159. if( !ExprHasProperty(p, EP_TokenOnly) ){
  76160. pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
  76161. pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
  76162. }
  76163. }
  76164. }
  76165. }
  76166. return pNew;
  76167. }
  76168. /*
  76169. ** Create and return a deep copy of the object passed as the second
  76170. ** argument. If an OOM condition is encountered, NULL is returned
  76171. ** and the db->mallocFailed flag set.
  76172. */
  76173. #ifndef SQLITE_OMIT_CTE
  76174. static With *withDup(sqlite3 *db, With *p){
  76175. With *pRet = 0;
  76176. if( p ){
  76177. int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
  76178. pRet = sqlite3DbMallocZero(db, nByte);
  76179. if( pRet ){
  76180. int i;
  76181. pRet->nCte = p->nCte;
  76182. for(i=0; i<p->nCte; i++){
  76183. pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
  76184. pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
  76185. pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
  76186. }
  76187. }
  76188. }
  76189. return pRet;
  76190. }
  76191. #else
  76192. # define withDup(x,y) 0
  76193. #endif
  76194. /*
  76195. ** The following group of routines make deep copies of expressions,
  76196. ** expression lists, ID lists, and select statements. The copies can
  76197. ** be deleted (by being passed to their respective ...Delete() routines)
  76198. ** without effecting the originals.
  76199. **
  76200. ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
  76201. ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
  76202. ** by subsequent calls to sqlite*ListAppend() routines.
  76203. **
  76204. ** Any tables that the SrcList might point to are not duplicated.
  76205. **
  76206. ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
  76207. ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
  76208. ** truncated version of the usual Expr structure that will be stored as
  76209. ** part of the in-memory representation of the database schema.
  76210. */
  76211. SQLITE_PRIVATE Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
  76212. return exprDup(db, p, flags, 0);
  76213. }
  76214. SQLITE_PRIVATE ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
  76215. ExprList *pNew;
  76216. struct ExprList_item *pItem, *pOldItem;
  76217. int i;
  76218. if( p==0 ) return 0;
  76219. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  76220. if( pNew==0 ) return 0;
  76221. pNew->nExpr = i = p->nExpr;
  76222. if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
  76223. pNew->a = pItem = sqlite3DbMallocRaw(db, i*sizeof(p->a[0]) );
  76224. if( pItem==0 ){
  76225. sqlite3DbFree(db, pNew);
  76226. return 0;
  76227. }
  76228. pOldItem = p->a;
  76229. for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
  76230. Expr *pOldExpr = pOldItem->pExpr;
  76231. pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
  76232. pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  76233. pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
  76234. pItem->sortOrder = pOldItem->sortOrder;
  76235. pItem->done = 0;
  76236. pItem->bSpanIsTab = pOldItem->bSpanIsTab;
  76237. pItem->u = pOldItem->u;
  76238. }
  76239. return pNew;
  76240. }
  76241. /*
  76242. ** If cursors, triggers, views and subqueries are all omitted from
  76243. ** the build, then none of the following routines, except for
  76244. ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
  76245. ** called with a NULL argument.
  76246. */
  76247. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
  76248. || !defined(SQLITE_OMIT_SUBQUERY)
  76249. SQLITE_PRIVATE SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
  76250. SrcList *pNew;
  76251. int i;
  76252. int nByte;
  76253. if( p==0 ) return 0;
  76254. nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
  76255. pNew = sqlite3DbMallocRaw(db, nByte );
  76256. if( pNew==0 ) return 0;
  76257. pNew->nSrc = pNew->nAlloc = p->nSrc;
  76258. for(i=0; i<p->nSrc; i++){
  76259. struct SrcList_item *pNewItem = &pNew->a[i];
  76260. struct SrcList_item *pOldItem = &p->a[i];
  76261. Table *pTab;
  76262. pNewItem->pSchema = pOldItem->pSchema;
  76263. pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
  76264. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  76265. pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
  76266. pNewItem->jointype = pOldItem->jointype;
  76267. pNewItem->iCursor = pOldItem->iCursor;
  76268. pNewItem->addrFillSub = pOldItem->addrFillSub;
  76269. pNewItem->regReturn = pOldItem->regReturn;
  76270. pNewItem->isCorrelated = pOldItem->isCorrelated;
  76271. pNewItem->viaCoroutine = pOldItem->viaCoroutine;
  76272. pNewItem->isRecursive = pOldItem->isRecursive;
  76273. pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
  76274. pNewItem->notIndexed = pOldItem->notIndexed;
  76275. pNewItem->pIndex = pOldItem->pIndex;
  76276. pTab = pNewItem->pTab = pOldItem->pTab;
  76277. if( pTab ){
  76278. pTab->nRef++;
  76279. }
  76280. pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
  76281. pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
  76282. pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
  76283. pNewItem->colUsed = pOldItem->colUsed;
  76284. }
  76285. return pNew;
  76286. }
  76287. SQLITE_PRIVATE IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
  76288. IdList *pNew;
  76289. int i;
  76290. if( p==0 ) return 0;
  76291. pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
  76292. if( pNew==0 ) return 0;
  76293. pNew->nId = p->nId;
  76294. pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
  76295. if( pNew->a==0 ){
  76296. sqlite3DbFree(db, pNew);
  76297. return 0;
  76298. }
  76299. /* Note that because the size of the allocation for p->a[] is not
  76300. ** necessarily a power of two, sqlite3IdListAppend() may not be called
  76301. ** on the duplicate created by this function. */
  76302. for(i=0; i<p->nId; i++){
  76303. struct IdList_item *pNewItem = &pNew->a[i];
  76304. struct IdList_item *pOldItem = &p->a[i];
  76305. pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
  76306. pNewItem->idx = pOldItem->idx;
  76307. }
  76308. return pNew;
  76309. }
  76310. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  76311. Select *pNew, *pPrior;
  76312. if( p==0 ) return 0;
  76313. pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
  76314. if( pNew==0 ) return 0;
  76315. pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
  76316. pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
  76317. pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
  76318. pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
  76319. pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
  76320. pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
  76321. pNew->op = p->op;
  76322. pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
  76323. if( pPrior ) pPrior->pNext = pNew;
  76324. pNew->pNext = 0;
  76325. pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
  76326. pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
  76327. pNew->iLimit = 0;
  76328. pNew->iOffset = 0;
  76329. pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
  76330. pNew->addrOpenEphm[0] = -1;
  76331. pNew->addrOpenEphm[1] = -1;
  76332. pNew->nSelectRow = p->nSelectRow;
  76333. pNew->pWith = withDup(db, p->pWith);
  76334. sqlite3SelectSetName(pNew, p->zSelName);
  76335. return pNew;
  76336. }
  76337. #else
  76338. SQLITE_PRIVATE Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
  76339. assert( p==0 );
  76340. return 0;
  76341. }
  76342. #endif
  76343. /*
  76344. ** Add a new element to the end of an expression list. If pList is
  76345. ** initially NULL, then create a new expression list.
  76346. **
  76347. ** If a memory allocation error occurs, the entire list is freed and
  76348. ** NULL is returned. If non-NULL is returned, then it is guaranteed
  76349. ** that the new entry was successfully appended.
  76350. */
  76351. SQLITE_PRIVATE ExprList *sqlite3ExprListAppend(
  76352. Parse *pParse, /* Parsing context */
  76353. ExprList *pList, /* List to which to append. Might be NULL */
  76354. Expr *pExpr /* Expression to be appended. Might be NULL */
  76355. ){
  76356. sqlite3 *db = pParse->db;
  76357. if( pList==0 ){
  76358. pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
  76359. if( pList==0 ){
  76360. goto no_mem;
  76361. }
  76362. pList->a = sqlite3DbMallocRaw(db, sizeof(pList->a[0]));
  76363. if( pList->a==0 ) goto no_mem;
  76364. }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
  76365. struct ExprList_item *a;
  76366. assert( pList->nExpr>0 );
  76367. a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
  76368. if( a==0 ){
  76369. goto no_mem;
  76370. }
  76371. pList->a = a;
  76372. }
  76373. assert( pList->a!=0 );
  76374. if( 1 ){
  76375. struct ExprList_item *pItem = &pList->a[pList->nExpr++];
  76376. memset(pItem, 0, sizeof(*pItem));
  76377. pItem->pExpr = pExpr;
  76378. }
  76379. return pList;
  76380. no_mem:
  76381. /* Avoid leaking memory if malloc has failed. */
  76382. sqlite3ExprDelete(db, pExpr);
  76383. sqlite3ExprListDelete(db, pList);
  76384. return 0;
  76385. }
  76386. /*
  76387. ** Set the ExprList.a[].zName element of the most recently added item
  76388. ** on the expression list.
  76389. **
  76390. ** pList might be NULL following an OOM error. But pName should never be
  76391. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  76392. ** is set.
  76393. */
  76394. SQLITE_PRIVATE void sqlite3ExprListSetName(
  76395. Parse *pParse, /* Parsing context */
  76396. ExprList *pList, /* List to which to add the span. */
  76397. Token *pName, /* Name to be added */
  76398. int dequote /* True to cause the name to be dequoted */
  76399. ){
  76400. assert( pList!=0 || pParse->db->mallocFailed!=0 );
  76401. if( pList ){
  76402. struct ExprList_item *pItem;
  76403. assert( pList->nExpr>0 );
  76404. pItem = &pList->a[pList->nExpr-1];
  76405. assert( pItem->zName==0 );
  76406. pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
  76407. if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
  76408. }
  76409. }
  76410. /*
  76411. ** Set the ExprList.a[].zSpan element of the most recently added item
  76412. ** on the expression list.
  76413. **
  76414. ** pList might be NULL following an OOM error. But pSpan should never be
  76415. ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
  76416. ** is set.
  76417. */
  76418. SQLITE_PRIVATE void sqlite3ExprListSetSpan(
  76419. Parse *pParse, /* Parsing context */
  76420. ExprList *pList, /* List to which to add the span. */
  76421. ExprSpan *pSpan /* The span to be added */
  76422. ){
  76423. sqlite3 *db = pParse->db;
  76424. assert( pList!=0 || db->mallocFailed!=0 );
  76425. if( pList ){
  76426. struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
  76427. assert( pList->nExpr>0 );
  76428. assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
  76429. sqlite3DbFree(db, pItem->zSpan);
  76430. pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  76431. (int)(pSpan->zEnd - pSpan->zStart));
  76432. }
  76433. }
  76434. /*
  76435. ** If the expression list pEList contains more than iLimit elements,
  76436. ** leave an error message in pParse.
  76437. */
  76438. SQLITE_PRIVATE void sqlite3ExprListCheckLength(
  76439. Parse *pParse,
  76440. ExprList *pEList,
  76441. const char *zObject
  76442. ){
  76443. int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
  76444. testcase( pEList && pEList->nExpr==mx );
  76445. testcase( pEList && pEList->nExpr==mx+1 );
  76446. if( pEList && pEList->nExpr>mx ){
  76447. sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
  76448. }
  76449. }
  76450. /*
  76451. ** Delete an entire expression list.
  76452. */
  76453. SQLITE_PRIVATE void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
  76454. int i;
  76455. struct ExprList_item *pItem;
  76456. if( pList==0 ) return;
  76457. assert( pList->a!=0 || pList->nExpr==0 );
  76458. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  76459. sqlite3ExprDelete(db, pItem->pExpr);
  76460. sqlite3DbFree(db, pItem->zName);
  76461. sqlite3DbFree(db, pItem->zSpan);
  76462. }
  76463. sqlite3DbFree(db, pList->a);
  76464. sqlite3DbFree(db, pList);
  76465. }
  76466. /*
  76467. ** These routines are Walker callbacks. Walker.u.pi is a pointer
  76468. ** to an integer. These routines are checking an expression to see
  76469. ** if it is a constant. Set *Walker.u.i to 0 if the expression is
  76470. ** not constant.
  76471. **
  76472. ** These callback routines are used to implement the following:
  76473. **
  76474. ** sqlite3ExprIsConstant() pWalker->u.i==1
  76475. ** sqlite3ExprIsConstantNotJoin() pWalker->u.i==2
  76476. ** sqlite3ExprIsConstantOrFunction() pWalker->u.i==3 or 4
  76477. **
  76478. ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
  76479. ** in a CREATE TABLE statement. The Walker.u.i value is 4 when parsing
  76480. ** an existing schema and 3 when processing a new statement. A bound
  76481. ** parameter raises an error for new statements, but is silently converted
  76482. ** to NULL for existing schemas. This allows sqlite_master tables that
  76483. ** contain a bound parameter because they were generated by older versions
  76484. ** of SQLite to be parsed by newer versions of SQLite without raising a
  76485. ** malformed schema error.
  76486. */
  76487. static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
  76488. /* If pWalker->u.i is 2 then any term of the expression that comes from
  76489. ** the ON or USING clauses of a join disqualifies the expression
  76490. ** from being considered constant. */
  76491. if( pWalker->u.i==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
  76492. pWalker->u.i = 0;
  76493. return WRC_Abort;
  76494. }
  76495. switch( pExpr->op ){
  76496. /* Consider functions to be constant if all their arguments are constant
  76497. ** and either pWalker->u.i==3 or 4 or the function as the SQLITE_FUNC_CONST
  76498. ** flag. */
  76499. case TK_FUNCTION:
  76500. if( pWalker->u.i>=3 || ExprHasProperty(pExpr,EP_Constant) ){
  76501. return WRC_Continue;
  76502. }
  76503. /* Fall through */
  76504. case TK_ID:
  76505. case TK_COLUMN:
  76506. case TK_AGG_FUNCTION:
  76507. case TK_AGG_COLUMN:
  76508. testcase( pExpr->op==TK_ID );
  76509. testcase( pExpr->op==TK_COLUMN );
  76510. testcase( pExpr->op==TK_AGG_FUNCTION );
  76511. testcase( pExpr->op==TK_AGG_COLUMN );
  76512. pWalker->u.i = 0;
  76513. return WRC_Abort;
  76514. case TK_VARIABLE:
  76515. if( pWalker->u.i==4 ){
  76516. /* Silently convert bound parameters that appear inside of CREATE
  76517. ** statements into a NULL when parsing the CREATE statement text out
  76518. ** of the sqlite_master table */
  76519. pExpr->op = TK_NULL;
  76520. }else if( pWalker->u.i==3 ){
  76521. /* A bound parameter in a CREATE statement that originates from
  76522. ** sqlite3_prepare() causes an error */
  76523. pWalker->u.i = 0;
  76524. return WRC_Abort;
  76525. }
  76526. /* Fall through */
  76527. default:
  76528. testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
  76529. testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
  76530. return WRC_Continue;
  76531. }
  76532. }
  76533. static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
  76534. UNUSED_PARAMETER(NotUsed);
  76535. pWalker->u.i = 0;
  76536. return WRC_Abort;
  76537. }
  76538. static int exprIsConst(Expr *p, int initFlag){
  76539. Walker w;
  76540. memset(&w, 0, sizeof(w));
  76541. w.u.i = initFlag;
  76542. w.xExprCallback = exprNodeIsConstant;
  76543. w.xSelectCallback = selectNodeIsConstant;
  76544. sqlite3WalkExpr(&w, p);
  76545. return w.u.i;
  76546. }
  76547. /*
  76548. ** Walk an expression tree. Return 1 if the expression is constant
  76549. ** and 0 if it involves variables or function calls.
  76550. **
  76551. ** For the purposes of this function, a double-quoted string (ex: "abc")
  76552. ** is considered a variable but a single-quoted string (ex: 'abc') is
  76553. ** a constant.
  76554. */
  76555. SQLITE_PRIVATE int sqlite3ExprIsConstant(Expr *p){
  76556. return exprIsConst(p, 1);
  76557. }
  76558. /*
  76559. ** Walk an expression tree. Return 1 if the expression is constant
  76560. ** that does no originate from the ON or USING clauses of a join.
  76561. ** Return 0 if it involves variables or function calls or terms from
  76562. ** an ON or USING clause.
  76563. */
  76564. SQLITE_PRIVATE int sqlite3ExprIsConstantNotJoin(Expr *p){
  76565. return exprIsConst(p, 2);
  76566. }
  76567. /*
  76568. ** Walk an expression tree. Return 1 if the expression is constant
  76569. ** or a function call with constant arguments. Return and 0 if there
  76570. ** are any variables.
  76571. **
  76572. ** For the purposes of this function, a double-quoted string (ex: "abc")
  76573. ** is considered a variable but a single-quoted string (ex: 'abc') is
  76574. ** a constant.
  76575. */
  76576. SQLITE_PRIVATE int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
  76577. assert( isInit==0 || isInit==1 );
  76578. return exprIsConst(p, 3+isInit);
  76579. }
  76580. /*
  76581. ** If the expression p codes a constant integer that is small enough
  76582. ** to fit in a 32-bit integer, return 1 and put the value of the integer
  76583. ** in *pValue. If the expression is not an integer or if it is too big
  76584. ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
  76585. */
  76586. SQLITE_PRIVATE int sqlite3ExprIsInteger(Expr *p, int *pValue){
  76587. int rc = 0;
  76588. /* If an expression is an integer literal that fits in a signed 32-bit
  76589. ** integer, then the EP_IntValue flag will have already been set */
  76590. assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
  76591. || sqlite3GetInt32(p->u.zToken, &rc)==0 );
  76592. if( p->flags & EP_IntValue ){
  76593. *pValue = p->u.iValue;
  76594. return 1;
  76595. }
  76596. switch( p->op ){
  76597. case TK_UPLUS: {
  76598. rc = sqlite3ExprIsInteger(p->pLeft, pValue);
  76599. break;
  76600. }
  76601. case TK_UMINUS: {
  76602. int v;
  76603. if( sqlite3ExprIsInteger(p->pLeft, &v) ){
  76604. assert( v!=(-2147483647-1) );
  76605. *pValue = -v;
  76606. rc = 1;
  76607. }
  76608. break;
  76609. }
  76610. default: break;
  76611. }
  76612. return rc;
  76613. }
  76614. /*
  76615. ** Return FALSE if there is no chance that the expression can be NULL.
  76616. **
  76617. ** If the expression might be NULL or if the expression is too complex
  76618. ** to tell return TRUE.
  76619. **
  76620. ** This routine is used as an optimization, to skip OP_IsNull opcodes
  76621. ** when we know that a value cannot be NULL. Hence, a false positive
  76622. ** (returning TRUE when in fact the expression can never be NULL) might
  76623. ** be a small performance hit but is otherwise harmless. On the other
  76624. ** hand, a false negative (returning FALSE when the result could be NULL)
  76625. ** will likely result in an incorrect answer. So when in doubt, return
  76626. ** TRUE.
  76627. */
  76628. SQLITE_PRIVATE int sqlite3ExprCanBeNull(const Expr *p){
  76629. u8 op;
  76630. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  76631. op = p->op;
  76632. if( op==TK_REGISTER ) op = p->op2;
  76633. switch( op ){
  76634. case TK_INTEGER:
  76635. case TK_STRING:
  76636. case TK_FLOAT:
  76637. case TK_BLOB:
  76638. return 0;
  76639. case TK_COLUMN:
  76640. assert( p->pTab!=0 );
  76641. return ExprHasProperty(p, EP_CanBeNull) ||
  76642. (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
  76643. default:
  76644. return 1;
  76645. }
  76646. }
  76647. /*
  76648. ** Return TRUE if the given expression is a constant which would be
  76649. ** unchanged by OP_Affinity with the affinity given in the second
  76650. ** argument.
  76651. **
  76652. ** This routine is used to determine if the OP_Affinity operation
  76653. ** can be omitted. When in doubt return FALSE. A false negative
  76654. ** is harmless. A false positive, however, can result in the wrong
  76655. ** answer.
  76656. */
  76657. SQLITE_PRIVATE int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
  76658. u8 op;
  76659. if( aff==SQLITE_AFF_NONE ) return 1;
  76660. while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
  76661. op = p->op;
  76662. if( op==TK_REGISTER ) op = p->op2;
  76663. switch( op ){
  76664. case TK_INTEGER: {
  76665. return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
  76666. }
  76667. case TK_FLOAT: {
  76668. return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
  76669. }
  76670. case TK_STRING: {
  76671. return aff==SQLITE_AFF_TEXT;
  76672. }
  76673. case TK_BLOB: {
  76674. return 1;
  76675. }
  76676. case TK_COLUMN: {
  76677. assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
  76678. return p->iColumn<0
  76679. && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
  76680. }
  76681. default: {
  76682. return 0;
  76683. }
  76684. }
  76685. }
  76686. /*
  76687. ** Return TRUE if the given string is a row-id column name.
  76688. */
  76689. SQLITE_PRIVATE int sqlite3IsRowid(const char *z){
  76690. if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
  76691. if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
  76692. if( sqlite3StrICmp(z, "OID")==0 ) return 1;
  76693. return 0;
  76694. }
  76695. /*
  76696. ** Return true if we are able to the IN operator optimization on a
  76697. ** query of the form
  76698. **
  76699. ** x IN (SELECT ...)
  76700. **
  76701. ** Where the SELECT... clause is as specified by the parameter to this
  76702. ** routine.
  76703. **
  76704. ** The Select object passed in has already been preprocessed and no
  76705. ** errors have been found.
  76706. */
  76707. #ifndef SQLITE_OMIT_SUBQUERY
  76708. static int isCandidateForInOpt(Select *p){
  76709. SrcList *pSrc;
  76710. ExprList *pEList;
  76711. Table *pTab;
  76712. if( p==0 ) return 0; /* right-hand side of IN is SELECT */
  76713. if( p->pPrior ) return 0; /* Not a compound SELECT */
  76714. if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
  76715. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  76716. testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  76717. return 0; /* No DISTINCT keyword and no aggregate functions */
  76718. }
  76719. assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
  76720. if( p->pLimit ) return 0; /* Has no LIMIT clause */
  76721. assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
  76722. if( p->pWhere ) return 0; /* Has no WHERE clause */
  76723. pSrc = p->pSrc;
  76724. assert( pSrc!=0 );
  76725. if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
  76726. if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
  76727. pTab = pSrc->a[0].pTab;
  76728. if( NEVER(pTab==0) ) return 0;
  76729. assert( pTab->pSelect==0 ); /* FROM clause is not a view */
  76730. if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
  76731. pEList = p->pEList;
  76732. if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
  76733. if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
  76734. return 1;
  76735. }
  76736. #endif /* SQLITE_OMIT_SUBQUERY */
  76737. /*
  76738. ** Code an OP_Once instruction and allocate space for its flag. Return the
  76739. ** address of the new instruction.
  76740. */
  76741. SQLITE_PRIVATE int sqlite3CodeOnce(Parse *pParse){
  76742. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  76743. return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
  76744. }
  76745. /*
  76746. ** Generate code that checks the left-most column of index table iCur to see if
  76747. ** it contains any NULL entries. Cause the register at regHasNull to be set
  76748. ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
  76749. ** to be set to NULL if iCur contains one or more NULL values.
  76750. */
  76751. static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
  76752. int j1;
  76753. sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
  76754. j1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
  76755. sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
  76756. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  76757. VdbeComment((v, "first_entry_in(%d)", iCur));
  76758. sqlite3VdbeJumpHere(v, j1);
  76759. }
  76760. #ifndef SQLITE_OMIT_SUBQUERY
  76761. /*
  76762. ** The argument is an IN operator with a list (not a subquery) on the
  76763. ** right-hand side. Return TRUE if that list is constant.
  76764. */
  76765. static int sqlite3InRhsIsConstant(Expr *pIn){
  76766. Expr *pLHS;
  76767. int res;
  76768. assert( !ExprHasProperty(pIn, EP_xIsSelect) );
  76769. pLHS = pIn->pLeft;
  76770. pIn->pLeft = 0;
  76771. res = sqlite3ExprIsConstant(pIn);
  76772. pIn->pLeft = pLHS;
  76773. return res;
  76774. }
  76775. #endif
  76776. /*
  76777. ** This function is used by the implementation of the IN (...) operator.
  76778. ** The pX parameter is the expression on the RHS of the IN operator, which
  76779. ** might be either a list of expressions or a subquery.
  76780. **
  76781. ** The job of this routine is to find or create a b-tree object that can
  76782. ** be used either to test for membership in the RHS set or to iterate through
  76783. ** all members of the RHS set, skipping duplicates.
  76784. **
  76785. ** A cursor is opened on the b-tree object that is the RHS of the IN operator
  76786. ** and pX->iTable is set to the index of that cursor.
  76787. **
  76788. ** The returned value of this function indicates the b-tree type, as follows:
  76789. **
  76790. ** IN_INDEX_ROWID - The cursor was opened on a database table.
  76791. ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
  76792. ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
  76793. ** IN_INDEX_EPH - The cursor was opened on a specially created and
  76794. ** populated epheremal table.
  76795. ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
  76796. ** implemented as a sequence of comparisons.
  76797. **
  76798. ** An existing b-tree might be used if the RHS expression pX is a simple
  76799. ** subquery such as:
  76800. **
  76801. ** SELECT <column> FROM <table>
  76802. **
  76803. ** If the RHS of the IN operator is a list or a more complex subquery, then
  76804. ** an ephemeral table might need to be generated from the RHS and then
  76805. ** pX->iTable made to point to the ephemeral table instead of an
  76806. ** existing table.
  76807. **
  76808. ** The inFlags parameter must contain exactly one of the bits
  76809. ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
  76810. ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
  76811. ** fast membership test. When the IN_INDEX_LOOP bit is set, the
  76812. ** IN index will be used to loop over all values of the RHS of the
  76813. ** IN operator.
  76814. **
  76815. ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
  76816. ** through the set members) then the b-tree must not contain duplicates.
  76817. ** An epheremal table must be used unless the selected <column> is guaranteed
  76818. ** to be unique - either because it is an INTEGER PRIMARY KEY or it
  76819. ** has a UNIQUE constraint or UNIQUE index.
  76820. **
  76821. ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
  76822. ** for fast set membership tests) then an epheremal table must
  76823. ** be used unless <column> is an INTEGER PRIMARY KEY or an index can
  76824. ** be found with <column> as its left-most column.
  76825. **
  76826. ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
  76827. ** if the RHS of the IN operator is a list (not a subquery) then this
  76828. ** routine might decide that creating an ephemeral b-tree for membership
  76829. ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
  76830. ** calling routine should implement the IN operator using a sequence
  76831. ** of Eq or Ne comparison operations.
  76832. **
  76833. ** When the b-tree is being used for membership tests, the calling function
  76834. ** might need to know whether or not the RHS side of the IN operator
  76835. ** contains a NULL. If prRhsHasNull is not a NULL pointer and
  76836. ** if there is any chance that the (...) might contain a NULL value at
  76837. ** runtime, then a register is allocated and the register number written
  76838. ** to *prRhsHasNull. If there is no chance that the (...) contains a
  76839. ** NULL value, then *prRhsHasNull is left unchanged.
  76840. **
  76841. ** If a register is allocated and its location stored in *prRhsHasNull, then
  76842. ** the value in that register will be NULL if the b-tree contains one or more
  76843. ** NULL values, and it will be some non-NULL value if the b-tree contains no
  76844. ** NULL values.
  76845. */
  76846. #ifndef SQLITE_OMIT_SUBQUERY
  76847. SQLITE_PRIVATE int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
  76848. Select *p; /* SELECT to the right of IN operator */
  76849. int eType = 0; /* Type of RHS table. IN_INDEX_* */
  76850. int iTab = pParse->nTab++; /* Cursor of the RHS table */
  76851. int mustBeUnique; /* True if RHS must be unique */
  76852. Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
  76853. assert( pX->op==TK_IN );
  76854. mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
  76855. /* Check to see if an existing table or index can be used to
  76856. ** satisfy the query. This is preferable to generating a new
  76857. ** ephemeral table.
  76858. */
  76859. p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
  76860. if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
  76861. sqlite3 *db = pParse->db; /* Database connection */
  76862. Table *pTab; /* Table <table>. */
  76863. Expr *pExpr; /* Expression <column> */
  76864. i16 iCol; /* Index of column <column> */
  76865. i16 iDb; /* Database idx for pTab */
  76866. assert( p ); /* Because of isCandidateForInOpt(p) */
  76867. assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
  76868. assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
  76869. assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
  76870. pTab = p->pSrc->a[0].pTab;
  76871. pExpr = p->pEList->a[0].pExpr;
  76872. iCol = (i16)pExpr->iColumn;
  76873. /* Code an OP_Transaction and OP_TableLock for <table>. */
  76874. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  76875. sqlite3CodeVerifySchema(pParse, iDb);
  76876. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  76877. /* This function is only called from two places. In both cases the vdbe
  76878. ** has already been allocated. So assume sqlite3GetVdbe() is always
  76879. ** successful here.
  76880. */
  76881. assert(v);
  76882. if( iCol<0 ){
  76883. int iAddr = sqlite3CodeOnce(pParse);
  76884. VdbeCoverage(v);
  76885. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  76886. eType = IN_INDEX_ROWID;
  76887. sqlite3VdbeJumpHere(v, iAddr);
  76888. }else{
  76889. Index *pIdx; /* Iterator variable */
  76890. /* The collation sequence used by the comparison. If an index is to
  76891. ** be used in place of a temp-table, it must be ordered according
  76892. ** to this collation sequence. */
  76893. CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
  76894. /* Check that the affinity that will be used to perform the
  76895. ** comparison is the same as the affinity of the column. If
  76896. ** it is not, it is not possible to use any index.
  76897. */
  76898. int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
  76899. for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
  76900. if( (pIdx->aiColumn[0]==iCol)
  76901. && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
  76902. && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
  76903. ){
  76904. int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  76905. sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
  76906. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  76907. VdbeComment((v, "%s", pIdx->zName));
  76908. assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
  76909. eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
  76910. if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
  76911. *prRhsHasNull = ++pParse->nMem;
  76912. sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
  76913. }
  76914. sqlite3VdbeJumpHere(v, iAddr);
  76915. }
  76916. }
  76917. }
  76918. }
  76919. /* If no preexisting index is available for the IN clause
  76920. ** and IN_INDEX_NOOP is an allowed reply
  76921. ** and the RHS of the IN operator is a list, not a subquery
  76922. ** and the RHS is not contant or has two or fewer terms,
  76923. ** then it is not worth creating an ephemeral table to evaluate
  76924. ** the IN operator so return IN_INDEX_NOOP.
  76925. */
  76926. if( eType==0
  76927. && (inFlags & IN_INDEX_NOOP_OK)
  76928. && !ExprHasProperty(pX, EP_xIsSelect)
  76929. && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
  76930. ){
  76931. eType = IN_INDEX_NOOP;
  76932. }
  76933. if( eType==0 ){
  76934. /* Could not find an existing table or index to use as the RHS b-tree.
  76935. ** We will have to generate an ephemeral table to do the job.
  76936. */
  76937. u32 savedNQueryLoop = pParse->nQueryLoop;
  76938. int rMayHaveNull = 0;
  76939. eType = IN_INDEX_EPH;
  76940. if( inFlags & IN_INDEX_LOOP ){
  76941. pParse->nQueryLoop = 0;
  76942. if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
  76943. eType = IN_INDEX_ROWID;
  76944. }
  76945. }else if( prRhsHasNull ){
  76946. *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
  76947. }
  76948. sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
  76949. pParse->nQueryLoop = savedNQueryLoop;
  76950. }else{
  76951. pX->iTable = iTab;
  76952. }
  76953. return eType;
  76954. }
  76955. #endif
  76956. /*
  76957. ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
  76958. ** or IN operators. Examples:
  76959. **
  76960. ** (SELECT a FROM b) -- subquery
  76961. ** EXISTS (SELECT a FROM b) -- EXISTS subquery
  76962. ** x IN (4,5,11) -- IN operator with list on right-hand side
  76963. ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
  76964. **
  76965. ** The pExpr parameter describes the expression that contains the IN
  76966. ** operator or subquery.
  76967. **
  76968. ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
  76969. ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
  76970. ** to some integer key column of a table B-Tree. In this case, use an
  76971. ** intkey B-Tree to store the set of IN(...) values instead of the usual
  76972. ** (slower) variable length keys B-Tree.
  76973. **
  76974. ** If rMayHaveNull is non-zero, that means that the operation is an IN
  76975. ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
  76976. ** All this routine does is initialize the register given by rMayHaveNull
  76977. ** to NULL. Calling routines will take care of changing this register
  76978. ** value to non-NULL if the RHS is NULL-free.
  76979. **
  76980. ** For a SELECT or EXISTS operator, return the register that holds the
  76981. ** result. For IN operators or if an error occurs, the return value is 0.
  76982. */
  76983. #ifndef SQLITE_OMIT_SUBQUERY
  76984. SQLITE_PRIVATE int sqlite3CodeSubselect(
  76985. Parse *pParse, /* Parsing context */
  76986. Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
  76987. int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
  76988. int isRowid /* If true, LHS of IN operator is a rowid */
  76989. ){
  76990. int jmpIfDynamic = -1; /* One-time test address */
  76991. int rReg = 0; /* Register storing resulting */
  76992. Vdbe *v = sqlite3GetVdbe(pParse);
  76993. if( NEVER(v==0) ) return 0;
  76994. sqlite3ExprCachePush(pParse);
  76995. /* This code must be run in its entirety every time it is encountered
  76996. ** if any of the following is true:
  76997. **
  76998. ** * The right-hand side is a correlated subquery
  76999. ** * The right-hand side is an expression list containing variables
  77000. ** * We are inside a trigger
  77001. **
  77002. ** If all of the above are false, then we can run this code just once
  77003. ** save the results, and reuse the same result on subsequent invocations.
  77004. */
  77005. if( !ExprHasProperty(pExpr, EP_VarSelect) ){
  77006. jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  77007. }
  77008. #ifndef SQLITE_OMIT_EXPLAIN
  77009. if( pParse->explain==2 ){
  77010. char *zMsg = sqlite3MPrintf(
  77011. pParse->db, "EXECUTE %s%s SUBQUERY %d", jmpIfDynamic>=0?"":"CORRELATED ",
  77012. pExpr->op==TK_IN?"LIST":"SCALAR", pParse->iNextSelectId
  77013. );
  77014. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  77015. }
  77016. #endif
  77017. switch( pExpr->op ){
  77018. case TK_IN: {
  77019. char affinity; /* Affinity of the LHS of the IN */
  77020. int addr; /* Address of OP_OpenEphemeral instruction */
  77021. Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
  77022. KeyInfo *pKeyInfo = 0; /* Key information */
  77023. affinity = sqlite3ExprAffinity(pLeft);
  77024. /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
  77025. ** expression it is handled the same way. An ephemeral table is
  77026. ** filled with single-field index keys representing the results
  77027. ** from the SELECT or the <exprlist>.
  77028. **
  77029. ** If the 'x' expression is a column value, or the SELECT...
  77030. ** statement returns a column value, then the affinity of that
  77031. ** column is used to build the index keys. If both 'x' and the
  77032. ** SELECT... statement are columns, then numeric affinity is used
  77033. ** if either column has NUMERIC or INTEGER affinity. If neither
  77034. ** 'x' nor the SELECT... statement are columns, then numeric affinity
  77035. ** is used.
  77036. */
  77037. pExpr->iTable = pParse->nTab++;
  77038. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
  77039. pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
  77040. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  77041. /* Case 1: expr IN (SELECT ...)
  77042. **
  77043. ** Generate code to write the results of the select into the temporary
  77044. ** table allocated and opened above.
  77045. */
  77046. Select *pSelect = pExpr->x.pSelect;
  77047. SelectDest dest;
  77048. ExprList *pEList;
  77049. assert( !isRowid );
  77050. sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
  77051. dest.affSdst = (u8)affinity;
  77052. assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
  77053. pSelect->iLimit = 0;
  77054. testcase( pSelect->selFlags & SF_Distinct );
  77055. testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
  77056. if( sqlite3Select(pParse, pSelect, &dest) ){
  77057. sqlite3KeyInfoUnref(pKeyInfo);
  77058. return 0;
  77059. }
  77060. pEList = pSelect->pEList;
  77061. assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
  77062. assert( pEList!=0 );
  77063. assert( pEList->nExpr>0 );
  77064. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  77065. pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
  77066. pEList->a[0].pExpr);
  77067. }else if( ALWAYS(pExpr->x.pList!=0) ){
  77068. /* Case 2: expr IN (exprlist)
  77069. **
  77070. ** For each expression, build an index key from the evaluation and
  77071. ** store it in the temporary table. If <expr> is a column, then use
  77072. ** that columns affinity when building index keys. If <expr> is not
  77073. ** a column, use numeric affinity.
  77074. */
  77075. int i;
  77076. ExprList *pList = pExpr->x.pList;
  77077. struct ExprList_item *pItem;
  77078. int r1, r2, r3;
  77079. if( !affinity ){
  77080. affinity = SQLITE_AFF_NONE;
  77081. }
  77082. if( pKeyInfo ){
  77083. assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
  77084. pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  77085. }
  77086. /* Loop through each expression in <exprlist>. */
  77087. r1 = sqlite3GetTempReg(pParse);
  77088. r2 = sqlite3GetTempReg(pParse);
  77089. if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
  77090. for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
  77091. Expr *pE2 = pItem->pExpr;
  77092. int iValToIns;
  77093. /* If the expression is not constant then we will need to
  77094. ** disable the test that was generated above that makes sure
  77095. ** this code only executes once. Because for a non-constant
  77096. ** expression we need to rerun this code each time.
  77097. */
  77098. if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
  77099. sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
  77100. jmpIfDynamic = -1;
  77101. }
  77102. /* Evaluate the expression and insert it into the temp table */
  77103. if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
  77104. sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
  77105. }else{
  77106. r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
  77107. if( isRowid ){
  77108. sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
  77109. sqlite3VdbeCurrentAddr(v)+2);
  77110. VdbeCoverage(v);
  77111. sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
  77112. }else{
  77113. sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
  77114. sqlite3ExprCacheAffinityChange(pParse, r3, 1);
  77115. sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
  77116. }
  77117. }
  77118. }
  77119. sqlite3ReleaseTempReg(pParse, r1);
  77120. sqlite3ReleaseTempReg(pParse, r2);
  77121. }
  77122. if( pKeyInfo ){
  77123. sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
  77124. }
  77125. break;
  77126. }
  77127. case TK_EXISTS:
  77128. case TK_SELECT:
  77129. default: {
  77130. /* If this has to be a scalar SELECT. Generate code to put the
  77131. ** value of this select in a memory cell and record the number
  77132. ** of the memory cell in iColumn. If this is an EXISTS, write
  77133. ** an integer 0 (not exists) or 1 (exists) into a memory cell
  77134. ** and record that memory cell in iColumn.
  77135. */
  77136. Select *pSel; /* SELECT statement to encode */
  77137. SelectDest dest; /* How to deal with SELECt result */
  77138. testcase( pExpr->op==TK_EXISTS );
  77139. testcase( pExpr->op==TK_SELECT );
  77140. assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
  77141. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  77142. pSel = pExpr->x.pSelect;
  77143. sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
  77144. if( pExpr->op==TK_SELECT ){
  77145. dest.eDest = SRT_Mem;
  77146. dest.iSdst = dest.iSDParm;
  77147. sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
  77148. VdbeComment((v, "Init subquery result"));
  77149. }else{
  77150. dest.eDest = SRT_Exists;
  77151. sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
  77152. VdbeComment((v, "Init EXISTS result"));
  77153. }
  77154. sqlite3ExprDelete(pParse->db, pSel->pLimit);
  77155. pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
  77156. &sqlite3IntTokens[1]);
  77157. pSel->iLimit = 0;
  77158. if( sqlite3Select(pParse, pSel, &dest) ){
  77159. return 0;
  77160. }
  77161. rReg = dest.iSDParm;
  77162. ExprSetVVAProperty(pExpr, EP_NoReduce);
  77163. break;
  77164. }
  77165. }
  77166. if( rHasNullFlag ){
  77167. sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
  77168. }
  77169. if( jmpIfDynamic>=0 ){
  77170. sqlite3VdbeJumpHere(v, jmpIfDynamic);
  77171. }
  77172. sqlite3ExprCachePop(pParse);
  77173. return rReg;
  77174. }
  77175. #endif /* SQLITE_OMIT_SUBQUERY */
  77176. #ifndef SQLITE_OMIT_SUBQUERY
  77177. /*
  77178. ** Generate code for an IN expression.
  77179. **
  77180. ** x IN (SELECT ...)
  77181. ** x IN (value, value, ...)
  77182. **
  77183. ** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
  77184. ** is an array of zero or more values. The expression is true if the LHS is
  77185. ** contained within the RHS. The value of the expression is unknown (NULL)
  77186. ** if the LHS is NULL or if the LHS is not contained within the RHS and the
  77187. ** RHS contains one or more NULL values.
  77188. **
  77189. ** This routine generates code that jumps to destIfFalse if the LHS is not
  77190. ** contained within the RHS. If due to NULLs we cannot determine if the LHS
  77191. ** is contained in the RHS then jump to destIfNull. If the LHS is contained
  77192. ** within the RHS then fall through.
  77193. */
  77194. static void sqlite3ExprCodeIN(
  77195. Parse *pParse, /* Parsing and code generating context */
  77196. Expr *pExpr, /* The IN expression */
  77197. int destIfFalse, /* Jump here if LHS is not contained in the RHS */
  77198. int destIfNull /* Jump here if the results are unknown due to NULLs */
  77199. ){
  77200. int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
  77201. char affinity; /* Comparison affinity to use */
  77202. int eType; /* Type of the RHS */
  77203. int r1; /* Temporary use register */
  77204. Vdbe *v; /* Statement under construction */
  77205. /* Compute the RHS. After this step, the table with cursor
  77206. ** pExpr->iTable will contains the values that make up the RHS.
  77207. */
  77208. v = pParse->pVdbe;
  77209. assert( v!=0 ); /* OOM detected prior to this routine */
  77210. VdbeNoopComment((v, "begin IN expr"));
  77211. eType = sqlite3FindInIndex(pParse, pExpr,
  77212. IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
  77213. destIfFalse==destIfNull ? 0 : &rRhsHasNull);
  77214. /* Figure out the affinity to use to create a key from the results
  77215. ** of the expression. affinityStr stores a static string suitable for
  77216. ** P4 of OP_MakeRecord.
  77217. */
  77218. affinity = comparisonAffinity(pExpr);
  77219. /* Code the LHS, the <expr> from "<expr> IN (...)".
  77220. */
  77221. sqlite3ExprCachePush(pParse);
  77222. r1 = sqlite3GetTempReg(pParse);
  77223. sqlite3ExprCode(pParse, pExpr->pLeft, r1);
  77224. /* If sqlite3FindInIndex() did not find or create an index that is
  77225. ** suitable for evaluating the IN operator, then evaluate using a
  77226. ** sequence of comparisons.
  77227. */
  77228. if( eType==IN_INDEX_NOOP ){
  77229. ExprList *pList = pExpr->x.pList;
  77230. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
  77231. int labelOk = sqlite3VdbeMakeLabel(v);
  77232. int r2, regToFree;
  77233. int regCkNull = 0;
  77234. int ii;
  77235. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77236. if( destIfNull!=destIfFalse ){
  77237. regCkNull = sqlite3GetTempReg(pParse);
  77238. sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
  77239. }
  77240. for(ii=0; ii<pList->nExpr; ii++){
  77241. r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
  77242. if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
  77243. sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
  77244. }
  77245. if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
  77246. sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
  77247. (void*)pColl, P4_COLLSEQ);
  77248. VdbeCoverageIf(v, ii<pList->nExpr-1);
  77249. VdbeCoverageIf(v, ii==pList->nExpr-1);
  77250. sqlite3VdbeChangeP5(v, affinity);
  77251. }else{
  77252. assert( destIfNull==destIfFalse );
  77253. sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
  77254. (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
  77255. sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
  77256. }
  77257. sqlite3ReleaseTempReg(pParse, regToFree);
  77258. }
  77259. if( regCkNull ){
  77260. sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
  77261. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  77262. }
  77263. sqlite3VdbeResolveLabel(v, labelOk);
  77264. sqlite3ReleaseTempReg(pParse, regCkNull);
  77265. }else{
  77266. /* If the LHS is NULL, then the result is either false or NULL depending
  77267. ** on whether the RHS is empty or not, respectively.
  77268. */
  77269. if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
  77270. if( destIfNull==destIfFalse ){
  77271. /* Shortcut for the common case where the false and NULL outcomes are
  77272. ** the same. */
  77273. sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
  77274. }else{
  77275. int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
  77276. sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
  77277. VdbeCoverage(v);
  77278. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
  77279. sqlite3VdbeJumpHere(v, addr1);
  77280. }
  77281. }
  77282. if( eType==IN_INDEX_ROWID ){
  77283. /* In this case, the RHS is the ROWID of table b-tree
  77284. */
  77285. sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
  77286. sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
  77287. VdbeCoverage(v);
  77288. }else{
  77289. /* In this case, the RHS is an index b-tree.
  77290. */
  77291. sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
  77292. /* If the set membership test fails, then the result of the
  77293. ** "x IN (...)" expression must be either 0 or NULL. If the set
  77294. ** contains no NULL values, then the result is 0. If the set
  77295. ** contains one or more NULL values, then the result of the
  77296. ** expression is also NULL.
  77297. */
  77298. assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
  77299. if( rRhsHasNull==0 ){
  77300. /* This branch runs if it is known at compile time that the RHS
  77301. ** cannot contain NULL values. This happens as the result
  77302. ** of a "NOT NULL" constraint in the database schema.
  77303. **
  77304. ** Also run this branch if NULL is equivalent to FALSE
  77305. ** for this particular IN operator.
  77306. */
  77307. sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
  77308. VdbeCoverage(v);
  77309. }else{
  77310. /* In this branch, the RHS of the IN might contain a NULL and
  77311. ** the presence of a NULL on the RHS makes a difference in the
  77312. ** outcome.
  77313. */
  77314. int j1;
  77315. /* First check to see if the LHS is contained in the RHS. If so,
  77316. ** then the answer is TRUE the presence of NULLs in the RHS does
  77317. ** not matter. If the LHS is not contained in the RHS, then the
  77318. ** answer is NULL if the RHS contains NULLs and the answer is
  77319. ** FALSE if the RHS is NULL-free.
  77320. */
  77321. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
  77322. VdbeCoverage(v);
  77323. sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
  77324. VdbeCoverage(v);
  77325. sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
  77326. sqlite3VdbeJumpHere(v, j1);
  77327. }
  77328. }
  77329. }
  77330. sqlite3ReleaseTempReg(pParse, r1);
  77331. sqlite3ExprCachePop(pParse);
  77332. VdbeComment((v, "end IN expr"));
  77333. }
  77334. #endif /* SQLITE_OMIT_SUBQUERY */
  77335. /*
  77336. ** Duplicate an 8-byte value
  77337. */
  77338. static char *dup8bytes(Vdbe *v, const char *in){
  77339. char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
  77340. if( out ){
  77341. memcpy(out, in, 8);
  77342. }
  77343. return out;
  77344. }
  77345. #ifndef SQLITE_OMIT_FLOATING_POINT
  77346. /*
  77347. ** Generate an instruction that will put the floating point
  77348. ** value described by z[0..n-1] into register iMem.
  77349. **
  77350. ** The z[] string will probably not be zero-terminated. But the
  77351. ** z[n] character is guaranteed to be something that does not look
  77352. ** like the continuation of the number.
  77353. */
  77354. static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
  77355. if( ALWAYS(z!=0) ){
  77356. double value;
  77357. char *zV;
  77358. sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
  77359. assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
  77360. if( negateFlag ) value = -value;
  77361. zV = dup8bytes(v, (char*)&value);
  77362. sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
  77363. }
  77364. }
  77365. #endif
  77366. /*
  77367. ** Generate an instruction that will put the integer describe by
  77368. ** text z[0..n-1] into register iMem.
  77369. **
  77370. ** Expr.u.zToken is always UTF8 and zero-terminated.
  77371. */
  77372. static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
  77373. Vdbe *v = pParse->pVdbe;
  77374. if( pExpr->flags & EP_IntValue ){
  77375. int i = pExpr->u.iValue;
  77376. assert( i>=0 );
  77377. if( negFlag ) i = -i;
  77378. sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
  77379. }else{
  77380. int c;
  77381. i64 value;
  77382. const char *z = pExpr->u.zToken;
  77383. assert( z!=0 );
  77384. c = sqlite3DecOrHexToI64(z, &value);
  77385. if( c==0 || (c==2 && negFlag) ){
  77386. char *zV;
  77387. if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
  77388. zV = dup8bytes(v, (char*)&value);
  77389. sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
  77390. }else{
  77391. #ifdef SQLITE_OMIT_FLOATING_POINT
  77392. sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
  77393. #else
  77394. #ifndef SQLITE_OMIT_HEX_INTEGER
  77395. if( sqlite3_strnicmp(z,"0x",2)==0 ){
  77396. sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
  77397. }else
  77398. #endif
  77399. {
  77400. codeReal(v, z, negFlag, iMem);
  77401. }
  77402. #endif
  77403. }
  77404. }
  77405. }
  77406. /*
  77407. ** Clear a cache entry.
  77408. */
  77409. static void cacheEntryClear(Parse *pParse, struct yColCache *p){
  77410. if( p->tempReg ){
  77411. if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  77412. pParse->aTempReg[pParse->nTempReg++] = p->iReg;
  77413. }
  77414. p->tempReg = 0;
  77415. }
  77416. }
  77417. /*
  77418. ** Record in the column cache that a particular column from a
  77419. ** particular table is stored in a particular register.
  77420. */
  77421. SQLITE_PRIVATE void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
  77422. int i;
  77423. int minLru;
  77424. int idxLru;
  77425. struct yColCache *p;
  77426. assert( iReg>0 ); /* Register numbers are always positive */
  77427. assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
  77428. /* The SQLITE_ColumnCache flag disables the column cache. This is used
  77429. ** for testing only - to verify that SQLite always gets the same answer
  77430. ** with and without the column cache.
  77431. */
  77432. if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
  77433. /* First replace any existing entry.
  77434. **
  77435. ** Actually, the way the column cache is currently used, we are guaranteed
  77436. ** that the object will never already be in cache. Verify this guarantee.
  77437. */
  77438. #ifndef NDEBUG
  77439. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77440. assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
  77441. }
  77442. #endif
  77443. /* Find an empty slot and replace it */
  77444. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77445. if( p->iReg==0 ){
  77446. p->iLevel = pParse->iCacheLevel;
  77447. p->iTable = iTab;
  77448. p->iColumn = iCol;
  77449. p->iReg = iReg;
  77450. p->tempReg = 0;
  77451. p->lru = pParse->iCacheCnt++;
  77452. return;
  77453. }
  77454. }
  77455. /* Replace the last recently used */
  77456. minLru = 0x7fffffff;
  77457. idxLru = -1;
  77458. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77459. if( p->lru<minLru ){
  77460. idxLru = i;
  77461. minLru = p->lru;
  77462. }
  77463. }
  77464. if( ALWAYS(idxLru>=0) ){
  77465. p = &pParse->aColCache[idxLru];
  77466. p->iLevel = pParse->iCacheLevel;
  77467. p->iTable = iTab;
  77468. p->iColumn = iCol;
  77469. p->iReg = iReg;
  77470. p->tempReg = 0;
  77471. p->lru = pParse->iCacheCnt++;
  77472. return;
  77473. }
  77474. }
  77475. /*
  77476. ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
  77477. ** Purge the range of registers from the column cache.
  77478. */
  77479. SQLITE_PRIVATE void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
  77480. int i;
  77481. int iLast = iReg + nReg - 1;
  77482. struct yColCache *p;
  77483. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77484. int r = p->iReg;
  77485. if( r>=iReg && r<=iLast ){
  77486. cacheEntryClear(pParse, p);
  77487. p->iReg = 0;
  77488. }
  77489. }
  77490. }
  77491. /*
  77492. ** Remember the current column cache context. Any new entries added
  77493. ** added to the column cache after this call are removed when the
  77494. ** corresponding pop occurs.
  77495. */
  77496. SQLITE_PRIVATE void sqlite3ExprCachePush(Parse *pParse){
  77497. pParse->iCacheLevel++;
  77498. #ifdef SQLITE_DEBUG
  77499. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  77500. printf("PUSH to %d\n", pParse->iCacheLevel);
  77501. }
  77502. #endif
  77503. }
  77504. /*
  77505. ** Remove from the column cache any entries that were added since the
  77506. ** the previous sqlite3ExprCachePush operation. In other words, restore
  77507. ** the cache to the state it was in prior the most recent Push.
  77508. */
  77509. SQLITE_PRIVATE void sqlite3ExprCachePop(Parse *pParse){
  77510. int i;
  77511. struct yColCache *p;
  77512. assert( pParse->iCacheLevel>=1 );
  77513. pParse->iCacheLevel--;
  77514. #ifdef SQLITE_DEBUG
  77515. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  77516. printf("POP to %d\n", pParse->iCacheLevel);
  77517. }
  77518. #endif
  77519. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77520. if( p->iReg && p->iLevel>pParse->iCacheLevel ){
  77521. cacheEntryClear(pParse, p);
  77522. p->iReg = 0;
  77523. }
  77524. }
  77525. }
  77526. /*
  77527. ** When a cached column is reused, make sure that its register is
  77528. ** no longer available as a temp register. ticket #3879: that same
  77529. ** register might be in the cache in multiple places, so be sure to
  77530. ** get them all.
  77531. */
  77532. static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
  77533. int i;
  77534. struct yColCache *p;
  77535. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77536. if( p->iReg==iReg ){
  77537. p->tempReg = 0;
  77538. }
  77539. }
  77540. }
  77541. /*
  77542. ** Generate code to extract the value of the iCol-th column of a table.
  77543. */
  77544. SQLITE_PRIVATE void sqlite3ExprCodeGetColumnOfTable(
  77545. Vdbe *v, /* The VDBE under construction */
  77546. Table *pTab, /* The table containing the value */
  77547. int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
  77548. int iCol, /* Index of the column to extract */
  77549. int regOut /* Extract the value into this register */
  77550. ){
  77551. if( iCol<0 || iCol==pTab->iPKey ){
  77552. sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
  77553. }else{
  77554. int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
  77555. int x = iCol;
  77556. if( !HasRowid(pTab) ){
  77557. x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
  77558. }
  77559. sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
  77560. }
  77561. if( iCol>=0 ){
  77562. sqlite3ColumnDefault(v, pTab, iCol, regOut);
  77563. }
  77564. }
  77565. /*
  77566. ** Generate code that will extract the iColumn-th column from
  77567. ** table pTab and store the column value in a register. An effort
  77568. ** is made to store the column value in register iReg, but this is
  77569. ** not guaranteed. The location of the column value is returned.
  77570. **
  77571. ** There must be an open cursor to pTab in iTable when this routine
  77572. ** is called. If iColumn<0 then code is generated that extracts the rowid.
  77573. */
  77574. SQLITE_PRIVATE int sqlite3ExprCodeGetColumn(
  77575. Parse *pParse, /* Parsing and code generating context */
  77576. Table *pTab, /* Description of the table we are reading from */
  77577. int iColumn, /* Index of the table column */
  77578. int iTable, /* The cursor pointing to the table */
  77579. int iReg, /* Store results here */
  77580. u8 p5 /* P5 value for OP_Column */
  77581. ){
  77582. Vdbe *v = pParse->pVdbe;
  77583. int i;
  77584. struct yColCache *p;
  77585. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77586. if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
  77587. p->lru = pParse->iCacheCnt++;
  77588. sqlite3ExprCachePinRegister(pParse, p->iReg);
  77589. return p->iReg;
  77590. }
  77591. }
  77592. assert( v!=0 );
  77593. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
  77594. if( p5 ){
  77595. sqlite3VdbeChangeP5(v, p5);
  77596. }else{
  77597. sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
  77598. }
  77599. return iReg;
  77600. }
  77601. /*
  77602. ** Clear all column cache entries.
  77603. */
  77604. SQLITE_PRIVATE void sqlite3ExprCacheClear(Parse *pParse){
  77605. int i;
  77606. struct yColCache *p;
  77607. #if SQLITE_DEBUG
  77608. if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
  77609. printf("CLEAR\n");
  77610. }
  77611. #endif
  77612. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77613. if( p->iReg ){
  77614. cacheEntryClear(pParse, p);
  77615. p->iReg = 0;
  77616. }
  77617. }
  77618. }
  77619. /*
  77620. ** Record the fact that an affinity change has occurred on iCount
  77621. ** registers starting with iStart.
  77622. */
  77623. SQLITE_PRIVATE void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
  77624. sqlite3ExprCacheRemove(pParse, iStart, iCount);
  77625. }
  77626. /*
  77627. ** Generate code to move content from registers iFrom...iFrom+nReg-1
  77628. ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
  77629. */
  77630. SQLITE_PRIVATE void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
  77631. assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
  77632. sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
  77633. sqlite3ExprCacheRemove(pParse, iFrom, nReg);
  77634. }
  77635. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  77636. /*
  77637. ** Return true if any register in the range iFrom..iTo (inclusive)
  77638. ** is used as part of the column cache.
  77639. **
  77640. ** This routine is used within assert() and testcase() macros only
  77641. ** and does not appear in a normal build.
  77642. */
  77643. static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
  77644. int i;
  77645. struct yColCache *p;
  77646. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  77647. int r = p->iReg;
  77648. if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
  77649. }
  77650. return 0;
  77651. }
  77652. #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
  77653. /*
  77654. ** Convert an expression node to a TK_REGISTER
  77655. */
  77656. static void exprToRegister(Expr *p, int iReg){
  77657. p->op2 = p->op;
  77658. p->op = TK_REGISTER;
  77659. p->iTable = iReg;
  77660. ExprClearProperty(p, EP_Skip);
  77661. }
  77662. /*
  77663. ** Generate code into the current Vdbe to evaluate the given
  77664. ** expression. Attempt to store the results in register "target".
  77665. ** Return the register where results are stored.
  77666. **
  77667. ** With this routine, there is no guarantee that results will
  77668. ** be stored in target. The result might be stored in some other
  77669. ** register if it is convenient to do so. The calling function
  77670. ** must check the return code and move the results to the desired
  77671. ** register.
  77672. */
  77673. SQLITE_PRIVATE int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
  77674. Vdbe *v = pParse->pVdbe; /* The VM under construction */
  77675. int op; /* The opcode being coded */
  77676. int inReg = target; /* Results stored in register inReg */
  77677. int regFree1 = 0; /* If non-zero free this temporary register */
  77678. int regFree2 = 0; /* If non-zero free this temporary register */
  77679. int r1, r2, r3, r4; /* Various register numbers */
  77680. sqlite3 *db = pParse->db; /* The database connection */
  77681. Expr tempX; /* Temporary expression node */
  77682. assert( target>0 && target<=pParse->nMem );
  77683. if( v==0 ){
  77684. assert( pParse->db->mallocFailed );
  77685. return 0;
  77686. }
  77687. if( pExpr==0 ){
  77688. op = TK_NULL;
  77689. }else{
  77690. op = pExpr->op;
  77691. }
  77692. switch( op ){
  77693. case TK_AGG_COLUMN: {
  77694. AggInfo *pAggInfo = pExpr->pAggInfo;
  77695. struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
  77696. if( !pAggInfo->directMode ){
  77697. assert( pCol->iMem>0 );
  77698. inReg = pCol->iMem;
  77699. break;
  77700. }else if( pAggInfo->useSortingIdx ){
  77701. sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
  77702. pCol->iSorterColumn, target);
  77703. break;
  77704. }
  77705. /* Otherwise, fall thru into the TK_COLUMN case */
  77706. }
  77707. case TK_COLUMN: {
  77708. int iTab = pExpr->iTable;
  77709. if( iTab<0 ){
  77710. if( pParse->ckBase>0 ){
  77711. /* Generating CHECK constraints or inserting into partial index */
  77712. inReg = pExpr->iColumn + pParse->ckBase;
  77713. break;
  77714. }else{
  77715. /* Deleting from a partial index */
  77716. iTab = pParse->iPartIdxTab;
  77717. }
  77718. }
  77719. inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
  77720. pExpr->iColumn, iTab, target,
  77721. pExpr->op2);
  77722. break;
  77723. }
  77724. case TK_INTEGER: {
  77725. codeInteger(pParse, pExpr, 0, target);
  77726. break;
  77727. }
  77728. #ifndef SQLITE_OMIT_FLOATING_POINT
  77729. case TK_FLOAT: {
  77730. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77731. codeReal(v, pExpr->u.zToken, 0, target);
  77732. break;
  77733. }
  77734. #endif
  77735. case TK_STRING: {
  77736. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77737. sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
  77738. break;
  77739. }
  77740. case TK_NULL: {
  77741. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  77742. break;
  77743. }
  77744. #ifndef SQLITE_OMIT_BLOB_LITERAL
  77745. case TK_BLOB: {
  77746. int n;
  77747. const char *z;
  77748. char *zBlob;
  77749. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77750. assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
  77751. assert( pExpr->u.zToken[1]=='\'' );
  77752. z = &pExpr->u.zToken[2];
  77753. n = sqlite3Strlen30(z) - 1;
  77754. assert( z[n]=='\'' );
  77755. zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
  77756. sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
  77757. break;
  77758. }
  77759. #endif
  77760. case TK_VARIABLE: {
  77761. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77762. assert( pExpr->u.zToken!=0 );
  77763. assert( pExpr->u.zToken[0]!=0 );
  77764. sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
  77765. if( pExpr->u.zToken[1]!=0 ){
  77766. assert( pExpr->u.zToken[0]=='?'
  77767. || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
  77768. sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
  77769. }
  77770. break;
  77771. }
  77772. case TK_REGISTER: {
  77773. inReg = pExpr->iTable;
  77774. break;
  77775. }
  77776. case TK_AS: {
  77777. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  77778. break;
  77779. }
  77780. #ifndef SQLITE_OMIT_CAST
  77781. case TK_CAST: {
  77782. /* Expressions of the form: CAST(pLeft AS token) */
  77783. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  77784. if( inReg!=target ){
  77785. sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
  77786. inReg = target;
  77787. }
  77788. sqlite3VdbeAddOp2(v, OP_Cast, target,
  77789. sqlite3AffinityType(pExpr->u.zToken, 0));
  77790. testcase( usedAsColumnCache(pParse, inReg, inReg) );
  77791. sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
  77792. break;
  77793. }
  77794. #endif /* SQLITE_OMIT_CAST */
  77795. case TK_LT:
  77796. case TK_LE:
  77797. case TK_GT:
  77798. case TK_GE:
  77799. case TK_NE:
  77800. case TK_EQ: {
  77801. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77802. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77803. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77804. r1, r2, inReg, SQLITE_STOREP2);
  77805. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  77806. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  77807. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  77808. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  77809. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  77810. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  77811. testcase( regFree1==0 );
  77812. testcase( regFree2==0 );
  77813. break;
  77814. }
  77815. case TK_IS:
  77816. case TK_ISNOT: {
  77817. testcase( op==TK_IS );
  77818. testcase( op==TK_ISNOT );
  77819. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77820. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77821. op = (op==TK_IS) ? TK_EQ : TK_NE;
  77822. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  77823. r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
  77824. VdbeCoverageIf(v, op==TK_EQ);
  77825. VdbeCoverageIf(v, op==TK_NE);
  77826. testcase( regFree1==0 );
  77827. testcase( regFree2==0 );
  77828. break;
  77829. }
  77830. case TK_AND:
  77831. case TK_OR:
  77832. case TK_PLUS:
  77833. case TK_STAR:
  77834. case TK_MINUS:
  77835. case TK_REM:
  77836. case TK_BITAND:
  77837. case TK_BITOR:
  77838. case TK_SLASH:
  77839. case TK_LSHIFT:
  77840. case TK_RSHIFT:
  77841. case TK_CONCAT: {
  77842. assert( TK_AND==OP_And ); testcase( op==TK_AND );
  77843. assert( TK_OR==OP_Or ); testcase( op==TK_OR );
  77844. assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
  77845. assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
  77846. assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
  77847. assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
  77848. assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
  77849. assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
  77850. assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
  77851. assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
  77852. assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
  77853. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77854. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  77855. sqlite3VdbeAddOp3(v, op, r2, r1, target);
  77856. testcase( regFree1==0 );
  77857. testcase( regFree2==0 );
  77858. break;
  77859. }
  77860. case TK_UMINUS: {
  77861. Expr *pLeft = pExpr->pLeft;
  77862. assert( pLeft );
  77863. if( pLeft->op==TK_INTEGER ){
  77864. codeInteger(pParse, pLeft, 1, target);
  77865. #ifndef SQLITE_OMIT_FLOATING_POINT
  77866. }else if( pLeft->op==TK_FLOAT ){
  77867. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77868. codeReal(v, pLeft->u.zToken, 1, target);
  77869. #endif
  77870. }else{
  77871. tempX.op = TK_INTEGER;
  77872. tempX.flags = EP_IntValue|EP_TokenOnly;
  77873. tempX.u.iValue = 0;
  77874. r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
  77875. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
  77876. sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
  77877. testcase( regFree2==0 );
  77878. }
  77879. inReg = target;
  77880. break;
  77881. }
  77882. case TK_BITNOT:
  77883. case TK_NOT: {
  77884. assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
  77885. assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
  77886. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77887. testcase( regFree1==0 );
  77888. inReg = target;
  77889. sqlite3VdbeAddOp2(v, op, r1, inReg);
  77890. break;
  77891. }
  77892. case TK_ISNULL:
  77893. case TK_NOTNULL: {
  77894. int addr;
  77895. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  77896. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  77897. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  77898. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  77899. testcase( regFree1==0 );
  77900. addr = sqlite3VdbeAddOp1(v, op, r1);
  77901. VdbeCoverageIf(v, op==TK_ISNULL);
  77902. VdbeCoverageIf(v, op==TK_NOTNULL);
  77903. sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
  77904. sqlite3VdbeJumpHere(v, addr);
  77905. break;
  77906. }
  77907. case TK_AGG_FUNCTION: {
  77908. AggInfo *pInfo = pExpr->pAggInfo;
  77909. if( pInfo==0 ){
  77910. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77911. sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
  77912. }else{
  77913. inReg = pInfo->aFunc[pExpr->iAgg].iMem;
  77914. }
  77915. break;
  77916. }
  77917. case TK_FUNCTION: {
  77918. ExprList *pFarg; /* List of function arguments */
  77919. int nFarg; /* Number of function arguments */
  77920. FuncDef *pDef; /* The function definition object */
  77921. int nId; /* Length of the function name in bytes */
  77922. const char *zId; /* The function name */
  77923. u32 constMask = 0; /* Mask of function arguments that are constant */
  77924. int i; /* Loop counter */
  77925. u8 enc = ENC(db); /* The text encoding used by this database */
  77926. CollSeq *pColl = 0; /* A collating sequence */
  77927. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  77928. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  77929. pFarg = 0;
  77930. }else{
  77931. pFarg = pExpr->x.pList;
  77932. }
  77933. nFarg = pFarg ? pFarg->nExpr : 0;
  77934. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  77935. zId = pExpr->u.zToken;
  77936. nId = sqlite3Strlen30(zId);
  77937. pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
  77938. if( pDef==0 || pDef->xFunc==0 ){
  77939. sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
  77940. break;
  77941. }
  77942. /* Attempt a direct implementation of the built-in COALESCE() and
  77943. ** IFNULL() functions. This avoids unnecessary evaluation of
  77944. ** arguments past the first non-NULL argument.
  77945. */
  77946. if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
  77947. int endCoalesce = sqlite3VdbeMakeLabel(v);
  77948. assert( nFarg>=2 );
  77949. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  77950. for(i=1; i<nFarg; i++){
  77951. sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
  77952. VdbeCoverage(v);
  77953. sqlite3ExprCacheRemove(pParse, target, 1);
  77954. sqlite3ExprCachePush(pParse);
  77955. sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
  77956. sqlite3ExprCachePop(pParse);
  77957. }
  77958. sqlite3VdbeResolveLabel(v, endCoalesce);
  77959. break;
  77960. }
  77961. /* The UNLIKELY() function is a no-op. The result is the value
  77962. ** of the first argument.
  77963. */
  77964. if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
  77965. assert( nFarg>=1 );
  77966. sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
  77967. break;
  77968. }
  77969. for(i=0; i<nFarg; i++){
  77970. if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
  77971. testcase( i==31 );
  77972. constMask |= MASKBIT32(i);
  77973. }
  77974. if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
  77975. pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
  77976. }
  77977. }
  77978. if( pFarg ){
  77979. if( constMask ){
  77980. r1 = pParse->nMem+1;
  77981. pParse->nMem += nFarg;
  77982. }else{
  77983. r1 = sqlite3GetTempRange(pParse, nFarg);
  77984. }
  77985. /* For length() and typeof() functions with a column argument,
  77986. ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
  77987. ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
  77988. ** loading.
  77989. */
  77990. if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
  77991. u8 exprOp;
  77992. assert( nFarg==1 );
  77993. assert( pFarg->a[0].pExpr!=0 );
  77994. exprOp = pFarg->a[0].pExpr->op;
  77995. if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
  77996. assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
  77997. assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
  77998. testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
  77999. pFarg->a[0].pExpr->op2 =
  78000. pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
  78001. }
  78002. }
  78003. sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
  78004. sqlite3ExprCodeExprList(pParse, pFarg, r1,
  78005. SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
  78006. sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
  78007. }else{
  78008. r1 = 0;
  78009. }
  78010. #ifndef SQLITE_OMIT_VIRTUALTABLE
  78011. /* Possibly overload the function if the first argument is
  78012. ** a virtual table column.
  78013. **
  78014. ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
  78015. ** second argument, not the first, as the argument to test to
  78016. ** see if it is a column in a virtual table. This is done because
  78017. ** the left operand of infix functions (the operand we want to
  78018. ** control overloading) ends up as the second argument to the
  78019. ** function. The expression "A glob B" is equivalent to
  78020. ** "glob(B,A). We want to use the A in "A glob B" to test
  78021. ** for function overloading. But we use the B term in "glob(B,A)".
  78022. */
  78023. if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
  78024. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
  78025. }else if( nFarg>0 ){
  78026. pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
  78027. }
  78028. #endif
  78029. if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  78030. if( !pColl ) pColl = db->pDfltColl;
  78031. sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
  78032. }
  78033. sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
  78034. (char*)pDef, P4_FUNCDEF);
  78035. sqlite3VdbeChangeP5(v, (u8)nFarg);
  78036. if( nFarg && constMask==0 ){
  78037. sqlite3ReleaseTempRange(pParse, r1, nFarg);
  78038. }
  78039. break;
  78040. }
  78041. #ifndef SQLITE_OMIT_SUBQUERY
  78042. case TK_EXISTS:
  78043. case TK_SELECT: {
  78044. testcase( op==TK_EXISTS );
  78045. testcase( op==TK_SELECT );
  78046. inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
  78047. break;
  78048. }
  78049. case TK_IN: {
  78050. int destIfFalse = sqlite3VdbeMakeLabel(v);
  78051. int destIfNull = sqlite3VdbeMakeLabel(v);
  78052. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  78053. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  78054. sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
  78055. sqlite3VdbeResolveLabel(v, destIfFalse);
  78056. sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
  78057. sqlite3VdbeResolveLabel(v, destIfNull);
  78058. break;
  78059. }
  78060. #endif /* SQLITE_OMIT_SUBQUERY */
  78061. /*
  78062. ** x BETWEEN y AND z
  78063. **
  78064. ** This is equivalent to
  78065. **
  78066. ** x>=y AND x<=z
  78067. **
  78068. ** X is stored in pExpr->pLeft.
  78069. ** Y is stored in pExpr->pList->a[0].pExpr.
  78070. ** Z is stored in pExpr->pList->a[1].pExpr.
  78071. */
  78072. case TK_BETWEEN: {
  78073. Expr *pLeft = pExpr->pLeft;
  78074. struct ExprList_item *pLItem = pExpr->x.pList->a;
  78075. Expr *pRight = pLItem->pExpr;
  78076. r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
  78077. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  78078. testcase( regFree1==0 );
  78079. testcase( regFree2==0 );
  78080. r3 = sqlite3GetTempReg(pParse);
  78081. r4 = sqlite3GetTempReg(pParse);
  78082. codeCompare(pParse, pLeft, pRight, OP_Ge,
  78083. r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
  78084. pLItem++;
  78085. pRight = pLItem->pExpr;
  78086. sqlite3ReleaseTempReg(pParse, regFree2);
  78087. r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
  78088. testcase( regFree2==0 );
  78089. codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
  78090. VdbeCoverage(v);
  78091. sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
  78092. sqlite3ReleaseTempReg(pParse, r3);
  78093. sqlite3ReleaseTempReg(pParse, r4);
  78094. break;
  78095. }
  78096. case TK_COLLATE:
  78097. case TK_UPLUS: {
  78098. inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
  78099. break;
  78100. }
  78101. case TK_TRIGGER: {
  78102. /* If the opcode is TK_TRIGGER, then the expression is a reference
  78103. ** to a column in the new.* or old.* pseudo-tables available to
  78104. ** trigger programs. In this case Expr.iTable is set to 1 for the
  78105. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  78106. ** is set to the column of the pseudo-table to read, or to -1 to
  78107. ** read the rowid field.
  78108. **
  78109. ** The expression is implemented using an OP_Param opcode. The p1
  78110. ** parameter is set to 0 for an old.rowid reference, or to (i+1)
  78111. ** to reference another column of the old.* pseudo-table, where
  78112. ** i is the index of the column. For a new.rowid reference, p1 is
  78113. ** set to (n+1), where n is the number of columns in each pseudo-table.
  78114. ** For a reference to any other column in the new.* pseudo-table, p1
  78115. ** is set to (n+2+i), where n and i are as defined previously. For
  78116. ** example, if the table on which triggers are being fired is
  78117. ** declared as:
  78118. **
  78119. ** CREATE TABLE t1(a, b);
  78120. **
  78121. ** Then p1 is interpreted as follows:
  78122. **
  78123. ** p1==0 -> old.rowid p1==3 -> new.rowid
  78124. ** p1==1 -> old.a p1==4 -> new.a
  78125. ** p1==2 -> old.b p1==5 -> new.b
  78126. */
  78127. Table *pTab = pExpr->pTab;
  78128. int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
  78129. assert( pExpr->iTable==0 || pExpr->iTable==1 );
  78130. assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
  78131. assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
  78132. assert( p1>=0 && p1<(pTab->nCol*2+2) );
  78133. sqlite3VdbeAddOp2(v, OP_Param, p1, target);
  78134. VdbeComment((v, "%s.%s -> $%d",
  78135. (pExpr->iTable ? "new" : "old"),
  78136. (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
  78137. target
  78138. ));
  78139. #ifndef SQLITE_OMIT_FLOATING_POINT
  78140. /* If the column has REAL affinity, it may currently be stored as an
  78141. ** integer. Use OP_RealAffinity to make sure it is really real. */
  78142. if( pExpr->iColumn>=0
  78143. && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
  78144. ){
  78145. sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
  78146. }
  78147. #endif
  78148. break;
  78149. }
  78150. /*
  78151. ** Form A:
  78152. ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  78153. **
  78154. ** Form B:
  78155. ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
  78156. **
  78157. ** Form A is can be transformed into the equivalent form B as follows:
  78158. ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
  78159. ** WHEN x=eN THEN rN ELSE y END
  78160. **
  78161. ** X (if it exists) is in pExpr->pLeft.
  78162. ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
  78163. ** odd. The Y is also optional. If the number of elements in x.pList
  78164. ** is even, then Y is omitted and the "otherwise" result is NULL.
  78165. ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
  78166. **
  78167. ** The result of the expression is the Ri for the first matching Ei,
  78168. ** or if there is no matching Ei, the ELSE term Y, or if there is
  78169. ** no ELSE term, NULL.
  78170. */
  78171. default: assert( op==TK_CASE ); {
  78172. int endLabel; /* GOTO label for end of CASE stmt */
  78173. int nextCase; /* GOTO label for next WHEN clause */
  78174. int nExpr; /* 2x number of WHEN terms */
  78175. int i; /* Loop counter */
  78176. ExprList *pEList; /* List of WHEN terms */
  78177. struct ExprList_item *aListelem; /* Array of WHEN terms */
  78178. Expr opCompare; /* The X==Ei expression */
  78179. Expr *pX; /* The X expression */
  78180. Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
  78181. VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
  78182. assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
  78183. assert(pExpr->x.pList->nExpr > 0);
  78184. pEList = pExpr->x.pList;
  78185. aListelem = pEList->a;
  78186. nExpr = pEList->nExpr;
  78187. endLabel = sqlite3VdbeMakeLabel(v);
  78188. if( (pX = pExpr->pLeft)!=0 ){
  78189. tempX = *pX;
  78190. testcase( pX->op==TK_COLUMN );
  78191. exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
  78192. testcase( regFree1==0 );
  78193. opCompare.op = TK_EQ;
  78194. opCompare.pLeft = &tempX;
  78195. pTest = &opCompare;
  78196. /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
  78197. ** The value in regFree1 might get SCopy-ed into the file result.
  78198. ** So make sure that the regFree1 register is not reused for other
  78199. ** purposes and possibly overwritten. */
  78200. regFree1 = 0;
  78201. }
  78202. for(i=0; i<nExpr-1; i=i+2){
  78203. sqlite3ExprCachePush(pParse);
  78204. if( pX ){
  78205. assert( pTest!=0 );
  78206. opCompare.pRight = aListelem[i].pExpr;
  78207. }else{
  78208. pTest = aListelem[i].pExpr;
  78209. }
  78210. nextCase = sqlite3VdbeMakeLabel(v);
  78211. testcase( pTest->op==TK_COLUMN );
  78212. sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
  78213. testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
  78214. sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
  78215. sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
  78216. sqlite3ExprCachePop(pParse);
  78217. sqlite3VdbeResolveLabel(v, nextCase);
  78218. }
  78219. if( (nExpr&1)!=0 ){
  78220. sqlite3ExprCachePush(pParse);
  78221. sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
  78222. sqlite3ExprCachePop(pParse);
  78223. }else{
  78224. sqlite3VdbeAddOp2(v, OP_Null, 0, target);
  78225. }
  78226. assert( db->mallocFailed || pParse->nErr>0
  78227. || pParse->iCacheLevel==iCacheLevel );
  78228. sqlite3VdbeResolveLabel(v, endLabel);
  78229. break;
  78230. }
  78231. #ifndef SQLITE_OMIT_TRIGGER
  78232. case TK_RAISE: {
  78233. assert( pExpr->affinity==OE_Rollback
  78234. || pExpr->affinity==OE_Abort
  78235. || pExpr->affinity==OE_Fail
  78236. || pExpr->affinity==OE_Ignore
  78237. );
  78238. if( !pParse->pTriggerTab ){
  78239. sqlite3ErrorMsg(pParse,
  78240. "RAISE() may only be used within a trigger-program");
  78241. return 0;
  78242. }
  78243. if( pExpr->affinity==OE_Abort ){
  78244. sqlite3MayAbort(pParse);
  78245. }
  78246. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  78247. if( pExpr->affinity==OE_Ignore ){
  78248. sqlite3VdbeAddOp4(
  78249. v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
  78250. VdbeCoverage(v);
  78251. }else{
  78252. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
  78253. pExpr->affinity, pExpr->u.zToken, 0, 0);
  78254. }
  78255. break;
  78256. }
  78257. #endif
  78258. }
  78259. sqlite3ReleaseTempReg(pParse, regFree1);
  78260. sqlite3ReleaseTempReg(pParse, regFree2);
  78261. return inReg;
  78262. }
  78263. /*
  78264. ** Factor out the code of the given expression to initialization time.
  78265. */
  78266. SQLITE_PRIVATE void sqlite3ExprCodeAtInit(
  78267. Parse *pParse, /* Parsing context */
  78268. Expr *pExpr, /* The expression to code when the VDBE initializes */
  78269. int regDest, /* Store the value in this register */
  78270. u8 reusable /* True if this expression is reusable */
  78271. ){
  78272. ExprList *p;
  78273. assert( ConstFactorOk(pParse) );
  78274. p = pParse->pConstExpr;
  78275. pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
  78276. p = sqlite3ExprListAppend(pParse, p, pExpr);
  78277. if( p ){
  78278. struct ExprList_item *pItem = &p->a[p->nExpr-1];
  78279. pItem->u.iConstExprReg = regDest;
  78280. pItem->reusable = reusable;
  78281. }
  78282. pParse->pConstExpr = p;
  78283. }
  78284. /*
  78285. ** Generate code to evaluate an expression and store the results
  78286. ** into a register. Return the register number where the results
  78287. ** are stored.
  78288. **
  78289. ** If the register is a temporary register that can be deallocated,
  78290. ** then write its number into *pReg. If the result register is not
  78291. ** a temporary, then set *pReg to zero.
  78292. **
  78293. ** If pExpr is a constant, then this routine might generate this
  78294. ** code to fill the register in the initialization section of the
  78295. ** VDBE program, in order to factor it out of the evaluation loop.
  78296. */
  78297. SQLITE_PRIVATE int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
  78298. int r2;
  78299. pExpr = sqlite3ExprSkipCollate(pExpr);
  78300. if( ConstFactorOk(pParse)
  78301. && pExpr->op!=TK_REGISTER
  78302. && sqlite3ExprIsConstantNotJoin(pExpr)
  78303. ){
  78304. ExprList *p = pParse->pConstExpr;
  78305. int i;
  78306. *pReg = 0;
  78307. if( p ){
  78308. struct ExprList_item *pItem;
  78309. for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
  78310. if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
  78311. return pItem->u.iConstExprReg;
  78312. }
  78313. }
  78314. }
  78315. r2 = ++pParse->nMem;
  78316. sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
  78317. }else{
  78318. int r1 = sqlite3GetTempReg(pParse);
  78319. r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
  78320. if( r2==r1 ){
  78321. *pReg = r1;
  78322. }else{
  78323. sqlite3ReleaseTempReg(pParse, r1);
  78324. *pReg = 0;
  78325. }
  78326. }
  78327. return r2;
  78328. }
  78329. /*
  78330. ** Generate code that will evaluate expression pExpr and store the
  78331. ** results in register target. The results are guaranteed to appear
  78332. ** in register target.
  78333. */
  78334. SQLITE_PRIVATE void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
  78335. int inReg;
  78336. assert( target>0 && target<=pParse->nMem );
  78337. if( pExpr && pExpr->op==TK_REGISTER ){
  78338. sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
  78339. }else{
  78340. inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
  78341. assert( pParse->pVdbe || pParse->db->mallocFailed );
  78342. if( inReg!=target && pParse->pVdbe ){
  78343. sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
  78344. }
  78345. }
  78346. }
  78347. /*
  78348. ** Generate code that will evaluate expression pExpr and store the
  78349. ** results in register target. The results are guaranteed to appear
  78350. ** in register target. If the expression is constant, then this routine
  78351. ** might choose to code the expression at initialization time.
  78352. */
  78353. SQLITE_PRIVATE void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
  78354. if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
  78355. sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
  78356. }else{
  78357. sqlite3ExprCode(pParse, pExpr, target);
  78358. }
  78359. }
  78360. /*
  78361. ** Generate code that evaluates the given expression and puts the result
  78362. ** in register target.
  78363. **
  78364. ** Also make a copy of the expression results into another "cache" register
  78365. ** and modify the expression so that the next time it is evaluated,
  78366. ** the result is a copy of the cache register.
  78367. **
  78368. ** This routine is used for expressions that are used multiple
  78369. ** times. They are evaluated once and the results of the expression
  78370. ** are reused.
  78371. */
  78372. SQLITE_PRIVATE void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
  78373. Vdbe *v = pParse->pVdbe;
  78374. int iMem;
  78375. assert( target>0 );
  78376. assert( pExpr->op!=TK_REGISTER );
  78377. sqlite3ExprCode(pParse, pExpr, target);
  78378. iMem = ++pParse->nMem;
  78379. sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
  78380. exprToRegister(pExpr, iMem);
  78381. }
  78382. #ifdef SQLITE_DEBUG
  78383. /*
  78384. ** Generate a human-readable explanation of an expression tree.
  78385. */
  78386. SQLITE_PRIVATE void sqlite3TreeViewExpr(TreeView *pView, const Expr *pExpr, u8 moreToFollow){
  78387. const char *zBinOp = 0; /* Binary operator */
  78388. const char *zUniOp = 0; /* Unary operator */
  78389. pView = sqlite3TreeViewPush(pView, moreToFollow);
  78390. if( pExpr==0 ){
  78391. sqlite3TreeViewLine(pView, "nil");
  78392. sqlite3TreeViewPop(pView);
  78393. return;
  78394. }
  78395. switch( pExpr->op ){
  78396. case TK_AGG_COLUMN: {
  78397. sqlite3TreeViewLine(pView, "AGG{%d:%d}",
  78398. pExpr->iTable, pExpr->iColumn);
  78399. break;
  78400. }
  78401. case TK_COLUMN: {
  78402. if( pExpr->iTable<0 ){
  78403. /* This only happens when coding check constraints */
  78404. sqlite3TreeViewLine(pView, "COLUMN(%d)", pExpr->iColumn);
  78405. }else{
  78406. sqlite3TreeViewLine(pView, "{%d:%d}",
  78407. pExpr->iTable, pExpr->iColumn);
  78408. }
  78409. break;
  78410. }
  78411. case TK_INTEGER: {
  78412. if( pExpr->flags & EP_IntValue ){
  78413. sqlite3TreeViewLine(pView, "%d", pExpr->u.iValue);
  78414. }else{
  78415. sqlite3TreeViewLine(pView, "%s", pExpr->u.zToken);
  78416. }
  78417. break;
  78418. }
  78419. #ifndef SQLITE_OMIT_FLOATING_POINT
  78420. case TK_FLOAT: {
  78421. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  78422. break;
  78423. }
  78424. #endif
  78425. case TK_STRING: {
  78426. sqlite3TreeViewLine(pView,"%Q", pExpr->u.zToken);
  78427. break;
  78428. }
  78429. case TK_NULL: {
  78430. sqlite3TreeViewLine(pView,"NULL");
  78431. break;
  78432. }
  78433. #ifndef SQLITE_OMIT_BLOB_LITERAL
  78434. case TK_BLOB: {
  78435. sqlite3TreeViewLine(pView,"%s", pExpr->u.zToken);
  78436. break;
  78437. }
  78438. #endif
  78439. case TK_VARIABLE: {
  78440. sqlite3TreeViewLine(pView,"VARIABLE(%s,%d)",
  78441. pExpr->u.zToken, pExpr->iColumn);
  78442. break;
  78443. }
  78444. case TK_REGISTER: {
  78445. sqlite3TreeViewLine(pView,"REGISTER(%d)", pExpr->iTable);
  78446. break;
  78447. }
  78448. case TK_AS: {
  78449. sqlite3TreeViewLine(pView,"AS %Q", pExpr->u.zToken);
  78450. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  78451. break;
  78452. }
  78453. case TK_ID: {
  78454. sqlite3TreeViewLine(pView,"ID %Q", pExpr->u.zToken);
  78455. break;
  78456. }
  78457. #ifndef SQLITE_OMIT_CAST
  78458. case TK_CAST: {
  78459. /* Expressions of the form: CAST(pLeft AS token) */
  78460. sqlite3TreeViewLine(pView,"CAST %Q", pExpr->u.zToken);
  78461. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  78462. break;
  78463. }
  78464. #endif /* SQLITE_OMIT_CAST */
  78465. case TK_LT: zBinOp = "LT"; break;
  78466. case TK_LE: zBinOp = "LE"; break;
  78467. case TK_GT: zBinOp = "GT"; break;
  78468. case TK_GE: zBinOp = "GE"; break;
  78469. case TK_NE: zBinOp = "NE"; break;
  78470. case TK_EQ: zBinOp = "EQ"; break;
  78471. case TK_IS: zBinOp = "IS"; break;
  78472. case TK_ISNOT: zBinOp = "ISNOT"; break;
  78473. case TK_AND: zBinOp = "AND"; break;
  78474. case TK_OR: zBinOp = "OR"; break;
  78475. case TK_PLUS: zBinOp = "ADD"; break;
  78476. case TK_STAR: zBinOp = "MUL"; break;
  78477. case TK_MINUS: zBinOp = "SUB"; break;
  78478. case TK_REM: zBinOp = "REM"; break;
  78479. case TK_BITAND: zBinOp = "BITAND"; break;
  78480. case TK_BITOR: zBinOp = "BITOR"; break;
  78481. case TK_SLASH: zBinOp = "DIV"; break;
  78482. case TK_LSHIFT: zBinOp = "LSHIFT"; break;
  78483. case TK_RSHIFT: zBinOp = "RSHIFT"; break;
  78484. case TK_CONCAT: zBinOp = "CONCAT"; break;
  78485. case TK_DOT: zBinOp = "DOT"; break;
  78486. case TK_UMINUS: zUniOp = "UMINUS"; break;
  78487. case TK_UPLUS: zUniOp = "UPLUS"; break;
  78488. case TK_BITNOT: zUniOp = "BITNOT"; break;
  78489. case TK_NOT: zUniOp = "NOT"; break;
  78490. case TK_ISNULL: zUniOp = "ISNULL"; break;
  78491. case TK_NOTNULL: zUniOp = "NOTNULL"; break;
  78492. case TK_COLLATE: {
  78493. sqlite3TreeViewLine(pView, "COLLATE %Q", pExpr->u.zToken);
  78494. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  78495. break;
  78496. }
  78497. case TK_AGG_FUNCTION:
  78498. case TK_FUNCTION: {
  78499. ExprList *pFarg; /* List of function arguments */
  78500. if( ExprHasProperty(pExpr, EP_TokenOnly) ){
  78501. pFarg = 0;
  78502. }else{
  78503. pFarg = pExpr->x.pList;
  78504. }
  78505. if( pExpr->op==TK_AGG_FUNCTION ){
  78506. sqlite3TreeViewLine(pView, "AGG_FUNCTION%d %Q",
  78507. pExpr->op2, pExpr->u.zToken);
  78508. }else{
  78509. sqlite3TreeViewLine(pView, "FUNCTION %Q", pExpr->u.zToken);
  78510. }
  78511. if( pFarg ){
  78512. sqlite3TreeViewExprList(pView, pFarg, 0, 0);
  78513. }
  78514. break;
  78515. }
  78516. #ifndef SQLITE_OMIT_SUBQUERY
  78517. case TK_EXISTS: {
  78518. sqlite3TreeViewLine(pView, "EXISTS-expr");
  78519. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  78520. break;
  78521. }
  78522. case TK_SELECT: {
  78523. sqlite3TreeViewLine(pView, "SELECT-expr");
  78524. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  78525. break;
  78526. }
  78527. case TK_IN: {
  78528. sqlite3TreeViewLine(pView, "IN");
  78529. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  78530. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  78531. sqlite3TreeViewSelect(pView, pExpr->x.pSelect, 0);
  78532. }else{
  78533. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  78534. }
  78535. break;
  78536. }
  78537. #endif /* SQLITE_OMIT_SUBQUERY */
  78538. /*
  78539. ** x BETWEEN y AND z
  78540. **
  78541. ** This is equivalent to
  78542. **
  78543. ** x>=y AND x<=z
  78544. **
  78545. ** X is stored in pExpr->pLeft.
  78546. ** Y is stored in pExpr->pList->a[0].pExpr.
  78547. ** Z is stored in pExpr->pList->a[1].pExpr.
  78548. */
  78549. case TK_BETWEEN: {
  78550. Expr *pX = pExpr->pLeft;
  78551. Expr *pY = pExpr->x.pList->a[0].pExpr;
  78552. Expr *pZ = pExpr->x.pList->a[1].pExpr;
  78553. sqlite3TreeViewLine(pView, "BETWEEN");
  78554. sqlite3TreeViewExpr(pView, pX, 1);
  78555. sqlite3TreeViewExpr(pView, pY, 1);
  78556. sqlite3TreeViewExpr(pView, pZ, 0);
  78557. break;
  78558. }
  78559. case TK_TRIGGER: {
  78560. /* If the opcode is TK_TRIGGER, then the expression is a reference
  78561. ** to a column in the new.* or old.* pseudo-tables available to
  78562. ** trigger programs. In this case Expr.iTable is set to 1 for the
  78563. ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
  78564. ** is set to the column of the pseudo-table to read, or to -1 to
  78565. ** read the rowid field.
  78566. */
  78567. sqlite3TreeViewLine(pView, "%s(%d)",
  78568. pExpr->iTable ? "NEW" : "OLD", pExpr->iColumn);
  78569. break;
  78570. }
  78571. case TK_CASE: {
  78572. sqlite3TreeViewLine(pView, "CASE");
  78573. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  78574. sqlite3TreeViewExprList(pView, pExpr->x.pList, 0, 0);
  78575. break;
  78576. }
  78577. #ifndef SQLITE_OMIT_TRIGGER
  78578. case TK_RAISE: {
  78579. const char *zType = "unk";
  78580. switch( pExpr->affinity ){
  78581. case OE_Rollback: zType = "rollback"; break;
  78582. case OE_Abort: zType = "abort"; break;
  78583. case OE_Fail: zType = "fail"; break;
  78584. case OE_Ignore: zType = "ignore"; break;
  78585. }
  78586. sqlite3TreeViewLine(pView, "RAISE %s(%Q)", zType, pExpr->u.zToken);
  78587. break;
  78588. }
  78589. #endif
  78590. default: {
  78591. sqlite3TreeViewLine(pView, "op=%d", pExpr->op);
  78592. break;
  78593. }
  78594. }
  78595. if( zBinOp ){
  78596. sqlite3TreeViewLine(pView, "%s", zBinOp);
  78597. sqlite3TreeViewExpr(pView, pExpr->pLeft, 1);
  78598. sqlite3TreeViewExpr(pView, pExpr->pRight, 0);
  78599. }else if( zUniOp ){
  78600. sqlite3TreeViewLine(pView, "%s", zUniOp);
  78601. sqlite3TreeViewExpr(pView, pExpr->pLeft, 0);
  78602. }
  78603. sqlite3TreeViewPop(pView);
  78604. }
  78605. #endif /* SQLITE_DEBUG */
  78606. #ifdef SQLITE_DEBUG
  78607. /*
  78608. ** Generate a human-readable explanation of an expression list.
  78609. */
  78610. SQLITE_PRIVATE void sqlite3TreeViewExprList(
  78611. TreeView *pView,
  78612. const ExprList *pList,
  78613. u8 moreToFollow,
  78614. const char *zLabel
  78615. ){
  78616. int i;
  78617. pView = sqlite3TreeViewPush(pView, moreToFollow);
  78618. if( zLabel==0 || zLabel[0]==0 ) zLabel = "LIST";
  78619. if( pList==0 ){
  78620. sqlite3TreeViewLine(pView, "%s (empty)", zLabel);
  78621. }else{
  78622. sqlite3TreeViewLine(pView, "%s", zLabel);
  78623. for(i=0; i<pList->nExpr; i++){
  78624. sqlite3TreeViewExpr(pView, pList->a[i].pExpr, i<pList->nExpr-1);
  78625. #if 0
  78626. if( pList->a[i].zName ){
  78627. sqlite3ExplainPrintf(pOut, " AS %s", pList->a[i].zName);
  78628. }
  78629. if( pList->a[i].bSpanIsTab ){
  78630. sqlite3ExplainPrintf(pOut, " (%s)", pList->a[i].zSpan);
  78631. }
  78632. #endif
  78633. }
  78634. }
  78635. sqlite3TreeViewPop(pView);
  78636. }
  78637. #endif /* SQLITE_DEBUG */
  78638. /*
  78639. ** Generate code that pushes the value of every element of the given
  78640. ** expression list into a sequence of registers beginning at target.
  78641. **
  78642. ** Return the number of elements evaluated.
  78643. **
  78644. ** The SQLITE_ECEL_DUP flag prevents the arguments from being
  78645. ** filled using OP_SCopy. OP_Copy must be used instead.
  78646. **
  78647. ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
  78648. ** factored out into initialization code.
  78649. */
  78650. SQLITE_PRIVATE int sqlite3ExprCodeExprList(
  78651. Parse *pParse, /* Parsing context */
  78652. ExprList *pList, /* The expression list to be coded */
  78653. int target, /* Where to write results */
  78654. u8 flags /* SQLITE_ECEL_* flags */
  78655. ){
  78656. struct ExprList_item *pItem;
  78657. int i, n;
  78658. u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
  78659. assert( pList!=0 );
  78660. assert( target>0 );
  78661. assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
  78662. n = pList->nExpr;
  78663. if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
  78664. for(pItem=pList->a, i=0; i<n; i++, pItem++){
  78665. Expr *pExpr = pItem->pExpr;
  78666. if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
  78667. sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
  78668. }else{
  78669. int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
  78670. if( inReg!=target+i ){
  78671. VdbeOp *pOp;
  78672. Vdbe *v = pParse->pVdbe;
  78673. if( copyOp==OP_Copy
  78674. && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
  78675. && pOp->p1+pOp->p3+1==inReg
  78676. && pOp->p2+pOp->p3+1==target+i
  78677. ){
  78678. pOp->p3++;
  78679. }else{
  78680. sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
  78681. }
  78682. }
  78683. }
  78684. }
  78685. return n;
  78686. }
  78687. /*
  78688. ** Generate code for a BETWEEN operator.
  78689. **
  78690. ** x BETWEEN y AND z
  78691. **
  78692. ** The above is equivalent to
  78693. **
  78694. ** x>=y AND x<=z
  78695. **
  78696. ** Code it as such, taking care to do the common subexpression
  78697. ** elimination of x.
  78698. */
  78699. static void exprCodeBetween(
  78700. Parse *pParse, /* Parsing and code generating context */
  78701. Expr *pExpr, /* The BETWEEN expression */
  78702. int dest, /* Jump here if the jump is taken */
  78703. int jumpIfTrue, /* Take the jump if the BETWEEN is true */
  78704. int jumpIfNull /* Take the jump if the BETWEEN is NULL */
  78705. ){
  78706. Expr exprAnd; /* The AND operator in x>=y AND x<=z */
  78707. Expr compLeft; /* The x>=y term */
  78708. Expr compRight; /* The x<=z term */
  78709. Expr exprX; /* The x subexpression */
  78710. int regFree1 = 0; /* Temporary use register */
  78711. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  78712. exprX = *pExpr->pLeft;
  78713. exprAnd.op = TK_AND;
  78714. exprAnd.pLeft = &compLeft;
  78715. exprAnd.pRight = &compRight;
  78716. compLeft.op = TK_GE;
  78717. compLeft.pLeft = &exprX;
  78718. compLeft.pRight = pExpr->x.pList->a[0].pExpr;
  78719. compRight.op = TK_LE;
  78720. compRight.pLeft = &exprX;
  78721. compRight.pRight = pExpr->x.pList->a[1].pExpr;
  78722. exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
  78723. if( jumpIfTrue ){
  78724. sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
  78725. }else{
  78726. sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
  78727. }
  78728. sqlite3ReleaseTempReg(pParse, regFree1);
  78729. /* Ensure adequate test coverage */
  78730. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
  78731. testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
  78732. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
  78733. testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
  78734. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
  78735. testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
  78736. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
  78737. testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
  78738. }
  78739. /*
  78740. ** Generate code for a boolean expression such that a jump is made
  78741. ** to the label "dest" if the expression is true but execution
  78742. ** continues straight thru if the expression is false.
  78743. **
  78744. ** If the expression evaluates to NULL (neither true nor false), then
  78745. ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
  78746. **
  78747. ** This code depends on the fact that certain token values (ex: TK_EQ)
  78748. ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
  78749. ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
  78750. ** the make process cause these values to align. Assert()s in the code
  78751. ** below verify that the numbers are aligned correctly.
  78752. */
  78753. SQLITE_PRIVATE void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  78754. Vdbe *v = pParse->pVdbe;
  78755. int op = 0;
  78756. int regFree1 = 0;
  78757. int regFree2 = 0;
  78758. int r1, r2;
  78759. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  78760. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  78761. if( NEVER(pExpr==0) ) return; /* No way this can happen */
  78762. op = pExpr->op;
  78763. switch( op ){
  78764. case TK_AND: {
  78765. int d2 = sqlite3VdbeMakeLabel(v);
  78766. testcase( jumpIfNull==0 );
  78767. sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
  78768. sqlite3ExprCachePush(pParse);
  78769. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  78770. sqlite3VdbeResolveLabel(v, d2);
  78771. sqlite3ExprCachePop(pParse);
  78772. break;
  78773. }
  78774. case TK_OR: {
  78775. testcase( jumpIfNull==0 );
  78776. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  78777. sqlite3ExprCachePush(pParse);
  78778. sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
  78779. sqlite3ExprCachePop(pParse);
  78780. break;
  78781. }
  78782. case TK_NOT: {
  78783. testcase( jumpIfNull==0 );
  78784. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  78785. break;
  78786. }
  78787. case TK_LT:
  78788. case TK_LE:
  78789. case TK_GT:
  78790. case TK_GE:
  78791. case TK_NE:
  78792. case TK_EQ: {
  78793. testcase( jumpIfNull==0 );
  78794. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78795. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  78796. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  78797. r1, r2, dest, jumpIfNull);
  78798. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  78799. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  78800. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  78801. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  78802. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  78803. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  78804. testcase( regFree1==0 );
  78805. testcase( regFree2==0 );
  78806. break;
  78807. }
  78808. case TK_IS:
  78809. case TK_ISNOT: {
  78810. testcase( op==TK_IS );
  78811. testcase( op==TK_ISNOT );
  78812. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78813. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  78814. op = (op==TK_IS) ? TK_EQ : TK_NE;
  78815. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  78816. r1, r2, dest, SQLITE_NULLEQ);
  78817. VdbeCoverageIf(v, op==TK_EQ);
  78818. VdbeCoverageIf(v, op==TK_NE);
  78819. testcase( regFree1==0 );
  78820. testcase( regFree2==0 );
  78821. break;
  78822. }
  78823. case TK_ISNULL:
  78824. case TK_NOTNULL: {
  78825. assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
  78826. assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
  78827. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78828. sqlite3VdbeAddOp2(v, op, r1, dest);
  78829. VdbeCoverageIf(v, op==TK_ISNULL);
  78830. VdbeCoverageIf(v, op==TK_NOTNULL);
  78831. testcase( regFree1==0 );
  78832. break;
  78833. }
  78834. case TK_BETWEEN: {
  78835. testcase( jumpIfNull==0 );
  78836. exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
  78837. break;
  78838. }
  78839. #ifndef SQLITE_OMIT_SUBQUERY
  78840. case TK_IN: {
  78841. int destIfFalse = sqlite3VdbeMakeLabel(v);
  78842. int destIfNull = jumpIfNull ? dest : destIfFalse;
  78843. sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
  78844. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  78845. sqlite3VdbeResolveLabel(v, destIfFalse);
  78846. break;
  78847. }
  78848. #endif
  78849. default: {
  78850. if( exprAlwaysTrue(pExpr) ){
  78851. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  78852. }else if( exprAlwaysFalse(pExpr) ){
  78853. /* No-op */
  78854. }else{
  78855. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  78856. sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
  78857. VdbeCoverage(v);
  78858. testcase( regFree1==0 );
  78859. testcase( jumpIfNull==0 );
  78860. }
  78861. break;
  78862. }
  78863. }
  78864. sqlite3ReleaseTempReg(pParse, regFree1);
  78865. sqlite3ReleaseTempReg(pParse, regFree2);
  78866. }
  78867. /*
  78868. ** Generate code for a boolean expression such that a jump is made
  78869. ** to the label "dest" if the expression is false but execution
  78870. ** continues straight thru if the expression is true.
  78871. **
  78872. ** If the expression evaluates to NULL (neither true nor false) then
  78873. ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
  78874. ** is 0.
  78875. */
  78876. SQLITE_PRIVATE void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
  78877. Vdbe *v = pParse->pVdbe;
  78878. int op = 0;
  78879. int regFree1 = 0;
  78880. int regFree2 = 0;
  78881. int r1, r2;
  78882. assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
  78883. if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
  78884. if( pExpr==0 ) return;
  78885. /* The value of pExpr->op and op are related as follows:
  78886. **
  78887. ** pExpr->op op
  78888. ** --------- ----------
  78889. ** TK_ISNULL OP_NotNull
  78890. ** TK_NOTNULL OP_IsNull
  78891. ** TK_NE OP_Eq
  78892. ** TK_EQ OP_Ne
  78893. ** TK_GT OP_Le
  78894. ** TK_LE OP_Gt
  78895. ** TK_GE OP_Lt
  78896. ** TK_LT OP_Ge
  78897. **
  78898. ** For other values of pExpr->op, op is undefined and unused.
  78899. ** The value of TK_ and OP_ constants are arranged such that we
  78900. ** can compute the mapping above using the following expression.
  78901. ** Assert()s verify that the computation is correct.
  78902. */
  78903. op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
  78904. /* Verify correct alignment of TK_ and OP_ constants
  78905. */
  78906. assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
  78907. assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
  78908. assert( pExpr->op!=TK_NE || op==OP_Eq );
  78909. assert( pExpr->op!=TK_EQ || op==OP_Ne );
  78910. assert( pExpr->op!=TK_LT || op==OP_Ge );
  78911. assert( pExpr->op!=TK_LE || op==OP_Gt );
  78912. assert( pExpr->op!=TK_GT || op==OP_Le );
  78913. assert( pExpr->op!=TK_GE || op==OP_Lt );
  78914. switch( pExpr->op ){
  78915. case TK_AND: {
  78916. testcase( jumpIfNull==0 );
  78917. sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
  78918. sqlite3ExprCachePush(pParse);
  78919. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  78920. sqlite3ExprCachePop(pParse);
  78921. break;
  78922. }
  78923. case TK_OR: {
  78924. int d2 = sqlite3VdbeMakeLabel(v);
  78925. testcase( jumpIfNull==0 );
  78926. sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
  78927. sqlite3ExprCachePush(pParse);
  78928. sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
  78929. sqlite3VdbeResolveLabel(v, d2);
  78930. sqlite3ExprCachePop(pParse);
  78931. break;
  78932. }
  78933. case TK_NOT: {
  78934. testcase( jumpIfNull==0 );
  78935. sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
  78936. break;
  78937. }
  78938. case TK_LT:
  78939. case TK_LE:
  78940. case TK_GT:
  78941. case TK_GE:
  78942. case TK_NE:
  78943. case TK_EQ: {
  78944. testcase( jumpIfNull==0 );
  78945. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78946. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  78947. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  78948. r1, r2, dest, jumpIfNull);
  78949. assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
  78950. assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
  78951. assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
  78952. assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
  78953. assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
  78954. assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
  78955. testcase( regFree1==0 );
  78956. testcase( regFree2==0 );
  78957. break;
  78958. }
  78959. case TK_IS:
  78960. case TK_ISNOT: {
  78961. testcase( pExpr->op==TK_IS );
  78962. testcase( pExpr->op==TK_ISNOT );
  78963. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78964. r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
  78965. op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
  78966. codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
  78967. r1, r2, dest, SQLITE_NULLEQ);
  78968. VdbeCoverageIf(v, op==TK_EQ);
  78969. VdbeCoverageIf(v, op==TK_NE);
  78970. testcase( regFree1==0 );
  78971. testcase( regFree2==0 );
  78972. break;
  78973. }
  78974. case TK_ISNULL:
  78975. case TK_NOTNULL: {
  78976. r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
  78977. sqlite3VdbeAddOp2(v, op, r1, dest);
  78978. testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
  78979. testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
  78980. testcase( regFree1==0 );
  78981. break;
  78982. }
  78983. case TK_BETWEEN: {
  78984. testcase( jumpIfNull==0 );
  78985. exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
  78986. break;
  78987. }
  78988. #ifndef SQLITE_OMIT_SUBQUERY
  78989. case TK_IN: {
  78990. if( jumpIfNull ){
  78991. sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
  78992. }else{
  78993. int destIfNull = sqlite3VdbeMakeLabel(v);
  78994. sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
  78995. sqlite3VdbeResolveLabel(v, destIfNull);
  78996. }
  78997. break;
  78998. }
  78999. #endif
  79000. default: {
  79001. if( exprAlwaysFalse(pExpr) ){
  79002. sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
  79003. }else if( exprAlwaysTrue(pExpr) ){
  79004. /* no-op */
  79005. }else{
  79006. r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
  79007. sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
  79008. VdbeCoverage(v);
  79009. testcase( regFree1==0 );
  79010. testcase( jumpIfNull==0 );
  79011. }
  79012. break;
  79013. }
  79014. }
  79015. sqlite3ReleaseTempReg(pParse, regFree1);
  79016. sqlite3ReleaseTempReg(pParse, regFree2);
  79017. }
  79018. /*
  79019. ** Do a deep comparison of two expression trees. Return 0 if the two
  79020. ** expressions are completely identical. Return 1 if they differ only
  79021. ** by a COLLATE operator at the top level. Return 2 if there are differences
  79022. ** other than the top-level COLLATE operator.
  79023. **
  79024. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  79025. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  79026. **
  79027. ** The pA side might be using TK_REGISTER. If that is the case and pB is
  79028. ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
  79029. **
  79030. ** Sometimes this routine will return 2 even if the two expressions
  79031. ** really are equivalent. If we cannot prove that the expressions are
  79032. ** identical, we return 2 just to be safe. So if this routine
  79033. ** returns 2, then you do not really know for certain if the two
  79034. ** expressions are the same. But if you get a 0 or 1 return, then you
  79035. ** can be sure the expressions are the same. In the places where
  79036. ** this routine is used, it does not hurt to get an extra 2 - that
  79037. ** just might result in some slightly slower code. But returning
  79038. ** an incorrect 0 or 1 could lead to a malfunction.
  79039. */
  79040. SQLITE_PRIVATE int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
  79041. u32 combinedFlags;
  79042. if( pA==0 || pB==0 ){
  79043. return pB==pA ? 0 : 2;
  79044. }
  79045. combinedFlags = pA->flags | pB->flags;
  79046. if( combinedFlags & EP_IntValue ){
  79047. if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
  79048. return 0;
  79049. }
  79050. return 2;
  79051. }
  79052. if( pA->op!=pB->op ){
  79053. if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
  79054. return 1;
  79055. }
  79056. if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
  79057. return 1;
  79058. }
  79059. return 2;
  79060. }
  79061. if( pA->op!=TK_COLUMN && ALWAYS(pA->op!=TK_AGG_COLUMN) && pA->u.zToken ){
  79062. if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
  79063. return pA->op==TK_COLLATE ? 1 : 2;
  79064. }
  79065. }
  79066. if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
  79067. if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
  79068. if( combinedFlags & EP_xIsSelect ) return 2;
  79069. if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
  79070. if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
  79071. if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
  79072. if( ALWAYS((combinedFlags & EP_Reduced)==0) ){
  79073. if( pA->iColumn!=pB->iColumn ) return 2;
  79074. if( pA->iTable!=pB->iTable
  79075. && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
  79076. }
  79077. }
  79078. return 0;
  79079. }
  79080. /*
  79081. ** Compare two ExprList objects. Return 0 if they are identical and
  79082. ** non-zero if they differ in any way.
  79083. **
  79084. ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
  79085. ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
  79086. **
  79087. ** This routine might return non-zero for equivalent ExprLists. The
  79088. ** only consequence will be disabled optimizations. But this routine
  79089. ** must never return 0 if the two ExprList objects are different, or
  79090. ** a malfunction will result.
  79091. **
  79092. ** Two NULL pointers are considered to be the same. But a NULL pointer
  79093. ** always differs from a non-NULL pointer.
  79094. */
  79095. SQLITE_PRIVATE int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
  79096. int i;
  79097. if( pA==0 && pB==0 ) return 0;
  79098. if( pA==0 || pB==0 ) return 1;
  79099. if( pA->nExpr!=pB->nExpr ) return 1;
  79100. for(i=0; i<pA->nExpr; i++){
  79101. Expr *pExprA = pA->a[i].pExpr;
  79102. Expr *pExprB = pB->a[i].pExpr;
  79103. if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
  79104. if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
  79105. }
  79106. return 0;
  79107. }
  79108. /*
  79109. ** Return true if we can prove the pE2 will always be true if pE1 is
  79110. ** true. Return false if we cannot complete the proof or if pE2 might
  79111. ** be false. Examples:
  79112. **
  79113. ** pE1: x==5 pE2: x==5 Result: true
  79114. ** pE1: x>0 pE2: x==5 Result: false
  79115. ** pE1: x=21 pE2: x=21 OR y=43 Result: true
  79116. ** pE1: x!=123 pE2: x IS NOT NULL Result: true
  79117. ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
  79118. ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
  79119. ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
  79120. **
  79121. ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
  79122. ** Expr.iTable<0 then assume a table number given by iTab.
  79123. **
  79124. ** When in doubt, return false. Returning true might give a performance
  79125. ** improvement. Returning false might cause a performance reduction, but
  79126. ** it will always give the correct answer and is hence always safe.
  79127. */
  79128. SQLITE_PRIVATE int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
  79129. if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
  79130. return 1;
  79131. }
  79132. if( pE2->op==TK_OR
  79133. && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
  79134. || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
  79135. ){
  79136. return 1;
  79137. }
  79138. if( pE2->op==TK_NOTNULL
  79139. && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
  79140. && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
  79141. ){
  79142. return 1;
  79143. }
  79144. return 0;
  79145. }
  79146. /*
  79147. ** An instance of the following structure is used by the tree walker
  79148. ** to count references to table columns in the arguments of an
  79149. ** aggregate function, in order to implement the
  79150. ** sqlite3FunctionThisSrc() routine.
  79151. */
  79152. struct SrcCount {
  79153. SrcList *pSrc; /* One particular FROM clause in a nested query */
  79154. int nThis; /* Number of references to columns in pSrcList */
  79155. int nOther; /* Number of references to columns in other FROM clauses */
  79156. };
  79157. /*
  79158. ** Count the number of references to columns.
  79159. */
  79160. static int exprSrcCount(Walker *pWalker, Expr *pExpr){
  79161. /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
  79162. ** is always called before sqlite3ExprAnalyzeAggregates() and so the
  79163. ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
  79164. ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
  79165. ** NEVER() will need to be removed. */
  79166. if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
  79167. int i;
  79168. struct SrcCount *p = pWalker->u.pSrcCount;
  79169. SrcList *pSrc = p->pSrc;
  79170. for(i=0; i<pSrc->nSrc; i++){
  79171. if( pExpr->iTable==pSrc->a[i].iCursor ) break;
  79172. }
  79173. if( i<pSrc->nSrc ){
  79174. p->nThis++;
  79175. }else{
  79176. p->nOther++;
  79177. }
  79178. }
  79179. return WRC_Continue;
  79180. }
  79181. /*
  79182. ** Determine if any of the arguments to the pExpr Function reference
  79183. ** pSrcList. Return true if they do. Also return true if the function
  79184. ** has no arguments or has only constant arguments. Return false if pExpr
  79185. ** references columns but not columns of tables found in pSrcList.
  79186. */
  79187. SQLITE_PRIVATE int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
  79188. Walker w;
  79189. struct SrcCount cnt;
  79190. assert( pExpr->op==TK_AGG_FUNCTION );
  79191. memset(&w, 0, sizeof(w));
  79192. w.xExprCallback = exprSrcCount;
  79193. w.u.pSrcCount = &cnt;
  79194. cnt.pSrc = pSrcList;
  79195. cnt.nThis = 0;
  79196. cnt.nOther = 0;
  79197. sqlite3WalkExprList(&w, pExpr->x.pList);
  79198. return cnt.nThis>0 || cnt.nOther==0;
  79199. }
  79200. /*
  79201. ** Add a new element to the pAggInfo->aCol[] array. Return the index of
  79202. ** the new element. Return a negative number if malloc fails.
  79203. */
  79204. static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
  79205. int i;
  79206. pInfo->aCol = sqlite3ArrayAllocate(
  79207. db,
  79208. pInfo->aCol,
  79209. sizeof(pInfo->aCol[0]),
  79210. &pInfo->nColumn,
  79211. &i
  79212. );
  79213. return i;
  79214. }
  79215. /*
  79216. ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
  79217. ** the new element. Return a negative number if malloc fails.
  79218. */
  79219. static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
  79220. int i;
  79221. pInfo->aFunc = sqlite3ArrayAllocate(
  79222. db,
  79223. pInfo->aFunc,
  79224. sizeof(pInfo->aFunc[0]),
  79225. &pInfo->nFunc,
  79226. &i
  79227. );
  79228. return i;
  79229. }
  79230. /*
  79231. ** This is the xExprCallback for a tree walker. It is used to
  79232. ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
  79233. ** for additional information.
  79234. */
  79235. static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
  79236. int i;
  79237. NameContext *pNC = pWalker->u.pNC;
  79238. Parse *pParse = pNC->pParse;
  79239. SrcList *pSrcList = pNC->pSrcList;
  79240. AggInfo *pAggInfo = pNC->pAggInfo;
  79241. switch( pExpr->op ){
  79242. case TK_AGG_COLUMN:
  79243. case TK_COLUMN: {
  79244. testcase( pExpr->op==TK_AGG_COLUMN );
  79245. testcase( pExpr->op==TK_COLUMN );
  79246. /* Check to see if the column is in one of the tables in the FROM
  79247. ** clause of the aggregate query */
  79248. if( ALWAYS(pSrcList!=0) ){
  79249. struct SrcList_item *pItem = pSrcList->a;
  79250. for(i=0; i<pSrcList->nSrc; i++, pItem++){
  79251. struct AggInfo_col *pCol;
  79252. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  79253. if( pExpr->iTable==pItem->iCursor ){
  79254. /* If we reach this point, it means that pExpr refers to a table
  79255. ** that is in the FROM clause of the aggregate query.
  79256. **
  79257. ** Make an entry for the column in pAggInfo->aCol[] if there
  79258. ** is not an entry there already.
  79259. */
  79260. int k;
  79261. pCol = pAggInfo->aCol;
  79262. for(k=0; k<pAggInfo->nColumn; k++, pCol++){
  79263. if( pCol->iTable==pExpr->iTable &&
  79264. pCol->iColumn==pExpr->iColumn ){
  79265. break;
  79266. }
  79267. }
  79268. if( (k>=pAggInfo->nColumn)
  79269. && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
  79270. ){
  79271. pCol = &pAggInfo->aCol[k];
  79272. pCol->pTab = pExpr->pTab;
  79273. pCol->iTable = pExpr->iTable;
  79274. pCol->iColumn = pExpr->iColumn;
  79275. pCol->iMem = ++pParse->nMem;
  79276. pCol->iSorterColumn = -1;
  79277. pCol->pExpr = pExpr;
  79278. if( pAggInfo->pGroupBy ){
  79279. int j, n;
  79280. ExprList *pGB = pAggInfo->pGroupBy;
  79281. struct ExprList_item *pTerm = pGB->a;
  79282. n = pGB->nExpr;
  79283. for(j=0; j<n; j++, pTerm++){
  79284. Expr *pE = pTerm->pExpr;
  79285. if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
  79286. pE->iColumn==pExpr->iColumn ){
  79287. pCol->iSorterColumn = j;
  79288. break;
  79289. }
  79290. }
  79291. }
  79292. if( pCol->iSorterColumn<0 ){
  79293. pCol->iSorterColumn = pAggInfo->nSortingColumn++;
  79294. }
  79295. }
  79296. /* There is now an entry for pExpr in pAggInfo->aCol[] (either
  79297. ** because it was there before or because we just created it).
  79298. ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
  79299. ** pAggInfo->aCol[] entry.
  79300. */
  79301. ExprSetVVAProperty(pExpr, EP_NoReduce);
  79302. pExpr->pAggInfo = pAggInfo;
  79303. pExpr->op = TK_AGG_COLUMN;
  79304. pExpr->iAgg = (i16)k;
  79305. break;
  79306. } /* endif pExpr->iTable==pItem->iCursor */
  79307. } /* end loop over pSrcList */
  79308. }
  79309. return WRC_Prune;
  79310. }
  79311. case TK_AGG_FUNCTION: {
  79312. if( (pNC->ncFlags & NC_InAggFunc)==0
  79313. && pWalker->walkerDepth==pExpr->op2
  79314. ){
  79315. /* Check to see if pExpr is a duplicate of another aggregate
  79316. ** function that is already in the pAggInfo structure
  79317. */
  79318. struct AggInfo_func *pItem = pAggInfo->aFunc;
  79319. for(i=0; i<pAggInfo->nFunc; i++, pItem++){
  79320. if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
  79321. break;
  79322. }
  79323. }
  79324. if( i>=pAggInfo->nFunc ){
  79325. /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
  79326. */
  79327. u8 enc = ENC(pParse->db);
  79328. i = addAggInfoFunc(pParse->db, pAggInfo);
  79329. if( i>=0 ){
  79330. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  79331. pItem = &pAggInfo->aFunc[i];
  79332. pItem->pExpr = pExpr;
  79333. pItem->iMem = ++pParse->nMem;
  79334. assert( !ExprHasProperty(pExpr, EP_IntValue) );
  79335. pItem->pFunc = sqlite3FindFunction(pParse->db,
  79336. pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
  79337. pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
  79338. if( pExpr->flags & EP_Distinct ){
  79339. pItem->iDistinct = pParse->nTab++;
  79340. }else{
  79341. pItem->iDistinct = -1;
  79342. }
  79343. }
  79344. }
  79345. /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
  79346. */
  79347. assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
  79348. ExprSetVVAProperty(pExpr, EP_NoReduce);
  79349. pExpr->iAgg = (i16)i;
  79350. pExpr->pAggInfo = pAggInfo;
  79351. return WRC_Prune;
  79352. }else{
  79353. return WRC_Continue;
  79354. }
  79355. }
  79356. }
  79357. return WRC_Continue;
  79358. }
  79359. static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
  79360. UNUSED_PARAMETER(pWalker);
  79361. UNUSED_PARAMETER(pSelect);
  79362. return WRC_Continue;
  79363. }
  79364. /*
  79365. ** Analyze the pExpr expression looking for aggregate functions and
  79366. ** for variables that need to be added to AggInfo object that pNC->pAggInfo
  79367. ** points to. Additional entries are made on the AggInfo object as
  79368. ** necessary.
  79369. **
  79370. ** This routine should only be called after the expression has been
  79371. ** analyzed by sqlite3ResolveExprNames().
  79372. */
  79373. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
  79374. Walker w;
  79375. memset(&w, 0, sizeof(w));
  79376. w.xExprCallback = analyzeAggregate;
  79377. w.xSelectCallback = analyzeAggregatesInSelect;
  79378. w.u.pNC = pNC;
  79379. assert( pNC->pSrcList!=0 );
  79380. sqlite3WalkExpr(&w, pExpr);
  79381. }
  79382. /*
  79383. ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
  79384. ** expression list. Return the number of errors.
  79385. **
  79386. ** If an error is found, the analysis is cut short.
  79387. */
  79388. SQLITE_PRIVATE void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
  79389. struct ExprList_item *pItem;
  79390. int i;
  79391. if( pList ){
  79392. for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
  79393. sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
  79394. }
  79395. }
  79396. }
  79397. /*
  79398. ** Allocate a single new register for use to hold some intermediate result.
  79399. */
  79400. SQLITE_PRIVATE int sqlite3GetTempReg(Parse *pParse){
  79401. if( pParse->nTempReg==0 ){
  79402. return ++pParse->nMem;
  79403. }
  79404. return pParse->aTempReg[--pParse->nTempReg];
  79405. }
  79406. /*
  79407. ** Deallocate a register, making available for reuse for some other
  79408. ** purpose.
  79409. **
  79410. ** If a register is currently being used by the column cache, then
  79411. ** the deallocation is deferred until the column cache line that uses
  79412. ** the register becomes stale.
  79413. */
  79414. SQLITE_PRIVATE void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
  79415. if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
  79416. int i;
  79417. struct yColCache *p;
  79418. for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
  79419. if( p->iReg==iReg ){
  79420. p->tempReg = 1;
  79421. return;
  79422. }
  79423. }
  79424. pParse->aTempReg[pParse->nTempReg++] = iReg;
  79425. }
  79426. }
  79427. /*
  79428. ** Allocate or deallocate a block of nReg consecutive registers
  79429. */
  79430. SQLITE_PRIVATE int sqlite3GetTempRange(Parse *pParse, int nReg){
  79431. int i, n;
  79432. i = pParse->iRangeReg;
  79433. n = pParse->nRangeReg;
  79434. if( nReg<=n ){
  79435. assert( !usedAsColumnCache(pParse, i, i+n-1) );
  79436. pParse->iRangeReg += nReg;
  79437. pParse->nRangeReg -= nReg;
  79438. }else{
  79439. i = pParse->nMem+1;
  79440. pParse->nMem += nReg;
  79441. }
  79442. return i;
  79443. }
  79444. SQLITE_PRIVATE void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
  79445. sqlite3ExprCacheRemove(pParse, iReg, nReg);
  79446. if( nReg>pParse->nRangeReg ){
  79447. pParse->nRangeReg = nReg;
  79448. pParse->iRangeReg = iReg;
  79449. }
  79450. }
  79451. /*
  79452. ** Mark all temporary registers as being unavailable for reuse.
  79453. */
  79454. SQLITE_PRIVATE void sqlite3ClearTempRegCache(Parse *pParse){
  79455. pParse->nTempReg = 0;
  79456. pParse->nRangeReg = 0;
  79457. }
  79458. /************** End of expr.c ************************************************/
  79459. /************** Begin file alter.c *******************************************/
  79460. /*
  79461. ** 2005 February 15
  79462. **
  79463. ** The author disclaims copyright to this source code. In place of
  79464. ** a legal notice, here is a blessing:
  79465. **
  79466. ** May you do good and not evil.
  79467. ** May you find forgiveness for yourself and forgive others.
  79468. ** May you share freely, never taking more than you give.
  79469. **
  79470. *************************************************************************
  79471. ** This file contains C code routines that used to generate VDBE code
  79472. ** that implements the ALTER TABLE command.
  79473. */
  79474. /*
  79475. ** The code in this file only exists if we are not omitting the
  79476. ** ALTER TABLE logic from the build.
  79477. */
  79478. #ifndef SQLITE_OMIT_ALTERTABLE
  79479. /*
  79480. ** This function is used by SQL generated to implement the
  79481. ** ALTER TABLE command. The first argument is the text of a CREATE TABLE or
  79482. ** CREATE INDEX command. The second is a table name. The table name in
  79483. ** the CREATE TABLE or CREATE INDEX statement is replaced with the third
  79484. ** argument and the result returned. Examples:
  79485. **
  79486. ** sqlite_rename_table('CREATE TABLE abc(a, b, c)', 'def')
  79487. ** -> 'CREATE TABLE def(a, b, c)'
  79488. **
  79489. ** sqlite_rename_table('CREATE INDEX i ON abc(a)', 'def')
  79490. ** -> 'CREATE INDEX i ON def(a, b, c)'
  79491. */
  79492. static void renameTableFunc(
  79493. sqlite3_context *context,
  79494. int NotUsed,
  79495. sqlite3_value **argv
  79496. ){
  79497. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  79498. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  79499. int token;
  79500. Token tname;
  79501. unsigned char const *zCsr = zSql;
  79502. int len = 0;
  79503. char *zRet;
  79504. sqlite3 *db = sqlite3_context_db_handle(context);
  79505. UNUSED_PARAMETER(NotUsed);
  79506. /* The principle used to locate the table name in the CREATE TABLE
  79507. ** statement is that the table name is the first non-space token that
  79508. ** is immediately followed by a TK_LP or TK_USING token.
  79509. */
  79510. if( zSql ){
  79511. do {
  79512. if( !*zCsr ){
  79513. /* Ran out of input before finding an opening bracket. Return NULL. */
  79514. return;
  79515. }
  79516. /* Store the token that zCsr points to in tname. */
  79517. tname.z = (char*)zCsr;
  79518. tname.n = len;
  79519. /* Advance zCsr to the next token. Store that token type in 'token',
  79520. ** and its length in 'len' (to be used next iteration of this loop).
  79521. */
  79522. do {
  79523. zCsr += len;
  79524. len = sqlite3GetToken(zCsr, &token);
  79525. } while( token==TK_SPACE );
  79526. assert( len>0 );
  79527. } while( token!=TK_LP && token!=TK_USING );
  79528. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  79529. zSql, zTableName, tname.z+tname.n);
  79530. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  79531. }
  79532. }
  79533. /*
  79534. ** This C function implements an SQL user function that is used by SQL code
  79535. ** generated by the ALTER TABLE ... RENAME command to modify the definition
  79536. ** of any foreign key constraints that use the table being renamed as the
  79537. ** parent table. It is passed three arguments:
  79538. **
  79539. ** 1) The complete text of the CREATE TABLE statement being modified,
  79540. ** 2) The old name of the table being renamed, and
  79541. ** 3) The new name of the table being renamed.
  79542. **
  79543. ** It returns the new CREATE TABLE statement. For example:
  79544. **
  79545. ** sqlite_rename_parent('CREATE TABLE t1(a REFERENCES t2)', 't2', 't3')
  79546. ** -> 'CREATE TABLE t1(a REFERENCES t3)'
  79547. */
  79548. #ifndef SQLITE_OMIT_FOREIGN_KEY
  79549. static void renameParentFunc(
  79550. sqlite3_context *context,
  79551. int NotUsed,
  79552. sqlite3_value **argv
  79553. ){
  79554. sqlite3 *db = sqlite3_context_db_handle(context);
  79555. char *zOutput = 0;
  79556. char *zResult;
  79557. unsigned char const *zInput = sqlite3_value_text(argv[0]);
  79558. unsigned char const *zOld = sqlite3_value_text(argv[1]);
  79559. unsigned char const *zNew = sqlite3_value_text(argv[2]);
  79560. unsigned const char *z; /* Pointer to token */
  79561. int n; /* Length of token z */
  79562. int token; /* Type of token */
  79563. UNUSED_PARAMETER(NotUsed);
  79564. if( zInput==0 || zOld==0 ) return;
  79565. for(z=zInput; *z; z=z+n){
  79566. n = sqlite3GetToken(z, &token);
  79567. if( token==TK_REFERENCES ){
  79568. char *zParent;
  79569. do {
  79570. z += n;
  79571. n = sqlite3GetToken(z, &token);
  79572. }while( token==TK_SPACE );
  79573. zParent = sqlite3DbStrNDup(db, (const char *)z, n);
  79574. if( zParent==0 ) break;
  79575. sqlite3Dequote(zParent);
  79576. if( 0==sqlite3StrICmp((const char *)zOld, zParent) ){
  79577. char *zOut = sqlite3MPrintf(db, "%s%.*s\"%w\"",
  79578. (zOutput?zOutput:""), (int)(z-zInput), zInput, (const char *)zNew
  79579. );
  79580. sqlite3DbFree(db, zOutput);
  79581. zOutput = zOut;
  79582. zInput = &z[n];
  79583. }
  79584. sqlite3DbFree(db, zParent);
  79585. }
  79586. }
  79587. zResult = sqlite3MPrintf(db, "%s%s", (zOutput?zOutput:""), zInput),
  79588. sqlite3_result_text(context, zResult, -1, SQLITE_DYNAMIC);
  79589. sqlite3DbFree(db, zOutput);
  79590. }
  79591. #endif
  79592. #ifndef SQLITE_OMIT_TRIGGER
  79593. /* This function is used by SQL generated to implement the
  79594. ** ALTER TABLE command. The first argument is the text of a CREATE TRIGGER
  79595. ** statement. The second is a table name. The table name in the CREATE
  79596. ** TRIGGER statement is replaced with the third argument and the result
  79597. ** returned. This is analagous to renameTableFunc() above, except for CREATE
  79598. ** TRIGGER, not CREATE INDEX and CREATE TABLE.
  79599. */
  79600. static void renameTriggerFunc(
  79601. sqlite3_context *context,
  79602. int NotUsed,
  79603. sqlite3_value **argv
  79604. ){
  79605. unsigned char const *zSql = sqlite3_value_text(argv[0]);
  79606. unsigned char const *zTableName = sqlite3_value_text(argv[1]);
  79607. int token;
  79608. Token tname;
  79609. int dist = 3;
  79610. unsigned char const *zCsr = zSql;
  79611. int len = 0;
  79612. char *zRet;
  79613. sqlite3 *db = sqlite3_context_db_handle(context);
  79614. UNUSED_PARAMETER(NotUsed);
  79615. /* The principle used to locate the table name in the CREATE TRIGGER
  79616. ** statement is that the table name is the first token that is immediately
  79617. ** preceded by either TK_ON or TK_DOT and immediately followed by one
  79618. ** of TK_WHEN, TK_BEGIN or TK_FOR.
  79619. */
  79620. if( zSql ){
  79621. do {
  79622. if( !*zCsr ){
  79623. /* Ran out of input before finding the table name. Return NULL. */
  79624. return;
  79625. }
  79626. /* Store the token that zCsr points to in tname. */
  79627. tname.z = (char*)zCsr;
  79628. tname.n = len;
  79629. /* Advance zCsr to the next token. Store that token type in 'token',
  79630. ** and its length in 'len' (to be used next iteration of this loop).
  79631. */
  79632. do {
  79633. zCsr += len;
  79634. len = sqlite3GetToken(zCsr, &token);
  79635. }while( token==TK_SPACE );
  79636. assert( len>0 );
  79637. /* Variable 'dist' stores the number of tokens read since the most
  79638. ** recent TK_DOT or TK_ON. This means that when a WHEN, FOR or BEGIN
  79639. ** token is read and 'dist' equals 2, the condition stated above
  79640. ** to be met.
  79641. **
  79642. ** Note that ON cannot be a database, table or column name, so
  79643. ** there is no need to worry about syntax like
  79644. ** "CREATE TRIGGER ... ON ON.ON BEGIN ..." etc.
  79645. */
  79646. dist++;
  79647. if( token==TK_DOT || token==TK_ON ){
  79648. dist = 0;
  79649. }
  79650. } while( dist!=2 || (token!=TK_WHEN && token!=TK_FOR && token!=TK_BEGIN) );
  79651. /* Variable tname now contains the token that is the old table-name
  79652. ** in the CREATE TRIGGER statement.
  79653. */
  79654. zRet = sqlite3MPrintf(db, "%.*s\"%w\"%s", (int)(((u8*)tname.z) - zSql),
  79655. zSql, zTableName, tname.z+tname.n);
  79656. sqlite3_result_text(context, zRet, -1, SQLITE_DYNAMIC);
  79657. }
  79658. }
  79659. #endif /* !SQLITE_OMIT_TRIGGER */
  79660. /*
  79661. ** Register built-in functions used to help implement ALTER TABLE
  79662. */
  79663. SQLITE_PRIVATE void sqlite3AlterFunctions(void){
  79664. static SQLITE_WSD FuncDef aAlterTableFuncs[] = {
  79665. FUNCTION(sqlite_rename_table, 2, 0, 0, renameTableFunc),
  79666. #ifndef SQLITE_OMIT_TRIGGER
  79667. FUNCTION(sqlite_rename_trigger, 2, 0, 0, renameTriggerFunc),
  79668. #endif
  79669. #ifndef SQLITE_OMIT_FOREIGN_KEY
  79670. FUNCTION(sqlite_rename_parent, 3, 0, 0, renameParentFunc),
  79671. #endif
  79672. };
  79673. int i;
  79674. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  79675. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aAlterTableFuncs);
  79676. for(i=0; i<ArraySize(aAlterTableFuncs); i++){
  79677. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  79678. }
  79679. }
  79680. /*
  79681. ** This function is used to create the text of expressions of the form:
  79682. **
  79683. ** name=<constant1> OR name=<constant2> OR ...
  79684. **
  79685. ** If argument zWhere is NULL, then a pointer string containing the text
  79686. ** "name=<constant>" is returned, where <constant> is the quoted version
  79687. ** of the string passed as argument zConstant. The returned buffer is
  79688. ** allocated using sqlite3DbMalloc(). It is the responsibility of the
  79689. ** caller to ensure that it is eventually freed.
  79690. **
  79691. ** If argument zWhere is not NULL, then the string returned is
  79692. ** "<where> OR name=<constant>", where <where> is the contents of zWhere.
  79693. ** In this case zWhere is passed to sqlite3DbFree() before returning.
  79694. **
  79695. */
  79696. static char *whereOrName(sqlite3 *db, char *zWhere, char *zConstant){
  79697. char *zNew;
  79698. if( !zWhere ){
  79699. zNew = sqlite3MPrintf(db, "name=%Q", zConstant);
  79700. }else{
  79701. zNew = sqlite3MPrintf(db, "%s OR name=%Q", zWhere, zConstant);
  79702. sqlite3DbFree(db, zWhere);
  79703. }
  79704. return zNew;
  79705. }
  79706. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79707. /*
  79708. ** Generate the text of a WHERE expression which can be used to select all
  79709. ** tables that have foreign key constraints that refer to table pTab (i.e.
  79710. ** constraints for which pTab is the parent table) from the sqlite_master
  79711. ** table.
  79712. */
  79713. static char *whereForeignKeys(Parse *pParse, Table *pTab){
  79714. FKey *p;
  79715. char *zWhere = 0;
  79716. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  79717. zWhere = whereOrName(pParse->db, zWhere, p->pFrom->zName);
  79718. }
  79719. return zWhere;
  79720. }
  79721. #endif
  79722. /*
  79723. ** Generate the text of a WHERE expression which can be used to select all
  79724. ** temporary triggers on table pTab from the sqlite_temp_master table. If
  79725. ** table pTab has no temporary triggers, or is itself stored in the
  79726. ** temporary database, NULL is returned.
  79727. */
  79728. static char *whereTempTriggers(Parse *pParse, Table *pTab){
  79729. Trigger *pTrig;
  79730. char *zWhere = 0;
  79731. const Schema *pTempSchema = pParse->db->aDb[1].pSchema; /* Temp db schema */
  79732. /* If the table is not located in the temp-db (in which case NULL is
  79733. ** returned, loop through the tables list of triggers. For each trigger
  79734. ** that is not part of the temp-db schema, add a clause to the WHERE
  79735. ** expression being built up in zWhere.
  79736. */
  79737. if( pTab->pSchema!=pTempSchema ){
  79738. sqlite3 *db = pParse->db;
  79739. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  79740. if( pTrig->pSchema==pTempSchema ){
  79741. zWhere = whereOrName(db, zWhere, pTrig->zName);
  79742. }
  79743. }
  79744. }
  79745. if( zWhere ){
  79746. char *zNew = sqlite3MPrintf(pParse->db, "type='trigger' AND (%s)", zWhere);
  79747. sqlite3DbFree(pParse->db, zWhere);
  79748. zWhere = zNew;
  79749. }
  79750. return zWhere;
  79751. }
  79752. /*
  79753. ** Generate code to drop and reload the internal representation of table
  79754. ** pTab from the database, including triggers and temporary triggers.
  79755. ** Argument zName is the name of the table in the database schema at
  79756. ** the time the generated code is executed. This can be different from
  79757. ** pTab->zName if this function is being called to code part of an
  79758. ** "ALTER TABLE RENAME TO" statement.
  79759. */
  79760. static void reloadTableSchema(Parse *pParse, Table *pTab, const char *zName){
  79761. Vdbe *v;
  79762. char *zWhere;
  79763. int iDb; /* Index of database containing pTab */
  79764. #ifndef SQLITE_OMIT_TRIGGER
  79765. Trigger *pTrig;
  79766. #endif
  79767. v = sqlite3GetVdbe(pParse);
  79768. if( NEVER(v==0) ) return;
  79769. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  79770. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  79771. assert( iDb>=0 );
  79772. #ifndef SQLITE_OMIT_TRIGGER
  79773. /* Drop any table triggers from the internal schema. */
  79774. for(pTrig=sqlite3TriggerList(pParse, pTab); pTrig; pTrig=pTrig->pNext){
  79775. int iTrigDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  79776. assert( iTrigDb==iDb || iTrigDb==1 );
  79777. sqlite3VdbeAddOp4(v, OP_DropTrigger, iTrigDb, 0, 0, pTrig->zName, 0);
  79778. }
  79779. #endif
  79780. /* Drop the table and index from the internal schema. */
  79781. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  79782. /* Reload the table, index and permanent trigger schemas. */
  79783. zWhere = sqlite3MPrintf(pParse->db, "tbl_name=%Q", zName);
  79784. if( !zWhere ) return;
  79785. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  79786. #ifndef SQLITE_OMIT_TRIGGER
  79787. /* Now, if the table is not stored in the temp database, reload any temp
  79788. ** triggers. Don't use IN(...) in case SQLITE_OMIT_SUBQUERY is defined.
  79789. */
  79790. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  79791. sqlite3VdbeAddParseSchemaOp(v, 1, zWhere);
  79792. }
  79793. #endif
  79794. }
  79795. /*
  79796. ** Parameter zName is the name of a table that is about to be altered
  79797. ** (either with ALTER TABLE ... RENAME TO or ALTER TABLE ... ADD COLUMN).
  79798. ** If the table is a system table, this function leaves an error message
  79799. ** in pParse->zErr (system tables may not be altered) and returns non-zero.
  79800. **
  79801. ** Or, if zName is not a system table, zero is returned.
  79802. */
  79803. static int isSystemTable(Parse *pParse, const char *zName){
  79804. if( sqlite3Strlen30(zName)>6 && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  79805. sqlite3ErrorMsg(pParse, "table %s may not be altered", zName);
  79806. return 1;
  79807. }
  79808. return 0;
  79809. }
  79810. /*
  79811. ** Generate code to implement the "ALTER TABLE xxx RENAME TO yyy"
  79812. ** command.
  79813. */
  79814. SQLITE_PRIVATE void sqlite3AlterRenameTable(
  79815. Parse *pParse, /* Parser context. */
  79816. SrcList *pSrc, /* The table to rename. */
  79817. Token *pName /* The new table name. */
  79818. ){
  79819. int iDb; /* Database that contains the table */
  79820. char *zDb; /* Name of database iDb */
  79821. Table *pTab; /* Table being renamed */
  79822. char *zName = 0; /* NULL-terminated version of pName */
  79823. sqlite3 *db = pParse->db; /* Database connection */
  79824. int nTabName; /* Number of UTF-8 characters in zTabName */
  79825. const char *zTabName; /* Original name of the table */
  79826. Vdbe *v;
  79827. #ifndef SQLITE_OMIT_TRIGGER
  79828. char *zWhere = 0; /* Where clause to locate temp triggers */
  79829. #endif
  79830. VTable *pVTab = 0; /* Non-zero if this is a v-tab with an xRename() */
  79831. int savedDbFlags; /* Saved value of db->flags */
  79832. savedDbFlags = db->flags;
  79833. if( NEVER(db->mallocFailed) ) goto exit_rename_table;
  79834. assert( pSrc->nSrc==1 );
  79835. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  79836. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  79837. if( !pTab ) goto exit_rename_table;
  79838. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  79839. zDb = db->aDb[iDb].zName;
  79840. db->flags |= SQLITE_PreferBuiltin;
  79841. /* Get a NULL terminated version of the new table name. */
  79842. zName = sqlite3NameFromToken(db, pName);
  79843. if( !zName ) goto exit_rename_table;
  79844. /* Check that a table or index named 'zName' does not already exist
  79845. ** in database iDb. If so, this is an error.
  79846. */
  79847. if( sqlite3FindTable(db, zName, zDb) || sqlite3FindIndex(db, zName, zDb) ){
  79848. sqlite3ErrorMsg(pParse,
  79849. "there is already another table or index with this name: %s", zName);
  79850. goto exit_rename_table;
  79851. }
  79852. /* Make sure it is not a system table being altered, or a reserved name
  79853. ** that the table is being renamed to.
  79854. */
  79855. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  79856. goto exit_rename_table;
  79857. }
  79858. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){ goto
  79859. exit_rename_table;
  79860. }
  79861. #ifndef SQLITE_OMIT_VIEW
  79862. if( pTab->pSelect ){
  79863. sqlite3ErrorMsg(pParse, "view %s may not be altered", pTab->zName);
  79864. goto exit_rename_table;
  79865. }
  79866. #endif
  79867. #ifndef SQLITE_OMIT_AUTHORIZATION
  79868. /* Invoke the authorization callback. */
  79869. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  79870. goto exit_rename_table;
  79871. }
  79872. #endif
  79873. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79874. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  79875. goto exit_rename_table;
  79876. }
  79877. if( IsVirtual(pTab) ){
  79878. pVTab = sqlite3GetVTable(db, pTab);
  79879. if( pVTab->pVtab->pModule->xRename==0 ){
  79880. pVTab = 0;
  79881. }
  79882. }
  79883. #endif
  79884. /* Begin a transaction for database iDb.
  79885. ** Then modify the schema cookie (since the ALTER TABLE modifies the
  79886. ** schema). Open a statement transaction if the table is a virtual
  79887. ** table.
  79888. */
  79889. v = sqlite3GetVdbe(pParse);
  79890. if( v==0 ){
  79891. goto exit_rename_table;
  79892. }
  79893. sqlite3BeginWriteOperation(pParse, pVTab!=0, iDb);
  79894. sqlite3ChangeCookie(pParse, iDb);
  79895. /* If this is a virtual table, invoke the xRename() function if
  79896. ** one is defined. The xRename() callback will modify the names
  79897. ** of any resources used by the v-table implementation (including other
  79898. ** SQLite tables) that are identified by the name of the virtual table.
  79899. */
  79900. #ifndef SQLITE_OMIT_VIRTUALTABLE
  79901. if( pVTab ){
  79902. int i = ++pParse->nMem;
  79903. sqlite3VdbeAddOp4(v, OP_String8, 0, i, 0, zName, 0);
  79904. sqlite3VdbeAddOp4(v, OP_VRename, i, 0, 0,(const char*)pVTab, P4_VTAB);
  79905. sqlite3MayAbort(pParse);
  79906. }
  79907. #endif
  79908. /* figure out how many UTF-8 characters are in zName */
  79909. zTabName = pTab->zName;
  79910. nTabName = sqlite3Utf8CharLen(zTabName, -1);
  79911. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79912. if( db->flags&SQLITE_ForeignKeys ){
  79913. /* If foreign-key support is enabled, rewrite the CREATE TABLE
  79914. ** statements corresponding to all child tables of foreign key constraints
  79915. ** for which the renamed table is the parent table. */
  79916. if( (zWhere=whereForeignKeys(pParse, pTab))!=0 ){
  79917. sqlite3NestedParse(pParse,
  79918. "UPDATE \"%w\".%s SET "
  79919. "sql = sqlite_rename_parent(sql, %Q, %Q) "
  79920. "WHERE %s;", zDb, SCHEMA_TABLE(iDb), zTabName, zName, zWhere);
  79921. sqlite3DbFree(db, zWhere);
  79922. }
  79923. }
  79924. #endif
  79925. /* Modify the sqlite_master table to use the new table name. */
  79926. sqlite3NestedParse(pParse,
  79927. "UPDATE %Q.%s SET "
  79928. #ifdef SQLITE_OMIT_TRIGGER
  79929. "sql = sqlite_rename_table(sql, %Q), "
  79930. #else
  79931. "sql = CASE "
  79932. "WHEN type = 'trigger' THEN sqlite_rename_trigger(sql, %Q)"
  79933. "ELSE sqlite_rename_table(sql, %Q) END, "
  79934. #endif
  79935. "tbl_name = %Q, "
  79936. "name = CASE "
  79937. "WHEN type='table' THEN %Q "
  79938. "WHEN name LIKE 'sqlite_autoindex%%' AND type='index' THEN "
  79939. "'sqlite_autoindex_' || %Q || substr(name,%d+18) "
  79940. "ELSE name END "
  79941. "WHERE tbl_name=%Q COLLATE nocase AND "
  79942. "(type='table' OR type='index' OR type='trigger');",
  79943. zDb, SCHEMA_TABLE(iDb), zName, zName, zName,
  79944. #ifndef SQLITE_OMIT_TRIGGER
  79945. zName,
  79946. #endif
  79947. zName, nTabName, zTabName
  79948. );
  79949. #ifndef SQLITE_OMIT_AUTOINCREMENT
  79950. /* If the sqlite_sequence table exists in this database, then update
  79951. ** it with the new table name.
  79952. */
  79953. if( sqlite3FindTable(db, "sqlite_sequence", zDb) ){
  79954. sqlite3NestedParse(pParse,
  79955. "UPDATE \"%w\".sqlite_sequence set name = %Q WHERE name = %Q",
  79956. zDb, zName, pTab->zName);
  79957. }
  79958. #endif
  79959. #ifndef SQLITE_OMIT_TRIGGER
  79960. /* If there are TEMP triggers on this table, modify the sqlite_temp_master
  79961. ** table. Don't do this if the table being ALTERed is itself located in
  79962. ** the temp database.
  79963. */
  79964. if( (zWhere=whereTempTriggers(pParse, pTab))!=0 ){
  79965. sqlite3NestedParse(pParse,
  79966. "UPDATE sqlite_temp_master SET "
  79967. "sql = sqlite_rename_trigger(sql, %Q), "
  79968. "tbl_name = %Q "
  79969. "WHERE %s;", zName, zName, zWhere);
  79970. sqlite3DbFree(db, zWhere);
  79971. }
  79972. #endif
  79973. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  79974. if( db->flags&SQLITE_ForeignKeys ){
  79975. FKey *p;
  79976. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  79977. Table *pFrom = p->pFrom;
  79978. if( pFrom!=pTab ){
  79979. reloadTableSchema(pParse, p->pFrom, pFrom->zName);
  79980. }
  79981. }
  79982. }
  79983. #endif
  79984. /* Drop and reload the internal table schema. */
  79985. reloadTableSchema(pParse, pTab, zName);
  79986. exit_rename_table:
  79987. sqlite3SrcListDelete(db, pSrc);
  79988. sqlite3DbFree(db, zName);
  79989. db->flags = savedDbFlags;
  79990. }
  79991. /*
  79992. ** Generate code to make sure the file format number is at least minFormat.
  79993. ** The generated code will increase the file format number if necessary.
  79994. */
  79995. SQLITE_PRIVATE void sqlite3MinimumFileFormat(Parse *pParse, int iDb, int minFormat){
  79996. Vdbe *v;
  79997. v = sqlite3GetVdbe(pParse);
  79998. /* The VDBE should have been allocated before this routine is called.
  79999. ** If that allocation failed, we would have quit before reaching this
  80000. ** point */
  80001. if( ALWAYS(v) ){
  80002. int r1 = sqlite3GetTempReg(pParse);
  80003. int r2 = sqlite3GetTempReg(pParse);
  80004. int j1;
  80005. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, r1, BTREE_FILE_FORMAT);
  80006. sqlite3VdbeUsesBtree(v, iDb);
  80007. sqlite3VdbeAddOp2(v, OP_Integer, minFormat, r2);
  80008. j1 = sqlite3VdbeAddOp3(v, OP_Ge, r2, 0, r1);
  80009. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL); VdbeCoverage(v);
  80010. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, r2);
  80011. sqlite3VdbeJumpHere(v, j1);
  80012. sqlite3ReleaseTempReg(pParse, r1);
  80013. sqlite3ReleaseTempReg(pParse, r2);
  80014. }
  80015. }
  80016. /*
  80017. ** This function is called after an "ALTER TABLE ... ADD" statement
  80018. ** has been parsed. Argument pColDef contains the text of the new
  80019. ** column definition.
  80020. **
  80021. ** The Table structure pParse->pNewTable was extended to include
  80022. ** the new column during parsing.
  80023. */
  80024. SQLITE_PRIVATE void sqlite3AlterFinishAddColumn(Parse *pParse, Token *pColDef){
  80025. Table *pNew; /* Copy of pParse->pNewTable */
  80026. Table *pTab; /* Table being altered */
  80027. int iDb; /* Database number */
  80028. const char *zDb; /* Database name */
  80029. const char *zTab; /* Table name */
  80030. char *zCol; /* Null-terminated column definition */
  80031. Column *pCol; /* The new column */
  80032. Expr *pDflt; /* Default value for the new column */
  80033. sqlite3 *db; /* The database connection; */
  80034. db = pParse->db;
  80035. if( pParse->nErr || db->mallocFailed ) return;
  80036. pNew = pParse->pNewTable;
  80037. assert( pNew );
  80038. assert( sqlite3BtreeHoldsAllMutexes(db) );
  80039. iDb = sqlite3SchemaToIndex(db, pNew->pSchema);
  80040. zDb = db->aDb[iDb].zName;
  80041. zTab = &pNew->zName[16]; /* Skip the "sqlite_altertab_" prefix on the name */
  80042. pCol = &pNew->aCol[pNew->nCol-1];
  80043. pDflt = pCol->pDflt;
  80044. pTab = sqlite3FindTable(db, zTab, zDb);
  80045. assert( pTab );
  80046. #ifndef SQLITE_OMIT_AUTHORIZATION
  80047. /* Invoke the authorization callback. */
  80048. if( sqlite3AuthCheck(pParse, SQLITE_ALTER_TABLE, zDb, pTab->zName, 0) ){
  80049. return;
  80050. }
  80051. #endif
  80052. /* If the default value for the new column was specified with a
  80053. ** literal NULL, then set pDflt to 0. This simplifies checking
  80054. ** for an SQL NULL default below.
  80055. */
  80056. if( pDflt && pDflt->op==TK_NULL ){
  80057. pDflt = 0;
  80058. }
  80059. /* Check that the new column is not specified as PRIMARY KEY or UNIQUE.
  80060. ** If there is a NOT NULL constraint, then the default value for the
  80061. ** column must not be NULL.
  80062. */
  80063. if( pCol->colFlags & COLFLAG_PRIMKEY ){
  80064. sqlite3ErrorMsg(pParse, "Cannot add a PRIMARY KEY column");
  80065. return;
  80066. }
  80067. if( pNew->pIndex ){
  80068. sqlite3ErrorMsg(pParse, "Cannot add a UNIQUE column");
  80069. return;
  80070. }
  80071. if( (db->flags&SQLITE_ForeignKeys) && pNew->pFKey && pDflt ){
  80072. sqlite3ErrorMsg(pParse,
  80073. "Cannot add a REFERENCES column with non-NULL default value");
  80074. return;
  80075. }
  80076. if( pCol->notNull && !pDflt ){
  80077. sqlite3ErrorMsg(pParse,
  80078. "Cannot add a NOT NULL column with default value NULL");
  80079. return;
  80080. }
  80081. /* Ensure the default expression is something that sqlite3ValueFromExpr()
  80082. ** can handle (i.e. not CURRENT_TIME etc.)
  80083. */
  80084. if( pDflt ){
  80085. sqlite3_value *pVal = 0;
  80086. if( sqlite3ValueFromExpr(db, pDflt, SQLITE_UTF8, SQLITE_AFF_NONE, &pVal) ){
  80087. db->mallocFailed = 1;
  80088. return;
  80089. }
  80090. if( !pVal ){
  80091. sqlite3ErrorMsg(pParse, "Cannot add a column with non-constant default");
  80092. return;
  80093. }
  80094. sqlite3ValueFree(pVal);
  80095. }
  80096. /* Modify the CREATE TABLE statement. */
  80097. zCol = sqlite3DbStrNDup(db, (char*)pColDef->z, pColDef->n);
  80098. if( zCol ){
  80099. char *zEnd = &zCol[pColDef->n-1];
  80100. int savedDbFlags = db->flags;
  80101. while( zEnd>zCol && (*zEnd==';' || sqlite3Isspace(*zEnd)) ){
  80102. *zEnd-- = '\0';
  80103. }
  80104. db->flags |= SQLITE_PreferBuiltin;
  80105. sqlite3NestedParse(pParse,
  80106. "UPDATE \"%w\".%s SET "
  80107. "sql = substr(sql,1,%d) || ', ' || %Q || substr(sql,%d) "
  80108. "WHERE type = 'table' AND name = %Q",
  80109. zDb, SCHEMA_TABLE(iDb), pNew->addColOffset, zCol, pNew->addColOffset+1,
  80110. zTab
  80111. );
  80112. sqlite3DbFree(db, zCol);
  80113. db->flags = savedDbFlags;
  80114. }
  80115. /* If the default value of the new column is NULL, then set the file
  80116. ** format to 2. If the default value of the new column is not NULL,
  80117. ** the file format becomes 3.
  80118. */
  80119. sqlite3MinimumFileFormat(pParse, iDb, pDflt ? 3 : 2);
  80120. /* Reload the schema of the modified table. */
  80121. reloadTableSchema(pParse, pTab, pTab->zName);
  80122. }
  80123. /*
  80124. ** This function is called by the parser after the table-name in
  80125. ** an "ALTER TABLE <table-name> ADD" statement is parsed. Argument
  80126. ** pSrc is the full-name of the table being altered.
  80127. **
  80128. ** This routine makes a (partial) copy of the Table structure
  80129. ** for the table being altered and sets Parse.pNewTable to point
  80130. ** to it. Routines called by the parser as the column definition
  80131. ** is parsed (i.e. sqlite3AddColumn()) add the new Column data to
  80132. ** the copy. The copy of the Table structure is deleted by tokenize.c
  80133. ** after parsing is finished.
  80134. **
  80135. ** Routine sqlite3AlterFinishAddColumn() will be called to complete
  80136. ** coding the "ALTER TABLE ... ADD" statement.
  80137. */
  80138. SQLITE_PRIVATE void sqlite3AlterBeginAddColumn(Parse *pParse, SrcList *pSrc){
  80139. Table *pNew;
  80140. Table *pTab;
  80141. Vdbe *v;
  80142. int iDb;
  80143. int i;
  80144. int nAlloc;
  80145. sqlite3 *db = pParse->db;
  80146. /* Look up the table being altered. */
  80147. assert( pParse->pNewTable==0 );
  80148. assert( sqlite3BtreeHoldsAllMutexes(db) );
  80149. if( db->mallocFailed ) goto exit_begin_add_column;
  80150. pTab = sqlite3LocateTableItem(pParse, 0, &pSrc->a[0]);
  80151. if( !pTab ) goto exit_begin_add_column;
  80152. #ifndef SQLITE_OMIT_VIRTUALTABLE
  80153. if( IsVirtual(pTab) ){
  80154. sqlite3ErrorMsg(pParse, "virtual tables may not be altered");
  80155. goto exit_begin_add_column;
  80156. }
  80157. #endif
  80158. /* Make sure this is not an attempt to ALTER a view. */
  80159. if( pTab->pSelect ){
  80160. sqlite3ErrorMsg(pParse, "Cannot add a column to a view");
  80161. goto exit_begin_add_column;
  80162. }
  80163. if( SQLITE_OK!=isSystemTable(pParse, pTab->zName) ){
  80164. goto exit_begin_add_column;
  80165. }
  80166. assert( pTab->addColOffset>0 );
  80167. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  80168. /* Put a copy of the Table struct in Parse.pNewTable for the
  80169. ** sqlite3AddColumn() function and friends to modify. But modify
  80170. ** the name by adding an "sqlite_altertab_" prefix. By adding this
  80171. ** prefix, we insure that the name will not collide with an existing
  80172. ** table because user table are not allowed to have the "sqlite_"
  80173. ** prefix on their name.
  80174. */
  80175. pNew = (Table*)sqlite3DbMallocZero(db, sizeof(Table));
  80176. if( !pNew ) goto exit_begin_add_column;
  80177. pParse->pNewTable = pNew;
  80178. pNew->nRef = 1;
  80179. pNew->nCol = pTab->nCol;
  80180. assert( pNew->nCol>0 );
  80181. nAlloc = (((pNew->nCol-1)/8)*8)+8;
  80182. assert( nAlloc>=pNew->nCol && nAlloc%8==0 && nAlloc-pNew->nCol<8 );
  80183. pNew->aCol = (Column*)sqlite3DbMallocZero(db, sizeof(Column)*nAlloc);
  80184. pNew->zName = sqlite3MPrintf(db, "sqlite_altertab_%s", pTab->zName);
  80185. if( !pNew->aCol || !pNew->zName ){
  80186. db->mallocFailed = 1;
  80187. goto exit_begin_add_column;
  80188. }
  80189. memcpy(pNew->aCol, pTab->aCol, sizeof(Column)*pNew->nCol);
  80190. for(i=0; i<pNew->nCol; i++){
  80191. Column *pCol = &pNew->aCol[i];
  80192. pCol->zName = sqlite3DbStrDup(db, pCol->zName);
  80193. pCol->zColl = 0;
  80194. pCol->zType = 0;
  80195. pCol->pDflt = 0;
  80196. pCol->zDflt = 0;
  80197. }
  80198. pNew->pSchema = db->aDb[iDb].pSchema;
  80199. pNew->addColOffset = pTab->addColOffset;
  80200. pNew->nRef = 1;
  80201. /* Begin a transaction and increment the schema cookie. */
  80202. sqlite3BeginWriteOperation(pParse, 0, iDb);
  80203. v = sqlite3GetVdbe(pParse);
  80204. if( !v ) goto exit_begin_add_column;
  80205. sqlite3ChangeCookie(pParse, iDb);
  80206. exit_begin_add_column:
  80207. sqlite3SrcListDelete(db, pSrc);
  80208. return;
  80209. }
  80210. #endif /* SQLITE_ALTER_TABLE */
  80211. /************** End of alter.c ***********************************************/
  80212. /************** Begin file analyze.c *****************************************/
  80213. /*
  80214. ** 2005-07-08
  80215. **
  80216. ** The author disclaims copyright to this source code. In place of
  80217. ** a legal notice, here is a blessing:
  80218. **
  80219. ** May you do good and not evil.
  80220. ** May you find forgiveness for yourself and forgive others.
  80221. ** May you share freely, never taking more than you give.
  80222. **
  80223. *************************************************************************
  80224. ** This file contains code associated with the ANALYZE command.
  80225. **
  80226. ** The ANALYZE command gather statistics about the content of tables
  80227. ** and indices. These statistics are made available to the query planner
  80228. ** to help it make better decisions about how to perform queries.
  80229. **
  80230. ** The following system tables are or have been supported:
  80231. **
  80232. ** CREATE TABLE sqlite_stat1(tbl, idx, stat);
  80233. ** CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
  80234. ** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
  80235. ** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
  80236. **
  80237. ** Additional tables might be added in future releases of SQLite.
  80238. ** The sqlite_stat2 table is not created or used unless the SQLite version
  80239. ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
  80240. ** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
  80241. ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
  80242. ** created and used by SQLite versions 3.7.9 and later and with
  80243. ** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
  80244. ** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
  80245. ** version of sqlite_stat3 and is only available when compiled with
  80246. ** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
  80247. ** not possible to enable both STAT3 and STAT4 at the same time. If they
  80248. ** are both enabled, then STAT4 takes precedence.
  80249. **
  80250. ** For most applications, sqlite_stat1 provides all the statistics required
  80251. ** for the query planner to make good choices.
  80252. **
  80253. ** Format of sqlite_stat1:
  80254. **
  80255. ** There is normally one row per index, with the index identified by the
  80256. ** name in the idx column. The tbl column is the name of the table to
  80257. ** which the index belongs. In each such row, the stat column will be
  80258. ** a string consisting of a list of integers. The first integer in this
  80259. ** list is the number of rows in the index. (This is the same as the
  80260. ** number of rows in the table, except for partial indices.) The second
  80261. ** integer is the average number of rows in the index that have the same
  80262. ** value in the first column of the index. The third integer is the average
  80263. ** number of rows in the index that have the same value for the first two
  80264. ** columns. The N-th integer (for N>1) is the average number of rows in
  80265. ** the index which have the same value for the first N-1 columns. For
  80266. ** a K-column index, there will be K+1 integers in the stat column. If
  80267. ** the index is unique, then the last integer will be 1.
  80268. **
  80269. ** The list of integers in the stat column can optionally be followed
  80270. ** by the keyword "unordered". The "unordered" keyword, if it is present,
  80271. ** must be separated from the last integer by a single space. If the
  80272. ** "unordered" keyword is present, then the query planner assumes that
  80273. ** the index is unordered and will not use the index for a range query.
  80274. **
  80275. ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
  80276. ** column contains a single integer which is the (estimated) number of
  80277. ** rows in the table identified by sqlite_stat1.tbl.
  80278. **
  80279. ** Format of sqlite_stat2:
  80280. **
  80281. ** The sqlite_stat2 is only created and is only used if SQLite is compiled
  80282. ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
  80283. ** 3.6.18 and 3.7.8. The "stat2" table contains additional information
  80284. ** about the distribution of keys within an index. The index is identified by
  80285. ** the "idx" column and the "tbl" column is the name of the table to which
  80286. ** the index belongs. There are usually 10 rows in the sqlite_stat2
  80287. ** table for each index.
  80288. **
  80289. ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
  80290. ** inclusive are samples of the left-most key value in the index taken at
  80291. ** evenly spaced points along the index. Let the number of samples be S
  80292. ** (10 in the standard build) and let C be the number of rows in the index.
  80293. ** Then the sampled rows are given by:
  80294. **
  80295. ** rownumber = (i*C*2 + C)/(S*2)
  80296. **
  80297. ** For i between 0 and S-1. Conceptually, the index space is divided into
  80298. ** S uniform buckets and the samples are the middle row from each bucket.
  80299. **
  80300. ** The format for sqlite_stat2 is recorded here for legacy reference. This
  80301. ** version of SQLite does not support sqlite_stat2. It neither reads nor
  80302. ** writes the sqlite_stat2 table. This version of SQLite only supports
  80303. ** sqlite_stat3.
  80304. **
  80305. ** Format for sqlite_stat3:
  80306. **
  80307. ** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
  80308. ** sqlite_stat4 format will be described first. Further information
  80309. ** about sqlite_stat3 follows the sqlite_stat4 description.
  80310. **
  80311. ** Format for sqlite_stat4:
  80312. **
  80313. ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
  80314. ** to aid the query planner in choosing good indices based on the values
  80315. ** that indexed columns are compared against in the WHERE clauses of
  80316. ** queries.
  80317. **
  80318. ** The sqlite_stat4 table contains multiple entries for each index.
  80319. ** The idx column names the index and the tbl column is the table of the
  80320. ** index. If the idx and tbl columns are the same, then the sample is
  80321. ** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
  80322. ** binary encoding of a key from the index. The nEq column is a
  80323. ** list of integers. The first integer is the approximate number
  80324. ** of entries in the index whose left-most column exactly matches
  80325. ** the left-most column of the sample. The second integer in nEq
  80326. ** is the approximate number of entries in the index where the
  80327. ** first two columns match the first two columns of the sample.
  80328. ** And so forth. nLt is another list of integers that show the approximate
  80329. ** number of entries that are strictly less than the sample. The first
  80330. ** integer in nLt contains the number of entries in the index where the
  80331. ** left-most column is less than the left-most column of the sample.
  80332. ** The K-th integer in the nLt entry is the number of index entries
  80333. ** where the first K columns are less than the first K columns of the
  80334. ** sample. The nDLt column is like nLt except that it contains the
  80335. ** number of distinct entries in the index that are less than the
  80336. ** sample.
  80337. **
  80338. ** There can be an arbitrary number of sqlite_stat4 entries per index.
  80339. ** The ANALYZE command will typically generate sqlite_stat4 tables
  80340. ** that contain between 10 and 40 samples which are distributed across
  80341. ** the key space, though not uniformly, and which include samples with
  80342. ** large nEq values.
  80343. **
  80344. ** Format for sqlite_stat3 redux:
  80345. **
  80346. ** The sqlite_stat3 table is like sqlite_stat4 except that it only
  80347. ** looks at the left-most column of the index. The sqlite_stat3.sample
  80348. ** column contains the actual value of the left-most column instead
  80349. ** of a blob encoding of the complete index key as is found in
  80350. ** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
  80351. ** all contain just a single integer which is the same as the first
  80352. ** integer in the equivalent columns in sqlite_stat4.
  80353. */
  80354. #ifndef SQLITE_OMIT_ANALYZE
  80355. #if defined(SQLITE_ENABLE_STAT4)
  80356. # define IsStat4 1
  80357. # define IsStat3 0
  80358. #elif defined(SQLITE_ENABLE_STAT3)
  80359. # define IsStat4 0
  80360. # define IsStat3 1
  80361. #else
  80362. # define IsStat4 0
  80363. # define IsStat3 0
  80364. # undef SQLITE_STAT4_SAMPLES
  80365. # define SQLITE_STAT4_SAMPLES 1
  80366. #endif
  80367. #define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
  80368. /*
  80369. ** This routine generates code that opens the sqlite_statN tables.
  80370. ** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
  80371. ** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
  80372. ** appropriate compile-time options are provided.
  80373. **
  80374. ** If the sqlite_statN tables do not previously exist, it is created.
  80375. **
  80376. ** Argument zWhere may be a pointer to a buffer containing a table name,
  80377. ** or it may be a NULL pointer. If it is not NULL, then all entries in
  80378. ** the sqlite_statN tables associated with the named table are deleted.
  80379. ** If zWhere==0, then code is generated to delete all stat table entries.
  80380. */
  80381. static void openStatTable(
  80382. Parse *pParse, /* Parsing context */
  80383. int iDb, /* The database we are looking in */
  80384. int iStatCur, /* Open the sqlite_stat1 table on this cursor */
  80385. const char *zWhere, /* Delete entries for this table or index */
  80386. const char *zWhereType /* Either "tbl" or "idx" */
  80387. ){
  80388. static const struct {
  80389. const char *zName;
  80390. const char *zCols;
  80391. } aTable[] = {
  80392. { "sqlite_stat1", "tbl,idx,stat" },
  80393. #if defined(SQLITE_ENABLE_STAT4)
  80394. { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
  80395. { "sqlite_stat3", 0 },
  80396. #elif defined(SQLITE_ENABLE_STAT3)
  80397. { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
  80398. { "sqlite_stat4", 0 },
  80399. #else
  80400. { "sqlite_stat3", 0 },
  80401. { "sqlite_stat4", 0 },
  80402. #endif
  80403. };
  80404. int i;
  80405. sqlite3 *db = pParse->db;
  80406. Db *pDb;
  80407. Vdbe *v = sqlite3GetVdbe(pParse);
  80408. int aRoot[ArraySize(aTable)];
  80409. u8 aCreateTbl[ArraySize(aTable)];
  80410. if( v==0 ) return;
  80411. assert( sqlite3BtreeHoldsAllMutexes(db) );
  80412. assert( sqlite3VdbeDb(v)==db );
  80413. pDb = &db->aDb[iDb];
  80414. /* Create new statistic tables if they do not exist, or clear them
  80415. ** if they do already exist.
  80416. */
  80417. for(i=0; i<ArraySize(aTable); i++){
  80418. const char *zTab = aTable[i].zName;
  80419. Table *pStat;
  80420. if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
  80421. if( aTable[i].zCols ){
  80422. /* The sqlite_statN table does not exist. Create it. Note that a
  80423. ** side-effect of the CREATE TABLE statement is to leave the rootpage
  80424. ** of the new table in register pParse->regRoot. This is important
  80425. ** because the OpenWrite opcode below will be needing it. */
  80426. sqlite3NestedParse(pParse,
  80427. "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
  80428. );
  80429. aRoot[i] = pParse->regRoot;
  80430. aCreateTbl[i] = OPFLAG_P2ISREG;
  80431. }
  80432. }else{
  80433. /* The table already exists. If zWhere is not NULL, delete all entries
  80434. ** associated with the table zWhere. If zWhere is NULL, delete the
  80435. ** entire contents of the table. */
  80436. aRoot[i] = pStat->tnum;
  80437. aCreateTbl[i] = 0;
  80438. sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
  80439. if( zWhere ){
  80440. sqlite3NestedParse(pParse,
  80441. "DELETE FROM %Q.%s WHERE %s=%Q",
  80442. pDb->zName, zTab, zWhereType, zWhere
  80443. );
  80444. }else{
  80445. /* The sqlite_stat[134] table already exists. Delete all rows. */
  80446. sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
  80447. }
  80448. }
  80449. }
  80450. /* Open the sqlite_stat[134] tables for writing. */
  80451. for(i=0; aTable[i].zCols; i++){
  80452. assert( i<ArraySize(aTable) );
  80453. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
  80454. sqlite3VdbeChangeP5(v, aCreateTbl[i]);
  80455. VdbeComment((v, aTable[i].zName));
  80456. }
  80457. }
  80458. /*
  80459. ** Recommended number of samples for sqlite_stat4
  80460. */
  80461. #ifndef SQLITE_STAT4_SAMPLES
  80462. # define SQLITE_STAT4_SAMPLES 24
  80463. #endif
  80464. /*
  80465. ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
  80466. ** share an instance of the following structure to hold their state
  80467. ** information.
  80468. */
  80469. typedef struct Stat4Accum Stat4Accum;
  80470. typedef struct Stat4Sample Stat4Sample;
  80471. struct Stat4Sample {
  80472. tRowcnt *anEq; /* sqlite_stat4.nEq */
  80473. tRowcnt *anDLt; /* sqlite_stat4.nDLt */
  80474. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80475. tRowcnt *anLt; /* sqlite_stat4.nLt */
  80476. union {
  80477. i64 iRowid; /* Rowid in main table of the key */
  80478. u8 *aRowid; /* Key for WITHOUT ROWID tables */
  80479. } u;
  80480. u32 nRowid; /* Sizeof aRowid[] */
  80481. u8 isPSample; /* True if a periodic sample */
  80482. int iCol; /* If !isPSample, the reason for inclusion */
  80483. u32 iHash; /* Tiebreaker hash */
  80484. #endif
  80485. };
  80486. struct Stat4Accum {
  80487. tRowcnt nRow; /* Number of rows in the entire table */
  80488. tRowcnt nPSample; /* How often to do a periodic sample */
  80489. int nCol; /* Number of columns in index + pk/rowid */
  80490. int nKeyCol; /* Number of index columns w/o the pk/rowid */
  80491. int mxSample; /* Maximum number of samples to accumulate */
  80492. Stat4Sample current; /* Current row as a Stat4Sample */
  80493. u32 iPrn; /* Pseudo-random number used for sampling */
  80494. Stat4Sample *aBest; /* Array of nCol best samples */
  80495. int iMin; /* Index in a[] of entry with minimum score */
  80496. int nSample; /* Current number of samples */
  80497. int iGet; /* Index of current sample accessed by stat_get() */
  80498. Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
  80499. sqlite3 *db; /* Database connection, for malloc() */
  80500. };
  80501. /* Reclaim memory used by a Stat4Sample
  80502. */
  80503. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80504. static void sampleClear(sqlite3 *db, Stat4Sample *p){
  80505. assert( db!=0 );
  80506. if( p->nRowid ){
  80507. sqlite3DbFree(db, p->u.aRowid);
  80508. p->nRowid = 0;
  80509. }
  80510. }
  80511. #endif
  80512. /* Initialize the BLOB value of a ROWID
  80513. */
  80514. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80515. static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
  80516. assert( db!=0 );
  80517. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  80518. p->u.aRowid = sqlite3DbMallocRaw(db, n);
  80519. if( p->u.aRowid ){
  80520. p->nRowid = n;
  80521. memcpy(p->u.aRowid, pData, n);
  80522. }else{
  80523. p->nRowid = 0;
  80524. }
  80525. }
  80526. #endif
  80527. /* Initialize the INTEGER value of a ROWID.
  80528. */
  80529. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80530. static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
  80531. assert( db!=0 );
  80532. if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
  80533. p->nRowid = 0;
  80534. p->u.iRowid = iRowid;
  80535. }
  80536. #endif
  80537. /*
  80538. ** Copy the contents of object (*pFrom) into (*pTo).
  80539. */
  80540. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80541. static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
  80542. pTo->isPSample = pFrom->isPSample;
  80543. pTo->iCol = pFrom->iCol;
  80544. pTo->iHash = pFrom->iHash;
  80545. memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
  80546. memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
  80547. memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
  80548. if( pFrom->nRowid ){
  80549. sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
  80550. }else{
  80551. sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
  80552. }
  80553. }
  80554. #endif
  80555. /*
  80556. ** Reclaim all memory of a Stat4Accum structure.
  80557. */
  80558. static void stat4Destructor(void *pOld){
  80559. Stat4Accum *p = (Stat4Accum*)pOld;
  80560. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80561. int i;
  80562. for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
  80563. for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
  80564. sampleClear(p->db, &p->current);
  80565. #endif
  80566. sqlite3DbFree(p->db, p);
  80567. }
  80568. /*
  80569. ** Implementation of the stat_init(N,K,C) SQL function. The three parameters
  80570. ** are:
  80571. ** N: The number of columns in the index including the rowid/pk (note 1)
  80572. ** K: The number of columns in the index excluding the rowid/pk.
  80573. ** C: The number of rows in the index (note 2)
  80574. **
  80575. ** Note 1: In the special case of the covering index that implements a
  80576. ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
  80577. ** total number of columns in the table.
  80578. **
  80579. ** Note 2: C is only used for STAT3 and STAT4.
  80580. **
  80581. ** For indexes on ordinary rowid tables, N==K+1. But for indexes on
  80582. ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
  80583. ** PRIMARY KEY of the table. The covering index that implements the
  80584. ** original WITHOUT ROWID table as N==K as a special case.
  80585. **
  80586. ** This routine allocates the Stat4Accum object in heap memory. The return
  80587. ** value is a pointer to the Stat4Accum object. The datatype of the
  80588. ** return value is BLOB, but it is really just a pointer to the Stat4Accum
  80589. ** object.
  80590. */
  80591. static void statInit(
  80592. sqlite3_context *context,
  80593. int argc,
  80594. sqlite3_value **argv
  80595. ){
  80596. Stat4Accum *p;
  80597. int nCol; /* Number of columns in index being sampled */
  80598. int nKeyCol; /* Number of key columns */
  80599. int nColUp; /* nCol rounded up for alignment */
  80600. int n; /* Bytes of space to allocate */
  80601. sqlite3 *db; /* Database connection */
  80602. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80603. int mxSample = SQLITE_STAT4_SAMPLES;
  80604. #endif
  80605. /* Decode the three function arguments */
  80606. UNUSED_PARAMETER(argc);
  80607. nCol = sqlite3_value_int(argv[0]);
  80608. assert( nCol>0 );
  80609. nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
  80610. nKeyCol = sqlite3_value_int(argv[1]);
  80611. assert( nKeyCol<=nCol );
  80612. assert( nKeyCol>0 );
  80613. /* Allocate the space required for the Stat4Accum object */
  80614. n = sizeof(*p)
  80615. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
  80616. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
  80617. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80618. + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
  80619. + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
  80620. + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
  80621. #endif
  80622. ;
  80623. db = sqlite3_context_db_handle(context);
  80624. p = sqlite3DbMallocZero(db, n);
  80625. if( p==0 ){
  80626. sqlite3_result_error_nomem(context);
  80627. return;
  80628. }
  80629. p->db = db;
  80630. p->nRow = 0;
  80631. p->nCol = nCol;
  80632. p->nKeyCol = nKeyCol;
  80633. p->current.anDLt = (tRowcnt*)&p[1];
  80634. p->current.anEq = &p->current.anDLt[nColUp];
  80635. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80636. {
  80637. u8 *pSpace; /* Allocated space not yet assigned */
  80638. int i; /* Used to iterate through p->aSample[] */
  80639. p->iGet = -1;
  80640. p->mxSample = mxSample;
  80641. p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
  80642. p->current.anLt = &p->current.anEq[nColUp];
  80643. p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[2])*0xd0944565;
  80644. /* Set up the Stat4Accum.a[] and aBest[] arrays */
  80645. p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
  80646. p->aBest = &p->a[mxSample];
  80647. pSpace = (u8*)(&p->a[mxSample+nCol]);
  80648. for(i=0; i<(mxSample+nCol); i++){
  80649. p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  80650. p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  80651. p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
  80652. }
  80653. assert( (pSpace - (u8*)p)==n );
  80654. for(i=0; i<nCol; i++){
  80655. p->aBest[i].iCol = i;
  80656. }
  80657. }
  80658. #endif
  80659. /* Return a pointer to the allocated object to the caller. Note that
  80660. ** only the pointer (the 2nd parameter) matters. The size of the object
  80661. ** (given by the 3rd parameter) is never used and can be any positive
  80662. ** value. */
  80663. sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
  80664. }
  80665. static const FuncDef statInitFuncdef = {
  80666. 2+IsStat34, /* nArg */
  80667. SQLITE_UTF8, /* funcFlags */
  80668. 0, /* pUserData */
  80669. 0, /* pNext */
  80670. statInit, /* xFunc */
  80671. 0, /* xStep */
  80672. 0, /* xFinalize */
  80673. "stat_init", /* zName */
  80674. 0, /* pHash */
  80675. 0 /* pDestructor */
  80676. };
  80677. #ifdef SQLITE_ENABLE_STAT4
  80678. /*
  80679. ** pNew and pOld are both candidate non-periodic samples selected for
  80680. ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
  80681. ** considering only any trailing columns and the sample hash value, this
  80682. ** function returns true if sample pNew is to be preferred over pOld.
  80683. ** In other words, if we assume that the cardinalities of the selected
  80684. ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
  80685. **
  80686. ** This function assumes that for each argument sample, the contents of
  80687. ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
  80688. */
  80689. static int sampleIsBetterPost(
  80690. Stat4Accum *pAccum,
  80691. Stat4Sample *pNew,
  80692. Stat4Sample *pOld
  80693. ){
  80694. int nCol = pAccum->nCol;
  80695. int i;
  80696. assert( pNew->iCol==pOld->iCol );
  80697. for(i=pNew->iCol+1; i<nCol; i++){
  80698. if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
  80699. if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
  80700. }
  80701. if( pNew->iHash>pOld->iHash ) return 1;
  80702. return 0;
  80703. }
  80704. #endif
  80705. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80706. /*
  80707. ** Return true if pNew is to be preferred over pOld.
  80708. **
  80709. ** This function assumes that for each argument sample, the contents of
  80710. ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
  80711. */
  80712. static int sampleIsBetter(
  80713. Stat4Accum *pAccum,
  80714. Stat4Sample *pNew,
  80715. Stat4Sample *pOld
  80716. ){
  80717. tRowcnt nEqNew = pNew->anEq[pNew->iCol];
  80718. tRowcnt nEqOld = pOld->anEq[pOld->iCol];
  80719. assert( pOld->isPSample==0 && pNew->isPSample==0 );
  80720. assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
  80721. if( (nEqNew>nEqOld) ) return 1;
  80722. #ifdef SQLITE_ENABLE_STAT4
  80723. if( nEqNew==nEqOld ){
  80724. if( pNew->iCol<pOld->iCol ) return 1;
  80725. return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
  80726. }
  80727. return 0;
  80728. #else
  80729. return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
  80730. #endif
  80731. }
  80732. /*
  80733. ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
  80734. ** remove the least desirable sample from p->a[] to make room.
  80735. */
  80736. static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
  80737. Stat4Sample *pSample = 0;
  80738. int i;
  80739. assert( IsStat4 || nEqZero==0 );
  80740. #ifdef SQLITE_ENABLE_STAT4
  80741. if( pNew->isPSample==0 ){
  80742. Stat4Sample *pUpgrade = 0;
  80743. assert( pNew->anEq[pNew->iCol]>0 );
  80744. /* This sample is being added because the prefix that ends in column
  80745. ** iCol occurs many times in the table. However, if we have already
  80746. ** added a sample that shares this prefix, there is no need to add
  80747. ** this one. Instead, upgrade the priority of the highest priority
  80748. ** existing sample that shares this prefix. */
  80749. for(i=p->nSample-1; i>=0; i--){
  80750. Stat4Sample *pOld = &p->a[i];
  80751. if( pOld->anEq[pNew->iCol]==0 ){
  80752. if( pOld->isPSample ) return;
  80753. assert( pOld->iCol>pNew->iCol );
  80754. assert( sampleIsBetter(p, pNew, pOld) );
  80755. if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
  80756. pUpgrade = pOld;
  80757. }
  80758. }
  80759. }
  80760. if( pUpgrade ){
  80761. pUpgrade->iCol = pNew->iCol;
  80762. pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
  80763. goto find_new_min;
  80764. }
  80765. }
  80766. #endif
  80767. /* If necessary, remove sample iMin to make room for the new sample. */
  80768. if( p->nSample>=p->mxSample ){
  80769. Stat4Sample *pMin = &p->a[p->iMin];
  80770. tRowcnt *anEq = pMin->anEq;
  80771. tRowcnt *anLt = pMin->anLt;
  80772. tRowcnt *anDLt = pMin->anDLt;
  80773. sampleClear(p->db, pMin);
  80774. memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
  80775. pSample = &p->a[p->nSample-1];
  80776. pSample->nRowid = 0;
  80777. pSample->anEq = anEq;
  80778. pSample->anDLt = anDLt;
  80779. pSample->anLt = anLt;
  80780. p->nSample = p->mxSample-1;
  80781. }
  80782. /* The "rows less-than" for the rowid column must be greater than that
  80783. ** for the last sample in the p->a[] array. Otherwise, the samples would
  80784. ** be out of order. */
  80785. #ifdef SQLITE_ENABLE_STAT4
  80786. assert( p->nSample==0
  80787. || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
  80788. #endif
  80789. /* Insert the new sample */
  80790. pSample = &p->a[p->nSample];
  80791. sampleCopy(p, pSample, pNew);
  80792. p->nSample++;
  80793. /* Zero the first nEqZero entries in the anEq[] array. */
  80794. memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
  80795. #ifdef SQLITE_ENABLE_STAT4
  80796. find_new_min:
  80797. #endif
  80798. if( p->nSample>=p->mxSample ){
  80799. int iMin = -1;
  80800. for(i=0; i<p->mxSample; i++){
  80801. if( p->a[i].isPSample ) continue;
  80802. if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
  80803. iMin = i;
  80804. }
  80805. }
  80806. assert( iMin>=0 );
  80807. p->iMin = iMin;
  80808. }
  80809. }
  80810. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  80811. /*
  80812. ** Field iChng of the index being scanned has changed. So at this point
  80813. ** p->current contains a sample that reflects the previous row of the
  80814. ** index. The value of anEq[iChng] and subsequent anEq[] elements are
  80815. ** correct at this point.
  80816. */
  80817. static void samplePushPrevious(Stat4Accum *p, int iChng){
  80818. #ifdef SQLITE_ENABLE_STAT4
  80819. int i;
  80820. /* Check if any samples from the aBest[] array should be pushed
  80821. ** into IndexSample.a[] at this point. */
  80822. for(i=(p->nCol-2); i>=iChng; i--){
  80823. Stat4Sample *pBest = &p->aBest[i];
  80824. pBest->anEq[i] = p->current.anEq[i];
  80825. if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
  80826. sampleInsert(p, pBest, i);
  80827. }
  80828. }
  80829. /* Update the anEq[] fields of any samples already collected. */
  80830. for(i=p->nSample-1; i>=0; i--){
  80831. int j;
  80832. for(j=iChng; j<p->nCol; j++){
  80833. if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
  80834. }
  80835. }
  80836. #endif
  80837. #if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
  80838. if( iChng==0 ){
  80839. tRowcnt nLt = p->current.anLt[0];
  80840. tRowcnt nEq = p->current.anEq[0];
  80841. /* Check if this is to be a periodic sample. If so, add it. */
  80842. if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
  80843. p->current.isPSample = 1;
  80844. sampleInsert(p, &p->current, 0);
  80845. p->current.isPSample = 0;
  80846. }else
  80847. /* Or if it is a non-periodic sample. Add it in this case too. */
  80848. if( p->nSample<p->mxSample
  80849. || sampleIsBetter(p, &p->current, &p->a[p->iMin])
  80850. ){
  80851. sampleInsert(p, &p->current, 0);
  80852. }
  80853. }
  80854. #endif
  80855. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  80856. UNUSED_PARAMETER( p );
  80857. UNUSED_PARAMETER( iChng );
  80858. #endif
  80859. }
  80860. /*
  80861. ** Implementation of the stat_push SQL function: stat_push(P,C,R)
  80862. ** Arguments:
  80863. **
  80864. ** P Pointer to the Stat4Accum object created by stat_init()
  80865. ** C Index of left-most column to differ from previous row
  80866. ** R Rowid for the current row. Might be a key record for
  80867. ** WITHOUT ROWID tables.
  80868. **
  80869. ** This SQL function always returns NULL. It's purpose it to accumulate
  80870. ** statistical data and/or samples in the Stat4Accum object about the
  80871. ** index being analyzed. The stat_get() SQL function will later be used to
  80872. ** extract relevant information for constructing the sqlite_statN tables.
  80873. **
  80874. ** The R parameter is only used for STAT3 and STAT4
  80875. */
  80876. static void statPush(
  80877. sqlite3_context *context,
  80878. int argc,
  80879. sqlite3_value **argv
  80880. ){
  80881. int i;
  80882. /* The three function arguments */
  80883. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  80884. int iChng = sqlite3_value_int(argv[1]);
  80885. UNUSED_PARAMETER( argc );
  80886. UNUSED_PARAMETER( context );
  80887. assert( p->nCol>0 );
  80888. assert( iChng<p->nCol );
  80889. if( p->nRow==0 ){
  80890. /* This is the first call to this function. Do initialization. */
  80891. for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
  80892. }else{
  80893. /* Second and subsequent calls get processed here */
  80894. samplePushPrevious(p, iChng);
  80895. /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
  80896. ** to the current row of the index. */
  80897. for(i=0; i<iChng; i++){
  80898. p->current.anEq[i]++;
  80899. }
  80900. for(i=iChng; i<p->nCol; i++){
  80901. p->current.anDLt[i]++;
  80902. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80903. p->current.anLt[i] += p->current.anEq[i];
  80904. #endif
  80905. p->current.anEq[i] = 1;
  80906. }
  80907. }
  80908. p->nRow++;
  80909. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80910. if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
  80911. sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
  80912. }else{
  80913. sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
  80914. sqlite3_value_blob(argv[2]));
  80915. }
  80916. p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
  80917. #endif
  80918. #ifdef SQLITE_ENABLE_STAT4
  80919. {
  80920. tRowcnt nLt = p->current.anLt[p->nCol-1];
  80921. /* Check if this is to be a periodic sample. If so, add it. */
  80922. if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
  80923. p->current.isPSample = 1;
  80924. p->current.iCol = 0;
  80925. sampleInsert(p, &p->current, p->nCol-1);
  80926. p->current.isPSample = 0;
  80927. }
  80928. /* Update the aBest[] array. */
  80929. for(i=0; i<(p->nCol-1); i++){
  80930. p->current.iCol = i;
  80931. if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
  80932. sampleCopy(p, &p->aBest[i], &p->current);
  80933. }
  80934. }
  80935. }
  80936. #endif
  80937. }
  80938. static const FuncDef statPushFuncdef = {
  80939. 2+IsStat34, /* nArg */
  80940. SQLITE_UTF8, /* funcFlags */
  80941. 0, /* pUserData */
  80942. 0, /* pNext */
  80943. statPush, /* xFunc */
  80944. 0, /* xStep */
  80945. 0, /* xFinalize */
  80946. "stat_push", /* zName */
  80947. 0, /* pHash */
  80948. 0 /* pDestructor */
  80949. };
  80950. #define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
  80951. #define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
  80952. #define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
  80953. #define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
  80954. #define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
  80955. /*
  80956. ** Implementation of the stat_get(P,J) SQL function. This routine is
  80957. ** used to query statistical information that has been gathered into
  80958. ** the Stat4Accum object by prior calls to stat_push(). The P parameter
  80959. ** has type BLOB but it is really just a pointer to the Stat4Accum object.
  80960. ** The content to returned is determined by the parameter J
  80961. ** which is one of the STAT_GET_xxxx values defined above.
  80962. **
  80963. ** If neither STAT3 nor STAT4 are enabled, then J is always
  80964. ** STAT_GET_STAT1 and is hence omitted and this routine becomes
  80965. ** a one-parameter function, stat_get(P), that always returns the
  80966. ** stat1 table entry information.
  80967. */
  80968. static void statGet(
  80969. sqlite3_context *context,
  80970. int argc,
  80971. sqlite3_value **argv
  80972. ){
  80973. Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
  80974. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  80975. /* STAT3 and STAT4 have a parameter on this routine. */
  80976. int eCall = sqlite3_value_int(argv[1]);
  80977. assert( argc==2 );
  80978. assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
  80979. || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
  80980. || eCall==STAT_GET_NDLT
  80981. );
  80982. if( eCall==STAT_GET_STAT1 )
  80983. #else
  80984. assert( argc==1 );
  80985. #endif
  80986. {
  80987. /* Return the value to store in the "stat" column of the sqlite_stat1
  80988. ** table for this index.
  80989. **
  80990. ** The value is a string composed of a list of integers describing
  80991. ** the index. The first integer in the list is the total number of
  80992. ** entries in the index. There is one additional integer in the list
  80993. ** for each indexed column. This additional integer is an estimate of
  80994. ** the number of rows matched by a stabbing query on the index using
  80995. ** a key with the corresponding number of fields. In other words,
  80996. ** if the index is on columns (a,b) and the sqlite_stat1 value is
  80997. ** "100 10 2", then SQLite estimates that:
  80998. **
  80999. ** * the index contains 100 rows,
  81000. ** * "WHERE a=?" matches 10 rows, and
  81001. ** * "WHERE a=? AND b=?" matches 2 rows.
  81002. **
  81003. ** If D is the count of distinct values and K is the total number of
  81004. ** rows, then each estimate is computed as:
  81005. **
  81006. ** I = (K+D-1)/D
  81007. */
  81008. char *z;
  81009. int i;
  81010. char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
  81011. if( zRet==0 ){
  81012. sqlite3_result_error_nomem(context);
  81013. return;
  81014. }
  81015. sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
  81016. z = zRet + sqlite3Strlen30(zRet);
  81017. for(i=0; i<p->nKeyCol; i++){
  81018. u64 nDistinct = p->current.anDLt[i] + 1;
  81019. u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
  81020. sqlite3_snprintf(24, z, " %llu", iVal);
  81021. z += sqlite3Strlen30(z);
  81022. assert( p->current.anEq[i] );
  81023. }
  81024. assert( z[0]=='\0' && z>zRet );
  81025. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  81026. }
  81027. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81028. else if( eCall==STAT_GET_ROWID ){
  81029. if( p->iGet<0 ){
  81030. samplePushPrevious(p, 0);
  81031. p->iGet = 0;
  81032. }
  81033. if( p->iGet<p->nSample ){
  81034. Stat4Sample *pS = p->a + p->iGet;
  81035. if( pS->nRowid==0 ){
  81036. sqlite3_result_int64(context, pS->u.iRowid);
  81037. }else{
  81038. sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
  81039. SQLITE_TRANSIENT);
  81040. }
  81041. }
  81042. }else{
  81043. tRowcnt *aCnt = 0;
  81044. assert( p->iGet<p->nSample );
  81045. switch( eCall ){
  81046. case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
  81047. case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
  81048. default: {
  81049. aCnt = p->a[p->iGet].anDLt;
  81050. p->iGet++;
  81051. break;
  81052. }
  81053. }
  81054. if( IsStat3 ){
  81055. sqlite3_result_int64(context, (i64)aCnt[0]);
  81056. }else{
  81057. char *zRet = sqlite3MallocZero(p->nCol * 25);
  81058. if( zRet==0 ){
  81059. sqlite3_result_error_nomem(context);
  81060. }else{
  81061. int i;
  81062. char *z = zRet;
  81063. for(i=0; i<p->nCol; i++){
  81064. sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
  81065. z += sqlite3Strlen30(z);
  81066. }
  81067. assert( z[0]=='\0' && z>zRet );
  81068. z[-1] = '\0';
  81069. sqlite3_result_text(context, zRet, -1, sqlite3_free);
  81070. }
  81071. }
  81072. }
  81073. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  81074. #ifndef SQLITE_DEBUG
  81075. UNUSED_PARAMETER( argc );
  81076. #endif
  81077. }
  81078. static const FuncDef statGetFuncdef = {
  81079. 1+IsStat34, /* nArg */
  81080. SQLITE_UTF8, /* funcFlags */
  81081. 0, /* pUserData */
  81082. 0, /* pNext */
  81083. statGet, /* xFunc */
  81084. 0, /* xStep */
  81085. 0, /* xFinalize */
  81086. "stat_get", /* zName */
  81087. 0, /* pHash */
  81088. 0 /* pDestructor */
  81089. };
  81090. static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
  81091. assert( regOut!=regStat4 && regOut!=regStat4+1 );
  81092. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81093. sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
  81094. #elif SQLITE_DEBUG
  81095. assert( iParam==STAT_GET_STAT1 );
  81096. #else
  81097. UNUSED_PARAMETER( iParam );
  81098. #endif
  81099. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
  81100. sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
  81101. sqlite3VdbeChangeP5(v, 1 + IsStat34);
  81102. }
  81103. /*
  81104. ** Generate code to do an analysis of all indices associated with
  81105. ** a single table.
  81106. */
  81107. static void analyzeOneTable(
  81108. Parse *pParse, /* Parser context */
  81109. Table *pTab, /* Table whose indices are to be analyzed */
  81110. Index *pOnlyIdx, /* If not NULL, only analyze this one index */
  81111. int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
  81112. int iMem, /* Available memory locations begin here */
  81113. int iTab /* Next available cursor */
  81114. ){
  81115. sqlite3 *db = pParse->db; /* Database handle */
  81116. Index *pIdx; /* An index to being analyzed */
  81117. int iIdxCur; /* Cursor open on index being analyzed */
  81118. int iTabCur; /* Table cursor */
  81119. Vdbe *v; /* The virtual machine being built up */
  81120. int i; /* Loop counter */
  81121. int jZeroRows = -1; /* Jump from here if number of rows is zero */
  81122. int iDb; /* Index of database containing pTab */
  81123. u8 needTableCnt = 1; /* True to count the table */
  81124. int regNewRowid = iMem++; /* Rowid for the inserted record */
  81125. int regStat4 = iMem++; /* Register to hold Stat4Accum object */
  81126. int regChng = iMem++; /* Index of changed index field */
  81127. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81128. int regRowid = iMem++; /* Rowid argument passed to stat_push() */
  81129. #endif
  81130. int regTemp = iMem++; /* Temporary use register */
  81131. int regTabname = iMem++; /* Register containing table name */
  81132. int regIdxname = iMem++; /* Register containing index name */
  81133. int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
  81134. int regPrev = iMem; /* MUST BE LAST (see below) */
  81135. pParse->nMem = MAX(pParse->nMem, iMem);
  81136. v = sqlite3GetVdbe(pParse);
  81137. if( v==0 || NEVER(pTab==0) ){
  81138. return;
  81139. }
  81140. if( pTab->tnum==0 ){
  81141. /* Do not gather statistics on views or virtual tables */
  81142. return;
  81143. }
  81144. if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
  81145. /* Do not gather statistics on system tables */
  81146. return;
  81147. }
  81148. assert( sqlite3BtreeHoldsAllMutexes(db) );
  81149. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  81150. assert( iDb>=0 );
  81151. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81152. #ifndef SQLITE_OMIT_AUTHORIZATION
  81153. if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
  81154. db->aDb[iDb].zName ) ){
  81155. return;
  81156. }
  81157. #endif
  81158. /* Establish a read-lock on the table at the shared-cache level.
  81159. ** Open a read-only cursor on the table. Also allocate a cursor number
  81160. ** to use for scanning indexes (iIdxCur). No index cursor is opened at
  81161. ** this time though. */
  81162. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  81163. iTabCur = iTab++;
  81164. iIdxCur = iTab++;
  81165. pParse->nTab = MAX(pParse->nTab, iTab);
  81166. sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
  81167. sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
  81168. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  81169. int nCol; /* Number of columns in pIdx. "N" */
  81170. int addrRewind; /* Address of "OP_Rewind iIdxCur" */
  81171. int addrNextRow; /* Address of "next_row:" */
  81172. const char *zIdxName; /* Name of the index */
  81173. int nColTest; /* Number of columns to test for changes */
  81174. if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
  81175. if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
  81176. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
  81177. nCol = pIdx->nKeyCol;
  81178. zIdxName = pTab->zName;
  81179. nColTest = nCol - 1;
  81180. }else{
  81181. nCol = pIdx->nColumn;
  81182. zIdxName = pIdx->zName;
  81183. nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
  81184. }
  81185. /* Populate the register containing the index name. */
  81186. sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
  81187. VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
  81188. /*
  81189. ** Pseudo-code for loop that calls stat_push():
  81190. **
  81191. ** Rewind csr
  81192. ** if eof(csr) goto end_of_scan;
  81193. ** regChng = 0
  81194. ** goto chng_addr_0;
  81195. **
  81196. ** next_row:
  81197. ** regChng = 0
  81198. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  81199. ** regChng = 1
  81200. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  81201. ** ...
  81202. ** regChng = N
  81203. ** goto chng_addr_N
  81204. **
  81205. ** chng_addr_0:
  81206. ** regPrev(0) = idx(0)
  81207. ** chng_addr_1:
  81208. ** regPrev(1) = idx(1)
  81209. ** ...
  81210. **
  81211. ** endDistinctTest:
  81212. ** regRowid = idx(rowid)
  81213. ** stat_push(P, regChng, regRowid)
  81214. ** Next csr
  81215. ** if !eof(csr) goto next_row;
  81216. **
  81217. ** end_of_scan:
  81218. */
  81219. /* Make sure there are enough memory cells allocated to accommodate
  81220. ** the regPrev array and a trailing rowid (the rowid slot is required
  81221. ** when building a record to insert into the sample column of
  81222. ** the sqlite_stat4 table. */
  81223. pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
  81224. /* Open a read-only cursor on the index being analyzed. */
  81225. assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
  81226. sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
  81227. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  81228. VdbeComment((v, "%s", pIdx->zName));
  81229. /* Invoke the stat_init() function. The arguments are:
  81230. **
  81231. ** (1) the number of columns in the index including the rowid
  81232. ** (or for a WITHOUT ROWID table, the number of PK columns),
  81233. ** (2) the number of columns in the key without the rowid/pk
  81234. ** (3) the number of rows in the index,
  81235. **
  81236. **
  81237. ** The third argument is only used for STAT3 and STAT4
  81238. */
  81239. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81240. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
  81241. #endif
  81242. sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
  81243. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
  81244. sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
  81245. sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
  81246. sqlite3VdbeChangeP5(v, 2+IsStat34);
  81247. /* Implementation of the following:
  81248. **
  81249. ** Rewind csr
  81250. ** if eof(csr) goto end_of_scan;
  81251. ** regChng = 0
  81252. ** goto next_push_0;
  81253. **
  81254. */
  81255. addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
  81256. VdbeCoverage(v);
  81257. sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
  81258. addrNextRow = sqlite3VdbeCurrentAddr(v);
  81259. if( nColTest>0 ){
  81260. int endDistinctTest = sqlite3VdbeMakeLabel(v);
  81261. int *aGotoChng; /* Array of jump instruction addresses */
  81262. aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*nColTest);
  81263. if( aGotoChng==0 ) continue;
  81264. /*
  81265. ** next_row:
  81266. ** regChng = 0
  81267. ** if( idx(0) != regPrev(0) ) goto chng_addr_0
  81268. ** regChng = 1
  81269. ** if( idx(1) != regPrev(1) ) goto chng_addr_1
  81270. ** ...
  81271. ** regChng = N
  81272. ** goto endDistinctTest
  81273. */
  81274. sqlite3VdbeAddOp0(v, OP_Goto);
  81275. addrNextRow = sqlite3VdbeCurrentAddr(v);
  81276. if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
  81277. /* For a single-column UNIQUE index, once we have found a non-NULL
  81278. ** row, we know that all the rest will be distinct, so skip
  81279. ** subsequent distinctness tests. */
  81280. sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
  81281. VdbeCoverage(v);
  81282. }
  81283. for(i=0; i<nColTest; i++){
  81284. char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
  81285. sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
  81286. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
  81287. aGotoChng[i] =
  81288. sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
  81289. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  81290. VdbeCoverage(v);
  81291. }
  81292. sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
  81293. sqlite3VdbeAddOp2(v, OP_Goto, 0, endDistinctTest);
  81294. /*
  81295. ** chng_addr_0:
  81296. ** regPrev(0) = idx(0)
  81297. ** chng_addr_1:
  81298. ** regPrev(1) = idx(1)
  81299. ** ...
  81300. */
  81301. sqlite3VdbeJumpHere(v, addrNextRow-1);
  81302. for(i=0; i<nColTest; i++){
  81303. sqlite3VdbeJumpHere(v, aGotoChng[i]);
  81304. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
  81305. }
  81306. sqlite3VdbeResolveLabel(v, endDistinctTest);
  81307. sqlite3DbFree(db, aGotoChng);
  81308. }
  81309. /*
  81310. ** chng_addr_N:
  81311. ** regRowid = idx(rowid) // STAT34 only
  81312. ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
  81313. ** Next csr
  81314. ** if !eof(csr) goto next_row;
  81315. */
  81316. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81317. assert( regRowid==(regStat4+2) );
  81318. if( HasRowid(pTab) ){
  81319. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
  81320. }else{
  81321. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  81322. int j, k, regKey;
  81323. regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  81324. for(j=0; j<pPk->nKeyCol; j++){
  81325. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  81326. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
  81327. VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
  81328. }
  81329. sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
  81330. sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
  81331. }
  81332. #endif
  81333. assert( regChng==(regStat4+1) );
  81334. sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
  81335. sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
  81336. sqlite3VdbeChangeP5(v, 2+IsStat34);
  81337. sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
  81338. /* Add the entry to the stat1 table. */
  81339. callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
  81340. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  81341. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  81342. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  81343. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  81344. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  81345. /* Add the entries to the stat3 or stat4 table. */
  81346. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81347. {
  81348. int regEq = regStat1;
  81349. int regLt = regStat1+1;
  81350. int regDLt = regStat1+2;
  81351. int regSample = regStat1+3;
  81352. int regCol = regStat1+4;
  81353. int regSampleRowid = regCol + nCol;
  81354. int addrNext;
  81355. int addrIsNull;
  81356. u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  81357. pParse->nMem = MAX(pParse->nMem, regCol+nCol);
  81358. addrNext = sqlite3VdbeCurrentAddr(v);
  81359. callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
  81360. addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
  81361. VdbeCoverage(v);
  81362. callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
  81363. callStatGet(v, regStat4, STAT_GET_NLT, regLt);
  81364. callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
  81365. sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
  81366. /* We know that the regSampleRowid row exists because it was read by
  81367. ** the previous loop. Thus the not-found jump of seekOp will never
  81368. ** be taken */
  81369. VdbeCoverageNeverTaken(v);
  81370. #ifdef SQLITE_ENABLE_STAT3
  81371. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  81372. pIdx->aiColumn[0], regSample);
  81373. #else
  81374. for(i=0; i<nCol; i++){
  81375. i16 iCol = pIdx->aiColumn[i];
  81376. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
  81377. }
  81378. sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
  81379. #endif
  81380. sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
  81381. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
  81382. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
  81383. sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
  81384. sqlite3VdbeJumpHere(v, addrIsNull);
  81385. }
  81386. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  81387. /* End of analysis */
  81388. sqlite3VdbeJumpHere(v, addrRewind);
  81389. }
  81390. /* Create a single sqlite_stat1 entry containing NULL as the index
  81391. ** name and the row count as the content.
  81392. */
  81393. if( pOnlyIdx==0 && needTableCnt ){
  81394. VdbeComment((v, "%s", pTab->zName));
  81395. sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
  81396. jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
  81397. sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
  81398. assert( "BBB"[0]==SQLITE_AFF_TEXT );
  81399. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
  81400. sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
  81401. sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
  81402. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  81403. sqlite3VdbeJumpHere(v, jZeroRows);
  81404. }
  81405. }
  81406. /*
  81407. ** Generate code that will cause the most recent index analysis to
  81408. ** be loaded into internal hash tables where is can be used.
  81409. */
  81410. static void loadAnalysis(Parse *pParse, int iDb){
  81411. Vdbe *v = sqlite3GetVdbe(pParse);
  81412. if( v ){
  81413. sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
  81414. }
  81415. }
  81416. /*
  81417. ** Generate code that will do an analysis of an entire database
  81418. */
  81419. static void analyzeDatabase(Parse *pParse, int iDb){
  81420. sqlite3 *db = pParse->db;
  81421. Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
  81422. HashElem *k;
  81423. int iStatCur;
  81424. int iMem;
  81425. int iTab;
  81426. sqlite3BeginWriteOperation(pParse, 0, iDb);
  81427. iStatCur = pParse->nTab;
  81428. pParse->nTab += 3;
  81429. openStatTable(pParse, iDb, iStatCur, 0, 0);
  81430. iMem = pParse->nMem+1;
  81431. iTab = pParse->nTab;
  81432. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81433. for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
  81434. Table *pTab = (Table*)sqliteHashData(k);
  81435. analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
  81436. }
  81437. loadAnalysis(pParse, iDb);
  81438. }
  81439. /*
  81440. ** Generate code that will do an analysis of a single table in
  81441. ** a database. If pOnlyIdx is not NULL then it is a single index
  81442. ** in pTab that should be analyzed.
  81443. */
  81444. static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
  81445. int iDb;
  81446. int iStatCur;
  81447. assert( pTab!=0 );
  81448. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  81449. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  81450. sqlite3BeginWriteOperation(pParse, 0, iDb);
  81451. iStatCur = pParse->nTab;
  81452. pParse->nTab += 3;
  81453. if( pOnlyIdx ){
  81454. openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
  81455. }else{
  81456. openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
  81457. }
  81458. analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
  81459. loadAnalysis(pParse, iDb);
  81460. }
  81461. /*
  81462. ** Generate code for the ANALYZE command. The parser calls this routine
  81463. ** when it recognizes an ANALYZE command.
  81464. **
  81465. ** ANALYZE -- 1
  81466. ** ANALYZE <database> -- 2
  81467. ** ANALYZE ?<database>.?<tablename> -- 3
  81468. **
  81469. ** Form 1 causes all indices in all attached databases to be analyzed.
  81470. ** Form 2 analyzes all indices the single database named.
  81471. ** Form 3 analyzes all indices associated with the named table.
  81472. */
  81473. SQLITE_PRIVATE void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
  81474. sqlite3 *db = pParse->db;
  81475. int iDb;
  81476. int i;
  81477. char *z, *zDb;
  81478. Table *pTab;
  81479. Index *pIdx;
  81480. Token *pTableName;
  81481. Vdbe *v;
  81482. /* Read the database schema. If an error occurs, leave an error message
  81483. ** and code in pParse and return NULL. */
  81484. assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
  81485. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  81486. return;
  81487. }
  81488. assert( pName2!=0 || pName1==0 );
  81489. if( pName1==0 ){
  81490. /* Form 1: Analyze everything */
  81491. for(i=0; i<db->nDb; i++){
  81492. if( i==1 ) continue; /* Do not analyze the TEMP database */
  81493. analyzeDatabase(pParse, i);
  81494. }
  81495. }else if( pName2->n==0 ){
  81496. /* Form 2: Analyze the database or table named */
  81497. iDb = sqlite3FindDb(db, pName1);
  81498. if( iDb>=0 ){
  81499. analyzeDatabase(pParse, iDb);
  81500. }else{
  81501. z = sqlite3NameFromToken(db, pName1);
  81502. if( z ){
  81503. if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
  81504. analyzeTable(pParse, pIdx->pTable, pIdx);
  81505. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
  81506. analyzeTable(pParse, pTab, 0);
  81507. }
  81508. sqlite3DbFree(db, z);
  81509. }
  81510. }
  81511. }else{
  81512. /* Form 3: Analyze the fully qualified table name */
  81513. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
  81514. if( iDb>=0 ){
  81515. zDb = db->aDb[iDb].zName;
  81516. z = sqlite3NameFromToken(db, pTableName);
  81517. if( z ){
  81518. if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
  81519. analyzeTable(pParse, pIdx->pTable, pIdx);
  81520. }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
  81521. analyzeTable(pParse, pTab, 0);
  81522. }
  81523. sqlite3DbFree(db, z);
  81524. }
  81525. }
  81526. }
  81527. v = sqlite3GetVdbe(pParse);
  81528. if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
  81529. }
  81530. /*
  81531. ** Used to pass information from the analyzer reader through to the
  81532. ** callback routine.
  81533. */
  81534. typedef struct analysisInfo analysisInfo;
  81535. struct analysisInfo {
  81536. sqlite3 *db;
  81537. const char *zDatabase;
  81538. };
  81539. /*
  81540. ** The first argument points to a nul-terminated string containing a
  81541. ** list of space separated integers. Read the first nOut of these into
  81542. ** the array aOut[].
  81543. */
  81544. static void decodeIntArray(
  81545. char *zIntArray, /* String containing int array to decode */
  81546. int nOut, /* Number of slots in aOut[] */
  81547. tRowcnt *aOut, /* Store integers here */
  81548. LogEst *aLog, /* Or, if aOut==0, here */
  81549. Index *pIndex /* Handle extra flags for this index, if not NULL */
  81550. ){
  81551. char *z = zIntArray;
  81552. int c;
  81553. int i;
  81554. tRowcnt v;
  81555. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81556. if( z==0 ) z = "";
  81557. #else
  81558. assert( z!=0 );
  81559. #endif
  81560. for(i=0; *z && i<nOut; i++){
  81561. v = 0;
  81562. while( (c=z[0])>='0' && c<='9' ){
  81563. v = v*10 + c - '0';
  81564. z++;
  81565. }
  81566. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81567. if( aOut ) aOut[i] = v;
  81568. if( aLog ) aLog[i] = sqlite3LogEst(v);
  81569. #else
  81570. assert( aOut==0 );
  81571. UNUSED_PARAMETER(aOut);
  81572. assert( aLog!=0 );
  81573. aLog[i] = sqlite3LogEst(v);
  81574. #endif
  81575. if( *z==' ' ) z++;
  81576. }
  81577. #ifndef SQLITE_ENABLE_STAT3_OR_STAT4
  81578. assert( pIndex!=0 );
  81579. #else
  81580. if( pIndex )
  81581. #endif
  81582. while( z[0] ){
  81583. if( sqlite3_strglob("unordered*", z)==0 ){
  81584. pIndex->bUnordered = 1;
  81585. }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
  81586. pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
  81587. }
  81588. #ifdef SQLITE_ENABLE_COSTMULT
  81589. else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
  81590. pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
  81591. }
  81592. #endif
  81593. while( z[0]!=0 && z[0]!=' ' ) z++;
  81594. while( z[0]==' ' ) z++;
  81595. }
  81596. }
  81597. /*
  81598. ** This callback is invoked once for each index when reading the
  81599. ** sqlite_stat1 table.
  81600. **
  81601. ** argv[0] = name of the table
  81602. ** argv[1] = name of the index (might be NULL)
  81603. ** argv[2] = results of analysis - on integer for each column
  81604. **
  81605. ** Entries for which argv[1]==NULL simply record the number of rows in
  81606. ** the table.
  81607. */
  81608. static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
  81609. analysisInfo *pInfo = (analysisInfo*)pData;
  81610. Index *pIndex;
  81611. Table *pTable;
  81612. const char *z;
  81613. assert( argc==3 );
  81614. UNUSED_PARAMETER2(NotUsed, argc);
  81615. if( argv==0 || argv[0]==0 || argv[2]==0 ){
  81616. return 0;
  81617. }
  81618. pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
  81619. if( pTable==0 ){
  81620. return 0;
  81621. }
  81622. if( argv[1]==0 ){
  81623. pIndex = 0;
  81624. }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
  81625. pIndex = sqlite3PrimaryKeyIndex(pTable);
  81626. }else{
  81627. pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
  81628. }
  81629. z = argv[2];
  81630. if( pIndex ){
  81631. int nCol = pIndex->nKeyCol+1;
  81632. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81633. tRowcnt * const aiRowEst = pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(
  81634. sizeof(tRowcnt) * nCol
  81635. );
  81636. if( aiRowEst==0 ) pInfo->db->mallocFailed = 1;
  81637. #else
  81638. tRowcnt * const aiRowEst = 0;
  81639. #endif
  81640. pIndex->bUnordered = 0;
  81641. decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
  81642. if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
  81643. }else{
  81644. Index fakeIdx;
  81645. fakeIdx.szIdxRow = pTable->szTabRow;
  81646. #ifdef SQLITE_ENABLE_COSTMULT
  81647. fakeIdx.pTable = pTable;
  81648. #endif
  81649. decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
  81650. pTable->szTabRow = fakeIdx.szIdxRow;
  81651. }
  81652. return 0;
  81653. }
  81654. /*
  81655. ** If the Index.aSample variable is not NULL, delete the aSample[] array
  81656. ** and its contents.
  81657. */
  81658. SQLITE_PRIVATE void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
  81659. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81660. if( pIdx->aSample ){
  81661. int j;
  81662. for(j=0; j<pIdx->nSample; j++){
  81663. IndexSample *p = &pIdx->aSample[j];
  81664. sqlite3DbFree(db, p->p);
  81665. }
  81666. sqlite3DbFree(db, pIdx->aSample);
  81667. }
  81668. if( db && db->pnBytesFreed==0 ){
  81669. pIdx->nSample = 0;
  81670. pIdx->aSample = 0;
  81671. }
  81672. #else
  81673. UNUSED_PARAMETER(db);
  81674. UNUSED_PARAMETER(pIdx);
  81675. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  81676. }
  81677. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81678. /*
  81679. ** Populate the pIdx->aAvgEq[] array based on the samples currently
  81680. ** stored in pIdx->aSample[].
  81681. */
  81682. static void initAvgEq(Index *pIdx){
  81683. if( pIdx ){
  81684. IndexSample *aSample = pIdx->aSample;
  81685. IndexSample *pFinal = &aSample[pIdx->nSample-1];
  81686. int iCol;
  81687. int nCol = 1;
  81688. if( pIdx->nSampleCol>1 ){
  81689. /* If this is stat4 data, then calculate aAvgEq[] values for all
  81690. ** sample columns except the last. The last is always set to 1, as
  81691. ** once the trailing PK fields are considered all index keys are
  81692. ** unique. */
  81693. nCol = pIdx->nSampleCol-1;
  81694. pIdx->aAvgEq[nCol] = 1;
  81695. }
  81696. for(iCol=0; iCol<nCol; iCol++){
  81697. int nSample = pIdx->nSample;
  81698. int i; /* Used to iterate through samples */
  81699. tRowcnt sumEq = 0; /* Sum of the nEq values */
  81700. tRowcnt avgEq = 0;
  81701. tRowcnt nRow; /* Number of rows in index */
  81702. i64 nSum100 = 0; /* Number of terms contributing to sumEq */
  81703. i64 nDist100; /* Number of distinct values in index */
  81704. if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
  81705. nRow = pFinal->anLt[iCol];
  81706. nDist100 = (i64)100 * pFinal->anDLt[iCol];
  81707. nSample--;
  81708. }else{
  81709. nRow = pIdx->aiRowEst[0];
  81710. nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
  81711. }
  81712. /* Set nSum to the number of distinct (iCol+1) field prefixes that
  81713. ** occur in the stat4 table for this index. Set sumEq to the sum of
  81714. ** the nEq values for column iCol for the same set (adding the value
  81715. ** only once where there exist duplicate prefixes). */
  81716. for(i=0; i<nSample; i++){
  81717. if( i==(pIdx->nSample-1)
  81718. || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
  81719. ){
  81720. sumEq += aSample[i].anEq[iCol];
  81721. nSum100 += 100;
  81722. }
  81723. }
  81724. if( nDist100>nSum100 ){
  81725. avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
  81726. }
  81727. if( avgEq==0 ) avgEq = 1;
  81728. pIdx->aAvgEq[iCol] = avgEq;
  81729. }
  81730. }
  81731. }
  81732. /*
  81733. ** Look up an index by name. Or, if the name of a WITHOUT ROWID table
  81734. ** is supplied instead, find the PRIMARY KEY index for that table.
  81735. */
  81736. static Index *findIndexOrPrimaryKey(
  81737. sqlite3 *db,
  81738. const char *zName,
  81739. const char *zDb
  81740. ){
  81741. Index *pIdx = sqlite3FindIndex(db, zName, zDb);
  81742. if( pIdx==0 ){
  81743. Table *pTab = sqlite3FindTable(db, zName, zDb);
  81744. if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
  81745. }
  81746. return pIdx;
  81747. }
  81748. /*
  81749. ** Load the content from either the sqlite_stat4 or sqlite_stat3 table
  81750. ** into the relevant Index.aSample[] arrays.
  81751. **
  81752. ** Arguments zSql1 and zSql2 must point to SQL statements that return
  81753. ** data equivalent to the following (statements are different for stat3,
  81754. ** see the caller of this function for details):
  81755. **
  81756. ** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
  81757. ** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
  81758. **
  81759. ** where %Q is replaced with the database name before the SQL is executed.
  81760. */
  81761. static int loadStatTbl(
  81762. sqlite3 *db, /* Database handle */
  81763. int bStat3, /* Assume single column records only */
  81764. const char *zSql1, /* SQL statement 1 (see above) */
  81765. const char *zSql2, /* SQL statement 2 (see above) */
  81766. const char *zDb /* Database name (e.g. "main") */
  81767. ){
  81768. int rc; /* Result codes from subroutines */
  81769. sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
  81770. char *zSql; /* Text of the SQL statement */
  81771. Index *pPrevIdx = 0; /* Previous index in the loop */
  81772. IndexSample *pSample; /* A slot in pIdx->aSample[] */
  81773. assert( db->lookaside.bEnabled==0 );
  81774. zSql = sqlite3MPrintf(db, zSql1, zDb);
  81775. if( !zSql ){
  81776. return SQLITE_NOMEM;
  81777. }
  81778. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  81779. sqlite3DbFree(db, zSql);
  81780. if( rc ) return rc;
  81781. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  81782. int nIdxCol = 1; /* Number of columns in stat4 records */
  81783. char *zIndex; /* Index name */
  81784. Index *pIdx; /* Pointer to the index object */
  81785. int nSample; /* Number of samples */
  81786. int nByte; /* Bytes of space required */
  81787. int i; /* Bytes of space required */
  81788. tRowcnt *pSpace;
  81789. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  81790. if( zIndex==0 ) continue;
  81791. nSample = sqlite3_column_int(pStmt, 1);
  81792. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  81793. assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
  81794. /* Index.nSample is non-zero at this point if data has already been
  81795. ** loaded from the stat4 table. In this case ignore stat3 data. */
  81796. if( pIdx==0 || pIdx->nSample ) continue;
  81797. if( bStat3==0 ){
  81798. assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
  81799. if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
  81800. nIdxCol = pIdx->nKeyCol;
  81801. }else{
  81802. nIdxCol = pIdx->nColumn;
  81803. }
  81804. }
  81805. pIdx->nSampleCol = nIdxCol;
  81806. nByte = sizeof(IndexSample) * nSample;
  81807. nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
  81808. nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
  81809. pIdx->aSample = sqlite3DbMallocZero(db, nByte);
  81810. if( pIdx->aSample==0 ){
  81811. sqlite3_finalize(pStmt);
  81812. return SQLITE_NOMEM;
  81813. }
  81814. pSpace = (tRowcnt*)&pIdx->aSample[nSample];
  81815. pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
  81816. for(i=0; i<nSample; i++){
  81817. pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
  81818. pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
  81819. pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
  81820. }
  81821. assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
  81822. }
  81823. rc = sqlite3_finalize(pStmt);
  81824. if( rc ) return rc;
  81825. zSql = sqlite3MPrintf(db, zSql2, zDb);
  81826. if( !zSql ){
  81827. return SQLITE_NOMEM;
  81828. }
  81829. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  81830. sqlite3DbFree(db, zSql);
  81831. if( rc ) return rc;
  81832. while( sqlite3_step(pStmt)==SQLITE_ROW ){
  81833. char *zIndex; /* Index name */
  81834. Index *pIdx; /* Pointer to the index object */
  81835. int nCol = 1; /* Number of columns in index */
  81836. zIndex = (char *)sqlite3_column_text(pStmt, 0);
  81837. if( zIndex==0 ) continue;
  81838. pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
  81839. if( pIdx==0 ) continue;
  81840. /* This next condition is true if data has already been loaded from
  81841. ** the sqlite_stat4 table. In this case ignore stat3 data. */
  81842. nCol = pIdx->nSampleCol;
  81843. if( bStat3 && nCol>1 ) continue;
  81844. if( pIdx!=pPrevIdx ){
  81845. initAvgEq(pPrevIdx);
  81846. pPrevIdx = pIdx;
  81847. }
  81848. pSample = &pIdx->aSample[pIdx->nSample];
  81849. decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
  81850. decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
  81851. decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
  81852. /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
  81853. ** This is in case the sample record is corrupted. In that case, the
  81854. ** sqlite3VdbeRecordCompare() may read up to two varints past the
  81855. ** end of the allocated buffer before it realizes it is dealing with
  81856. ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
  81857. ** a buffer overread. */
  81858. pSample->n = sqlite3_column_bytes(pStmt, 4);
  81859. pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
  81860. if( pSample->p==0 ){
  81861. sqlite3_finalize(pStmt);
  81862. return SQLITE_NOMEM;
  81863. }
  81864. memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
  81865. pIdx->nSample++;
  81866. }
  81867. rc = sqlite3_finalize(pStmt);
  81868. if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
  81869. return rc;
  81870. }
  81871. /*
  81872. ** Load content from the sqlite_stat4 and sqlite_stat3 tables into
  81873. ** the Index.aSample[] arrays of all indices.
  81874. */
  81875. static int loadStat4(sqlite3 *db, const char *zDb){
  81876. int rc = SQLITE_OK; /* Result codes from subroutines */
  81877. assert( db->lookaside.bEnabled==0 );
  81878. if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
  81879. rc = loadStatTbl(db, 0,
  81880. "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
  81881. "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
  81882. zDb
  81883. );
  81884. }
  81885. if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
  81886. rc = loadStatTbl(db, 1,
  81887. "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
  81888. "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
  81889. zDb
  81890. );
  81891. }
  81892. return rc;
  81893. }
  81894. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  81895. /*
  81896. ** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
  81897. ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
  81898. ** arrays. The contents of sqlite_stat3/4 are used to populate the
  81899. ** Index.aSample[] arrays.
  81900. **
  81901. ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
  81902. ** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
  81903. ** during compilation and the sqlite_stat3/4 table is present, no data is
  81904. ** read from it.
  81905. **
  81906. ** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
  81907. ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
  81908. ** returned. However, in this case, data is read from the sqlite_stat1
  81909. ** table (if it is present) before returning.
  81910. **
  81911. ** If an OOM error occurs, this function always sets db->mallocFailed.
  81912. ** This means if the caller does not care about other errors, the return
  81913. ** code may be ignored.
  81914. */
  81915. SQLITE_PRIVATE int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
  81916. analysisInfo sInfo;
  81917. HashElem *i;
  81918. char *zSql;
  81919. int rc;
  81920. assert( iDb>=0 && iDb<db->nDb );
  81921. assert( db->aDb[iDb].pBt!=0 );
  81922. /* Clear any prior statistics */
  81923. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  81924. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  81925. Index *pIdx = sqliteHashData(i);
  81926. sqlite3DefaultRowEst(pIdx);
  81927. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81928. sqlite3DeleteIndexSamples(db, pIdx);
  81929. pIdx->aSample = 0;
  81930. #endif
  81931. }
  81932. /* Check to make sure the sqlite_stat1 table exists */
  81933. sInfo.db = db;
  81934. sInfo.zDatabase = db->aDb[iDb].zName;
  81935. if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
  81936. return SQLITE_ERROR;
  81937. }
  81938. /* Load new statistics out of the sqlite_stat1 table */
  81939. zSql = sqlite3MPrintf(db,
  81940. "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
  81941. if( zSql==0 ){
  81942. rc = SQLITE_NOMEM;
  81943. }else{
  81944. rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
  81945. sqlite3DbFree(db, zSql);
  81946. }
  81947. /* Load the statistics from the sqlite_stat4 table. */
  81948. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  81949. if( rc==SQLITE_OK ){
  81950. int lookasideEnabled = db->lookaside.bEnabled;
  81951. db->lookaside.bEnabled = 0;
  81952. rc = loadStat4(db, sInfo.zDatabase);
  81953. db->lookaside.bEnabled = lookasideEnabled;
  81954. }
  81955. for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
  81956. Index *pIdx = sqliteHashData(i);
  81957. sqlite3_free(pIdx->aiRowEst);
  81958. pIdx->aiRowEst = 0;
  81959. }
  81960. #endif
  81961. if( rc==SQLITE_NOMEM ){
  81962. db->mallocFailed = 1;
  81963. }
  81964. return rc;
  81965. }
  81966. #endif /* SQLITE_OMIT_ANALYZE */
  81967. /************** End of analyze.c *********************************************/
  81968. /************** Begin file attach.c ******************************************/
  81969. /*
  81970. ** 2003 April 6
  81971. **
  81972. ** The author disclaims copyright to this source code. In place of
  81973. ** a legal notice, here is a blessing:
  81974. **
  81975. ** May you do good and not evil.
  81976. ** May you find forgiveness for yourself and forgive others.
  81977. ** May you share freely, never taking more than you give.
  81978. **
  81979. *************************************************************************
  81980. ** This file contains code used to implement the ATTACH and DETACH commands.
  81981. */
  81982. #ifndef SQLITE_OMIT_ATTACH
  81983. /*
  81984. ** Resolve an expression that was part of an ATTACH or DETACH statement. This
  81985. ** is slightly different from resolving a normal SQL expression, because simple
  81986. ** identifiers are treated as strings, not possible column names or aliases.
  81987. **
  81988. ** i.e. if the parser sees:
  81989. **
  81990. ** ATTACH DATABASE abc AS def
  81991. **
  81992. ** it treats the two expressions as literal strings 'abc' and 'def' instead of
  81993. ** looking for columns of the same name.
  81994. **
  81995. ** This only applies to the root node of pExpr, so the statement:
  81996. **
  81997. ** ATTACH DATABASE abc||def AS 'db2'
  81998. **
  81999. ** will fail because neither abc or def can be resolved.
  82000. */
  82001. static int resolveAttachExpr(NameContext *pName, Expr *pExpr)
  82002. {
  82003. int rc = SQLITE_OK;
  82004. if( pExpr ){
  82005. if( pExpr->op!=TK_ID ){
  82006. rc = sqlite3ResolveExprNames(pName, pExpr);
  82007. }else{
  82008. pExpr->op = TK_STRING;
  82009. }
  82010. }
  82011. return rc;
  82012. }
  82013. /*
  82014. ** An SQL user-function registered to do the work of an ATTACH statement. The
  82015. ** three arguments to the function come directly from an attach statement:
  82016. **
  82017. ** ATTACH DATABASE x AS y KEY z
  82018. **
  82019. ** SELECT sqlite_attach(x, y, z)
  82020. **
  82021. ** If the optional "KEY z" syntax is omitted, an SQL NULL is passed as the
  82022. ** third argument.
  82023. */
  82024. static void attachFunc(
  82025. sqlite3_context *context,
  82026. int NotUsed,
  82027. sqlite3_value **argv
  82028. ){
  82029. int i;
  82030. int rc = 0;
  82031. sqlite3 *db = sqlite3_context_db_handle(context);
  82032. const char *zName;
  82033. const char *zFile;
  82034. char *zPath = 0;
  82035. char *zErr = 0;
  82036. unsigned int flags;
  82037. Db *aNew;
  82038. char *zErrDyn = 0;
  82039. sqlite3_vfs *pVfs;
  82040. UNUSED_PARAMETER(NotUsed);
  82041. zFile = (const char *)sqlite3_value_text(argv[0]);
  82042. zName = (const char *)sqlite3_value_text(argv[1]);
  82043. if( zFile==0 ) zFile = "";
  82044. if( zName==0 ) zName = "";
  82045. /* Check for the following errors:
  82046. **
  82047. ** * Too many attached databases,
  82048. ** * Transaction currently open
  82049. ** * Specified database name already being used.
  82050. */
  82051. if( db->nDb>=db->aLimit[SQLITE_LIMIT_ATTACHED]+2 ){
  82052. zErrDyn = sqlite3MPrintf(db, "too many attached databases - max %d",
  82053. db->aLimit[SQLITE_LIMIT_ATTACHED]
  82054. );
  82055. goto attach_error;
  82056. }
  82057. if( !db->autoCommit ){
  82058. zErrDyn = sqlite3MPrintf(db, "cannot ATTACH database within transaction");
  82059. goto attach_error;
  82060. }
  82061. for(i=0; i<db->nDb; i++){
  82062. char *z = db->aDb[i].zName;
  82063. assert( z && zName );
  82064. if( sqlite3StrICmp(z, zName)==0 ){
  82065. zErrDyn = sqlite3MPrintf(db, "database %s is already in use", zName);
  82066. goto attach_error;
  82067. }
  82068. }
  82069. /* Allocate the new entry in the db->aDb[] array and initialize the schema
  82070. ** hash tables.
  82071. */
  82072. if( db->aDb==db->aDbStatic ){
  82073. aNew = sqlite3DbMallocRaw(db, sizeof(db->aDb[0])*3 );
  82074. if( aNew==0 ) return;
  82075. memcpy(aNew, db->aDb, sizeof(db->aDb[0])*2);
  82076. }else{
  82077. aNew = sqlite3DbRealloc(db, db->aDb, sizeof(db->aDb[0])*(db->nDb+1) );
  82078. if( aNew==0 ) return;
  82079. }
  82080. db->aDb = aNew;
  82081. aNew = &db->aDb[db->nDb];
  82082. memset(aNew, 0, sizeof(*aNew));
  82083. /* Open the database file. If the btree is successfully opened, use
  82084. ** it to obtain the database schema. At this point the schema may
  82085. ** or may not be initialized.
  82086. */
  82087. flags = db->openFlags;
  82088. rc = sqlite3ParseUri(db->pVfs->zName, zFile, &flags, &pVfs, &zPath, &zErr);
  82089. if( rc!=SQLITE_OK ){
  82090. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  82091. sqlite3_result_error(context, zErr, -1);
  82092. sqlite3_free(zErr);
  82093. return;
  82094. }
  82095. assert( pVfs );
  82096. flags |= SQLITE_OPEN_MAIN_DB;
  82097. rc = sqlite3BtreeOpen(pVfs, zPath, db, &aNew->pBt, 0, flags);
  82098. sqlite3_free( zPath );
  82099. db->nDb++;
  82100. if( rc==SQLITE_CONSTRAINT ){
  82101. rc = SQLITE_ERROR;
  82102. zErrDyn = sqlite3MPrintf(db, "database is already attached");
  82103. }else if( rc==SQLITE_OK ){
  82104. Pager *pPager;
  82105. aNew->pSchema = sqlite3SchemaGet(db, aNew->pBt);
  82106. if( !aNew->pSchema ){
  82107. rc = SQLITE_NOMEM;
  82108. }else if( aNew->pSchema->file_format && aNew->pSchema->enc!=ENC(db) ){
  82109. zErrDyn = sqlite3MPrintf(db,
  82110. "attached databases must use the same text encoding as main database");
  82111. rc = SQLITE_ERROR;
  82112. }
  82113. pPager = sqlite3BtreePager(aNew->pBt);
  82114. sqlite3PagerLockingMode(pPager, db->dfltLockMode);
  82115. sqlite3BtreeSecureDelete(aNew->pBt,
  82116. sqlite3BtreeSecureDelete(db->aDb[0].pBt,-1) );
  82117. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  82118. sqlite3BtreeSetPagerFlags(aNew->pBt, 3 | (db->flags & PAGER_FLAGS_MASK));
  82119. #endif
  82120. }
  82121. aNew->safety_level = 3;
  82122. aNew->zName = sqlite3DbStrDup(db, zName);
  82123. if( rc==SQLITE_OK && aNew->zName==0 ){
  82124. rc = SQLITE_NOMEM;
  82125. }
  82126. #ifdef SQLITE_HAS_CODEC
  82127. if( rc==SQLITE_OK ){
  82128. extern int sqlite3CodecAttach(sqlite3*, int, const void*, int);
  82129. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  82130. int nKey;
  82131. char *zKey;
  82132. int t = sqlite3_value_type(argv[2]);
  82133. switch( t ){
  82134. case SQLITE_INTEGER:
  82135. case SQLITE_FLOAT:
  82136. zErrDyn = sqlite3DbStrDup(db, "Invalid key value");
  82137. rc = SQLITE_ERROR;
  82138. break;
  82139. case SQLITE_TEXT:
  82140. case SQLITE_BLOB:
  82141. nKey = sqlite3_value_bytes(argv[2]);
  82142. zKey = (char *)sqlite3_value_blob(argv[2]);
  82143. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  82144. break;
  82145. case SQLITE_NULL:
  82146. /* No key specified. Use the key from the main database */
  82147. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  82148. if( nKey>0 || sqlite3BtreeGetReserve(db->aDb[0].pBt)>0 ){
  82149. rc = sqlite3CodecAttach(db, db->nDb-1, zKey, nKey);
  82150. }
  82151. break;
  82152. }
  82153. }
  82154. #endif
  82155. /* If the file was opened successfully, read the schema for the new database.
  82156. ** If this fails, or if opening the file failed, then close the file and
  82157. ** remove the entry from the db->aDb[] array. i.e. put everything back the way
  82158. ** we found it.
  82159. */
  82160. if( rc==SQLITE_OK ){
  82161. sqlite3BtreeEnterAll(db);
  82162. rc = sqlite3Init(db, &zErrDyn);
  82163. sqlite3BtreeLeaveAll(db);
  82164. }
  82165. #ifdef SQLITE_USER_AUTHENTICATION
  82166. if( rc==SQLITE_OK ){
  82167. u8 newAuth = 0;
  82168. rc = sqlite3UserAuthCheckLogin(db, zName, &newAuth);
  82169. if( newAuth<db->auth.authLevel ){
  82170. rc = SQLITE_AUTH_USER;
  82171. }
  82172. }
  82173. #endif
  82174. if( rc ){
  82175. int iDb = db->nDb - 1;
  82176. assert( iDb>=2 );
  82177. if( db->aDb[iDb].pBt ){
  82178. sqlite3BtreeClose(db->aDb[iDb].pBt);
  82179. db->aDb[iDb].pBt = 0;
  82180. db->aDb[iDb].pSchema = 0;
  82181. }
  82182. sqlite3ResetAllSchemasOfConnection(db);
  82183. db->nDb = iDb;
  82184. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  82185. db->mallocFailed = 1;
  82186. sqlite3DbFree(db, zErrDyn);
  82187. zErrDyn = sqlite3MPrintf(db, "out of memory");
  82188. }else if( zErrDyn==0 ){
  82189. zErrDyn = sqlite3MPrintf(db, "unable to open database: %s", zFile);
  82190. }
  82191. goto attach_error;
  82192. }
  82193. return;
  82194. attach_error:
  82195. /* Return an error if we get here */
  82196. if( zErrDyn ){
  82197. sqlite3_result_error(context, zErrDyn, -1);
  82198. sqlite3DbFree(db, zErrDyn);
  82199. }
  82200. if( rc ) sqlite3_result_error_code(context, rc);
  82201. }
  82202. /*
  82203. ** An SQL user-function registered to do the work of an DETACH statement. The
  82204. ** three arguments to the function come directly from a detach statement:
  82205. **
  82206. ** DETACH DATABASE x
  82207. **
  82208. ** SELECT sqlite_detach(x)
  82209. */
  82210. static void detachFunc(
  82211. sqlite3_context *context,
  82212. int NotUsed,
  82213. sqlite3_value **argv
  82214. ){
  82215. const char *zName = (const char *)sqlite3_value_text(argv[0]);
  82216. sqlite3 *db = sqlite3_context_db_handle(context);
  82217. int i;
  82218. Db *pDb = 0;
  82219. char zErr[128];
  82220. UNUSED_PARAMETER(NotUsed);
  82221. if( zName==0 ) zName = "";
  82222. for(i=0; i<db->nDb; i++){
  82223. pDb = &db->aDb[i];
  82224. if( pDb->pBt==0 ) continue;
  82225. if( sqlite3StrICmp(pDb->zName, zName)==0 ) break;
  82226. }
  82227. if( i>=db->nDb ){
  82228. sqlite3_snprintf(sizeof(zErr),zErr, "no such database: %s", zName);
  82229. goto detach_error;
  82230. }
  82231. if( i<2 ){
  82232. sqlite3_snprintf(sizeof(zErr),zErr, "cannot detach database %s", zName);
  82233. goto detach_error;
  82234. }
  82235. if( !db->autoCommit ){
  82236. sqlite3_snprintf(sizeof(zErr), zErr,
  82237. "cannot DETACH database within transaction");
  82238. goto detach_error;
  82239. }
  82240. if( sqlite3BtreeIsInReadTrans(pDb->pBt) || sqlite3BtreeIsInBackup(pDb->pBt) ){
  82241. sqlite3_snprintf(sizeof(zErr),zErr, "database %s is locked", zName);
  82242. goto detach_error;
  82243. }
  82244. sqlite3BtreeClose(pDb->pBt);
  82245. pDb->pBt = 0;
  82246. pDb->pSchema = 0;
  82247. sqlite3ResetAllSchemasOfConnection(db);
  82248. return;
  82249. detach_error:
  82250. sqlite3_result_error(context, zErr, -1);
  82251. }
  82252. /*
  82253. ** This procedure generates VDBE code for a single invocation of either the
  82254. ** sqlite_detach() or sqlite_attach() SQL user functions.
  82255. */
  82256. static void codeAttach(
  82257. Parse *pParse, /* The parser context */
  82258. int type, /* Either SQLITE_ATTACH or SQLITE_DETACH */
  82259. FuncDef const *pFunc,/* FuncDef wrapper for detachFunc() or attachFunc() */
  82260. Expr *pAuthArg, /* Expression to pass to authorization callback */
  82261. Expr *pFilename, /* Name of database file */
  82262. Expr *pDbname, /* Name of the database to use internally */
  82263. Expr *pKey /* Database key for encryption extension */
  82264. ){
  82265. int rc;
  82266. NameContext sName;
  82267. Vdbe *v;
  82268. sqlite3* db = pParse->db;
  82269. int regArgs;
  82270. memset(&sName, 0, sizeof(NameContext));
  82271. sName.pParse = pParse;
  82272. if(
  82273. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pFilename)) ||
  82274. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pDbname)) ||
  82275. SQLITE_OK!=(rc = resolveAttachExpr(&sName, pKey))
  82276. ){
  82277. pParse->nErr++;
  82278. goto attach_end;
  82279. }
  82280. #ifndef SQLITE_OMIT_AUTHORIZATION
  82281. if( pAuthArg ){
  82282. char *zAuthArg;
  82283. if( pAuthArg->op==TK_STRING ){
  82284. zAuthArg = pAuthArg->u.zToken;
  82285. }else{
  82286. zAuthArg = 0;
  82287. }
  82288. rc = sqlite3AuthCheck(pParse, type, zAuthArg, 0, 0);
  82289. if(rc!=SQLITE_OK ){
  82290. goto attach_end;
  82291. }
  82292. }
  82293. #endif /* SQLITE_OMIT_AUTHORIZATION */
  82294. v = sqlite3GetVdbe(pParse);
  82295. regArgs = sqlite3GetTempRange(pParse, 4);
  82296. sqlite3ExprCode(pParse, pFilename, regArgs);
  82297. sqlite3ExprCode(pParse, pDbname, regArgs+1);
  82298. sqlite3ExprCode(pParse, pKey, regArgs+2);
  82299. assert( v || db->mallocFailed );
  82300. if( v ){
  82301. sqlite3VdbeAddOp3(v, OP_Function, 0, regArgs+3-pFunc->nArg, regArgs+3);
  82302. assert( pFunc->nArg==-1 || (pFunc->nArg&0xff)==pFunc->nArg );
  82303. sqlite3VdbeChangeP5(v, (u8)(pFunc->nArg));
  82304. sqlite3VdbeChangeP4(v, -1, (char *)pFunc, P4_FUNCDEF);
  82305. /* Code an OP_Expire. For an ATTACH statement, set P1 to true (expire this
  82306. ** statement only). For DETACH, set it to false (expire all existing
  82307. ** statements).
  82308. */
  82309. sqlite3VdbeAddOp1(v, OP_Expire, (type==SQLITE_ATTACH));
  82310. }
  82311. attach_end:
  82312. sqlite3ExprDelete(db, pFilename);
  82313. sqlite3ExprDelete(db, pDbname);
  82314. sqlite3ExprDelete(db, pKey);
  82315. }
  82316. /*
  82317. ** Called by the parser to compile a DETACH statement.
  82318. **
  82319. ** DETACH pDbname
  82320. */
  82321. SQLITE_PRIVATE void sqlite3Detach(Parse *pParse, Expr *pDbname){
  82322. static const FuncDef detach_func = {
  82323. 1, /* nArg */
  82324. SQLITE_UTF8, /* funcFlags */
  82325. 0, /* pUserData */
  82326. 0, /* pNext */
  82327. detachFunc, /* xFunc */
  82328. 0, /* xStep */
  82329. 0, /* xFinalize */
  82330. "sqlite_detach", /* zName */
  82331. 0, /* pHash */
  82332. 0 /* pDestructor */
  82333. };
  82334. codeAttach(pParse, SQLITE_DETACH, &detach_func, pDbname, 0, 0, pDbname);
  82335. }
  82336. /*
  82337. ** Called by the parser to compile an ATTACH statement.
  82338. **
  82339. ** ATTACH p AS pDbname KEY pKey
  82340. */
  82341. SQLITE_PRIVATE void sqlite3Attach(Parse *pParse, Expr *p, Expr *pDbname, Expr *pKey){
  82342. static const FuncDef attach_func = {
  82343. 3, /* nArg */
  82344. SQLITE_UTF8, /* funcFlags */
  82345. 0, /* pUserData */
  82346. 0, /* pNext */
  82347. attachFunc, /* xFunc */
  82348. 0, /* xStep */
  82349. 0, /* xFinalize */
  82350. "sqlite_attach", /* zName */
  82351. 0, /* pHash */
  82352. 0 /* pDestructor */
  82353. };
  82354. codeAttach(pParse, SQLITE_ATTACH, &attach_func, p, p, pDbname, pKey);
  82355. }
  82356. #endif /* SQLITE_OMIT_ATTACH */
  82357. /*
  82358. ** Initialize a DbFixer structure. This routine must be called prior
  82359. ** to passing the structure to one of the sqliteFixAAAA() routines below.
  82360. */
  82361. SQLITE_PRIVATE void sqlite3FixInit(
  82362. DbFixer *pFix, /* The fixer to be initialized */
  82363. Parse *pParse, /* Error messages will be written here */
  82364. int iDb, /* This is the database that must be used */
  82365. const char *zType, /* "view", "trigger", or "index" */
  82366. const Token *pName /* Name of the view, trigger, or index */
  82367. ){
  82368. sqlite3 *db;
  82369. db = pParse->db;
  82370. assert( db->nDb>iDb );
  82371. pFix->pParse = pParse;
  82372. pFix->zDb = db->aDb[iDb].zName;
  82373. pFix->pSchema = db->aDb[iDb].pSchema;
  82374. pFix->zType = zType;
  82375. pFix->pName = pName;
  82376. pFix->bVarOnly = (iDb==1);
  82377. }
  82378. /*
  82379. ** The following set of routines walk through the parse tree and assign
  82380. ** a specific database to all table references where the database name
  82381. ** was left unspecified in the original SQL statement. The pFix structure
  82382. ** must have been initialized by a prior call to sqlite3FixInit().
  82383. **
  82384. ** These routines are used to make sure that an index, trigger, or
  82385. ** view in one database does not refer to objects in a different database.
  82386. ** (Exception: indices, triggers, and views in the TEMP database are
  82387. ** allowed to refer to anything.) If a reference is explicitly made
  82388. ** to an object in a different database, an error message is added to
  82389. ** pParse->zErrMsg and these routines return non-zero. If everything
  82390. ** checks out, these routines return 0.
  82391. */
  82392. SQLITE_PRIVATE int sqlite3FixSrcList(
  82393. DbFixer *pFix, /* Context of the fixation */
  82394. SrcList *pList /* The Source list to check and modify */
  82395. ){
  82396. int i;
  82397. const char *zDb;
  82398. struct SrcList_item *pItem;
  82399. if( NEVER(pList==0) ) return 0;
  82400. zDb = pFix->zDb;
  82401. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  82402. if( pFix->bVarOnly==0 ){
  82403. if( pItem->zDatabase && sqlite3StrICmp(pItem->zDatabase, zDb) ){
  82404. sqlite3ErrorMsg(pFix->pParse,
  82405. "%s %T cannot reference objects in database %s",
  82406. pFix->zType, pFix->pName, pItem->zDatabase);
  82407. return 1;
  82408. }
  82409. sqlite3DbFree(pFix->pParse->db, pItem->zDatabase);
  82410. pItem->zDatabase = 0;
  82411. pItem->pSchema = pFix->pSchema;
  82412. }
  82413. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  82414. if( sqlite3FixSelect(pFix, pItem->pSelect) ) return 1;
  82415. if( sqlite3FixExpr(pFix, pItem->pOn) ) return 1;
  82416. #endif
  82417. }
  82418. return 0;
  82419. }
  82420. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER)
  82421. SQLITE_PRIVATE int sqlite3FixSelect(
  82422. DbFixer *pFix, /* Context of the fixation */
  82423. Select *pSelect /* The SELECT statement to be fixed to one database */
  82424. ){
  82425. while( pSelect ){
  82426. if( sqlite3FixExprList(pFix, pSelect->pEList) ){
  82427. return 1;
  82428. }
  82429. if( sqlite3FixSrcList(pFix, pSelect->pSrc) ){
  82430. return 1;
  82431. }
  82432. if( sqlite3FixExpr(pFix, pSelect->pWhere) ){
  82433. return 1;
  82434. }
  82435. if( sqlite3FixExprList(pFix, pSelect->pGroupBy) ){
  82436. return 1;
  82437. }
  82438. if( sqlite3FixExpr(pFix, pSelect->pHaving) ){
  82439. return 1;
  82440. }
  82441. if( sqlite3FixExprList(pFix, pSelect->pOrderBy) ){
  82442. return 1;
  82443. }
  82444. if( sqlite3FixExpr(pFix, pSelect->pLimit) ){
  82445. return 1;
  82446. }
  82447. if( sqlite3FixExpr(pFix, pSelect->pOffset) ){
  82448. return 1;
  82449. }
  82450. pSelect = pSelect->pPrior;
  82451. }
  82452. return 0;
  82453. }
  82454. SQLITE_PRIVATE int sqlite3FixExpr(
  82455. DbFixer *pFix, /* Context of the fixation */
  82456. Expr *pExpr /* The expression to be fixed to one database */
  82457. ){
  82458. while( pExpr ){
  82459. if( pExpr->op==TK_VARIABLE ){
  82460. if( pFix->pParse->db->init.busy ){
  82461. pExpr->op = TK_NULL;
  82462. }else{
  82463. sqlite3ErrorMsg(pFix->pParse, "%s cannot use variables", pFix->zType);
  82464. return 1;
  82465. }
  82466. }
  82467. if( ExprHasProperty(pExpr, EP_TokenOnly) ) break;
  82468. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  82469. if( sqlite3FixSelect(pFix, pExpr->x.pSelect) ) return 1;
  82470. }else{
  82471. if( sqlite3FixExprList(pFix, pExpr->x.pList) ) return 1;
  82472. }
  82473. if( sqlite3FixExpr(pFix, pExpr->pRight) ){
  82474. return 1;
  82475. }
  82476. pExpr = pExpr->pLeft;
  82477. }
  82478. return 0;
  82479. }
  82480. SQLITE_PRIVATE int sqlite3FixExprList(
  82481. DbFixer *pFix, /* Context of the fixation */
  82482. ExprList *pList /* The expression to be fixed to one database */
  82483. ){
  82484. int i;
  82485. struct ExprList_item *pItem;
  82486. if( pList==0 ) return 0;
  82487. for(i=0, pItem=pList->a; i<pList->nExpr; i++, pItem++){
  82488. if( sqlite3FixExpr(pFix, pItem->pExpr) ){
  82489. return 1;
  82490. }
  82491. }
  82492. return 0;
  82493. }
  82494. #endif
  82495. #ifndef SQLITE_OMIT_TRIGGER
  82496. SQLITE_PRIVATE int sqlite3FixTriggerStep(
  82497. DbFixer *pFix, /* Context of the fixation */
  82498. TriggerStep *pStep /* The trigger step be fixed to one database */
  82499. ){
  82500. while( pStep ){
  82501. if( sqlite3FixSelect(pFix, pStep->pSelect) ){
  82502. return 1;
  82503. }
  82504. if( sqlite3FixExpr(pFix, pStep->pWhere) ){
  82505. return 1;
  82506. }
  82507. if( sqlite3FixExprList(pFix, pStep->pExprList) ){
  82508. return 1;
  82509. }
  82510. pStep = pStep->pNext;
  82511. }
  82512. return 0;
  82513. }
  82514. #endif
  82515. /************** End of attach.c **********************************************/
  82516. /************** Begin file auth.c ********************************************/
  82517. /*
  82518. ** 2003 January 11
  82519. **
  82520. ** The author disclaims copyright to this source code. In place of
  82521. ** a legal notice, here is a blessing:
  82522. **
  82523. ** May you do good and not evil.
  82524. ** May you find forgiveness for yourself and forgive others.
  82525. ** May you share freely, never taking more than you give.
  82526. **
  82527. *************************************************************************
  82528. ** This file contains code used to implement the sqlite3_set_authorizer()
  82529. ** API. This facility is an optional feature of the library. Embedded
  82530. ** systems that do not need this facility may omit it by recompiling
  82531. ** the library with -DSQLITE_OMIT_AUTHORIZATION=1
  82532. */
  82533. /*
  82534. ** All of the code in this file may be omitted by defining a single
  82535. ** macro.
  82536. */
  82537. #ifndef SQLITE_OMIT_AUTHORIZATION
  82538. /*
  82539. ** Set or clear the access authorization function.
  82540. **
  82541. ** The access authorization function is be called during the compilation
  82542. ** phase to verify that the user has read and/or write access permission on
  82543. ** various fields of the database. The first argument to the auth function
  82544. ** is a copy of the 3rd argument to this routine. The second argument
  82545. ** to the auth function is one of these constants:
  82546. **
  82547. ** SQLITE_CREATE_INDEX
  82548. ** SQLITE_CREATE_TABLE
  82549. ** SQLITE_CREATE_TEMP_INDEX
  82550. ** SQLITE_CREATE_TEMP_TABLE
  82551. ** SQLITE_CREATE_TEMP_TRIGGER
  82552. ** SQLITE_CREATE_TEMP_VIEW
  82553. ** SQLITE_CREATE_TRIGGER
  82554. ** SQLITE_CREATE_VIEW
  82555. ** SQLITE_DELETE
  82556. ** SQLITE_DROP_INDEX
  82557. ** SQLITE_DROP_TABLE
  82558. ** SQLITE_DROP_TEMP_INDEX
  82559. ** SQLITE_DROP_TEMP_TABLE
  82560. ** SQLITE_DROP_TEMP_TRIGGER
  82561. ** SQLITE_DROP_TEMP_VIEW
  82562. ** SQLITE_DROP_TRIGGER
  82563. ** SQLITE_DROP_VIEW
  82564. ** SQLITE_INSERT
  82565. ** SQLITE_PRAGMA
  82566. ** SQLITE_READ
  82567. ** SQLITE_SELECT
  82568. ** SQLITE_TRANSACTION
  82569. ** SQLITE_UPDATE
  82570. **
  82571. ** The third and fourth arguments to the auth function are the name of
  82572. ** the table and the column that are being accessed. The auth function
  82573. ** should return either SQLITE_OK, SQLITE_DENY, or SQLITE_IGNORE. If
  82574. ** SQLITE_OK is returned, it means that access is allowed. SQLITE_DENY
  82575. ** means that the SQL statement will never-run - the sqlite3_exec() call
  82576. ** will return with an error. SQLITE_IGNORE means that the SQL statement
  82577. ** should run but attempts to read the specified column will return NULL
  82578. ** and attempts to write the column will be ignored.
  82579. **
  82580. ** Setting the auth function to NULL disables this hook. The default
  82581. ** setting of the auth function is NULL.
  82582. */
  82583. SQLITE_API int sqlite3_set_authorizer(
  82584. sqlite3 *db,
  82585. int (*xAuth)(void*,int,const char*,const char*,const char*,const char*),
  82586. void *pArg
  82587. ){
  82588. sqlite3_mutex_enter(db->mutex);
  82589. db->xAuth = (sqlite3_xauth)xAuth;
  82590. db->pAuthArg = pArg;
  82591. sqlite3ExpirePreparedStatements(db);
  82592. sqlite3_mutex_leave(db->mutex);
  82593. return SQLITE_OK;
  82594. }
  82595. /*
  82596. ** Write an error message into pParse->zErrMsg that explains that the
  82597. ** user-supplied authorization function returned an illegal value.
  82598. */
  82599. static void sqliteAuthBadReturnCode(Parse *pParse){
  82600. sqlite3ErrorMsg(pParse, "authorizer malfunction");
  82601. pParse->rc = SQLITE_ERROR;
  82602. }
  82603. /*
  82604. ** Invoke the authorization callback for permission to read column zCol from
  82605. ** table zTab in database zDb. This function assumes that an authorization
  82606. ** callback has been registered (i.e. that sqlite3.xAuth is not NULL).
  82607. **
  82608. ** If SQLITE_IGNORE is returned and pExpr is not NULL, then pExpr is changed
  82609. ** to an SQL NULL expression. Otherwise, if pExpr is NULL, then SQLITE_IGNORE
  82610. ** is treated as SQLITE_DENY. In this case an error is left in pParse.
  82611. */
  82612. SQLITE_PRIVATE int sqlite3AuthReadCol(
  82613. Parse *pParse, /* The parser context */
  82614. const char *zTab, /* Table name */
  82615. const char *zCol, /* Column name */
  82616. int iDb /* Index of containing database. */
  82617. ){
  82618. sqlite3 *db = pParse->db; /* Database handle */
  82619. char *zDb = db->aDb[iDb].zName; /* Name of attached database */
  82620. int rc; /* Auth callback return code */
  82621. rc = db->xAuth(db->pAuthArg, SQLITE_READ, zTab,zCol,zDb,pParse->zAuthContext
  82622. #ifdef SQLITE_USER_AUTHENTICATION
  82623. ,db->auth.zAuthUser
  82624. #endif
  82625. );
  82626. if( rc==SQLITE_DENY ){
  82627. if( db->nDb>2 || iDb!=0 ){
  82628. sqlite3ErrorMsg(pParse, "access to %s.%s.%s is prohibited",zDb,zTab,zCol);
  82629. }else{
  82630. sqlite3ErrorMsg(pParse, "access to %s.%s is prohibited", zTab, zCol);
  82631. }
  82632. pParse->rc = SQLITE_AUTH;
  82633. }else if( rc!=SQLITE_IGNORE && rc!=SQLITE_OK ){
  82634. sqliteAuthBadReturnCode(pParse);
  82635. }
  82636. return rc;
  82637. }
  82638. /*
  82639. ** The pExpr should be a TK_COLUMN expression. The table referred to
  82640. ** is in pTabList or else it is the NEW or OLD table of a trigger.
  82641. ** Check to see if it is OK to read this particular column.
  82642. **
  82643. ** If the auth function returns SQLITE_IGNORE, change the TK_COLUMN
  82644. ** instruction into a TK_NULL. If the auth function returns SQLITE_DENY,
  82645. ** then generate an error.
  82646. */
  82647. SQLITE_PRIVATE void sqlite3AuthRead(
  82648. Parse *pParse, /* The parser context */
  82649. Expr *pExpr, /* The expression to check authorization on */
  82650. Schema *pSchema, /* The schema of the expression */
  82651. SrcList *pTabList /* All table that pExpr might refer to */
  82652. ){
  82653. sqlite3 *db = pParse->db;
  82654. Table *pTab = 0; /* The table being read */
  82655. const char *zCol; /* Name of the column of the table */
  82656. int iSrc; /* Index in pTabList->a[] of table being read */
  82657. int iDb; /* The index of the database the expression refers to */
  82658. int iCol; /* Index of column in table */
  82659. if( db->xAuth==0 ) return;
  82660. iDb = sqlite3SchemaToIndex(pParse->db, pSchema);
  82661. if( iDb<0 ){
  82662. /* An attempt to read a column out of a subquery or other
  82663. ** temporary table. */
  82664. return;
  82665. }
  82666. assert( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER );
  82667. if( pExpr->op==TK_TRIGGER ){
  82668. pTab = pParse->pTriggerTab;
  82669. }else{
  82670. assert( pTabList );
  82671. for(iSrc=0; ALWAYS(iSrc<pTabList->nSrc); iSrc++){
  82672. if( pExpr->iTable==pTabList->a[iSrc].iCursor ){
  82673. pTab = pTabList->a[iSrc].pTab;
  82674. break;
  82675. }
  82676. }
  82677. }
  82678. iCol = pExpr->iColumn;
  82679. if( NEVER(pTab==0) ) return;
  82680. if( iCol>=0 ){
  82681. assert( iCol<pTab->nCol );
  82682. zCol = pTab->aCol[iCol].zName;
  82683. }else if( pTab->iPKey>=0 ){
  82684. assert( pTab->iPKey<pTab->nCol );
  82685. zCol = pTab->aCol[pTab->iPKey].zName;
  82686. }else{
  82687. zCol = "ROWID";
  82688. }
  82689. assert( iDb>=0 && iDb<db->nDb );
  82690. if( SQLITE_IGNORE==sqlite3AuthReadCol(pParse, pTab->zName, zCol, iDb) ){
  82691. pExpr->op = TK_NULL;
  82692. }
  82693. }
  82694. /*
  82695. ** Do an authorization check using the code and arguments given. Return
  82696. ** either SQLITE_OK (zero) or SQLITE_IGNORE or SQLITE_DENY. If SQLITE_DENY
  82697. ** is returned, then the error count and error message in pParse are
  82698. ** modified appropriately.
  82699. */
  82700. SQLITE_PRIVATE int sqlite3AuthCheck(
  82701. Parse *pParse,
  82702. int code,
  82703. const char *zArg1,
  82704. const char *zArg2,
  82705. const char *zArg3
  82706. ){
  82707. sqlite3 *db = pParse->db;
  82708. int rc;
  82709. /* Don't do any authorization checks if the database is initialising
  82710. ** or if the parser is being invoked from within sqlite3_declare_vtab.
  82711. */
  82712. if( db->init.busy || IN_DECLARE_VTAB ){
  82713. return SQLITE_OK;
  82714. }
  82715. if( db->xAuth==0 ){
  82716. return SQLITE_OK;
  82717. }
  82718. rc = db->xAuth(db->pAuthArg, code, zArg1, zArg2, zArg3, pParse->zAuthContext
  82719. #ifdef SQLITE_USER_AUTHENTICATION
  82720. ,db->auth.zAuthUser
  82721. #endif
  82722. );
  82723. if( rc==SQLITE_DENY ){
  82724. sqlite3ErrorMsg(pParse, "not authorized");
  82725. pParse->rc = SQLITE_AUTH;
  82726. }else if( rc!=SQLITE_OK && rc!=SQLITE_IGNORE ){
  82727. rc = SQLITE_DENY;
  82728. sqliteAuthBadReturnCode(pParse);
  82729. }
  82730. return rc;
  82731. }
  82732. /*
  82733. ** Push an authorization context. After this routine is called, the
  82734. ** zArg3 argument to authorization callbacks will be zContext until
  82735. ** popped. Or if pParse==0, this routine is a no-op.
  82736. */
  82737. SQLITE_PRIVATE void sqlite3AuthContextPush(
  82738. Parse *pParse,
  82739. AuthContext *pContext,
  82740. const char *zContext
  82741. ){
  82742. assert( pParse );
  82743. pContext->pParse = pParse;
  82744. pContext->zAuthContext = pParse->zAuthContext;
  82745. pParse->zAuthContext = zContext;
  82746. }
  82747. /*
  82748. ** Pop an authorization context that was previously pushed
  82749. ** by sqlite3AuthContextPush
  82750. */
  82751. SQLITE_PRIVATE void sqlite3AuthContextPop(AuthContext *pContext){
  82752. if( pContext->pParse ){
  82753. pContext->pParse->zAuthContext = pContext->zAuthContext;
  82754. pContext->pParse = 0;
  82755. }
  82756. }
  82757. #endif /* SQLITE_OMIT_AUTHORIZATION */
  82758. /************** End of auth.c ************************************************/
  82759. /************** Begin file build.c *******************************************/
  82760. /*
  82761. ** 2001 September 15
  82762. **
  82763. ** The author disclaims copyright to this source code. In place of
  82764. ** a legal notice, here is a blessing:
  82765. **
  82766. ** May you do good and not evil.
  82767. ** May you find forgiveness for yourself and forgive others.
  82768. ** May you share freely, never taking more than you give.
  82769. **
  82770. *************************************************************************
  82771. ** This file contains C code routines that are called by the SQLite parser
  82772. ** when syntax rules are reduced. The routines in this file handle the
  82773. ** following kinds of SQL syntax:
  82774. **
  82775. ** CREATE TABLE
  82776. ** DROP TABLE
  82777. ** CREATE INDEX
  82778. ** DROP INDEX
  82779. ** creating ID lists
  82780. ** BEGIN TRANSACTION
  82781. ** COMMIT
  82782. ** ROLLBACK
  82783. */
  82784. /*
  82785. ** This routine is called when a new SQL statement is beginning to
  82786. ** be parsed. Initialize the pParse structure as needed.
  82787. */
  82788. SQLITE_PRIVATE void sqlite3BeginParse(Parse *pParse, int explainFlag){
  82789. pParse->explain = (u8)explainFlag;
  82790. pParse->nVar = 0;
  82791. }
  82792. #ifndef SQLITE_OMIT_SHARED_CACHE
  82793. /*
  82794. ** The TableLock structure is only used by the sqlite3TableLock() and
  82795. ** codeTableLocks() functions.
  82796. */
  82797. struct TableLock {
  82798. int iDb; /* The database containing the table to be locked */
  82799. int iTab; /* The root page of the table to be locked */
  82800. u8 isWriteLock; /* True for write lock. False for a read lock */
  82801. const char *zName; /* Name of the table */
  82802. };
  82803. /*
  82804. ** Record the fact that we want to lock a table at run-time.
  82805. **
  82806. ** The table to be locked has root page iTab and is found in database iDb.
  82807. ** A read or a write lock can be taken depending on isWritelock.
  82808. **
  82809. ** This routine just records the fact that the lock is desired. The
  82810. ** code to make the lock occur is generated by a later call to
  82811. ** codeTableLocks() which occurs during sqlite3FinishCoding().
  82812. */
  82813. SQLITE_PRIVATE void sqlite3TableLock(
  82814. Parse *pParse, /* Parsing context */
  82815. int iDb, /* Index of the database containing the table to lock */
  82816. int iTab, /* Root page number of the table to be locked */
  82817. u8 isWriteLock, /* True for a write lock */
  82818. const char *zName /* Name of the table to be locked */
  82819. ){
  82820. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  82821. int i;
  82822. int nBytes;
  82823. TableLock *p;
  82824. assert( iDb>=0 );
  82825. for(i=0; i<pToplevel->nTableLock; i++){
  82826. p = &pToplevel->aTableLock[i];
  82827. if( p->iDb==iDb && p->iTab==iTab ){
  82828. p->isWriteLock = (p->isWriteLock || isWriteLock);
  82829. return;
  82830. }
  82831. }
  82832. nBytes = sizeof(TableLock) * (pToplevel->nTableLock+1);
  82833. pToplevel->aTableLock =
  82834. sqlite3DbReallocOrFree(pToplevel->db, pToplevel->aTableLock, nBytes);
  82835. if( pToplevel->aTableLock ){
  82836. p = &pToplevel->aTableLock[pToplevel->nTableLock++];
  82837. p->iDb = iDb;
  82838. p->iTab = iTab;
  82839. p->isWriteLock = isWriteLock;
  82840. p->zName = zName;
  82841. }else{
  82842. pToplevel->nTableLock = 0;
  82843. pToplevel->db->mallocFailed = 1;
  82844. }
  82845. }
  82846. /*
  82847. ** Code an OP_TableLock instruction for each table locked by the
  82848. ** statement (configured by calls to sqlite3TableLock()).
  82849. */
  82850. static void codeTableLocks(Parse *pParse){
  82851. int i;
  82852. Vdbe *pVdbe;
  82853. pVdbe = sqlite3GetVdbe(pParse);
  82854. assert( pVdbe!=0 ); /* sqlite3GetVdbe cannot fail: VDBE already allocated */
  82855. for(i=0; i<pParse->nTableLock; i++){
  82856. TableLock *p = &pParse->aTableLock[i];
  82857. int p1 = p->iDb;
  82858. sqlite3VdbeAddOp4(pVdbe, OP_TableLock, p1, p->iTab, p->isWriteLock,
  82859. p->zName, P4_STATIC);
  82860. }
  82861. }
  82862. #else
  82863. #define codeTableLocks(x)
  82864. #endif
  82865. /*
  82866. ** Return TRUE if the given yDbMask object is empty - if it contains no
  82867. ** 1 bits. This routine is used by the DbMaskAllZero() and DbMaskNotZero()
  82868. ** macros when SQLITE_MAX_ATTACHED is greater than 30.
  82869. */
  82870. #if SQLITE_MAX_ATTACHED>30
  82871. SQLITE_PRIVATE int sqlite3DbMaskAllZero(yDbMask m){
  82872. int i;
  82873. for(i=0; i<sizeof(yDbMask); i++) if( m[i] ) return 0;
  82874. return 1;
  82875. }
  82876. #endif
  82877. /*
  82878. ** This routine is called after a single SQL statement has been
  82879. ** parsed and a VDBE program to execute that statement has been
  82880. ** prepared. This routine puts the finishing touches on the
  82881. ** VDBE program and resets the pParse structure for the next
  82882. ** parse.
  82883. **
  82884. ** Note that if an error occurred, it might be the case that
  82885. ** no VDBE code was generated.
  82886. */
  82887. SQLITE_PRIVATE void sqlite3FinishCoding(Parse *pParse){
  82888. sqlite3 *db;
  82889. Vdbe *v;
  82890. assert( pParse->pToplevel==0 );
  82891. db = pParse->db;
  82892. if( db->mallocFailed ) return;
  82893. if( pParse->nested ) return;
  82894. if( pParse->nErr ) return;
  82895. /* Begin by generating some termination code at the end of the
  82896. ** vdbe program
  82897. */
  82898. v = sqlite3GetVdbe(pParse);
  82899. assert( !pParse->isMultiWrite
  82900. || sqlite3VdbeAssertMayAbort(v, pParse->mayAbort));
  82901. if( v ){
  82902. while( sqlite3VdbeDeletePriorOpcode(v, OP_Close) ){}
  82903. sqlite3VdbeAddOp0(v, OP_Halt);
  82904. #if SQLITE_USER_AUTHENTICATION
  82905. if( pParse->nTableLock>0 && db->init.busy==0 ){
  82906. sqlite3UserAuthInit(db);
  82907. if( db->auth.authLevel<UAUTH_User ){
  82908. pParse->rc = SQLITE_AUTH_USER;
  82909. sqlite3ErrorMsg(pParse, "user not authenticated");
  82910. return;
  82911. }
  82912. }
  82913. #endif
  82914. /* The cookie mask contains one bit for each database file open.
  82915. ** (Bit 0 is for main, bit 1 is for temp, and so forth.) Bits are
  82916. ** set for each database that is used. Generate code to start a
  82917. ** transaction on each used database and to verify the schema cookie
  82918. ** on each used database.
  82919. */
  82920. if( db->mallocFailed==0
  82921. && (DbMaskNonZero(pParse->cookieMask) || pParse->pConstExpr)
  82922. ){
  82923. int iDb, i;
  82924. assert( sqlite3VdbeGetOp(v, 0)->opcode==OP_Init );
  82925. sqlite3VdbeJumpHere(v, 0);
  82926. for(iDb=0; iDb<db->nDb; iDb++){
  82927. if( DbMaskTest(pParse->cookieMask, iDb)==0 ) continue;
  82928. sqlite3VdbeUsesBtree(v, iDb);
  82929. sqlite3VdbeAddOp4Int(v,
  82930. OP_Transaction, /* Opcode */
  82931. iDb, /* P1 */
  82932. DbMaskTest(pParse->writeMask,iDb), /* P2 */
  82933. pParse->cookieValue[iDb], /* P3 */
  82934. db->aDb[iDb].pSchema->iGeneration /* P4 */
  82935. );
  82936. if( db->init.busy==0 ) sqlite3VdbeChangeP5(v, 1);
  82937. }
  82938. #ifndef SQLITE_OMIT_VIRTUALTABLE
  82939. for(i=0; i<pParse->nVtabLock; i++){
  82940. char *vtab = (char *)sqlite3GetVTable(db, pParse->apVtabLock[i]);
  82941. sqlite3VdbeAddOp4(v, OP_VBegin, 0, 0, 0, vtab, P4_VTAB);
  82942. }
  82943. pParse->nVtabLock = 0;
  82944. #endif
  82945. /* Once all the cookies have been verified and transactions opened,
  82946. ** obtain the required table-locks. This is a no-op unless the
  82947. ** shared-cache feature is enabled.
  82948. */
  82949. codeTableLocks(pParse);
  82950. /* Initialize any AUTOINCREMENT data structures required.
  82951. */
  82952. sqlite3AutoincrementBegin(pParse);
  82953. /* Code constant expressions that where factored out of inner loops */
  82954. if( pParse->pConstExpr ){
  82955. ExprList *pEL = pParse->pConstExpr;
  82956. pParse->okConstFactor = 0;
  82957. for(i=0; i<pEL->nExpr; i++){
  82958. sqlite3ExprCode(pParse, pEL->a[i].pExpr, pEL->a[i].u.iConstExprReg);
  82959. }
  82960. }
  82961. /* Finally, jump back to the beginning of the executable code. */
  82962. sqlite3VdbeAddOp2(v, OP_Goto, 0, 1);
  82963. }
  82964. }
  82965. /* Get the VDBE program ready for execution
  82966. */
  82967. if( v && ALWAYS(pParse->nErr==0) && !db->mallocFailed ){
  82968. assert( pParse->iCacheLevel==0 ); /* Disables and re-enables match */
  82969. /* A minimum of one cursor is required if autoincrement is used
  82970. * See ticket [a696379c1f08866] */
  82971. if( pParse->pAinc!=0 && pParse->nTab==0 ) pParse->nTab = 1;
  82972. sqlite3VdbeMakeReady(v, pParse);
  82973. pParse->rc = SQLITE_DONE;
  82974. pParse->colNamesSet = 0;
  82975. }else{
  82976. pParse->rc = SQLITE_ERROR;
  82977. }
  82978. pParse->nTab = 0;
  82979. pParse->nMem = 0;
  82980. pParse->nSet = 0;
  82981. pParse->nVar = 0;
  82982. DbMaskZero(pParse->cookieMask);
  82983. }
  82984. /*
  82985. ** Run the parser and code generator recursively in order to generate
  82986. ** code for the SQL statement given onto the end of the pParse context
  82987. ** currently under construction. When the parser is run recursively
  82988. ** this way, the final OP_Halt is not appended and other initialization
  82989. ** and finalization steps are omitted because those are handling by the
  82990. ** outermost parser.
  82991. **
  82992. ** Not everything is nestable. This facility is designed to permit
  82993. ** INSERT, UPDATE, and DELETE operations against SQLITE_MASTER. Use
  82994. ** care if you decide to try to use this routine for some other purposes.
  82995. */
  82996. SQLITE_PRIVATE void sqlite3NestedParse(Parse *pParse, const char *zFormat, ...){
  82997. va_list ap;
  82998. char *zSql;
  82999. char *zErrMsg = 0;
  83000. sqlite3 *db = pParse->db;
  83001. # define SAVE_SZ (sizeof(Parse) - offsetof(Parse,nVar))
  83002. char saveBuf[SAVE_SZ];
  83003. if( pParse->nErr ) return;
  83004. assert( pParse->nested<10 ); /* Nesting should only be of limited depth */
  83005. va_start(ap, zFormat);
  83006. zSql = sqlite3VMPrintf(db, zFormat, ap);
  83007. va_end(ap);
  83008. if( zSql==0 ){
  83009. return; /* A malloc must have failed */
  83010. }
  83011. pParse->nested++;
  83012. memcpy(saveBuf, &pParse->nVar, SAVE_SZ);
  83013. memset(&pParse->nVar, 0, SAVE_SZ);
  83014. sqlite3RunParser(pParse, zSql, &zErrMsg);
  83015. sqlite3DbFree(db, zErrMsg);
  83016. sqlite3DbFree(db, zSql);
  83017. memcpy(&pParse->nVar, saveBuf, SAVE_SZ);
  83018. pParse->nested--;
  83019. }
  83020. #if SQLITE_USER_AUTHENTICATION
  83021. /*
  83022. ** Return TRUE if zTable is the name of the system table that stores the
  83023. ** list of users and their access credentials.
  83024. */
  83025. SQLITE_PRIVATE int sqlite3UserAuthTable(const char *zTable){
  83026. return sqlite3_stricmp(zTable, "sqlite_user")==0;
  83027. }
  83028. #endif
  83029. /*
  83030. ** Locate the in-memory structure that describes a particular database
  83031. ** table given the name of that table and (optionally) the name of the
  83032. ** database containing the table. Return NULL if not found.
  83033. **
  83034. ** If zDatabase is 0, all databases are searched for the table and the
  83035. ** first matching table is returned. (No checking for duplicate table
  83036. ** names is done.) The search order is TEMP first, then MAIN, then any
  83037. ** auxiliary databases added using the ATTACH command.
  83038. **
  83039. ** See also sqlite3LocateTable().
  83040. */
  83041. SQLITE_PRIVATE Table *sqlite3FindTable(sqlite3 *db, const char *zName, const char *zDatabase){
  83042. Table *p = 0;
  83043. int i;
  83044. assert( zName!=0 );
  83045. /* All mutexes are required for schema access. Make sure we hold them. */
  83046. assert( zDatabase!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  83047. #if SQLITE_USER_AUTHENTICATION
  83048. /* Only the admin user is allowed to know that the sqlite_user table
  83049. ** exists */
  83050. if( db->auth.authLevel<UAUTH_Admin && sqlite3UserAuthTable(zName)!=0 ){
  83051. return 0;
  83052. }
  83053. #endif
  83054. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  83055. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  83056. if( zDatabase!=0 && sqlite3StrICmp(zDatabase, db->aDb[j].zName) ) continue;
  83057. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  83058. p = sqlite3HashFind(&db->aDb[j].pSchema->tblHash, zName);
  83059. if( p ) break;
  83060. }
  83061. return p;
  83062. }
  83063. /*
  83064. ** Locate the in-memory structure that describes a particular database
  83065. ** table given the name of that table and (optionally) the name of the
  83066. ** database containing the table. Return NULL if not found. Also leave an
  83067. ** error message in pParse->zErrMsg.
  83068. **
  83069. ** The difference between this routine and sqlite3FindTable() is that this
  83070. ** routine leaves an error message in pParse->zErrMsg where
  83071. ** sqlite3FindTable() does not.
  83072. */
  83073. SQLITE_PRIVATE Table *sqlite3LocateTable(
  83074. Parse *pParse, /* context in which to report errors */
  83075. int isView, /* True if looking for a VIEW rather than a TABLE */
  83076. const char *zName, /* Name of the table we are looking for */
  83077. const char *zDbase /* Name of the database. Might be NULL */
  83078. ){
  83079. Table *p;
  83080. /* Read the database schema. If an error occurs, leave an error message
  83081. ** and code in pParse and return NULL. */
  83082. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  83083. return 0;
  83084. }
  83085. p = sqlite3FindTable(pParse->db, zName, zDbase);
  83086. if( p==0 ){
  83087. const char *zMsg = isView ? "no such view" : "no such table";
  83088. if( zDbase ){
  83089. sqlite3ErrorMsg(pParse, "%s: %s.%s", zMsg, zDbase, zName);
  83090. }else{
  83091. sqlite3ErrorMsg(pParse, "%s: %s", zMsg, zName);
  83092. }
  83093. pParse->checkSchema = 1;
  83094. }
  83095. #if SQLITE_USER_AUTHENICATION
  83096. else if( pParse->db->auth.authLevel<UAUTH_User ){
  83097. sqlite3ErrorMsg(pParse, "user not authenticated");
  83098. p = 0;
  83099. }
  83100. #endif
  83101. return p;
  83102. }
  83103. /*
  83104. ** Locate the table identified by *p.
  83105. **
  83106. ** This is a wrapper around sqlite3LocateTable(). The difference between
  83107. ** sqlite3LocateTable() and this function is that this function restricts
  83108. ** the search to schema (p->pSchema) if it is not NULL. p->pSchema may be
  83109. ** non-NULL if it is part of a view or trigger program definition. See
  83110. ** sqlite3FixSrcList() for details.
  83111. */
  83112. SQLITE_PRIVATE Table *sqlite3LocateTableItem(
  83113. Parse *pParse,
  83114. int isView,
  83115. struct SrcList_item *p
  83116. ){
  83117. const char *zDb;
  83118. assert( p->pSchema==0 || p->zDatabase==0 );
  83119. if( p->pSchema ){
  83120. int iDb = sqlite3SchemaToIndex(pParse->db, p->pSchema);
  83121. zDb = pParse->db->aDb[iDb].zName;
  83122. }else{
  83123. zDb = p->zDatabase;
  83124. }
  83125. return sqlite3LocateTable(pParse, isView, p->zName, zDb);
  83126. }
  83127. /*
  83128. ** Locate the in-memory structure that describes
  83129. ** a particular index given the name of that index
  83130. ** and the name of the database that contains the index.
  83131. ** Return NULL if not found.
  83132. **
  83133. ** If zDatabase is 0, all databases are searched for the
  83134. ** table and the first matching index is returned. (No checking
  83135. ** for duplicate index names is done.) The search order is
  83136. ** TEMP first, then MAIN, then any auxiliary databases added
  83137. ** using the ATTACH command.
  83138. */
  83139. SQLITE_PRIVATE Index *sqlite3FindIndex(sqlite3 *db, const char *zName, const char *zDb){
  83140. Index *p = 0;
  83141. int i;
  83142. /* All mutexes are required for schema access. Make sure we hold them. */
  83143. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  83144. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  83145. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  83146. Schema *pSchema = db->aDb[j].pSchema;
  83147. assert( pSchema );
  83148. if( zDb && sqlite3StrICmp(zDb, db->aDb[j].zName) ) continue;
  83149. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  83150. p = sqlite3HashFind(&pSchema->idxHash, zName);
  83151. if( p ) break;
  83152. }
  83153. return p;
  83154. }
  83155. /*
  83156. ** Reclaim the memory used by an index
  83157. */
  83158. static void freeIndex(sqlite3 *db, Index *p){
  83159. #ifndef SQLITE_OMIT_ANALYZE
  83160. sqlite3DeleteIndexSamples(db, p);
  83161. #endif
  83162. if( db==0 || db->pnBytesFreed==0 ) sqlite3KeyInfoUnref(p->pKeyInfo);
  83163. sqlite3ExprDelete(db, p->pPartIdxWhere);
  83164. sqlite3DbFree(db, p->zColAff);
  83165. if( p->isResized ) sqlite3DbFree(db, p->azColl);
  83166. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  83167. sqlite3_free(p->aiRowEst);
  83168. #endif
  83169. sqlite3DbFree(db, p);
  83170. }
  83171. /*
  83172. ** For the index called zIdxName which is found in the database iDb,
  83173. ** unlike that index from its Table then remove the index from
  83174. ** the index hash table and free all memory structures associated
  83175. ** with the index.
  83176. */
  83177. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteIndex(sqlite3 *db, int iDb, const char *zIdxName){
  83178. Index *pIndex;
  83179. Hash *pHash;
  83180. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83181. pHash = &db->aDb[iDb].pSchema->idxHash;
  83182. pIndex = sqlite3HashInsert(pHash, zIdxName, 0);
  83183. if( ALWAYS(pIndex) ){
  83184. if( pIndex->pTable->pIndex==pIndex ){
  83185. pIndex->pTable->pIndex = pIndex->pNext;
  83186. }else{
  83187. Index *p;
  83188. /* Justification of ALWAYS(); The index must be on the list of
  83189. ** indices. */
  83190. p = pIndex->pTable->pIndex;
  83191. while( ALWAYS(p) && p->pNext!=pIndex ){ p = p->pNext; }
  83192. if( ALWAYS(p && p->pNext==pIndex) ){
  83193. p->pNext = pIndex->pNext;
  83194. }
  83195. }
  83196. freeIndex(db, pIndex);
  83197. }
  83198. db->flags |= SQLITE_InternChanges;
  83199. }
  83200. /*
  83201. ** Look through the list of open database files in db->aDb[] and if
  83202. ** any have been closed, remove them from the list. Reallocate the
  83203. ** db->aDb[] structure to a smaller size, if possible.
  83204. **
  83205. ** Entry 0 (the "main" database) and entry 1 (the "temp" database)
  83206. ** are never candidates for being collapsed.
  83207. */
  83208. SQLITE_PRIVATE void sqlite3CollapseDatabaseArray(sqlite3 *db){
  83209. int i, j;
  83210. for(i=j=2; i<db->nDb; i++){
  83211. struct Db *pDb = &db->aDb[i];
  83212. if( pDb->pBt==0 ){
  83213. sqlite3DbFree(db, pDb->zName);
  83214. pDb->zName = 0;
  83215. continue;
  83216. }
  83217. if( j<i ){
  83218. db->aDb[j] = db->aDb[i];
  83219. }
  83220. j++;
  83221. }
  83222. memset(&db->aDb[j], 0, (db->nDb-j)*sizeof(db->aDb[j]));
  83223. db->nDb = j;
  83224. if( db->nDb<=2 && db->aDb!=db->aDbStatic ){
  83225. memcpy(db->aDbStatic, db->aDb, 2*sizeof(db->aDb[0]));
  83226. sqlite3DbFree(db, db->aDb);
  83227. db->aDb = db->aDbStatic;
  83228. }
  83229. }
  83230. /*
  83231. ** Reset the schema for the database at index iDb. Also reset the
  83232. ** TEMP schema.
  83233. */
  83234. SQLITE_PRIVATE void sqlite3ResetOneSchema(sqlite3 *db, int iDb){
  83235. Db *pDb;
  83236. assert( iDb<db->nDb );
  83237. /* Case 1: Reset the single schema identified by iDb */
  83238. pDb = &db->aDb[iDb];
  83239. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83240. assert( pDb->pSchema!=0 );
  83241. sqlite3SchemaClear(pDb->pSchema);
  83242. /* If any database other than TEMP is reset, then also reset TEMP
  83243. ** since TEMP might be holding triggers that reference tables in the
  83244. ** other database.
  83245. */
  83246. if( iDb!=1 ){
  83247. pDb = &db->aDb[1];
  83248. assert( pDb->pSchema!=0 );
  83249. sqlite3SchemaClear(pDb->pSchema);
  83250. }
  83251. return;
  83252. }
  83253. /*
  83254. ** Erase all schema information from all attached databases (including
  83255. ** "main" and "temp") for a single database connection.
  83256. */
  83257. SQLITE_PRIVATE void sqlite3ResetAllSchemasOfConnection(sqlite3 *db){
  83258. int i;
  83259. sqlite3BtreeEnterAll(db);
  83260. for(i=0; i<db->nDb; i++){
  83261. Db *pDb = &db->aDb[i];
  83262. if( pDb->pSchema ){
  83263. sqlite3SchemaClear(pDb->pSchema);
  83264. }
  83265. }
  83266. db->flags &= ~SQLITE_InternChanges;
  83267. sqlite3VtabUnlockList(db);
  83268. sqlite3BtreeLeaveAll(db);
  83269. sqlite3CollapseDatabaseArray(db);
  83270. }
  83271. /*
  83272. ** This routine is called when a commit occurs.
  83273. */
  83274. SQLITE_PRIVATE void sqlite3CommitInternalChanges(sqlite3 *db){
  83275. db->flags &= ~SQLITE_InternChanges;
  83276. }
  83277. /*
  83278. ** Delete memory allocated for the column names of a table or view (the
  83279. ** Table.aCol[] array).
  83280. */
  83281. static void sqliteDeleteColumnNames(sqlite3 *db, Table *pTable){
  83282. int i;
  83283. Column *pCol;
  83284. assert( pTable!=0 );
  83285. if( (pCol = pTable->aCol)!=0 ){
  83286. for(i=0; i<pTable->nCol; i++, pCol++){
  83287. sqlite3DbFree(db, pCol->zName);
  83288. sqlite3ExprDelete(db, pCol->pDflt);
  83289. sqlite3DbFree(db, pCol->zDflt);
  83290. sqlite3DbFree(db, pCol->zType);
  83291. sqlite3DbFree(db, pCol->zColl);
  83292. }
  83293. sqlite3DbFree(db, pTable->aCol);
  83294. }
  83295. }
  83296. /*
  83297. ** Remove the memory data structures associated with the given
  83298. ** Table. No changes are made to disk by this routine.
  83299. **
  83300. ** This routine just deletes the data structure. It does not unlink
  83301. ** the table data structure from the hash table. But it does destroy
  83302. ** memory structures of the indices and foreign keys associated with
  83303. ** the table.
  83304. **
  83305. ** The db parameter is optional. It is needed if the Table object
  83306. ** contains lookaside memory. (Table objects in the schema do not use
  83307. ** lookaside memory, but some ephemeral Table objects do.) Or the
  83308. ** db parameter can be used with db->pnBytesFreed to measure the memory
  83309. ** used by the Table object.
  83310. */
  83311. SQLITE_PRIVATE void sqlite3DeleteTable(sqlite3 *db, Table *pTable){
  83312. Index *pIndex, *pNext;
  83313. TESTONLY( int nLookaside; ) /* Used to verify lookaside not used for schema */
  83314. assert( !pTable || pTable->nRef>0 );
  83315. /* Do not delete the table until the reference count reaches zero. */
  83316. if( !pTable ) return;
  83317. if( ((!db || db->pnBytesFreed==0) && (--pTable->nRef)>0) ) return;
  83318. /* Record the number of outstanding lookaside allocations in schema Tables
  83319. ** prior to doing any free() operations. Since schema Tables do not use
  83320. ** lookaside, this number should not change. */
  83321. TESTONLY( nLookaside = (db && (pTable->tabFlags & TF_Ephemeral)==0) ?
  83322. db->lookaside.nOut : 0 );
  83323. /* Delete all indices associated with this table. */
  83324. for(pIndex = pTable->pIndex; pIndex; pIndex=pNext){
  83325. pNext = pIndex->pNext;
  83326. assert( pIndex->pSchema==pTable->pSchema );
  83327. if( !db || db->pnBytesFreed==0 ){
  83328. char *zName = pIndex->zName;
  83329. TESTONLY ( Index *pOld = ) sqlite3HashInsert(
  83330. &pIndex->pSchema->idxHash, zName, 0
  83331. );
  83332. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  83333. assert( pOld==pIndex || pOld==0 );
  83334. }
  83335. freeIndex(db, pIndex);
  83336. }
  83337. /* Delete any foreign keys attached to this table. */
  83338. sqlite3FkDelete(db, pTable);
  83339. /* Delete the Table structure itself.
  83340. */
  83341. sqliteDeleteColumnNames(db, pTable);
  83342. sqlite3DbFree(db, pTable->zName);
  83343. sqlite3DbFree(db, pTable->zColAff);
  83344. sqlite3SelectDelete(db, pTable->pSelect);
  83345. #ifndef SQLITE_OMIT_CHECK
  83346. sqlite3ExprListDelete(db, pTable->pCheck);
  83347. #endif
  83348. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83349. sqlite3VtabClear(db, pTable);
  83350. #endif
  83351. sqlite3DbFree(db, pTable);
  83352. /* Verify that no lookaside memory was used by schema tables */
  83353. assert( nLookaside==0 || nLookaside==db->lookaside.nOut );
  83354. }
  83355. /*
  83356. ** Unlink the given table from the hash tables and the delete the
  83357. ** table structure with all its indices and foreign keys.
  83358. */
  83359. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTable(sqlite3 *db, int iDb, const char *zTabName){
  83360. Table *p;
  83361. Db *pDb;
  83362. assert( db!=0 );
  83363. assert( iDb>=0 && iDb<db->nDb );
  83364. assert( zTabName );
  83365. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83366. testcase( zTabName[0]==0 ); /* Zero-length table names are allowed */
  83367. pDb = &db->aDb[iDb];
  83368. p = sqlite3HashInsert(&pDb->pSchema->tblHash, zTabName, 0);
  83369. sqlite3DeleteTable(db, p);
  83370. db->flags |= SQLITE_InternChanges;
  83371. }
  83372. /*
  83373. ** Given a token, return a string that consists of the text of that
  83374. ** token. Space to hold the returned string
  83375. ** is obtained from sqliteMalloc() and must be freed by the calling
  83376. ** function.
  83377. **
  83378. ** Any quotation marks (ex: "name", 'name', [name], or `name`) that
  83379. ** surround the body of the token are removed.
  83380. **
  83381. ** Tokens are often just pointers into the original SQL text and so
  83382. ** are not \000 terminated and are not persistent. The returned string
  83383. ** is \000 terminated and is persistent.
  83384. */
  83385. SQLITE_PRIVATE char *sqlite3NameFromToken(sqlite3 *db, Token *pName){
  83386. char *zName;
  83387. if( pName ){
  83388. zName = sqlite3DbStrNDup(db, (char*)pName->z, pName->n);
  83389. sqlite3Dequote(zName);
  83390. }else{
  83391. zName = 0;
  83392. }
  83393. return zName;
  83394. }
  83395. /*
  83396. ** Open the sqlite_master table stored in database number iDb for
  83397. ** writing. The table is opened using cursor 0.
  83398. */
  83399. SQLITE_PRIVATE void sqlite3OpenMasterTable(Parse *p, int iDb){
  83400. Vdbe *v = sqlite3GetVdbe(p);
  83401. sqlite3TableLock(p, iDb, MASTER_ROOT, 1, SCHEMA_TABLE(iDb));
  83402. sqlite3VdbeAddOp4Int(v, OP_OpenWrite, 0, MASTER_ROOT, iDb, 5);
  83403. if( p->nTab==0 ){
  83404. p->nTab = 1;
  83405. }
  83406. }
  83407. /*
  83408. ** Parameter zName points to a nul-terminated buffer containing the name
  83409. ** of a database ("main", "temp" or the name of an attached db). This
  83410. ** function returns the index of the named database in db->aDb[], or
  83411. ** -1 if the named db cannot be found.
  83412. */
  83413. SQLITE_PRIVATE int sqlite3FindDbName(sqlite3 *db, const char *zName){
  83414. int i = -1; /* Database number */
  83415. if( zName ){
  83416. Db *pDb;
  83417. int n = sqlite3Strlen30(zName);
  83418. for(i=(db->nDb-1), pDb=&db->aDb[i]; i>=0; i--, pDb--){
  83419. if( (!OMIT_TEMPDB || i!=1 ) && n==sqlite3Strlen30(pDb->zName) &&
  83420. 0==sqlite3StrICmp(pDb->zName, zName) ){
  83421. break;
  83422. }
  83423. }
  83424. }
  83425. return i;
  83426. }
  83427. /*
  83428. ** The token *pName contains the name of a database (either "main" or
  83429. ** "temp" or the name of an attached db). This routine returns the
  83430. ** index of the named database in db->aDb[], or -1 if the named db
  83431. ** does not exist.
  83432. */
  83433. SQLITE_PRIVATE int sqlite3FindDb(sqlite3 *db, Token *pName){
  83434. int i; /* Database number */
  83435. char *zName; /* Name we are searching for */
  83436. zName = sqlite3NameFromToken(db, pName);
  83437. i = sqlite3FindDbName(db, zName);
  83438. sqlite3DbFree(db, zName);
  83439. return i;
  83440. }
  83441. /* The table or view or trigger name is passed to this routine via tokens
  83442. ** pName1 and pName2. If the table name was fully qualified, for example:
  83443. **
  83444. ** CREATE TABLE xxx.yyy (...);
  83445. **
  83446. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  83447. ** the table name is not fully qualified, i.e.:
  83448. **
  83449. ** CREATE TABLE yyy(...);
  83450. **
  83451. ** Then pName1 is set to "yyy" and pName2 is "".
  83452. **
  83453. ** This routine sets the *ppUnqual pointer to point at the token (pName1 or
  83454. ** pName2) that stores the unqualified table name. The index of the
  83455. ** database "xxx" is returned.
  83456. */
  83457. SQLITE_PRIVATE int sqlite3TwoPartName(
  83458. Parse *pParse, /* Parsing and code generating context */
  83459. Token *pName1, /* The "xxx" in the name "xxx.yyy" or "xxx" */
  83460. Token *pName2, /* The "yyy" in the name "xxx.yyy" */
  83461. Token **pUnqual /* Write the unqualified object name here */
  83462. ){
  83463. int iDb; /* Database holding the object */
  83464. sqlite3 *db = pParse->db;
  83465. if( ALWAYS(pName2!=0) && pName2->n>0 ){
  83466. if( db->init.busy ) {
  83467. sqlite3ErrorMsg(pParse, "corrupt database");
  83468. pParse->nErr++;
  83469. return -1;
  83470. }
  83471. *pUnqual = pName2;
  83472. iDb = sqlite3FindDb(db, pName1);
  83473. if( iDb<0 ){
  83474. sqlite3ErrorMsg(pParse, "unknown database %T", pName1);
  83475. pParse->nErr++;
  83476. return -1;
  83477. }
  83478. }else{
  83479. assert( db->init.iDb==0 || db->init.busy );
  83480. iDb = db->init.iDb;
  83481. *pUnqual = pName1;
  83482. }
  83483. return iDb;
  83484. }
  83485. /*
  83486. ** This routine is used to check if the UTF-8 string zName is a legal
  83487. ** unqualified name for a new schema object (table, index, view or
  83488. ** trigger). All names are legal except those that begin with the string
  83489. ** "sqlite_" (in upper, lower or mixed case). This portion of the namespace
  83490. ** is reserved for internal use.
  83491. */
  83492. SQLITE_PRIVATE int sqlite3CheckObjectName(Parse *pParse, const char *zName){
  83493. if( !pParse->db->init.busy && pParse->nested==0
  83494. && (pParse->db->flags & SQLITE_WriteSchema)==0
  83495. && 0==sqlite3StrNICmp(zName, "sqlite_", 7) ){
  83496. sqlite3ErrorMsg(pParse, "object name reserved for internal use: %s", zName);
  83497. return SQLITE_ERROR;
  83498. }
  83499. return SQLITE_OK;
  83500. }
  83501. /*
  83502. ** Return the PRIMARY KEY index of a table
  83503. */
  83504. SQLITE_PRIVATE Index *sqlite3PrimaryKeyIndex(Table *pTab){
  83505. Index *p;
  83506. for(p=pTab->pIndex; p && !IsPrimaryKeyIndex(p); p=p->pNext){}
  83507. return p;
  83508. }
  83509. /*
  83510. ** Return the column of index pIdx that corresponds to table
  83511. ** column iCol. Return -1 if not found.
  83512. */
  83513. SQLITE_PRIVATE i16 sqlite3ColumnOfIndex(Index *pIdx, i16 iCol){
  83514. int i;
  83515. for(i=0; i<pIdx->nColumn; i++){
  83516. if( iCol==pIdx->aiColumn[i] ) return i;
  83517. }
  83518. return -1;
  83519. }
  83520. /*
  83521. ** Begin constructing a new table representation in memory. This is
  83522. ** the first of several action routines that get called in response
  83523. ** to a CREATE TABLE statement. In particular, this routine is called
  83524. ** after seeing tokens "CREATE" and "TABLE" and the table name. The isTemp
  83525. ** flag is true if the table should be stored in the auxiliary database
  83526. ** file instead of in the main database file. This is normally the case
  83527. ** when the "TEMP" or "TEMPORARY" keyword occurs in between
  83528. ** CREATE and TABLE.
  83529. **
  83530. ** The new table record is initialized and put in pParse->pNewTable.
  83531. ** As more of the CREATE TABLE statement is parsed, additional action
  83532. ** routines will be called to add more information to this record.
  83533. ** At the end of the CREATE TABLE statement, the sqlite3EndTable() routine
  83534. ** is called to complete the construction of the new table record.
  83535. */
  83536. SQLITE_PRIVATE void sqlite3StartTable(
  83537. Parse *pParse, /* Parser context */
  83538. Token *pName1, /* First part of the name of the table or view */
  83539. Token *pName2, /* Second part of the name of the table or view */
  83540. int isTemp, /* True if this is a TEMP table */
  83541. int isView, /* True if this is a VIEW */
  83542. int isVirtual, /* True if this is a VIRTUAL table */
  83543. int noErr /* Do nothing if table already exists */
  83544. ){
  83545. Table *pTable;
  83546. char *zName = 0; /* The name of the new table */
  83547. sqlite3 *db = pParse->db;
  83548. Vdbe *v;
  83549. int iDb; /* Database number to create the table in */
  83550. Token *pName; /* Unqualified name of the table to create */
  83551. /* The table or view name to create is passed to this routine via tokens
  83552. ** pName1 and pName2. If the table name was fully qualified, for example:
  83553. **
  83554. ** CREATE TABLE xxx.yyy (...);
  83555. **
  83556. ** Then pName1 is set to "xxx" and pName2 "yyy". On the other hand if
  83557. ** the table name is not fully qualified, i.e.:
  83558. **
  83559. ** CREATE TABLE yyy(...);
  83560. **
  83561. ** Then pName1 is set to "yyy" and pName2 is "".
  83562. **
  83563. ** The call below sets the pName pointer to point at the token (pName1 or
  83564. ** pName2) that stores the unqualified table name. The variable iDb is
  83565. ** set to the index of the database that the table or view is to be
  83566. ** created in.
  83567. */
  83568. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  83569. if( iDb<0 ) return;
  83570. if( !OMIT_TEMPDB && isTemp && pName2->n>0 && iDb!=1 ){
  83571. /* If creating a temp table, the name may not be qualified. Unless
  83572. ** the database name is "temp" anyway. */
  83573. sqlite3ErrorMsg(pParse, "temporary table name must be unqualified");
  83574. return;
  83575. }
  83576. if( !OMIT_TEMPDB && isTemp ) iDb = 1;
  83577. pParse->sNameToken = *pName;
  83578. zName = sqlite3NameFromToken(db, pName);
  83579. if( zName==0 ) return;
  83580. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  83581. goto begin_table_error;
  83582. }
  83583. if( db->init.iDb==1 ) isTemp = 1;
  83584. #ifndef SQLITE_OMIT_AUTHORIZATION
  83585. assert( (isTemp & 1)==isTemp );
  83586. {
  83587. int code;
  83588. char *zDb = db->aDb[iDb].zName;
  83589. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(isTemp), 0, zDb) ){
  83590. goto begin_table_error;
  83591. }
  83592. if( isView ){
  83593. if( !OMIT_TEMPDB && isTemp ){
  83594. code = SQLITE_CREATE_TEMP_VIEW;
  83595. }else{
  83596. code = SQLITE_CREATE_VIEW;
  83597. }
  83598. }else{
  83599. if( !OMIT_TEMPDB && isTemp ){
  83600. code = SQLITE_CREATE_TEMP_TABLE;
  83601. }else{
  83602. code = SQLITE_CREATE_TABLE;
  83603. }
  83604. }
  83605. if( !isVirtual && sqlite3AuthCheck(pParse, code, zName, 0, zDb) ){
  83606. goto begin_table_error;
  83607. }
  83608. }
  83609. #endif
  83610. /* Make sure the new table name does not collide with an existing
  83611. ** index or table name in the same database. Issue an error message if
  83612. ** it does. The exception is if the statement being parsed was passed
  83613. ** to an sqlite3_declare_vtab() call. In that case only the column names
  83614. ** and types will be used, so there is no need to test for namespace
  83615. ** collisions.
  83616. */
  83617. if( !IN_DECLARE_VTAB ){
  83618. char *zDb = db->aDb[iDb].zName;
  83619. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  83620. goto begin_table_error;
  83621. }
  83622. pTable = sqlite3FindTable(db, zName, zDb);
  83623. if( pTable ){
  83624. if( !noErr ){
  83625. sqlite3ErrorMsg(pParse, "table %T already exists", pName);
  83626. }else{
  83627. assert( !db->init.busy );
  83628. sqlite3CodeVerifySchema(pParse, iDb);
  83629. }
  83630. goto begin_table_error;
  83631. }
  83632. if( sqlite3FindIndex(db, zName, zDb)!=0 ){
  83633. sqlite3ErrorMsg(pParse, "there is already an index named %s", zName);
  83634. goto begin_table_error;
  83635. }
  83636. }
  83637. pTable = sqlite3DbMallocZero(db, sizeof(Table));
  83638. if( pTable==0 ){
  83639. db->mallocFailed = 1;
  83640. pParse->rc = SQLITE_NOMEM;
  83641. pParse->nErr++;
  83642. goto begin_table_error;
  83643. }
  83644. pTable->zName = zName;
  83645. pTable->iPKey = -1;
  83646. pTable->pSchema = db->aDb[iDb].pSchema;
  83647. pTable->nRef = 1;
  83648. pTable->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  83649. assert( pParse->pNewTable==0 );
  83650. pParse->pNewTable = pTable;
  83651. /* If this is the magic sqlite_sequence table used by autoincrement,
  83652. ** then record a pointer to this table in the main database structure
  83653. ** so that INSERT can find the table easily.
  83654. */
  83655. #ifndef SQLITE_OMIT_AUTOINCREMENT
  83656. if( !pParse->nested && strcmp(zName, "sqlite_sequence")==0 ){
  83657. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  83658. pTable->pSchema->pSeqTab = pTable;
  83659. }
  83660. #endif
  83661. /* Begin generating the code that will insert the table record into
  83662. ** the SQLITE_MASTER table. Note in particular that we must go ahead
  83663. ** and allocate the record number for the table entry now. Before any
  83664. ** PRIMARY KEY or UNIQUE keywords are parsed. Those keywords will cause
  83665. ** indices to be created and the table record must come before the
  83666. ** indices. Hence, the record number for the table must be allocated
  83667. ** now.
  83668. */
  83669. if( !db->init.busy && (v = sqlite3GetVdbe(pParse))!=0 ){
  83670. int j1;
  83671. int fileFormat;
  83672. int reg1, reg2, reg3;
  83673. sqlite3BeginWriteOperation(pParse, 0, iDb);
  83674. #ifndef SQLITE_OMIT_VIRTUALTABLE
  83675. if( isVirtual ){
  83676. sqlite3VdbeAddOp0(v, OP_VBegin);
  83677. }
  83678. #endif
  83679. /* If the file format and encoding in the database have not been set,
  83680. ** set them now.
  83681. */
  83682. reg1 = pParse->regRowid = ++pParse->nMem;
  83683. reg2 = pParse->regRoot = ++pParse->nMem;
  83684. reg3 = ++pParse->nMem;
  83685. sqlite3VdbeAddOp3(v, OP_ReadCookie, iDb, reg3, BTREE_FILE_FORMAT);
  83686. sqlite3VdbeUsesBtree(v, iDb);
  83687. j1 = sqlite3VdbeAddOp1(v, OP_If, reg3); VdbeCoverage(v);
  83688. fileFormat = (db->flags & SQLITE_LegacyFileFmt)!=0 ?
  83689. 1 : SQLITE_MAX_FILE_FORMAT;
  83690. sqlite3VdbeAddOp2(v, OP_Integer, fileFormat, reg3);
  83691. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_FILE_FORMAT, reg3);
  83692. sqlite3VdbeAddOp2(v, OP_Integer, ENC(db), reg3);
  83693. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_TEXT_ENCODING, reg3);
  83694. sqlite3VdbeJumpHere(v, j1);
  83695. /* This just creates a place-holder record in the sqlite_master table.
  83696. ** The record created does not contain anything yet. It will be replaced
  83697. ** by the real entry in code generated at sqlite3EndTable().
  83698. **
  83699. ** The rowid for the new entry is left in register pParse->regRowid.
  83700. ** The root page number of the new table is left in reg pParse->regRoot.
  83701. ** The rowid and root page number values are needed by the code that
  83702. ** sqlite3EndTable will generate.
  83703. */
  83704. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  83705. if( isView || isVirtual ){
  83706. sqlite3VdbeAddOp2(v, OP_Integer, 0, reg2);
  83707. }else
  83708. #endif
  83709. {
  83710. pParse->addrCrTab = sqlite3VdbeAddOp2(v, OP_CreateTable, iDb, reg2);
  83711. }
  83712. sqlite3OpenMasterTable(pParse, iDb);
  83713. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, reg1);
  83714. sqlite3VdbeAddOp2(v, OP_Null, 0, reg3);
  83715. sqlite3VdbeAddOp3(v, OP_Insert, 0, reg3, reg1);
  83716. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  83717. sqlite3VdbeAddOp0(v, OP_Close);
  83718. }
  83719. /* Normal (non-error) return. */
  83720. return;
  83721. /* If an error occurs, we jump here */
  83722. begin_table_error:
  83723. sqlite3DbFree(db, zName);
  83724. return;
  83725. }
  83726. /*
  83727. ** This macro is used to compare two strings in a case-insensitive manner.
  83728. ** It is slightly faster than calling sqlite3StrICmp() directly, but
  83729. ** produces larger code.
  83730. **
  83731. ** WARNING: This macro is not compatible with the strcmp() family. It
  83732. ** returns true if the two strings are equal, otherwise false.
  83733. */
  83734. #define STRICMP(x, y) (\
  83735. sqlite3UpperToLower[*(unsigned char *)(x)]== \
  83736. sqlite3UpperToLower[*(unsigned char *)(y)] \
  83737. && sqlite3StrICmp((x)+1,(y)+1)==0 )
  83738. /*
  83739. ** Add a new column to the table currently being constructed.
  83740. **
  83741. ** The parser calls this routine once for each column declaration
  83742. ** in a CREATE TABLE statement. sqlite3StartTable() gets called
  83743. ** first to get things going. Then this routine is called for each
  83744. ** column.
  83745. */
  83746. SQLITE_PRIVATE void sqlite3AddColumn(Parse *pParse, Token *pName){
  83747. Table *p;
  83748. int i;
  83749. char *z;
  83750. Column *pCol;
  83751. sqlite3 *db = pParse->db;
  83752. if( (p = pParse->pNewTable)==0 ) return;
  83753. #if SQLITE_MAX_COLUMN
  83754. if( p->nCol+1>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  83755. sqlite3ErrorMsg(pParse, "too many columns on %s", p->zName);
  83756. return;
  83757. }
  83758. #endif
  83759. z = sqlite3NameFromToken(db, pName);
  83760. if( z==0 ) return;
  83761. for(i=0; i<p->nCol; i++){
  83762. if( STRICMP(z, p->aCol[i].zName) ){
  83763. sqlite3ErrorMsg(pParse, "duplicate column name: %s", z);
  83764. sqlite3DbFree(db, z);
  83765. return;
  83766. }
  83767. }
  83768. if( (p->nCol & 0x7)==0 ){
  83769. Column *aNew;
  83770. aNew = sqlite3DbRealloc(db,p->aCol,(p->nCol+8)*sizeof(p->aCol[0]));
  83771. if( aNew==0 ){
  83772. sqlite3DbFree(db, z);
  83773. return;
  83774. }
  83775. p->aCol = aNew;
  83776. }
  83777. pCol = &p->aCol[p->nCol];
  83778. memset(pCol, 0, sizeof(p->aCol[0]));
  83779. pCol->zName = z;
  83780. /* If there is no type specified, columns have the default affinity
  83781. ** 'NONE'. If there is a type specified, then sqlite3AddColumnType() will
  83782. ** be called next to set pCol->affinity correctly.
  83783. */
  83784. pCol->affinity = SQLITE_AFF_NONE;
  83785. pCol->szEst = 1;
  83786. p->nCol++;
  83787. }
  83788. /*
  83789. ** This routine is called by the parser while in the middle of
  83790. ** parsing a CREATE TABLE statement. A "NOT NULL" constraint has
  83791. ** been seen on a column. This routine sets the notNull flag on
  83792. ** the column currently under construction.
  83793. */
  83794. SQLITE_PRIVATE void sqlite3AddNotNull(Parse *pParse, int onError){
  83795. Table *p;
  83796. p = pParse->pNewTable;
  83797. if( p==0 || NEVER(p->nCol<1) ) return;
  83798. p->aCol[p->nCol-1].notNull = (u8)onError;
  83799. }
  83800. /*
  83801. ** Scan the column type name zType (length nType) and return the
  83802. ** associated affinity type.
  83803. **
  83804. ** This routine does a case-independent search of zType for the
  83805. ** substrings in the following table. If one of the substrings is
  83806. ** found, the corresponding affinity is returned. If zType contains
  83807. ** more than one of the substrings, entries toward the top of
  83808. ** the table take priority. For example, if zType is 'BLOBINT',
  83809. ** SQLITE_AFF_INTEGER is returned.
  83810. **
  83811. ** Substring | Affinity
  83812. ** --------------------------------
  83813. ** 'INT' | SQLITE_AFF_INTEGER
  83814. ** 'CHAR' | SQLITE_AFF_TEXT
  83815. ** 'CLOB' | SQLITE_AFF_TEXT
  83816. ** 'TEXT' | SQLITE_AFF_TEXT
  83817. ** 'BLOB' | SQLITE_AFF_NONE
  83818. ** 'REAL' | SQLITE_AFF_REAL
  83819. ** 'FLOA' | SQLITE_AFF_REAL
  83820. ** 'DOUB' | SQLITE_AFF_REAL
  83821. **
  83822. ** If none of the substrings in the above table are found,
  83823. ** SQLITE_AFF_NUMERIC is returned.
  83824. */
  83825. SQLITE_PRIVATE char sqlite3AffinityType(const char *zIn, u8 *pszEst){
  83826. u32 h = 0;
  83827. char aff = SQLITE_AFF_NUMERIC;
  83828. const char *zChar = 0;
  83829. if( zIn==0 ) return aff;
  83830. while( zIn[0] ){
  83831. h = (h<<8) + sqlite3UpperToLower[(*zIn)&0xff];
  83832. zIn++;
  83833. if( h==(('c'<<24)+('h'<<16)+('a'<<8)+'r') ){ /* CHAR */
  83834. aff = SQLITE_AFF_TEXT;
  83835. zChar = zIn;
  83836. }else if( h==(('c'<<24)+('l'<<16)+('o'<<8)+'b') ){ /* CLOB */
  83837. aff = SQLITE_AFF_TEXT;
  83838. }else if( h==(('t'<<24)+('e'<<16)+('x'<<8)+'t') ){ /* TEXT */
  83839. aff = SQLITE_AFF_TEXT;
  83840. }else if( h==(('b'<<24)+('l'<<16)+('o'<<8)+'b') /* BLOB */
  83841. && (aff==SQLITE_AFF_NUMERIC || aff==SQLITE_AFF_REAL) ){
  83842. aff = SQLITE_AFF_NONE;
  83843. if( zIn[0]=='(' ) zChar = zIn;
  83844. #ifndef SQLITE_OMIT_FLOATING_POINT
  83845. }else if( h==(('r'<<24)+('e'<<16)+('a'<<8)+'l') /* REAL */
  83846. && aff==SQLITE_AFF_NUMERIC ){
  83847. aff = SQLITE_AFF_REAL;
  83848. }else if( h==(('f'<<24)+('l'<<16)+('o'<<8)+'a') /* FLOA */
  83849. && aff==SQLITE_AFF_NUMERIC ){
  83850. aff = SQLITE_AFF_REAL;
  83851. }else if( h==(('d'<<24)+('o'<<16)+('u'<<8)+'b') /* DOUB */
  83852. && aff==SQLITE_AFF_NUMERIC ){
  83853. aff = SQLITE_AFF_REAL;
  83854. #endif
  83855. }else if( (h&0x00FFFFFF)==(('i'<<16)+('n'<<8)+'t') ){ /* INT */
  83856. aff = SQLITE_AFF_INTEGER;
  83857. break;
  83858. }
  83859. }
  83860. /* If pszEst is not NULL, store an estimate of the field size. The
  83861. ** estimate is scaled so that the size of an integer is 1. */
  83862. if( pszEst ){
  83863. *pszEst = 1; /* default size is approx 4 bytes */
  83864. if( aff<SQLITE_AFF_NUMERIC ){
  83865. if( zChar ){
  83866. while( zChar[0] ){
  83867. if( sqlite3Isdigit(zChar[0]) ){
  83868. int v = 0;
  83869. sqlite3GetInt32(zChar, &v);
  83870. v = v/4 + 1;
  83871. if( v>255 ) v = 255;
  83872. *pszEst = v; /* BLOB(k), VARCHAR(k), CHAR(k) -> r=(k/4+1) */
  83873. break;
  83874. }
  83875. zChar++;
  83876. }
  83877. }else{
  83878. *pszEst = 5; /* BLOB, TEXT, CLOB -> r=5 (approx 20 bytes)*/
  83879. }
  83880. }
  83881. }
  83882. return aff;
  83883. }
  83884. /*
  83885. ** This routine is called by the parser while in the middle of
  83886. ** parsing a CREATE TABLE statement. The pFirst token is the first
  83887. ** token in the sequence of tokens that describe the type of the
  83888. ** column currently under construction. pLast is the last token
  83889. ** in the sequence. Use this information to construct a string
  83890. ** that contains the typename of the column and store that string
  83891. ** in zType.
  83892. */
  83893. SQLITE_PRIVATE void sqlite3AddColumnType(Parse *pParse, Token *pType){
  83894. Table *p;
  83895. Column *pCol;
  83896. p = pParse->pNewTable;
  83897. if( p==0 || NEVER(p->nCol<1) ) return;
  83898. pCol = &p->aCol[p->nCol-1];
  83899. assert( pCol->zType==0 );
  83900. pCol->zType = sqlite3NameFromToken(pParse->db, pType);
  83901. pCol->affinity = sqlite3AffinityType(pCol->zType, &pCol->szEst);
  83902. }
  83903. /*
  83904. ** The expression is the default value for the most recently added column
  83905. ** of the table currently under construction.
  83906. **
  83907. ** Default value expressions must be constant. Raise an exception if this
  83908. ** is not the case.
  83909. **
  83910. ** This routine is called by the parser while in the middle of
  83911. ** parsing a CREATE TABLE statement.
  83912. */
  83913. SQLITE_PRIVATE void sqlite3AddDefaultValue(Parse *pParse, ExprSpan *pSpan){
  83914. Table *p;
  83915. Column *pCol;
  83916. sqlite3 *db = pParse->db;
  83917. p = pParse->pNewTable;
  83918. if( p!=0 ){
  83919. pCol = &(p->aCol[p->nCol-1]);
  83920. if( !sqlite3ExprIsConstantOrFunction(pSpan->pExpr, db->init.busy) ){
  83921. sqlite3ErrorMsg(pParse, "default value of column [%s] is not constant",
  83922. pCol->zName);
  83923. }else{
  83924. /* A copy of pExpr is used instead of the original, as pExpr contains
  83925. ** tokens that point to volatile memory. The 'span' of the expression
  83926. ** is required by pragma table_info.
  83927. */
  83928. sqlite3ExprDelete(db, pCol->pDflt);
  83929. pCol->pDflt = sqlite3ExprDup(db, pSpan->pExpr, EXPRDUP_REDUCE);
  83930. sqlite3DbFree(db, pCol->zDflt);
  83931. pCol->zDflt = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
  83932. (int)(pSpan->zEnd - pSpan->zStart));
  83933. }
  83934. }
  83935. sqlite3ExprDelete(db, pSpan->pExpr);
  83936. }
  83937. /*
  83938. ** Designate the PRIMARY KEY for the table. pList is a list of names
  83939. ** of columns that form the primary key. If pList is NULL, then the
  83940. ** most recently added column of the table is the primary key.
  83941. **
  83942. ** A table can have at most one primary key. If the table already has
  83943. ** a primary key (and this is the second primary key) then create an
  83944. ** error.
  83945. **
  83946. ** If the PRIMARY KEY is on a single column whose datatype is INTEGER,
  83947. ** then we will try to use that column as the rowid. Set the Table.iPKey
  83948. ** field of the table under construction to be the index of the
  83949. ** INTEGER PRIMARY KEY column. Table.iPKey is set to -1 if there is
  83950. ** no INTEGER PRIMARY KEY.
  83951. **
  83952. ** If the key is not an INTEGER PRIMARY KEY, then create a unique
  83953. ** index for the key. No index is created for INTEGER PRIMARY KEYs.
  83954. */
  83955. SQLITE_PRIVATE void sqlite3AddPrimaryKey(
  83956. Parse *pParse, /* Parsing context */
  83957. ExprList *pList, /* List of field names to be indexed */
  83958. int onError, /* What to do with a uniqueness conflict */
  83959. int autoInc, /* True if the AUTOINCREMENT keyword is present */
  83960. int sortOrder /* SQLITE_SO_ASC or SQLITE_SO_DESC */
  83961. ){
  83962. Table *pTab = pParse->pNewTable;
  83963. char *zType = 0;
  83964. int iCol = -1, i;
  83965. int nTerm;
  83966. if( pTab==0 || IN_DECLARE_VTAB ) goto primary_key_exit;
  83967. if( pTab->tabFlags & TF_HasPrimaryKey ){
  83968. sqlite3ErrorMsg(pParse,
  83969. "table \"%s\" has more than one primary key", pTab->zName);
  83970. goto primary_key_exit;
  83971. }
  83972. pTab->tabFlags |= TF_HasPrimaryKey;
  83973. if( pList==0 ){
  83974. iCol = pTab->nCol - 1;
  83975. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  83976. zType = pTab->aCol[iCol].zType;
  83977. nTerm = 1;
  83978. }else{
  83979. nTerm = pList->nExpr;
  83980. for(i=0; i<nTerm; i++){
  83981. for(iCol=0; iCol<pTab->nCol; iCol++){
  83982. if( sqlite3StrICmp(pList->a[i].zName, pTab->aCol[iCol].zName)==0 ){
  83983. pTab->aCol[iCol].colFlags |= COLFLAG_PRIMKEY;
  83984. zType = pTab->aCol[iCol].zType;
  83985. break;
  83986. }
  83987. }
  83988. }
  83989. }
  83990. if( nTerm==1
  83991. && zType && sqlite3StrICmp(zType, "INTEGER")==0
  83992. && sortOrder==SQLITE_SO_ASC
  83993. ){
  83994. pTab->iPKey = iCol;
  83995. pTab->keyConf = (u8)onError;
  83996. assert( autoInc==0 || autoInc==1 );
  83997. pTab->tabFlags |= autoInc*TF_Autoincrement;
  83998. if( pList ) pParse->iPkSortOrder = pList->a[0].sortOrder;
  83999. }else if( autoInc ){
  84000. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84001. sqlite3ErrorMsg(pParse, "AUTOINCREMENT is only allowed on an "
  84002. "INTEGER PRIMARY KEY");
  84003. #endif
  84004. }else{
  84005. Vdbe *v = pParse->pVdbe;
  84006. Index *p;
  84007. if( v ) pParse->addrSkipPK = sqlite3VdbeAddOp0(v, OP_Noop);
  84008. p = sqlite3CreateIndex(pParse, 0, 0, 0, pList, onError, 0,
  84009. 0, sortOrder, 0);
  84010. if( p ){
  84011. p->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  84012. if( v ) sqlite3VdbeJumpHere(v, pParse->addrSkipPK);
  84013. }
  84014. pList = 0;
  84015. }
  84016. primary_key_exit:
  84017. sqlite3ExprListDelete(pParse->db, pList);
  84018. return;
  84019. }
  84020. /*
  84021. ** Add a new CHECK constraint to the table currently under construction.
  84022. */
  84023. SQLITE_PRIVATE void sqlite3AddCheckConstraint(
  84024. Parse *pParse, /* Parsing context */
  84025. Expr *pCheckExpr /* The check expression */
  84026. ){
  84027. #ifndef SQLITE_OMIT_CHECK
  84028. Table *pTab = pParse->pNewTable;
  84029. sqlite3 *db = pParse->db;
  84030. if( pTab && !IN_DECLARE_VTAB
  84031. && !sqlite3BtreeIsReadonly(db->aDb[db->init.iDb].pBt)
  84032. ){
  84033. pTab->pCheck = sqlite3ExprListAppend(pParse, pTab->pCheck, pCheckExpr);
  84034. if( pParse->constraintName.n ){
  84035. sqlite3ExprListSetName(pParse, pTab->pCheck, &pParse->constraintName, 1);
  84036. }
  84037. }else
  84038. #endif
  84039. {
  84040. sqlite3ExprDelete(pParse->db, pCheckExpr);
  84041. }
  84042. }
  84043. /*
  84044. ** Set the collation function of the most recently parsed table column
  84045. ** to the CollSeq given.
  84046. */
  84047. SQLITE_PRIVATE void sqlite3AddCollateType(Parse *pParse, Token *pToken){
  84048. Table *p;
  84049. int i;
  84050. char *zColl; /* Dequoted name of collation sequence */
  84051. sqlite3 *db;
  84052. if( (p = pParse->pNewTable)==0 ) return;
  84053. i = p->nCol-1;
  84054. db = pParse->db;
  84055. zColl = sqlite3NameFromToken(db, pToken);
  84056. if( !zColl ) return;
  84057. if( sqlite3LocateCollSeq(pParse, zColl) ){
  84058. Index *pIdx;
  84059. sqlite3DbFree(db, p->aCol[i].zColl);
  84060. p->aCol[i].zColl = zColl;
  84061. /* If the column is declared as "<name> PRIMARY KEY COLLATE <type>",
  84062. ** then an index may have been created on this column before the
  84063. ** collation type was added. Correct this if it is the case.
  84064. */
  84065. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  84066. assert( pIdx->nKeyCol==1 );
  84067. if( pIdx->aiColumn[0]==i ){
  84068. pIdx->azColl[0] = p->aCol[i].zColl;
  84069. }
  84070. }
  84071. }else{
  84072. sqlite3DbFree(db, zColl);
  84073. }
  84074. }
  84075. /*
  84076. ** This function returns the collation sequence for database native text
  84077. ** encoding identified by the string zName, length nName.
  84078. **
  84079. ** If the requested collation sequence is not available, or not available
  84080. ** in the database native encoding, the collation factory is invoked to
  84081. ** request it. If the collation factory does not supply such a sequence,
  84082. ** and the sequence is available in another text encoding, then that is
  84083. ** returned instead.
  84084. **
  84085. ** If no versions of the requested collations sequence are available, or
  84086. ** another error occurs, NULL is returned and an error message written into
  84087. ** pParse.
  84088. **
  84089. ** This routine is a wrapper around sqlite3FindCollSeq(). This routine
  84090. ** invokes the collation factory if the named collation cannot be found
  84091. ** and generates an error message.
  84092. **
  84093. ** See also: sqlite3FindCollSeq(), sqlite3GetCollSeq()
  84094. */
  84095. SQLITE_PRIVATE CollSeq *sqlite3LocateCollSeq(Parse *pParse, const char *zName){
  84096. sqlite3 *db = pParse->db;
  84097. u8 enc = ENC(db);
  84098. u8 initbusy = db->init.busy;
  84099. CollSeq *pColl;
  84100. pColl = sqlite3FindCollSeq(db, enc, zName, initbusy);
  84101. if( !initbusy && (!pColl || !pColl->xCmp) ){
  84102. pColl = sqlite3GetCollSeq(pParse, enc, pColl, zName);
  84103. }
  84104. return pColl;
  84105. }
  84106. /*
  84107. ** Generate code that will increment the schema cookie.
  84108. **
  84109. ** The schema cookie is used to determine when the schema for the
  84110. ** database changes. After each schema change, the cookie value
  84111. ** changes. When a process first reads the schema it records the
  84112. ** cookie. Thereafter, whenever it goes to access the database,
  84113. ** it checks the cookie to make sure the schema has not changed
  84114. ** since it was last read.
  84115. **
  84116. ** This plan is not completely bullet-proof. It is possible for
  84117. ** the schema to change multiple times and for the cookie to be
  84118. ** set back to prior value. But schema changes are infrequent
  84119. ** and the probability of hitting the same cookie value is only
  84120. ** 1 chance in 2^32. So we're safe enough.
  84121. */
  84122. SQLITE_PRIVATE void sqlite3ChangeCookie(Parse *pParse, int iDb){
  84123. int r1 = sqlite3GetTempReg(pParse);
  84124. sqlite3 *db = pParse->db;
  84125. Vdbe *v = pParse->pVdbe;
  84126. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84127. sqlite3VdbeAddOp2(v, OP_Integer, db->aDb[iDb].pSchema->schema_cookie+1, r1);
  84128. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_SCHEMA_VERSION, r1);
  84129. sqlite3ReleaseTempReg(pParse, r1);
  84130. }
  84131. /*
  84132. ** Measure the number of characters needed to output the given
  84133. ** identifier. The number returned includes any quotes used
  84134. ** but does not include the null terminator.
  84135. **
  84136. ** The estimate is conservative. It might be larger that what is
  84137. ** really needed.
  84138. */
  84139. static int identLength(const char *z){
  84140. int n;
  84141. for(n=0; *z; n++, z++){
  84142. if( *z=='"' ){ n++; }
  84143. }
  84144. return n + 2;
  84145. }
  84146. /*
  84147. ** The first parameter is a pointer to an output buffer. The second
  84148. ** parameter is a pointer to an integer that contains the offset at
  84149. ** which to write into the output buffer. This function copies the
  84150. ** nul-terminated string pointed to by the third parameter, zSignedIdent,
  84151. ** to the specified offset in the buffer and updates *pIdx to refer
  84152. ** to the first byte after the last byte written before returning.
  84153. **
  84154. ** If the string zSignedIdent consists entirely of alpha-numeric
  84155. ** characters, does not begin with a digit and is not an SQL keyword,
  84156. ** then it is copied to the output buffer exactly as it is. Otherwise,
  84157. ** it is quoted using double-quotes.
  84158. */
  84159. static void identPut(char *z, int *pIdx, char *zSignedIdent){
  84160. unsigned char *zIdent = (unsigned char*)zSignedIdent;
  84161. int i, j, needQuote;
  84162. i = *pIdx;
  84163. for(j=0; zIdent[j]; j++){
  84164. if( !sqlite3Isalnum(zIdent[j]) && zIdent[j]!='_' ) break;
  84165. }
  84166. needQuote = sqlite3Isdigit(zIdent[0])
  84167. || sqlite3KeywordCode(zIdent, j)!=TK_ID
  84168. || zIdent[j]!=0
  84169. || j==0;
  84170. if( needQuote ) z[i++] = '"';
  84171. for(j=0; zIdent[j]; j++){
  84172. z[i++] = zIdent[j];
  84173. if( zIdent[j]=='"' ) z[i++] = '"';
  84174. }
  84175. if( needQuote ) z[i++] = '"';
  84176. z[i] = 0;
  84177. *pIdx = i;
  84178. }
  84179. /*
  84180. ** Generate a CREATE TABLE statement appropriate for the given
  84181. ** table. Memory to hold the text of the statement is obtained
  84182. ** from sqliteMalloc() and must be freed by the calling function.
  84183. */
  84184. static char *createTableStmt(sqlite3 *db, Table *p){
  84185. int i, k, n;
  84186. char *zStmt;
  84187. char *zSep, *zSep2, *zEnd;
  84188. Column *pCol;
  84189. n = 0;
  84190. for(pCol = p->aCol, i=0; i<p->nCol; i++, pCol++){
  84191. n += identLength(pCol->zName) + 5;
  84192. }
  84193. n += identLength(p->zName);
  84194. if( n<50 ){
  84195. zSep = "";
  84196. zSep2 = ",";
  84197. zEnd = ")";
  84198. }else{
  84199. zSep = "\n ";
  84200. zSep2 = ",\n ";
  84201. zEnd = "\n)";
  84202. }
  84203. n += 35 + 6*p->nCol;
  84204. zStmt = sqlite3DbMallocRaw(0, n);
  84205. if( zStmt==0 ){
  84206. db->mallocFailed = 1;
  84207. return 0;
  84208. }
  84209. sqlite3_snprintf(n, zStmt, "CREATE TABLE ");
  84210. k = sqlite3Strlen30(zStmt);
  84211. identPut(zStmt, &k, p->zName);
  84212. zStmt[k++] = '(';
  84213. for(pCol=p->aCol, i=0; i<p->nCol; i++, pCol++){
  84214. static const char * const azType[] = {
  84215. /* SQLITE_AFF_NONE */ "",
  84216. /* SQLITE_AFF_TEXT */ " TEXT",
  84217. /* SQLITE_AFF_NUMERIC */ " NUM",
  84218. /* SQLITE_AFF_INTEGER */ " INT",
  84219. /* SQLITE_AFF_REAL */ " REAL"
  84220. };
  84221. int len;
  84222. const char *zType;
  84223. sqlite3_snprintf(n-k, &zStmt[k], zSep);
  84224. k += sqlite3Strlen30(&zStmt[k]);
  84225. zSep = zSep2;
  84226. identPut(zStmt, &k, pCol->zName);
  84227. assert( pCol->affinity-SQLITE_AFF_NONE >= 0 );
  84228. assert( pCol->affinity-SQLITE_AFF_NONE < ArraySize(azType) );
  84229. testcase( pCol->affinity==SQLITE_AFF_NONE );
  84230. testcase( pCol->affinity==SQLITE_AFF_TEXT );
  84231. testcase( pCol->affinity==SQLITE_AFF_NUMERIC );
  84232. testcase( pCol->affinity==SQLITE_AFF_INTEGER );
  84233. testcase( pCol->affinity==SQLITE_AFF_REAL );
  84234. zType = azType[pCol->affinity - SQLITE_AFF_NONE];
  84235. len = sqlite3Strlen30(zType);
  84236. assert( pCol->affinity==SQLITE_AFF_NONE
  84237. || pCol->affinity==sqlite3AffinityType(zType, 0) );
  84238. memcpy(&zStmt[k], zType, len);
  84239. k += len;
  84240. assert( k<=n );
  84241. }
  84242. sqlite3_snprintf(n-k, &zStmt[k], "%s", zEnd);
  84243. return zStmt;
  84244. }
  84245. /*
  84246. ** Resize an Index object to hold N columns total. Return SQLITE_OK
  84247. ** on success and SQLITE_NOMEM on an OOM error.
  84248. */
  84249. static int resizeIndexObject(sqlite3 *db, Index *pIdx, int N){
  84250. char *zExtra;
  84251. int nByte;
  84252. if( pIdx->nColumn>=N ) return SQLITE_OK;
  84253. assert( pIdx->isResized==0 );
  84254. nByte = (sizeof(char*) + sizeof(i16) + 1)*N;
  84255. zExtra = sqlite3DbMallocZero(db, nByte);
  84256. if( zExtra==0 ) return SQLITE_NOMEM;
  84257. memcpy(zExtra, pIdx->azColl, sizeof(char*)*pIdx->nColumn);
  84258. pIdx->azColl = (char**)zExtra;
  84259. zExtra += sizeof(char*)*N;
  84260. memcpy(zExtra, pIdx->aiColumn, sizeof(i16)*pIdx->nColumn);
  84261. pIdx->aiColumn = (i16*)zExtra;
  84262. zExtra += sizeof(i16)*N;
  84263. memcpy(zExtra, pIdx->aSortOrder, pIdx->nColumn);
  84264. pIdx->aSortOrder = (u8*)zExtra;
  84265. pIdx->nColumn = N;
  84266. pIdx->isResized = 1;
  84267. return SQLITE_OK;
  84268. }
  84269. /*
  84270. ** Estimate the total row width for a table.
  84271. */
  84272. static void estimateTableWidth(Table *pTab){
  84273. unsigned wTable = 0;
  84274. const Column *pTabCol;
  84275. int i;
  84276. for(i=pTab->nCol, pTabCol=pTab->aCol; i>0; i--, pTabCol++){
  84277. wTable += pTabCol->szEst;
  84278. }
  84279. if( pTab->iPKey<0 ) wTable++;
  84280. pTab->szTabRow = sqlite3LogEst(wTable*4);
  84281. }
  84282. /*
  84283. ** Estimate the average size of a row for an index.
  84284. */
  84285. static void estimateIndexWidth(Index *pIdx){
  84286. unsigned wIndex = 0;
  84287. int i;
  84288. const Column *aCol = pIdx->pTable->aCol;
  84289. for(i=0; i<pIdx->nColumn; i++){
  84290. i16 x = pIdx->aiColumn[i];
  84291. assert( x<pIdx->pTable->nCol );
  84292. wIndex += x<0 ? 1 : aCol[pIdx->aiColumn[i]].szEst;
  84293. }
  84294. pIdx->szIdxRow = sqlite3LogEst(wIndex*4);
  84295. }
  84296. /* Return true if value x is found any of the first nCol entries of aiCol[]
  84297. */
  84298. static int hasColumn(const i16 *aiCol, int nCol, int x){
  84299. while( nCol-- > 0 ) if( x==*(aiCol++) ) return 1;
  84300. return 0;
  84301. }
  84302. /*
  84303. ** This routine runs at the end of parsing a CREATE TABLE statement that
  84304. ** has a WITHOUT ROWID clause. The job of this routine is to convert both
  84305. ** internal schema data structures and the generated VDBE code so that they
  84306. ** are appropriate for a WITHOUT ROWID table instead of a rowid table.
  84307. ** Changes include:
  84308. **
  84309. ** (1) Convert the OP_CreateTable into an OP_CreateIndex. There is
  84310. ** no rowid btree for a WITHOUT ROWID. Instead, the canonical
  84311. ** data storage is a covering index btree.
  84312. ** (2) Bypass the creation of the sqlite_master table entry
  84313. ** for the PRIMARY KEY as the primary key index is now
  84314. ** identified by the sqlite_master table entry of the table itself.
  84315. ** (3) Set the Index.tnum of the PRIMARY KEY Index object in the
  84316. ** schema to the rootpage from the main table.
  84317. ** (4) Set all columns of the PRIMARY KEY schema object to be NOT NULL.
  84318. ** (5) Add all table columns to the PRIMARY KEY Index object
  84319. ** so that the PRIMARY KEY is a covering index. The surplus
  84320. ** columns are part of KeyInfo.nXField and are not used for
  84321. ** sorting or lookup or uniqueness checks.
  84322. ** (6) Replace the rowid tail on all automatically generated UNIQUE
  84323. ** indices with the PRIMARY KEY columns.
  84324. */
  84325. static void convertToWithoutRowidTable(Parse *pParse, Table *pTab){
  84326. Index *pIdx;
  84327. Index *pPk;
  84328. int nPk;
  84329. int i, j;
  84330. sqlite3 *db = pParse->db;
  84331. Vdbe *v = pParse->pVdbe;
  84332. /* Convert the OP_CreateTable opcode that would normally create the
  84333. ** root-page for the table into an OP_CreateIndex opcode. The index
  84334. ** created will become the PRIMARY KEY index.
  84335. */
  84336. if( pParse->addrCrTab ){
  84337. assert( v );
  84338. sqlite3VdbeGetOp(v, pParse->addrCrTab)->opcode = OP_CreateIndex;
  84339. }
  84340. /* Bypass the creation of the PRIMARY KEY btree and the sqlite_master
  84341. ** table entry.
  84342. */
  84343. if( pParse->addrSkipPK ){
  84344. assert( v );
  84345. sqlite3VdbeGetOp(v, pParse->addrSkipPK)->opcode = OP_Goto;
  84346. }
  84347. /* Locate the PRIMARY KEY index. Or, if this table was originally
  84348. ** an INTEGER PRIMARY KEY table, create a new PRIMARY KEY index.
  84349. */
  84350. if( pTab->iPKey>=0 ){
  84351. ExprList *pList;
  84352. pList = sqlite3ExprListAppend(pParse, 0, 0);
  84353. if( pList==0 ) return;
  84354. pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  84355. pTab->aCol[pTab->iPKey].zName);
  84356. pList->a[0].sortOrder = pParse->iPkSortOrder;
  84357. assert( pParse->pNewTable==pTab );
  84358. pPk = sqlite3CreateIndex(pParse, 0, 0, 0, pList, pTab->keyConf, 0, 0, 0, 0);
  84359. if( pPk==0 ) return;
  84360. pPk->idxType = SQLITE_IDXTYPE_PRIMARYKEY;
  84361. pTab->iPKey = -1;
  84362. }else{
  84363. pPk = sqlite3PrimaryKeyIndex(pTab);
  84364. }
  84365. pPk->isCovering = 1;
  84366. assert( pPk!=0 );
  84367. nPk = pPk->nKeyCol;
  84368. /* Make sure every column of the PRIMARY KEY is NOT NULL */
  84369. for(i=0; i<nPk; i++){
  84370. pTab->aCol[pPk->aiColumn[i]].notNull = 1;
  84371. }
  84372. pPk->uniqNotNull = 1;
  84373. /* The root page of the PRIMARY KEY is the table root page */
  84374. pPk->tnum = pTab->tnum;
  84375. /* Update the in-memory representation of all UNIQUE indices by converting
  84376. ** the final rowid column into one or more columns of the PRIMARY KEY.
  84377. */
  84378. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  84379. int n;
  84380. if( IsPrimaryKeyIndex(pIdx) ) continue;
  84381. for(i=n=0; i<nPk; i++){
  84382. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ) n++;
  84383. }
  84384. if( n==0 ){
  84385. /* This index is a superset of the primary key */
  84386. pIdx->nColumn = pIdx->nKeyCol;
  84387. continue;
  84388. }
  84389. if( resizeIndexObject(db, pIdx, pIdx->nKeyCol+n) ) return;
  84390. for(i=0, j=pIdx->nKeyCol; i<nPk; i++){
  84391. if( !hasColumn(pIdx->aiColumn, pIdx->nKeyCol, pPk->aiColumn[i]) ){
  84392. pIdx->aiColumn[j] = pPk->aiColumn[i];
  84393. pIdx->azColl[j] = pPk->azColl[i];
  84394. j++;
  84395. }
  84396. }
  84397. assert( pIdx->nColumn>=pIdx->nKeyCol+n );
  84398. assert( pIdx->nColumn>=j );
  84399. }
  84400. /* Add all table columns to the PRIMARY KEY index
  84401. */
  84402. if( nPk<pTab->nCol ){
  84403. if( resizeIndexObject(db, pPk, pTab->nCol) ) return;
  84404. for(i=0, j=nPk; i<pTab->nCol; i++){
  84405. if( !hasColumn(pPk->aiColumn, j, i) ){
  84406. assert( j<pPk->nColumn );
  84407. pPk->aiColumn[j] = i;
  84408. pPk->azColl[j] = "BINARY";
  84409. j++;
  84410. }
  84411. }
  84412. assert( pPk->nColumn==j );
  84413. assert( pTab->nCol==j );
  84414. }else{
  84415. pPk->nColumn = pTab->nCol;
  84416. }
  84417. }
  84418. /*
  84419. ** This routine is called to report the final ")" that terminates
  84420. ** a CREATE TABLE statement.
  84421. **
  84422. ** The table structure that other action routines have been building
  84423. ** is added to the internal hash tables, assuming no errors have
  84424. ** occurred.
  84425. **
  84426. ** An entry for the table is made in the master table on disk, unless
  84427. ** this is a temporary table or db->init.busy==1. When db->init.busy==1
  84428. ** it means we are reading the sqlite_master table because we just
  84429. ** connected to the database or because the sqlite_master table has
  84430. ** recently changed, so the entry for this table already exists in
  84431. ** the sqlite_master table. We do not want to create it again.
  84432. **
  84433. ** If the pSelect argument is not NULL, it means that this routine
  84434. ** was called to create a table generated from a
  84435. ** "CREATE TABLE ... AS SELECT ..." statement. The column names of
  84436. ** the new table will match the result set of the SELECT.
  84437. */
  84438. SQLITE_PRIVATE void sqlite3EndTable(
  84439. Parse *pParse, /* Parse context */
  84440. Token *pCons, /* The ',' token after the last column defn. */
  84441. Token *pEnd, /* The ')' before options in the CREATE TABLE */
  84442. u8 tabOpts, /* Extra table options. Usually 0. */
  84443. Select *pSelect /* Select from a "CREATE ... AS SELECT" */
  84444. ){
  84445. Table *p; /* The new table */
  84446. sqlite3 *db = pParse->db; /* The database connection */
  84447. int iDb; /* Database in which the table lives */
  84448. Index *pIdx; /* An implied index of the table */
  84449. if( (pEnd==0 && pSelect==0) || db->mallocFailed ){
  84450. return;
  84451. }
  84452. p = pParse->pNewTable;
  84453. if( p==0 ) return;
  84454. assert( !db->init.busy || !pSelect );
  84455. /* If the db->init.busy is 1 it means we are reading the SQL off the
  84456. ** "sqlite_master" or "sqlite_temp_master" table on the disk.
  84457. ** So do not write to the disk again. Extract the root page number
  84458. ** for the table from the db->init.newTnum field. (The page number
  84459. ** should have been put there by the sqliteOpenCb routine.)
  84460. */
  84461. if( db->init.busy ){
  84462. p->tnum = db->init.newTnum;
  84463. }
  84464. /* Special processing for WITHOUT ROWID Tables */
  84465. if( tabOpts & TF_WithoutRowid ){
  84466. if( (p->tabFlags & TF_Autoincrement) ){
  84467. sqlite3ErrorMsg(pParse,
  84468. "AUTOINCREMENT not allowed on WITHOUT ROWID tables");
  84469. return;
  84470. }
  84471. if( (p->tabFlags & TF_HasPrimaryKey)==0 ){
  84472. sqlite3ErrorMsg(pParse, "PRIMARY KEY missing on table %s", p->zName);
  84473. }else{
  84474. p->tabFlags |= TF_WithoutRowid;
  84475. convertToWithoutRowidTable(pParse, p);
  84476. }
  84477. }
  84478. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  84479. #ifndef SQLITE_OMIT_CHECK
  84480. /* Resolve names in all CHECK constraint expressions.
  84481. */
  84482. if( p->pCheck ){
  84483. sqlite3ResolveSelfReference(pParse, p, NC_IsCheck, 0, p->pCheck);
  84484. }
  84485. #endif /* !defined(SQLITE_OMIT_CHECK) */
  84486. /* Estimate the average row size for the table and for all implied indices */
  84487. estimateTableWidth(p);
  84488. for(pIdx=p->pIndex; pIdx; pIdx=pIdx->pNext){
  84489. estimateIndexWidth(pIdx);
  84490. }
  84491. /* If not initializing, then create a record for the new table
  84492. ** in the SQLITE_MASTER table of the database.
  84493. **
  84494. ** If this is a TEMPORARY table, write the entry into the auxiliary
  84495. ** file instead of into the main database file.
  84496. */
  84497. if( !db->init.busy ){
  84498. int n;
  84499. Vdbe *v;
  84500. char *zType; /* "view" or "table" */
  84501. char *zType2; /* "VIEW" or "TABLE" */
  84502. char *zStmt; /* Text of the CREATE TABLE or CREATE VIEW statement */
  84503. v = sqlite3GetVdbe(pParse);
  84504. if( NEVER(v==0) ) return;
  84505. sqlite3VdbeAddOp1(v, OP_Close, 0);
  84506. /*
  84507. ** Initialize zType for the new view or table.
  84508. */
  84509. if( p->pSelect==0 ){
  84510. /* A regular table */
  84511. zType = "table";
  84512. zType2 = "TABLE";
  84513. #ifndef SQLITE_OMIT_VIEW
  84514. }else{
  84515. /* A view */
  84516. zType = "view";
  84517. zType2 = "VIEW";
  84518. #endif
  84519. }
  84520. /* If this is a CREATE TABLE xx AS SELECT ..., execute the SELECT
  84521. ** statement to populate the new table. The root-page number for the
  84522. ** new table is in register pParse->regRoot.
  84523. **
  84524. ** Once the SELECT has been coded by sqlite3Select(), it is in a
  84525. ** suitable state to query for the column names and types to be used
  84526. ** by the new table.
  84527. **
  84528. ** A shared-cache write-lock is not required to write to the new table,
  84529. ** as a schema-lock must have already been obtained to create it. Since
  84530. ** a schema-lock excludes all other database users, the write-lock would
  84531. ** be redundant.
  84532. */
  84533. if( pSelect ){
  84534. SelectDest dest;
  84535. Table *pSelTab;
  84536. assert(pParse->nTab==1);
  84537. sqlite3VdbeAddOp3(v, OP_OpenWrite, 1, pParse->regRoot, iDb);
  84538. sqlite3VdbeChangeP5(v, OPFLAG_P2ISREG);
  84539. pParse->nTab = 2;
  84540. sqlite3SelectDestInit(&dest, SRT_Table, 1);
  84541. sqlite3Select(pParse, pSelect, &dest);
  84542. sqlite3VdbeAddOp1(v, OP_Close, 1);
  84543. if( pParse->nErr==0 ){
  84544. pSelTab = sqlite3ResultSetOfSelect(pParse, pSelect);
  84545. if( pSelTab==0 ) return;
  84546. assert( p->aCol==0 );
  84547. p->nCol = pSelTab->nCol;
  84548. p->aCol = pSelTab->aCol;
  84549. pSelTab->nCol = 0;
  84550. pSelTab->aCol = 0;
  84551. sqlite3DeleteTable(db, pSelTab);
  84552. }
  84553. }
  84554. /* Compute the complete text of the CREATE statement */
  84555. if( pSelect ){
  84556. zStmt = createTableStmt(db, p);
  84557. }else{
  84558. Token *pEnd2 = tabOpts ? &pParse->sLastToken : pEnd;
  84559. n = (int)(pEnd2->z - pParse->sNameToken.z);
  84560. if( pEnd2->z[0]!=';' ) n += pEnd2->n;
  84561. zStmt = sqlite3MPrintf(db,
  84562. "CREATE %s %.*s", zType2, n, pParse->sNameToken.z
  84563. );
  84564. }
  84565. /* A slot for the record has already been allocated in the
  84566. ** SQLITE_MASTER table. We just need to update that slot with all
  84567. ** the information we've collected.
  84568. */
  84569. sqlite3NestedParse(pParse,
  84570. "UPDATE %Q.%s "
  84571. "SET type='%s', name=%Q, tbl_name=%Q, rootpage=#%d, sql=%Q "
  84572. "WHERE rowid=#%d",
  84573. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  84574. zType,
  84575. p->zName,
  84576. p->zName,
  84577. pParse->regRoot,
  84578. zStmt,
  84579. pParse->regRowid
  84580. );
  84581. sqlite3DbFree(db, zStmt);
  84582. sqlite3ChangeCookie(pParse, iDb);
  84583. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84584. /* Check to see if we need to create an sqlite_sequence table for
  84585. ** keeping track of autoincrement keys.
  84586. */
  84587. if( p->tabFlags & TF_Autoincrement ){
  84588. Db *pDb = &db->aDb[iDb];
  84589. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84590. if( pDb->pSchema->pSeqTab==0 ){
  84591. sqlite3NestedParse(pParse,
  84592. "CREATE TABLE %Q.sqlite_sequence(name,seq)",
  84593. pDb->zName
  84594. );
  84595. }
  84596. }
  84597. #endif
  84598. /* Reparse everything to update our internal data structures */
  84599. sqlite3VdbeAddParseSchemaOp(v, iDb,
  84600. sqlite3MPrintf(db, "tbl_name='%q' AND type!='trigger'", p->zName));
  84601. }
  84602. /* Add the table to the in-memory representation of the database.
  84603. */
  84604. if( db->init.busy ){
  84605. Table *pOld;
  84606. Schema *pSchema = p->pSchema;
  84607. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84608. pOld = sqlite3HashInsert(&pSchema->tblHash, p->zName, p);
  84609. if( pOld ){
  84610. assert( p==pOld ); /* Malloc must have failed inside HashInsert() */
  84611. db->mallocFailed = 1;
  84612. return;
  84613. }
  84614. pParse->pNewTable = 0;
  84615. db->flags |= SQLITE_InternChanges;
  84616. #ifndef SQLITE_OMIT_ALTERTABLE
  84617. if( !p->pSelect ){
  84618. const char *zName = (const char *)pParse->sNameToken.z;
  84619. int nName;
  84620. assert( !pSelect && pCons && pEnd );
  84621. if( pCons->z==0 ){
  84622. pCons = pEnd;
  84623. }
  84624. nName = (int)((const char *)pCons->z - zName);
  84625. p->addColOffset = 13 + sqlite3Utf8CharLen(zName, nName);
  84626. }
  84627. #endif
  84628. }
  84629. }
  84630. #ifndef SQLITE_OMIT_VIEW
  84631. /*
  84632. ** The parser calls this routine in order to create a new VIEW
  84633. */
  84634. SQLITE_PRIVATE void sqlite3CreateView(
  84635. Parse *pParse, /* The parsing context */
  84636. Token *pBegin, /* The CREATE token that begins the statement */
  84637. Token *pName1, /* The token that holds the name of the view */
  84638. Token *pName2, /* The token that holds the name of the view */
  84639. Select *pSelect, /* A SELECT statement that will become the new view */
  84640. int isTemp, /* TRUE for a TEMPORARY view */
  84641. int noErr /* Suppress error messages if VIEW already exists */
  84642. ){
  84643. Table *p;
  84644. int n;
  84645. const char *z;
  84646. Token sEnd;
  84647. DbFixer sFix;
  84648. Token *pName = 0;
  84649. int iDb;
  84650. sqlite3 *db = pParse->db;
  84651. if( pParse->nVar>0 ){
  84652. sqlite3ErrorMsg(pParse, "parameters are not allowed in views");
  84653. sqlite3SelectDelete(db, pSelect);
  84654. return;
  84655. }
  84656. sqlite3StartTable(pParse, pName1, pName2, isTemp, 1, 0, noErr);
  84657. p = pParse->pNewTable;
  84658. if( p==0 || pParse->nErr ){
  84659. sqlite3SelectDelete(db, pSelect);
  84660. return;
  84661. }
  84662. sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  84663. iDb = sqlite3SchemaToIndex(db, p->pSchema);
  84664. sqlite3FixInit(&sFix, pParse, iDb, "view", pName);
  84665. if( sqlite3FixSelect(&sFix, pSelect) ){
  84666. sqlite3SelectDelete(db, pSelect);
  84667. return;
  84668. }
  84669. /* Make a copy of the entire SELECT statement that defines the view.
  84670. ** This will force all the Expr.token.z values to be dynamically
  84671. ** allocated rather than point to the input string - which means that
  84672. ** they will persist after the current sqlite3_exec() call returns.
  84673. */
  84674. p->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  84675. sqlite3SelectDelete(db, pSelect);
  84676. if( db->mallocFailed ){
  84677. return;
  84678. }
  84679. if( !db->init.busy ){
  84680. sqlite3ViewGetColumnNames(pParse, p);
  84681. }
  84682. /* Locate the end of the CREATE VIEW statement. Make sEnd point to
  84683. ** the end.
  84684. */
  84685. sEnd = pParse->sLastToken;
  84686. if( ALWAYS(sEnd.z[0]!=0) && sEnd.z[0]!=';' ){
  84687. sEnd.z += sEnd.n;
  84688. }
  84689. sEnd.n = 0;
  84690. n = (int)(sEnd.z - pBegin->z);
  84691. z = pBegin->z;
  84692. while( ALWAYS(n>0) && sqlite3Isspace(z[n-1]) ){ n--; }
  84693. sEnd.z = &z[n-1];
  84694. sEnd.n = 1;
  84695. /* Use sqlite3EndTable() to add the view to the SQLITE_MASTER table */
  84696. sqlite3EndTable(pParse, 0, &sEnd, 0, 0);
  84697. return;
  84698. }
  84699. #endif /* SQLITE_OMIT_VIEW */
  84700. #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
  84701. /*
  84702. ** The Table structure pTable is really a VIEW. Fill in the names of
  84703. ** the columns of the view in the pTable structure. Return the number
  84704. ** of errors. If an error is seen leave an error message in pParse->zErrMsg.
  84705. */
  84706. SQLITE_PRIVATE int sqlite3ViewGetColumnNames(Parse *pParse, Table *pTable){
  84707. Table *pSelTab; /* A fake table from which we get the result set */
  84708. Select *pSel; /* Copy of the SELECT that implements the view */
  84709. int nErr = 0; /* Number of errors encountered */
  84710. int n; /* Temporarily holds the number of cursors assigned */
  84711. sqlite3 *db = pParse->db; /* Database connection for malloc errors */
  84712. sqlite3_xauth xAuth; /* Saved xAuth pointer */
  84713. assert( pTable );
  84714. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84715. if( sqlite3VtabCallConnect(pParse, pTable) ){
  84716. return SQLITE_ERROR;
  84717. }
  84718. if( IsVirtual(pTable) ) return 0;
  84719. #endif
  84720. #ifndef SQLITE_OMIT_VIEW
  84721. /* A positive nCol means the columns names for this view are
  84722. ** already known.
  84723. */
  84724. if( pTable->nCol>0 ) return 0;
  84725. /* A negative nCol is a special marker meaning that we are currently
  84726. ** trying to compute the column names. If we enter this routine with
  84727. ** a negative nCol, it means two or more views form a loop, like this:
  84728. **
  84729. ** CREATE VIEW one AS SELECT * FROM two;
  84730. ** CREATE VIEW two AS SELECT * FROM one;
  84731. **
  84732. ** Actually, the error above is now caught prior to reaching this point.
  84733. ** But the following test is still important as it does come up
  84734. ** in the following:
  84735. **
  84736. ** CREATE TABLE main.ex1(a);
  84737. ** CREATE TEMP VIEW ex1 AS SELECT a FROM ex1;
  84738. ** SELECT * FROM temp.ex1;
  84739. */
  84740. if( pTable->nCol<0 ){
  84741. sqlite3ErrorMsg(pParse, "view %s is circularly defined", pTable->zName);
  84742. return 1;
  84743. }
  84744. assert( pTable->nCol>=0 );
  84745. /* If we get this far, it means we need to compute the table names.
  84746. ** Note that the call to sqlite3ResultSetOfSelect() will expand any
  84747. ** "*" elements in the results set of the view and will assign cursors
  84748. ** to the elements of the FROM clause. But we do not want these changes
  84749. ** to be permanent. So the computation is done on a copy of the SELECT
  84750. ** statement that defines the view.
  84751. */
  84752. assert( pTable->pSelect );
  84753. pSel = sqlite3SelectDup(db, pTable->pSelect, 0);
  84754. if( pSel ){
  84755. u8 enableLookaside = db->lookaside.bEnabled;
  84756. n = pParse->nTab;
  84757. sqlite3SrcListAssignCursors(pParse, pSel->pSrc);
  84758. pTable->nCol = -1;
  84759. db->lookaside.bEnabled = 0;
  84760. #ifndef SQLITE_OMIT_AUTHORIZATION
  84761. xAuth = db->xAuth;
  84762. db->xAuth = 0;
  84763. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  84764. db->xAuth = xAuth;
  84765. #else
  84766. pSelTab = sqlite3ResultSetOfSelect(pParse, pSel);
  84767. #endif
  84768. db->lookaside.bEnabled = enableLookaside;
  84769. pParse->nTab = n;
  84770. if( pSelTab ){
  84771. assert( pTable->aCol==0 );
  84772. pTable->nCol = pSelTab->nCol;
  84773. pTable->aCol = pSelTab->aCol;
  84774. pSelTab->nCol = 0;
  84775. pSelTab->aCol = 0;
  84776. sqlite3DeleteTable(db, pSelTab);
  84777. assert( sqlite3SchemaMutexHeld(db, 0, pTable->pSchema) );
  84778. pTable->pSchema->schemaFlags |= DB_UnresetViews;
  84779. }else{
  84780. pTable->nCol = 0;
  84781. nErr++;
  84782. }
  84783. sqlite3SelectDelete(db, pSel);
  84784. } else {
  84785. nErr++;
  84786. }
  84787. #endif /* SQLITE_OMIT_VIEW */
  84788. return nErr;
  84789. }
  84790. #endif /* !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE) */
  84791. #ifndef SQLITE_OMIT_VIEW
  84792. /*
  84793. ** Clear the column names from every VIEW in database idx.
  84794. */
  84795. static void sqliteViewResetAll(sqlite3 *db, int idx){
  84796. HashElem *i;
  84797. assert( sqlite3SchemaMutexHeld(db, idx, 0) );
  84798. if( !DbHasProperty(db, idx, DB_UnresetViews) ) return;
  84799. for(i=sqliteHashFirst(&db->aDb[idx].pSchema->tblHash); i;i=sqliteHashNext(i)){
  84800. Table *pTab = sqliteHashData(i);
  84801. if( pTab->pSelect ){
  84802. sqliteDeleteColumnNames(db, pTab);
  84803. pTab->aCol = 0;
  84804. pTab->nCol = 0;
  84805. }
  84806. }
  84807. DbClearProperty(db, idx, DB_UnresetViews);
  84808. }
  84809. #else
  84810. # define sqliteViewResetAll(A,B)
  84811. #endif /* SQLITE_OMIT_VIEW */
  84812. /*
  84813. ** This function is called by the VDBE to adjust the internal schema
  84814. ** used by SQLite when the btree layer moves a table root page. The
  84815. ** root-page of a table or index in database iDb has changed from iFrom
  84816. ** to iTo.
  84817. **
  84818. ** Ticket #1728: The symbol table might still contain information
  84819. ** on tables and/or indices that are the process of being deleted.
  84820. ** If you are unlucky, one of those deleted indices or tables might
  84821. ** have the same rootpage number as the real table or index that is
  84822. ** being moved. So we cannot stop searching after the first match
  84823. ** because the first match might be for one of the deleted indices
  84824. ** or tables and not the table/index that is actually being moved.
  84825. ** We must continue looping until all tables and indices with
  84826. ** rootpage==iFrom have been converted to have a rootpage of iTo
  84827. ** in order to be certain that we got the right one.
  84828. */
  84829. #ifndef SQLITE_OMIT_AUTOVACUUM
  84830. SQLITE_PRIVATE void sqlite3RootPageMoved(sqlite3 *db, int iDb, int iFrom, int iTo){
  84831. HashElem *pElem;
  84832. Hash *pHash;
  84833. Db *pDb;
  84834. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  84835. pDb = &db->aDb[iDb];
  84836. pHash = &pDb->pSchema->tblHash;
  84837. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  84838. Table *pTab = sqliteHashData(pElem);
  84839. if( pTab->tnum==iFrom ){
  84840. pTab->tnum = iTo;
  84841. }
  84842. }
  84843. pHash = &pDb->pSchema->idxHash;
  84844. for(pElem=sqliteHashFirst(pHash); pElem; pElem=sqliteHashNext(pElem)){
  84845. Index *pIdx = sqliteHashData(pElem);
  84846. if( pIdx->tnum==iFrom ){
  84847. pIdx->tnum = iTo;
  84848. }
  84849. }
  84850. }
  84851. #endif
  84852. /*
  84853. ** Write code to erase the table with root-page iTable from database iDb.
  84854. ** Also write code to modify the sqlite_master table and internal schema
  84855. ** if a root-page of another table is moved by the btree-layer whilst
  84856. ** erasing iTable (this can happen with an auto-vacuum database).
  84857. */
  84858. static void destroyRootPage(Parse *pParse, int iTable, int iDb){
  84859. Vdbe *v = sqlite3GetVdbe(pParse);
  84860. int r1 = sqlite3GetTempReg(pParse);
  84861. sqlite3VdbeAddOp3(v, OP_Destroy, iTable, r1, iDb);
  84862. sqlite3MayAbort(pParse);
  84863. #ifndef SQLITE_OMIT_AUTOVACUUM
  84864. /* OP_Destroy stores an in integer r1. If this integer
  84865. ** is non-zero, then it is the root page number of a table moved to
  84866. ** location iTable. The following code modifies the sqlite_master table to
  84867. ** reflect this.
  84868. **
  84869. ** The "#NNN" in the SQL is a special constant that means whatever value
  84870. ** is in register NNN. See grammar rules associated with the TK_REGISTER
  84871. ** token for additional information.
  84872. */
  84873. sqlite3NestedParse(pParse,
  84874. "UPDATE %Q.%s SET rootpage=%d WHERE #%d AND rootpage=#%d",
  84875. pParse->db->aDb[iDb].zName, SCHEMA_TABLE(iDb), iTable, r1, r1);
  84876. #endif
  84877. sqlite3ReleaseTempReg(pParse, r1);
  84878. }
  84879. /*
  84880. ** Write VDBE code to erase table pTab and all associated indices on disk.
  84881. ** Code to update the sqlite_master tables and internal schema definitions
  84882. ** in case a root-page belonging to another table is moved by the btree layer
  84883. ** is also added (this can happen with an auto-vacuum database).
  84884. */
  84885. static void destroyTable(Parse *pParse, Table *pTab){
  84886. #ifdef SQLITE_OMIT_AUTOVACUUM
  84887. Index *pIdx;
  84888. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  84889. destroyRootPage(pParse, pTab->tnum, iDb);
  84890. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  84891. destroyRootPage(pParse, pIdx->tnum, iDb);
  84892. }
  84893. #else
  84894. /* If the database may be auto-vacuum capable (if SQLITE_OMIT_AUTOVACUUM
  84895. ** is not defined), then it is important to call OP_Destroy on the
  84896. ** table and index root-pages in order, starting with the numerically
  84897. ** largest root-page number. This guarantees that none of the root-pages
  84898. ** to be destroyed is relocated by an earlier OP_Destroy. i.e. if the
  84899. ** following were coded:
  84900. **
  84901. ** OP_Destroy 4 0
  84902. ** ...
  84903. ** OP_Destroy 5 0
  84904. **
  84905. ** and root page 5 happened to be the largest root-page number in the
  84906. ** database, then root page 5 would be moved to page 4 by the
  84907. ** "OP_Destroy 4 0" opcode. The subsequent "OP_Destroy 5 0" would hit
  84908. ** a free-list page.
  84909. */
  84910. int iTab = pTab->tnum;
  84911. int iDestroyed = 0;
  84912. while( 1 ){
  84913. Index *pIdx;
  84914. int iLargest = 0;
  84915. if( iDestroyed==0 || iTab<iDestroyed ){
  84916. iLargest = iTab;
  84917. }
  84918. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  84919. int iIdx = pIdx->tnum;
  84920. assert( pIdx->pSchema==pTab->pSchema );
  84921. if( (iDestroyed==0 || (iIdx<iDestroyed)) && iIdx>iLargest ){
  84922. iLargest = iIdx;
  84923. }
  84924. }
  84925. if( iLargest==0 ){
  84926. return;
  84927. }else{
  84928. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  84929. assert( iDb>=0 && iDb<pParse->db->nDb );
  84930. destroyRootPage(pParse, iLargest, iDb);
  84931. iDestroyed = iLargest;
  84932. }
  84933. }
  84934. #endif
  84935. }
  84936. /*
  84937. ** Remove entries from the sqlite_statN tables (for N in (1,2,3))
  84938. ** after a DROP INDEX or DROP TABLE command.
  84939. */
  84940. static void sqlite3ClearStatTables(
  84941. Parse *pParse, /* The parsing context */
  84942. int iDb, /* The database number */
  84943. const char *zType, /* "idx" or "tbl" */
  84944. const char *zName /* Name of index or table */
  84945. ){
  84946. int i;
  84947. const char *zDbName = pParse->db->aDb[iDb].zName;
  84948. for(i=1; i<=4; i++){
  84949. char zTab[24];
  84950. sqlite3_snprintf(sizeof(zTab),zTab,"sqlite_stat%d",i);
  84951. if( sqlite3FindTable(pParse->db, zTab, zDbName) ){
  84952. sqlite3NestedParse(pParse,
  84953. "DELETE FROM %Q.%s WHERE %s=%Q",
  84954. zDbName, zTab, zType, zName
  84955. );
  84956. }
  84957. }
  84958. }
  84959. /*
  84960. ** Generate code to drop a table.
  84961. */
  84962. SQLITE_PRIVATE void sqlite3CodeDropTable(Parse *pParse, Table *pTab, int iDb, int isView){
  84963. Vdbe *v;
  84964. sqlite3 *db = pParse->db;
  84965. Trigger *pTrigger;
  84966. Db *pDb = &db->aDb[iDb];
  84967. v = sqlite3GetVdbe(pParse);
  84968. assert( v!=0 );
  84969. sqlite3BeginWriteOperation(pParse, 1, iDb);
  84970. #ifndef SQLITE_OMIT_VIRTUALTABLE
  84971. if( IsVirtual(pTab) ){
  84972. sqlite3VdbeAddOp0(v, OP_VBegin);
  84973. }
  84974. #endif
  84975. /* Drop all triggers associated with the table being dropped. Code
  84976. ** is generated to remove entries from sqlite_master and/or
  84977. ** sqlite_temp_master if required.
  84978. */
  84979. pTrigger = sqlite3TriggerList(pParse, pTab);
  84980. while( pTrigger ){
  84981. assert( pTrigger->pSchema==pTab->pSchema ||
  84982. pTrigger->pSchema==db->aDb[1].pSchema );
  84983. sqlite3DropTriggerPtr(pParse, pTrigger);
  84984. pTrigger = pTrigger->pNext;
  84985. }
  84986. #ifndef SQLITE_OMIT_AUTOINCREMENT
  84987. /* Remove any entries of the sqlite_sequence table associated with
  84988. ** the table being dropped. This is done before the table is dropped
  84989. ** at the btree level, in case the sqlite_sequence table needs to
  84990. ** move as a result of the drop (can happen in auto-vacuum mode).
  84991. */
  84992. if( pTab->tabFlags & TF_Autoincrement ){
  84993. sqlite3NestedParse(pParse,
  84994. "DELETE FROM %Q.sqlite_sequence WHERE name=%Q",
  84995. pDb->zName, pTab->zName
  84996. );
  84997. }
  84998. #endif
  84999. /* Drop all SQLITE_MASTER table and index entries that refer to the
  85000. ** table. The program name loops through the master table and deletes
  85001. ** every row that refers to a table of the same name as the one being
  85002. ** dropped. Triggers are handled separately because a trigger can be
  85003. ** created in the temp database that refers to a table in another
  85004. ** database.
  85005. */
  85006. sqlite3NestedParse(pParse,
  85007. "DELETE FROM %Q.%s WHERE tbl_name=%Q and type!='trigger'",
  85008. pDb->zName, SCHEMA_TABLE(iDb), pTab->zName);
  85009. if( !isView && !IsVirtual(pTab) ){
  85010. destroyTable(pParse, pTab);
  85011. }
  85012. /* Remove the table entry from SQLite's internal schema and modify
  85013. ** the schema cookie.
  85014. */
  85015. if( IsVirtual(pTab) ){
  85016. sqlite3VdbeAddOp4(v, OP_VDestroy, iDb, 0, 0, pTab->zName, 0);
  85017. }
  85018. sqlite3VdbeAddOp4(v, OP_DropTable, iDb, 0, 0, pTab->zName, 0);
  85019. sqlite3ChangeCookie(pParse, iDb);
  85020. sqliteViewResetAll(db, iDb);
  85021. }
  85022. /*
  85023. ** This routine is called to do the work of a DROP TABLE statement.
  85024. ** pName is the name of the table to be dropped.
  85025. */
  85026. SQLITE_PRIVATE void sqlite3DropTable(Parse *pParse, SrcList *pName, int isView, int noErr){
  85027. Table *pTab;
  85028. Vdbe *v;
  85029. sqlite3 *db = pParse->db;
  85030. int iDb;
  85031. if( db->mallocFailed ){
  85032. goto exit_drop_table;
  85033. }
  85034. assert( pParse->nErr==0 );
  85035. assert( pName->nSrc==1 );
  85036. if( noErr ) db->suppressErr++;
  85037. pTab = sqlite3LocateTableItem(pParse, isView, &pName->a[0]);
  85038. if( noErr ) db->suppressErr--;
  85039. if( pTab==0 ){
  85040. if( noErr ) sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  85041. goto exit_drop_table;
  85042. }
  85043. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85044. assert( iDb>=0 && iDb<db->nDb );
  85045. /* If pTab is a virtual table, call ViewGetColumnNames() to ensure
  85046. ** it is initialized.
  85047. */
  85048. if( IsVirtual(pTab) && sqlite3ViewGetColumnNames(pParse, pTab) ){
  85049. goto exit_drop_table;
  85050. }
  85051. #ifndef SQLITE_OMIT_AUTHORIZATION
  85052. {
  85053. int code;
  85054. const char *zTab = SCHEMA_TABLE(iDb);
  85055. const char *zDb = db->aDb[iDb].zName;
  85056. const char *zArg2 = 0;
  85057. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb)){
  85058. goto exit_drop_table;
  85059. }
  85060. if( isView ){
  85061. if( !OMIT_TEMPDB && iDb==1 ){
  85062. code = SQLITE_DROP_TEMP_VIEW;
  85063. }else{
  85064. code = SQLITE_DROP_VIEW;
  85065. }
  85066. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85067. }else if( IsVirtual(pTab) ){
  85068. code = SQLITE_DROP_VTABLE;
  85069. zArg2 = sqlite3GetVTable(db, pTab)->pMod->zName;
  85070. #endif
  85071. }else{
  85072. if( !OMIT_TEMPDB && iDb==1 ){
  85073. code = SQLITE_DROP_TEMP_TABLE;
  85074. }else{
  85075. code = SQLITE_DROP_TABLE;
  85076. }
  85077. }
  85078. if( sqlite3AuthCheck(pParse, code, pTab->zName, zArg2, zDb) ){
  85079. goto exit_drop_table;
  85080. }
  85081. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb) ){
  85082. goto exit_drop_table;
  85083. }
  85084. }
  85085. #endif
  85086. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  85087. && sqlite3StrNICmp(pTab->zName, "sqlite_stat", 11)!=0 ){
  85088. sqlite3ErrorMsg(pParse, "table %s may not be dropped", pTab->zName);
  85089. goto exit_drop_table;
  85090. }
  85091. #ifndef SQLITE_OMIT_VIEW
  85092. /* Ensure DROP TABLE is not used on a view, and DROP VIEW is not used
  85093. ** on a table.
  85094. */
  85095. if( isView && pTab->pSelect==0 ){
  85096. sqlite3ErrorMsg(pParse, "use DROP TABLE to delete table %s", pTab->zName);
  85097. goto exit_drop_table;
  85098. }
  85099. if( !isView && pTab->pSelect ){
  85100. sqlite3ErrorMsg(pParse, "use DROP VIEW to delete view %s", pTab->zName);
  85101. goto exit_drop_table;
  85102. }
  85103. #endif
  85104. /* Generate code to remove the table from the master table
  85105. ** on disk.
  85106. */
  85107. v = sqlite3GetVdbe(pParse);
  85108. if( v ){
  85109. sqlite3BeginWriteOperation(pParse, 1, iDb);
  85110. sqlite3ClearStatTables(pParse, iDb, "tbl", pTab->zName);
  85111. sqlite3FkDropTable(pParse, pName, pTab);
  85112. sqlite3CodeDropTable(pParse, pTab, iDb, isView);
  85113. }
  85114. exit_drop_table:
  85115. sqlite3SrcListDelete(db, pName);
  85116. }
  85117. /*
  85118. ** This routine is called to create a new foreign key on the table
  85119. ** currently under construction. pFromCol determines which columns
  85120. ** in the current table point to the foreign key. If pFromCol==0 then
  85121. ** connect the key to the last column inserted. pTo is the name of
  85122. ** the table referred to (a.k.a the "parent" table). pToCol is a list
  85123. ** of tables in the parent pTo table. flags contains all
  85124. ** information about the conflict resolution algorithms specified
  85125. ** in the ON DELETE, ON UPDATE and ON INSERT clauses.
  85126. **
  85127. ** An FKey structure is created and added to the table currently
  85128. ** under construction in the pParse->pNewTable field.
  85129. **
  85130. ** The foreign key is set for IMMEDIATE processing. A subsequent call
  85131. ** to sqlite3DeferForeignKey() might change this to DEFERRED.
  85132. */
  85133. SQLITE_PRIVATE void sqlite3CreateForeignKey(
  85134. Parse *pParse, /* Parsing context */
  85135. ExprList *pFromCol, /* Columns in this table that point to other table */
  85136. Token *pTo, /* Name of the other table */
  85137. ExprList *pToCol, /* Columns in the other table */
  85138. int flags /* Conflict resolution algorithms. */
  85139. ){
  85140. sqlite3 *db = pParse->db;
  85141. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85142. FKey *pFKey = 0;
  85143. FKey *pNextTo;
  85144. Table *p = pParse->pNewTable;
  85145. int nByte;
  85146. int i;
  85147. int nCol;
  85148. char *z;
  85149. assert( pTo!=0 );
  85150. if( p==0 || IN_DECLARE_VTAB ) goto fk_end;
  85151. if( pFromCol==0 ){
  85152. int iCol = p->nCol-1;
  85153. if( NEVER(iCol<0) ) goto fk_end;
  85154. if( pToCol && pToCol->nExpr!=1 ){
  85155. sqlite3ErrorMsg(pParse, "foreign key on %s"
  85156. " should reference only one column of table %T",
  85157. p->aCol[iCol].zName, pTo);
  85158. goto fk_end;
  85159. }
  85160. nCol = 1;
  85161. }else if( pToCol && pToCol->nExpr!=pFromCol->nExpr ){
  85162. sqlite3ErrorMsg(pParse,
  85163. "number of columns in foreign key does not match the number of "
  85164. "columns in the referenced table");
  85165. goto fk_end;
  85166. }else{
  85167. nCol = pFromCol->nExpr;
  85168. }
  85169. nByte = sizeof(*pFKey) + (nCol-1)*sizeof(pFKey->aCol[0]) + pTo->n + 1;
  85170. if( pToCol ){
  85171. for(i=0; i<pToCol->nExpr; i++){
  85172. nByte += sqlite3Strlen30(pToCol->a[i].zName) + 1;
  85173. }
  85174. }
  85175. pFKey = sqlite3DbMallocZero(db, nByte );
  85176. if( pFKey==0 ){
  85177. goto fk_end;
  85178. }
  85179. pFKey->pFrom = p;
  85180. pFKey->pNextFrom = p->pFKey;
  85181. z = (char*)&pFKey->aCol[nCol];
  85182. pFKey->zTo = z;
  85183. memcpy(z, pTo->z, pTo->n);
  85184. z[pTo->n] = 0;
  85185. sqlite3Dequote(z);
  85186. z += pTo->n+1;
  85187. pFKey->nCol = nCol;
  85188. if( pFromCol==0 ){
  85189. pFKey->aCol[0].iFrom = p->nCol-1;
  85190. }else{
  85191. for(i=0; i<nCol; i++){
  85192. int j;
  85193. for(j=0; j<p->nCol; j++){
  85194. if( sqlite3StrICmp(p->aCol[j].zName, pFromCol->a[i].zName)==0 ){
  85195. pFKey->aCol[i].iFrom = j;
  85196. break;
  85197. }
  85198. }
  85199. if( j>=p->nCol ){
  85200. sqlite3ErrorMsg(pParse,
  85201. "unknown column \"%s\" in foreign key definition",
  85202. pFromCol->a[i].zName);
  85203. goto fk_end;
  85204. }
  85205. }
  85206. }
  85207. if( pToCol ){
  85208. for(i=0; i<nCol; i++){
  85209. int n = sqlite3Strlen30(pToCol->a[i].zName);
  85210. pFKey->aCol[i].zCol = z;
  85211. memcpy(z, pToCol->a[i].zName, n);
  85212. z[n] = 0;
  85213. z += n+1;
  85214. }
  85215. }
  85216. pFKey->isDeferred = 0;
  85217. pFKey->aAction[0] = (u8)(flags & 0xff); /* ON DELETE action */
  85218. pFKey->aAction[1] = (u8)((flags >> 8 ) & 0xff); /* ON UPDATE action */
  85219. assert( sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  85220. pNextTo = (FKey *)sqlite3HashInsert(&p->pSchema->fkeyHash,
  85221. pFKey->zTo, (void *)pFKey
  85222. );
  85223. if( pNextTo==pFKey ){
  85224. db->mallocFailed = 1;
  85225. goto fk_end;
  85226. }
  85227. if( pNextTo ){
  85228. assert( pNextTo->pPrevTo==0 );
  85229. pFKey->pNextTo = pNextTo;
  85230. pNextTo->pPrevTo = pFKey;
  85231. }
  85232. /* Link the foreign key to the table as the last step.
  85233. */
  85234. p->pFKey = pFKey;
  85235. pFKey = 0;
  85236. fk_end:
  85237. sqlite3DbFree(db, pFKey);
  85238. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  85239. sqlite3ExprListDelete(db, pFromCol);
  85240. sqlite3ExprListDelete(db, pToCol);
  85241. }
  85242. /*
  85243. ** This routine is called when an INITIALLY IMMEDIATE or INITIALLY DEFERRED
  85244. ** clause is seen as part of a foreign key definition. The isDeferred
  85245. ** parameter is 1 for INITIALLY DEFERRED and 0 for INITIALLY IMMEDIATE.
  85246. ** The behavior of the most recently created foreign key is adjusted
  85247. ** accordingly.
  85248. */
  85249. SQLITE_PRIVATE void sqlite3DeferForeignKey(Parse *pParse, int isDeferred){
  85250. #ifndef SQLITE_OMIT_FOREIGN_KEY
  85251. Table *pTab;
  85252. FKey *pFKey;
  85253. if( (pTab = pParse->pNewTable)==0 || (pFKey = pTab->pFKey)==0 ) return;
  85254. assert( isDeferred==0 || isDeferred==1 ); /* EV: R-30323-21917 */
  85255. pFKey->isDeferred = (u8)isDeferred;
  85256. #endif
  85257. }
  85258. /*
  85259. ** Generate code that will erase and refill index *pIdx. This is
  85260. ** used to initialize a newly created index or to recompute the
  85261. ** content of an index in response to a REINDEX command.
  85262. **
  85263. ** if memRootPage is not negative, it means that the index is newly
  85264. ** created. The register specified by memRootPage contains the
  85265. ** root page number of the index. If memRootPage is negative, then
  85266. ** the index already exists and must be cleared before being refilled and
  85267. ** the root page number of the index is taken from pIndex->tnum.
  85268. */
  85269. static void sqlite3RefillIndex(Parse *pParse, Index *pIndex, int memRootPage){
  85270. Table *pTab = pIndex->pTable; /* The table that is indexed */
  85271. int iTab = pParse->nTab++; /* Btree cursor used for pTab */
  85272. int iIdx = pParse->nTab++; /* Btree cursor used for pIndex */
  85273. int iSorter; /* Cursor opened by OpenSorter (if in use) */
  85274. int addr1; /* Address of top of loop */
  85275. int addr2; /* Address to jump to for next iteration */
  85276. int tnum; /* Root page of index */
  85277. int iPartIdxLabel; /* Jump to this label to skip a row */
  85278. Vdbe *v; /* Generate code into this virtual machine */
  85279. KeyInfo *pKey; /* KeyInfo for index */
  85280. int regRecord; /* Register holding assembled index record */
  85281. sqlite3 *db = pParse->db; /* The database connection */
  85282. int iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  85283. #ifndef SQLITE_OMIT_AUTHORIZATION
  85284. if( sqlite3AuthCheck(pParse, SQLITE_REINDEX, pIndex->zName, 0,
  85285. db->aDb[iDb].zName ) ){
  85286. return;
  85287. }
  85288. #endif
  85289. /* Require a write-lock on the table to perform this operation */
  85290. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  85291. v = sqlite3GetVdbe(pParse);
  85292. if( v==0 ) return;
  85293. if( memRootPage>=0 ){
  85294. tnum = memRootPage;
  85295. }else{
  85296. tnum = pIndex->tnum;
  85297. }
  85298. pKey = sqlite3KeyInfoOfIndex(pParse, pIndex);
  85299. /* Open the sorter cursor if we are to use one. */
  85300. iSorter = pParse->nTab++;
  85301. sqlite3VdbeAddOp4(v, OP_SorterOpen, iSorter, 0, pIndex->nKeyCol, (char*)
  85302. sqlite3KeyInfoRef(pKey), P4_KEYINFO);
  85303. /* Open the table. Loop through all rows of the table, inserting index
  85304. ** records into the sorter. */
  85305. sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
  85306. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iTab, 0); VdbeCoverage(v);
  85307. regRecord = sqlite3GetTempReg(pParse);
  85308. sqlite3GenerateIndexKey(pParse,pIndex,iTab,regRecord,0,&iPartIdxLabel,0,0);
  85309. sqlite3VdbeAddOp2(v, OP_SorterInsert, iSorter, regRecord);
  85310. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  85311. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr1+1); VdbeCoverage(v);
  85312. sqlite3VdbeJumpHere(v, addr1);
  85313. if( memRootPage<0 ) sqlite3VdbeAddOp2(v, OP_Clear, tnum, iDb);
  85314. sqlite3VdbeAddOp4(v, OP_OpenWrite, iIdx, tnum, iDb,
  85315. (char *)pKey, P4_KEYINFO);
  85316. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR|((memRootPage>=0)?OPFLAG_P2ISREG:0));
  85317. addr1 = sqlite3VdbeAddOp2(v, OP_SorterSort, iSorter, 0); VdbeCoverage(v);
  85318. assert( pKey!=0 || db->mallocFailed || pParse->nErr );
  85319. if( IsUniqueIndex(pIndex) && pKey!=0 ){
  85320. int j2 = sqlite3VdbeCurrentAddr(v) + 3;
  85321. sqlite3VdbeAddOp2(v, OP_Goto, 0, j2);
  85322. addr2 = sqlite3VdbeCurrentAddr(v);
  85323. sqlite3VdbeAddOp4Int(v, OP_SorterCompare, iSorter, j2, regRecord,
  85324. pIndex->nKeyCol); VdbeCoverage(v);
  85325. sqlite3UniqueConstraint(pParse, OE_Abort, pIndex);
  85326. }else{
  85327. addr2 = sqlite3VdbeCurrentAddr(v);
  85328. }
  85329. sqlite3VdbeAddOp3(v, OP_SorterData, iSorter, regRecord, iIdx);
  85330. sqlite3VdbeAddOp3(v, OP_IdxInsert, iIdx, regRecord, 1);
  85331. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  85332. sqlite3ReleaseTempReg(pParse, regRecord);
  85333. sqlite3VdbeAddOp2(v, OP_SorterNext, iSorter, addr2); VdbeCoverage(v);
  85334. sqlite3VdbeJumpHere(v, addr1);
  85335. sqlite3VdbeAddOp1(v, OP_Close, iTab);
  85336. sqlite3VdbeAddOp1(v, OP_Close, iIdx);
  85337. sqlite3VdbeAddOp1(v, OP_Close, iSorter);
  85338. }
  85339. /*
  85340. ** Allocate heap space to hold an Index object with nCol columns.
  85341. **
  85342. ** Increase the allocation size to provide an extra nExtra bytes
  85343. ** of 8-byte aligned space after the Index object and return a
  85344. ** pointer to this extra space in *ppExtra.
  85345. */
  85346. SQLITE_PRIVATE Index *sqlite3AllocateIndexObject(
  85347. sqlite3 *db, /* Database connection */
  85348. i16 nCol, /* Total number of columns in the index */
  85349. int nExtra, /* Number of bytes of extra space to alloc */
  85350. char **ppExtra /* Pointer to the "extra" space */
  85351. ){
  85352. Index *p; /* Allocated index object */
  85353. int nByte; /* Bytes of space for Index object + arrays */
  85354. nByte = ROUND8(sizeof(Index)) + /* Index structure */
  85355. ROUND8(sizeof(char*)*nCol) + /* Index.azColl */
  85356. ROUND8(sizeof(LogEst)*(nCol+1) + /* Index.aiRowLogEst */
  85357. sizeof(i16)*nCol + /* Index.aiColumn */
  85358. sizeof(u8)*nCol); /* Index.aSortOrder */
  85359. p = sqlite3DbMallocZero(db, nByte + nExtra);
  85360. if( p ){
  85361. char *pExtra = ((char*)p)+ROUND8(sizeof(Index));
  85362. p->azColl = (char**)pExtra; pExtra += ROUND8(sizeof(char*)*nCol);
  85363. p->aiRowLogEst = (LogEst*)pExtra; pExtra += sizeof(LogEst)*(nCol+1);
  85364. p->aiColumn = (i16*)pExtra; pExtra += sizeof(i16)*nCol;
  85365. p->aSortOrder = (u8*)pExtra;
  85366. p->nColumn = nCol;
  85367. p->nKeyCol = nCol - 1;
  85368. *ppExtra = ((char*)p) + nByte;
  85369. }
  85370. return p;
  85371. }
  85372. /*
  85373. ** Create a new index for an SQL table. pName1.pName2 is the name of the index
  85374. ** and pTblList is the name of the table that is to be indexed. Both will
  85375. ** be NULL for a primary key or an index that is created to satisfy a
  85376. ** UNIQUE constraint. If pTable and pIndex are NULL, use pParse->pNewTable
  85377. ** as the table to be indexed. pParse->pNewTable is a table that is
  85378. ** currently being constructed by a CREATE TABLE statement.
  85379. **
  85380. ** pList is a list of columns to be indexed. pList will be NULL if this
  85381. ** is a primary key or unique-constraint on the most recent column added
  85382. ** to the table currently under construction.
  85383. **
  85384. ** If the index is created successfully, return a pointer to the new Index
  85385. ** structure. This is used by sqlite3AddPrimaryKey() to mark the index
  85386. ** as the tables primary key (Index.idxType==SQLITE_IDXTYPE_PRIMARYKEY)
  85387. */
  85388. SQLITE_PRIVATE Index *sqlite3CreateIndex(
  85389. Parse *pParse, /* All information about this parse */
  85390. Token *pName1, /* First part of index name. May be NULL */
  85391. Token *pName2, /* Second part of index name. May be NULL */
  85392. SrcList *pTblName, /* Table to index. Use pParse->pNewTable if 0 */
  85393. ExprList *pList, /* A list of columns to be indexed */
  85394. int onError, /* OE_Abort, OE_Ignore, OE_Replace, or OE_None */
  85395. Token *pStart, /* The CREATE token that begins this statement */
  85396. Expr *pPIWhere, /* WHERE clause for partial indices */
  85397. int sortOrder, /* Sort order of primary key when pList==NULL */
  85398. int ifNotExist /* Omit error if index already exists */
  85399. ){
  85400. Index *pRet = 0; /* Pointer to return */
  85401. Table *pTab = 0; /* Table to be indexed */
  85402. Index *pIndex = 0; /* The index to be created */
  85403. char *zName = 0; /* Name of the index */
  85404. int nName; /* Number of characters in zName */
  85405. int i, j;
  85406. DbFixer sFix; /* For assigning database names to pTable */
  85407. int sortOrderMask; /* 1 to honor DESC in index. 0 to ignore. */
  85408. sqlite3 *db = pParse->db;
  85409. Db *pDb; /* The specific table containing the indexed database */
  85410. int iDb; /* Index of the database that is being written */
  85411. Token *pName = 0; /* Unqualified name of the index to create */
  85412. struct ExprList_item *pListItem; /* For looping over pList */
  85413. const Column *pTabCol; /* A column in the table */
  85414. int nExtra = 0; /* Space allocated for zExtra[] */
  85415. int nExtraCol; /* Number of extra columns needed */
  85416. char *zExtra = 0; /* Extra space after the Index object */
  85417. Index *pPk = 0; /* PRIMARY KEY index for WITHOUT ROWID tables */
  85418. assert( pParse->nErr==0 ); /* Never called with prior errors */
  85419. if( db->mallocFailed || IN_DECLARE_VTAB ){
  85420. goto exit_create_index;
  85421. }
  85422. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  85423. goto exit_create_index;
  85424. }
  85425. /*
  85426. ** Find the table that is to be indexed. Return early if not found.
  85427. */
  85428. if( pTblName!=0 ){
  85429. /* Use the two-part index name to determine the database
  85430. ** to search for the table. 'Fix' the table name to this db
  85431. ** before looking up the table.
  85432. */
  85433. assert( pName1 && pName2 );
  85434. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  85435. if( iDb<0 ) goto exit_create_index;
  85436. assert( pName && pName->z );
  85437. #ifndef SQLITE_OMIT_TEMPDB
  85438. /* If the index name was unqualified, check if the table
  85439. ** is a temp table. If so, set the database to 1. Do not do this
  85440. ** if initialising a database schema.
  85441. */
  85442. if( !db->init.busy ){
  85443. pTab = sqlite3SrcListLookup(pParse, pTblName);
  85444. if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
  85445. iDb = 1;
  85446. }
  85447. }
  85448. #endif
  85449. sqlite3FixInit(&sFix, pParse, iDb, "index", pName);
  85450. if( sqlite3FixSrcList(&sFix, pTblName) ){
  85451. /* Because the parser constructs pTblName from a single identifier,
  85452. ** sqlite3FixSrcList can never fail. */
  85453. assert(0);
  85454. }
  85455. pTab = sqlite3LocateTableItem(pParse, 0, &pTblName->a[0]);
  85456. assert( db->mallocFailed==0 || pTab==0 );
  85457. if( pTab==0 ) goto exit_create_index;
  85458. if( iDb==1 && db->aDb[iDb].pSchema!=pTab->pSchema ){
  85459. sqlite3ErrorMsg(pParse,
  85460. "cannot create a TEMP index on non-TEMP table \"%s\"",
  85461. pTab->zName);
  85462. goto exit_create_index;
  85463. }
  85464. if( !HasRowid(pTab) ) pPk = sqlite3PrimaryKeyIndex(pTab);
  85465. }else{
  85466. assert( pName==0 );
  85467. assert( pStart==0 );
  85468. pTab = pParse->pNewTable;
  85469. if( !pTab ) goto exit_create_index;
  85470. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  85471. }
  85472. pDb = &db->aDb[iDb];
  85473. assert( pTab!=0 );
  85474. assert( pParse->nErr==0 );
  85475. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0
  85476. && db->init.busy==0
  85477. #if SQLITE_USER_AUTHENTICATION
  85478. && sqlite3UserAuthTable(pTab->zName)==0
  85479. #endif
  85480. && sqlite3StrNICmp(&pTab->zName[7],"altertab_",9)!=0 ){
  85481. sqlite3ErrorMsg(pParse, "table %s may not be indexed", pTab->zName);
  85482. goto exit_create_index;
  85483. }
  85484. #ifndef SQLITE_OMIT_VIEW
  85485. if( pTab->pSelect ){
  85486. sqlite3ErrorMsg(pParse, "views may not be indexed");
  85487. goto exit_create_index;
  85488. }
  85489. #endif
  85490. #ifndef SQLITE_OMIT_VIRTUALTABLE
  85491. if( IsVirtual(pTab) ){
  85492. sqlite3ErrorMsg(pParse, "virtual tables may not be indexed");
  85493. goto exit_create_index;
  85494. }
  85495. #endif
  85496. /*
  85497. ** Find the name of the index. Make sure there is not already another
  85498. ** index or table with the same name.
  85499. **
  85500. ** Exception: If we are reading the names of permanent indices from the
  85501. ** sqlite_master table (because some other process changed the schema) and
  85502. ** one of the index names collides with the name of a temporary table or
  85503. ** index, then we will continue to process this index.
  85504. **
  85505. ** If pName==0 it means that we are
  85506. ** dealing with a primary key or UNIQUE constraint. We have to invent our
  85507. ** own name.
  85508. */
  85509. if( pName ){
  85510. zName = sqlite3NameFromToken(db, pName);
  85511. if( zName==0 ) goto exit_create_index;
  85512. assert( pName->z!=0 );
  85513. if( SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  85514. goto exit_create_index;
  85515. }
  85516. if( !db->init.busy ){
  85517. if( sqlite3FindTable(db, zName, 0)!=0 ){
  85518. sqlite3ErrorMsg(pParse, "there is already a table named %s", zName);
  85519. goto exit_create_index;
  85520. }
  85521. }
  85522. if( sqlite3FindIndex(db, zName, pDb->zName)!=0 ){
  85523. if( !ifNotExist ){
  85524. sqlite3ErrorMsg(pParse, "index %s already exists", zName);
  85525. }else{
  85526. assert( !db->init.busy );
  85527. sqlite3CodeVerifySchema(pParse, iDb);
  85528. }
  85529. goto exit_create_index;
  85530. }
  85531. }else{
  85532. int n;
  85533. Index *pLoop;
  85534. for(pLoop=pTab->pIndex, n=1; pLoop; pLoop=pLoop->pNext, n++){}
  85535. zName = sqlite3MPrintf(db, "sqlite_autoindex_%s_%d", pTab->zName, n);
  85536. if( zName==0 ){
  85537. goto exit_create_index;
  85538. }
  85539. }
  85540. /* Check for authorization to create an index.
  85541. */
  85542. #ifndef SQLITE_OMIT_AUTHORIZATION
  85543. {
  85544. const char *zDb = pDb->zName;
  85545. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iDb), 0, zDb) ){
  85546. goto exit_create_index;
  85547. }
  85548. i = SQLITE_CREATE_INDEX;
  85549. if( !OMIT_TEMPDB && iDb==1 ) i = SQLITE_CREATE_TEMP_INDEX;
  85550. if( sqlite3AuthCheck(pParse, i, zName, pTab->zName, zDb) ){
  85551. goto exit_create_index;
  85552. }
  85553. }
  85554. #endif
  85555. /* If pList==0, it means this routine was called to make a primary
  85556. ** key out of the last column added to the table under construction.
  85557. ** So create a fake list to simulate this.
  85558. */
  85559. if( pList==0 ){
  85560. pList = sqlite3ExprListAppend(pParse, 0, 0);
  85561. if( pList==0 ) goto exit_create_index;
  85562. pList->a[0].zName = sqlite3DbStrDup(pParse->db,
  85563. pTab->aCol[pTab->nCol-1].zName);
  85564. pList->a[0].sortOrder = (u8)sortOrder;
  85565. }
  85566. /* Figure out how many bytes of space are required to store explicitly
  85567. ** specified collation sequence names.
  85568. */
  85569. for(i=0; i<pList->nExpr; i++){
  85570. Expr *pExpr = pList->a[i].pExpr;
  85571. if( pExpr ){
  85572. assert( pExpr->op==TK_COLLATE );
  85573. nExtra += (1 + sqlite3Strlen30(pExpr->u.zToken));
  85574. }
  85575. }
  85576. /*
  85577. ** Allocate the index structure.
  85578. */
  85579. nName = sqlite3Strlen30(zName);
  85580. nExtraCol = pPk ? pPk->nKeyCol : 1;
  85581. pIndex = sqlite3AllocateIndexObject(db, pList->nExpr + nExtraCol,
  85582. nName + nExtra + 1, &zExtra);
  85583. if( db->mallocFailed ){
  85584. goto exit_create_index;
  85585. }
  85586. assert( EIGHT_BYTE_ALIGNMENT(pIndex->aiRowLogEst) );
  85587. assert( EIGHT_BYTE_ALIGNMENT(pIndex->azColl) );
  85588. pIndex->zName = zExtra;
  85589. zExtra += nName + 1;
  85590. memcpy(pIndex->zName, zName, nName+1);
  85591. pIndex->pTable = pTab;
  85592. pIndex->onError = (u8)onError;
  85593. pIndex->uniqNotNull = onError!=OE_None;
  85594. pIndex->idxType = pName ? SQLITE_IDXTYPE_APPDEF : SQLITE_IDXTYPE_UNIQUE;
  85595. pIndex->pSchema = db->aDb[iDb].pSchema;
  85596. pIndex->nKeyCol = pList->nExpr;
  85597. if( pPIWhere ){
  85598. sqlite3ResolveSelfReference(pParse, pTab, NC_PartIdx, pPIWhere, 0);
  85599. pIndex->pPartIdxWhere = pPIWhere;
  85600. pPIWhere = 0;
  85601. }
  85602. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  85603. /* Check to see if we should honor DESC requests on index columns
  85604. */
  85605. if( pDb->pSchema->file_format>=4 ){
  85606. sortOrderMask = -1; /* Honor DESC */
  85607. }else{
  85608. sortOrderMask = 0; /* Ignore DESC */
  85609. }
  85610. /* Scan the names of the columns of the table to be indexed and
  85611. ** load the column indices into the Index structure. Report an error
  85612. ** if any column is not found.
  85613. **
  85614. ** TODO: Add a test to make sure that the same column is not named
  85615. ** more than once within the same index. Only the first instance of
  85616. ** the column will ever be used by the optimizer. Note that using the
  85617. ** same column more than once cannot be an error because that would
  85618. ** break backwards compatibility - it needs to be a warning.
  85619. */
  85620. for(i=0, pListItem=pList->a; i<pList->nExpr; i++, pListItem++){
  85621. const char *zColName = pListItem->zName;
  85622. int requestedSortOrder;
  85623. char *zColl; /* Collation sequence name */
  85624. for(j=0, pTabCol=pTab->aCol; j<pTab->nCol; j++, pTabCol++){
  85625. if( sqlite3StrICmp(zColName, pTabCol->zName)==0 ) break;
  85626. }
  85627. if( j>=pTab->nCol ){
  85628. sqlite3ErrorMsg(pParse, "table %s has no column named %s",
  85629. pTab->zName, zColName);
  85630. pParse->checkSchema = 1;
  85631. goto exit_create_index;
  85632. }
  85633. assert( j<=0x7fff );
  85634. pIndex->aiColumn[i] = (i16)j;
  85635. if( pListItem->pExpr ){
  85636. int nColl;
  85637. assert( pListItem->pExpr->op==TK_COLLATE );
  85638. zColl = pListItem->pExpr->u.zToken;
  85639. nColl = sqlite3Strlen30(zColl) + 1;
  85640. assert( nExtra>=nColl );
  85641. memcpy(zExtra, zColl, nColl);
  85642. zColl = zExtra;
  85643. zExtra += nColl;
  85644. nExtra -= nColl;
  85645. }else{
  85646. zColl = pTab->aCol[j].zColl;
  85647. if( !zColl ) zColl = "BINARY";
  85648. }
  85649. if( !db->init.busy && !sqlite3LocateCollSeq(pParse, zColl) ){
  85650. goto exit_create_index;
  85651. }
  85652. pIndex->azColl[i] = zColl;
  85653. requestedSortOrder = pListItem->sortOrder & sortOrderMask;
  85654. pIndex->aSortOrder[i] = (u8)requestedSortOrder;
  85655. if( pTab->aCol[j].notNull==0 ) pIndex->uniqNotNull = 0;
  85656. }
  85657. if( pPk ){
  85658. for(j=0; j<pPk->nKeyCol; j++){
  85659. int x = pPk->aiColumn[j];
  85660. if( hasColumn(pIndex->aiColumn, pIndex->nKeyCol, x) ){
  85661. pIndex->nColumn--;
  85662. }else{
  85663. pIndex->aiColumn[i] = x;
  85664. pIndex->azColl[i] = pPk->azColl[j];
  85665. pIndex->aSortOrder[i] = pPk->aSortOrder[j];
  85666. i++;
  85667. }
  85668. }
  85669. assert( i==pIndex->nColumn );
  85670. }else{
  85671. pIndex->aiColumn[i] = -1;
  85672. pIndex->azColl[i] = "BINARY";
  85673. }
  85674. sqlite3DefaultRowEst(pIndex);
  85675. if( pParse->pNewTable==0 ) estimateIndexWidth(pIndex);
  85676. if( pTab==pParse->pNewTable ){
  85677. /* This routine has been called to create an automatic index as a
  85678. ** result of a PRIMARY KEY or UNIQUE clause on a column definition, or
  85679. ** a PRIMARY KEY or UNIQUE clause following the column definitions.
  85680. ** i.e. one of:
  85681. **
  85682. ** CREATE TABLE t(x PRIMARY KEY, y);
  85683. ** CREATE TABLE t(x, y, UNIQUE(x, y));
  85684. **
  85685. ** Either way, check to see if the table already has such an index. If
  85686. ** so, don't bother creating this one. This only applies to
  85687. ** automatically created indices. Users can do as they wish with
  85688. ** explicit indices.
  85689. **
  85690. ** Two UNIQUE or PRIMARY KEY constraints are considered equivalent
  85691. ** (and thus suppressing the second one) even if they have different
  85692. ** sort orders.
  85693. **
  85694. ** If there are different collating sequences or if the columns of
  85695. ** the constraint occur in different orders, then the constraints are
  85696. ** considered distinct and both result in separate indices.
  85697. */
  85698. Index *pIdx;
  85699. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  85700. int k;
  85701. assert( IsUniqueIndex(pIdx) );
  85702. assert( pIdx->idxType!=SQLITE_IDXTYPE_APPDEF );
  85703. assert( IsUniqueIndex(pIndex) );
  85704. if( pIdx->nKeyCol!=pIndex->nKeyCol ) continue;
  85705. for(k=0; k<pIdx->nKeyCol; k++){
  85706. const char *z1;
  85707. const char *z2;
  85708. if( pIdx->aiColumn[k]!=pIndex->aiColumn[k] ) break;
  85709. z1 = pIdx->azColl[k];
  85710. z2 = pIndex->azColl[k];
  85711. if( z1!=z2 && sqlite3StrICmp(z1, z2) ) break;
  85712. }
  85713. if( k==pIdx->nKeyCol ){
  85714. if( pIdx->onError!=pIndex->onError ){
  85715. /* This constraint creates the same index as a previous
  85716. ** constraint specified somewhere in the CREATE TABLE statement.
  85717. ** However the ON CONFLICT clauses are different. If both this
  85718. ** constraint and the previous equivalent constraint have explicit
  85719. ** ON CONFLICT clauses this is an error. Otherwise, use the
  85720. ** explicitly specified behavior for the index.
  85721. */
  85722. if( !(pIdx->onError==OE_Default || pIndex->onError==OE_Default) ){
  85723. sqlite3ErrorMsg(pParse,
  85724. "conflicting ON CONFLICT clauses specified", 0);
  85725. }
  85726. if( pIdx->onError==OE_Default ){
  85727. pIdx->onError = pIndex->onError;
  85728. }
  85729. }
  85730. goto exit_create_index;
  85731. }
  85732. }
  85733. }
  85734. /* Link the new Index structure to its table and to the other
  85735. ** in-memory database structures.
  85736. */
  85737. if( db->init.busy ){
  85738. Index *p;
  85739. assert( sqlite3SchemaMutexHeld(db, 0, pIndex->pSchema) );
  85740. p = sqlite3HashInsert(&pIndex->pSchema->idxHash,
  85741. pIndex->zName, pIndex);
  85742. if( p ){
  85743. assert( p==pIndex ); /* Malloc must have failed */
  85744. db->mallocFailed = 1;
  85745. goto exit_create_index;
  85746. }
  85747. db->flags |= SQLITE_InternChanges;
  85748. if( pTblName!=0 ){
  85749. pIndex->tnum = db->init.newTnum;
  85750. }
  85751. }
  85752. /* If this is the initial CREATE INDEX statement (or CREATE TABLE if the
  85753. ** index is an implied index for a UNIQUE or PRIMARY KEY constraint) then
  85754. ** emit code to allocate the index rootpage on disk and make an entry for
  85755. ** the index in the sqlite_master table and populate the index with
  85756. ** content. But, do not do this if we are simply reading the sqlite_master
  85757. ** table to parse the schema, or if this index is the PRIMARY KEY index
  85758. ** of a WITHOUT ROWID table.
  85759. **
  85760. ** If pTblName==0 it means this index is generated as an implied PRIMARY KEY
  85761. ** or UNIQUE index in a CREATE TABLE statement. Since the table
  85762. ** has just been created, it contains no data and the index initialization
  85763. ** step can be skipped.
  85764. */
  85765. else if( pParse->nErr==0 && (HasRowid(pTab) || pTblName!=0) ){
  85766. Vdbe *v;
  85767. char *zStmt;
  85768. int iMem = ++pParse->nMem;
  85769. v = sqlite3GetVdbe(pParse);
  85770. if( v==0 ) goto exit_create_index;
  85771. /* Create the rootpage for the index
  85772. */
  85773. sqlite3BeginWriteOperation(pParse, 1, iDb);
  85774. sqlite3VdbeAddOp2(v, OP_CreateIndex, iDb, iMem);
  85775. /* Gather the complete text of the CREATE INDEX statement into
  85776. ** the zStmt variable
  85777. */
  85778. if( pStart ){
  85779. int n = (int)(pParse->sLastToken.z - pName->z) + pParse->sLastToken.n;
  85780. if( pName->z[n-1]==';' ) n--;
  85781. /* A named index with an explicit CREATE INDEX statement */
  85782. zStmt = sqlite3MPrintf(db, "CREATE%s INDEX %.*s",
  85783. onError==OE_None ? "" : " UNIQUE", n, pName->z);
  85784. }else{
  85785. /* An automatic index created by a PRIMARY KEY or UNIQUE constraint */
  85786. /* zStmt = sqlite3MPrintf(""); */
  85787. zStmt = 0;
  85788. }
  85789. /* Add an entry in sqlite_master for this index
  85790. */
  85791. sqlite3NestedParse(pParse,
  85792. "INSERT INTO %Q.%s VALUES('index',%Q,%Q,#%d,%Q);",
  85793. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  85794. pIndex->zName,
  85795. pTab->zName,
  85796. iMem,
  85797. zStmt
  85798. );
  85799. sqlite3DbFree(db, zStmt);
  85800. /* Fill the index with data and reparse the schema. Code an OP_Expire
  85801. ** to invalidate all pre-compiled statements.
  85802. */
  85803. if( pTblName ){
  85804. sqlite3RefillIndex(pParse, pIndex, iMem);
  85805. sqlite3ChangeCookie(pParse, iDb);
  85806. sqlite3VdbeAddParseSchemaOp(v, iDb,
  85807. sqlite3MPrintf(db, "name='%q' AND type='index'", pIndex->zName));
  85808. sqlite3VdbeAddOp1(v, OP_Expire, 0);
  85809. }
  85810. }
  85811. /* When adding an index to the list of indices for a table, make
  85812. ** sure all indices labeled OE_Replace come after all those labeled
  85813. ** OE_Ignore. This is necessary for the correct constraint check
  85814. ** processing (in sqlite3GenerateConstraintChecks()) as part of
  85815. ** UPDATE and INSERT statements.
  85816. */
  85817. if( db->init.busy || pTblName==0 ){
  85818. if( onError!=OE_Replace || pTab->pIndex==0
  85819. || pTab->pIndex->onError==OE_Replace){
  85820. pIndex->pNext = pTab->pIndex;
  85821. pTab->pIndex = pIndex;
  85822. }else{
  85823. Index *pOther = pTab->pIndex;
  85824. while( pOther->pNext && pOther->pNext->onError!=OE_Replace ){
  85825. pOther = pOther->pNext;
  85826. }
  85827. pIndex->pNext = pOther->pNext;
  85828. pOther->pNext = pIndex;
  85829. }
  85830. pRet = pIndex;
  85831. pIndex = 0;
  85832. }
  85833. /* Clean up before exiting */
  85834. exit_create_index:
  85835. if( pIndex ) freeIndex(db, pIndex);
  85836. sqlite3ExprDelete(db, pPIWhere);
  85837. sqlite3ExprListDelete(db, pList);
  85838. sqlite3SrcListDelete(db, pTblName);
  85839. sqlite3DbFree(db, zName);
  85840. return pRet;
  85841. }
  85842. /*
  85843. ** Fill the Index.aiRowEst[] array with default information - information
  85844. ** to be used when we have not run the ANALYZE command.
  85845. **
  85846. ** aiRowEst[0] is supposed to contain the number of elements in the index.
  85847. ** Since we do not know, guess 1 million. aiRowEst[1] is an estimate of the
  85848. ** number of rows in the table that match any particular value of the
  85849. ** first column of the index. aiRowEst[2] is an estimate of the number
  85850. ** of rows that match any particular combination of the first 2 columns
  85851. ** of the index. And so forth. It must always be the case that
  85852. *
  85853. ** aiRowEst[N]<=aiRowEst[N-1]
  85854. ** aiRowEst[N]>=1
  85855. **
  85856. ** Apart from that, we have little to go on besides intuition as to
  85857. ** how aiRowEst[] should be initialized. The numbers generated here
  85858. ** are based on typical values found in actual indices.
  85859. */
  85860. SQLITE_PRIVATE void sqlite3DefaultRowEst(Index *pIdx){
  85861. /* 10, 9, 8, 7, 6 */
  85862. LogEst aVal[] = { 33, 32, 30, 28, 26 };
  85863. LogEst *a = pIdx->aiRowLogEst;
  85864. int nCopy = MIN(ArraySize(aVal), pIdx->nKeyCol);
  85865. int i;
  85866. /* Set the first entry (number of rows in the index) to the estimated
  85867. ** number of rows in the table. Or 10, if the estimated number of rows
  85868. ** in the table is less than that. */
  85869. a[0] = pIdx->pTable->nRowLogEst;
  85870. if( a[0]<33 ) a[0] = 33; assert( 33==sqlite3LogEst(10) );
  85871. /* Estimate that a[1] is 10, a[2] is 9, a[3] is 8, a[4] is 7, a[5] is
  85872. ** 6 and each subsequent value (if any) is 5. */
  85873. memcpy(&a[1], aVal, nCopy*sizeof(LogEst));
  85874. for(i=nCopy+1; i<=pIdx->nKeyCol; i++){
  85875. a[i] = 23; assert( 23==sqlite3LogEst(5) );
  85876. }
  85877. assert( 0==sqlite3LogEst(1) );
  85878. if( IsUniqueIndex(pIdx) ) a[pIdx->nKeyCol] = 0;
  85879. }
  85880. /*
  85881. ** This routine will drop an existing named index. This routine
  85882. ** implements the DROP INDEX statement.
  85883. */
  85884. SQLITE_PRIVATE void sqlite3DropIndex(Parse *pParse, SrcList *pName, int ifExists){
  85885. Index *pIndex;
  85886. Vdbe *v;
  85887. sqlite3 *db = pParse->db;
  85888. int iDb;
  85889. assert( pParse->nErr==0 ); /* Never called with prior errors */
  85890. if( db->mallocFailed ){
  85891. goto exit_drop_index;
  85892. }
  85893. assert( pName->nSrc==1 );
  85894. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  85895. goto exit_drop_index;
  85896. }
  85897. pIndex = sqlite3FindIndex(db, pName->a[0].zName, pName->a[0].zDatabase);
  85898. if( pIndex==0 ){
  85899. if( !ifExists ){
  85900. sqlite3ErrorMsg(pParse, "no such index: %S", pName, 0);
  85901. }else{
  85902. sqlite3CodeVerifyNamedSchema(pParse, pName->a[0].zDatabase);
  85903. }
  85904. pParse->checkSchema = 1;
  85905. goto exit_drop_index;
  85906. }
  85907. if( pIndex->idxType!=SQLITE_IDXTYPE_APPDEF ){
  85908. sqlite3ErrorMsg(pParse, "index associated with UNIQUE "
  85909. "or PRIMARY KEY constraint cannot be dropped", 0);
  85910. goto exit_drop_index;
  85911. }
  85912. iDb = sqlite3SchemaToIndex(db, pIndex->pSchema);
  85913. #ifndef SQLITE_OMIT_AUTHORIZATION
  85914. {
  85915. int code = SQLITE_DROP_INDEX;
  85916. Table *pTab = pIndex->pTable;
  85917. const char *zDb = db->aDb[iDb].zName;
  85918. const char *zTab = SCHEMA_TABLE(iDb);
  85919. if( sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  85920. goto exit_drop_index;
  85921. }
  85922. if( !OMIT_TEMPDB && iDb ) code = SQLITE_DROP_TEMP_INDEX;
  85923. if( sqlite3AuthCheck(pParse, code, pIndex->zName, pTab->zName, zDb) ){
  85924. goto exit_drop_index;
  85925. }
  85926. }
  85927. #endif
  85928. /* Generate code to remove the index and from the master table */
  85929. v = sqlite3GetVdbe(pParse);
  85930. if( v ){
  85931. sqlite3BeginWriteOperation(pParse, 1, iDb);
  85932. sqlite3NestedParse(pParse,
  85933. "DELETE FROM %Q.%s WHERE name=%Q AND type='index'",
  85934. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pIndex->zName
  85935. );
  85936. sqlite3ClearStatTables(pParse, iDb, "idx", pIndex->zName);
  85937. sqlite3ChangeCookie(pParse, iDb);
  85938. destroyRootPage(pParse, pIndex->tnum, iDb);
  85939. sqlite3VdbeAddOp4(v, OP_DropIndex, iDb, 0, 0, pIndex->zName, 0);
  85940. }
  85941. exit_drop_index:
  85942. sqlite3SrcListDelete(db, pName);
  85943. }
  85944. /*
  85945. ** pArray is a pointer to an array of objects. Each object in the
  85946. ** array is szEntry bytes in size. This routine uses sqlite3DbRealloc()
  85947. ** to extend the array so that there is space for a new object at the end.
  85948. **
  85949. ** When this function is called, *pnEntry contains the current size of
  85950. ** the array (in entries - so the allocation is ((*pnEntry) * szEntry) bytes
  85951. ** in total).
  85952. **
  85953. ** If the realloc() is successful (i.e. if no OOM condition occurs), the
  85954. ** space allocated for the new object is zeroed, *pnEntry updated to
  85955. ** reflect the new size of the array and a pointer to the new allocation
  85956. ** returned. *pIdx is set to the index of the new array entry in this case.
  85957. **
  85958. ** Otherwise, if the realloc() fails, *pIdx is set to -1, *pnEntry remains
  85959. ** unchanged and a copy of pArray returned.
  85960. */
  85961. SQLITE_PRIVATE void *sqlite3ArrayAllocate(
  85962. sqlite3 *db, /* Connection to notify of malloc failures */
  85963. void *pArray, /* Array of objects. Might be reallocated */
  85964. int szEntry, /* Size of each object in the array */
  85965. int *pnEntry, /* Number of objects currently in use */
  85966. int *pIdx /* Write the index of a new slot here */
  85967. ){
  85968. char *z;
  85969. int n = *pnEntry;
  85970. if( (n & (n-1))==0 ){
  85971. int sz = (n==0) ? 1 : 2*n;
  85972. void *pNew = sqlite3DbRealloc(db, pArray, sz*szEntry);
  85973. if( pNew==0 ){
  85974. *pIdx = -1;
  85975. return pArray;
  85976. }
  85977. pArray = pNew;
  85978. }
  85979. z = (char*)pArray;
  85980. memset(&z[n * szEntry], 0, szEntry);
  85981. *pIdx = n;
  85982. ++*pnEntry;
  85983. return pArray;
  85984. }
  85985. /*
  85986. ** Append a new element to the given IdList. Create a new IdList if
  85987. ** need be.
  85988. **
  85989. ** A new IdList is returned, or NULL if malloc() fails.
  85990. */
  85991. SQLITE_PRIVATE IdList *sqlite3IdListAppend(sqlite3 *db, IdList *pList, Token *pToken){
  85992. int i;
  85993. if( pList==0 ){
  85994. pList = sqlite3DbMallocZero(db, sizeof(IdList) );
  85995. if( pList==0 ) return 0;
  85996. }
  85997. pList->a = sqlite3ArrayAllocate(
  85998. db,
  85999. pList->a,
  86000. sizeof(pList->a[0]),
  86001. &pList->nId,
  86002. &i
  86003. );
  86004. if( i<0 ){
  86005. sqlite3IdListDelete(db, pList);
  86006. return 0;
  86007. }
  86008. pList->a[i].zName = sqlite3NameFromToken(db, pToken);
  86009. return pList;
  86010. }
  86011. /*
  86012. ** Delete an IdList.
  86013. */
  86014. SQLITE_PRIVATE void sqlite3IdListDelete(sqlite3 *db, IdList *pList){
  86015. int i;
  86016. if( pList==0 ) return;
  86017. for(i=0; i<pList->nId; i++){
  86018. sqlite3DbFree(db, pList->a[i].zName);
  86019. }
  86020. sqlite3DbFree(db, pList->a);
  86021. sqlite3DbFree(db, pList);
  86022. }
  86023. /*
  86024. ** Return the index in pList of the identifier named zId. Return -1
  86025. ** if not found.
  86026. */
  86027. SQLITE_PRIVATE int sqlite3IdListIndex(IdList *pList, const char *zName){
  86028. int i;
  86029. if( pList==0 ) return -1;
  86030. for(i=0; i<pList->nId; i++){
  86031. if( sqlite3StrICmp(pList->a[i].zName, zName)==0 ) return i;
  86032. }
  86033. return -1;
  86034. }
  86035. /*
  86036. ** Expand the space allocated for the given SrcList object by
  86037. ** creating nExtra new slots beginning at iStart. iStart is zero based.
  86038. ** New slots are zeroed.
  86039. **
  86040. ** For example, suppose a SrcList initially contains two entries: A,B.
  86041. ** To append 3 new entries onto the end, do this:
  86042. **
  86043. ** sqlite3SrcListEnlarge(db, pSrclist, 3, 2);
  86044. **
  86045. ** After the call above it would contain: A, B, nil, nil, nil.
  86046. ** If the iStart argument had been 1 instead of 2, then the result
  86047. ** would have been: A, nil, nil, nil, B. To prepend the new slots,
  86048. ** the iStart value would be 0. The result then would
  86049. ** be: nil, nil, nil, A, B.
  86050. **
  86051. ** If a memory allocation fails the SrcList is unchanged. The
  86052. ** db->mallocFailed flag will be set to true.
  86053. */
  86054. SQLITE_PRIVATE SrcList *sqlite3SrcListEnlarge(
  86055. sqlite3 *db, /* Database connection to notify of OOM errors */
  86056. SrcList *pSrc, /* The SrcList to be enlarged */
  86057. int nExtra, /* Number of new slots to add to pSrc->a[] */
  86058. int iStart /* Index in pSrc->a[] of first new slot */
  86059. ){
  86060. int i;
  86061. /* Sanity checking on calling parameters */
  86062. assert( iStart>=0 );
  86063. assert( nExtra>=1 );
  86064. assert( pSrc!=0 );
  86065. assert( iStart<=pSrc->nSrc );
  86066. /* Allocate additional space if needed */
  86067. if( (u32)pSrc->nSrc+nExtra>pSrc->nAlloc ){
  86068. SrcList *pNew;
  86069. int nAlloc = pSrc->nSrc+nExtra;
  86070. int nGot;
  86071. pNew = sqlite3DbRealloc(db, pSrc,
  86072. sizeof(*pSrc) + (nAlloc-1)*sizeof(pSrc->a[0]) );
  86073. if( pNew==0 ){
  86074. assert( db->mallocFailed );
  86075. return pSrc;
  86076. }
  86077. pSrc = pNew;
  86078. nGot = (sqlite3DbMallocSize(db, pNew) - sizeof(*pSrc))/sizeof(pSrc->a[0])+1;
  86079. pSrc->nAlloc = nGot;
  86080. }
  86081. /* Move existing slots that come after the newly inserted slots
  86082. ** out of the way */
  86083. for(i=pSrc->nSrc-1; i>=iStart; i--){
  86084. pSrc->a[i+nExtra] = pSrc->a[i];
  86085. }
  86086. pSrc->nSrc += nExtra;
  86087. /* Zero the newly allocated slots */
  86088. memset(&pSrc->a[iStart], 0, sizeof(pSrc->a[0])*nExtra);
  86089. for(i=iStart; i<iStart+nExtra; i++){
  86090. pSrc->a[i].iCursor = -1;
  86091. }
  86092. /* Return a pointer to the enlarged SrcList */
  86093. return pSrc;
  86094. }
  86095. /*
  86096. ** Append a new table name to the given SrcList. Create a new SrcList if
  86097. ** need be. A new entry is created in the SrcList even if pTable is NULL.
  86098. **
  86099. ** A SrcList is returned, or NULL if there is an OOM error. The returned
  86100. ** SrcList might be the same as the SrcList that was input or it might be
  86101. ** a new one. If an OOM error does occurs, then the prior value of pList
  86102. ** that is input to this routine is automatically freed.
  86103. **
  86104. ** If pDatabase is not null, it means that the table has an optional
  86105. ** database name prefix. Like this: "database.table". The pDatabase
  86106. ** points to the table name and the pTable points to the database name.
  86107. ** The SrcList.a[].zName field is filled with the table name which might
  86108. ** come from pTable (if pDatabase is NULL) or from pDatabase.
  86109. ** SrcList.a[].zDatabase is filled with the database name from pTable,
  86110. ** or with NULL if no database is specified.
  86111. **
  86112. ** In other words, if call like this:
  86113. **
  86114. ** sqlite3SrcListAppend(D,A,B,0);
  86115. **
  86116. ** Then B is a table name and the database name is unspecified. If called
  86117. ** like this:
  86118. **
  86119. ** sqlite3SrcListAppend(D,A,B,C);
  86120. **
  86121. ** Then C is the table name and B is the database name. If C is defined
  86122. ** then so is B. In other words, we never have a case where:
  86123. **
  86124. ** sqlite3SrcListAppend(D,A,0,C);
  86125. **
  86126. ** Both pTable and pDatabase are assumed to be quoted. They are dequoted
  86127. ** before being added to the SrcList.
  86128. */
  86129. SQLITE_PRIVATE SrcList *sqlite3SrcListAppend(
  86130. sqlite3 *db, /* Connection to notify of malloc failures */
  86131. SrcList *pList, /* Append to this SrcList. NULL creates a new SrcList */
  86132. Token *pTable, /* Table to append */
  86133. Token *pDatabase /* Database of the table */
  86134. ){
  86135. struct SrcList_item *pItem;
  86136. assert( pDatabase==0 || pTable!=0 ); /* Cannot have C without B */
  86137. if( pList==0 ){
  86138. pList = sqlite3DbMallocZero(db, sizeof(SrcList) );
  86139. if( pList==0 ) return 0;
  86140. pList->nAlloc = 1;
  86141. }
  86142. pList = sqlite3SrcListEnlarge(db, pList, 1, pList->nSrc);
  86143. if( db->mallocFailed ){
  86144. sqlite3SrcListDelete(db, pList);
  86145. return 0;
  86146. }
  86147. pItem = &pList->a[pList->nSrc-1];
  86148. if( pDatabase && pDatabase->z==0 ){
  86149. pDatabase = 0;
  86150. }
  86151. if( pDatabase ){
  86152. Token *pTemp = pDatabase;
  86153. pDatabase = pTable;
  86154. pTable = pTemp;
  86155. }
  86156. pItem->zName = sqlite3NameFromToken(db, pTable);
  86157. pItem->zDatabase = sqlite3NameFromToken(db, pDatabase);
  86158. return pList;
  86159. }
  86160. /*
  86161. ** Assign VdbeCursor index numbers to all tables in a SrcList
  86162. */
  86163. SQLITE_PRIVATE void sqlite3SrcListAssignCursors(Parse *pParse, SrcList *pList){
  86164. int i;
  86165. struct SrcList_item *pItem;
  86166. assert(pList || pParse->db->mallocFailed );
  86167. if( pList ){
  86168. for(i=0, pItem=pList->a; i<pList->nSrc; i++, pItem++){
  86169. if( pItem->iCursor>=0 ) break;
  86170. pItem->iCursor = pParse->nTab++;
  86171. if( pItem->pSelect ){
  86172. sqlite3SrcListAssignCursors(pParse, pItem->pSelect->pSrc);
  86173. }
  86174. }
  86175. }
  86176. }
  86177. /*
  86178. ** Delete an entire SrcList including all its substructure.
  86179. */
  86180. SQLITE_PRIVATE void sqlite3SrcListDelete(sqlite3 *db, SrcList *pList){
  86181. int i;
  86182. struct SrcList_item *pItem;
  86183. if( pList==0 ) return;
  86184. for(pItem=pList->a, i=0; i<pList->nSrc; i++, pItem++){
  86185. sqlite3DbFree(db, pItem->zDatabase);
  86186. sqlite3DbFree(db, pItem->zName);
  86187. sqlite3DbFree(db, pItem->zAlias);
  86188. sqlite3DbFree(db, pItem->zIndex);
  86189. sqlite3DeleteTable(db, pItem->pTab);
  86190. sqlite3SelectDelete(db, pItem->pSelect);
  86191. sqlite3ExprDelete(db, pItem->pOn);
  86192. sqlite3IdListDelete(db, pItem->pUsing);
  86193. }
  86194. sqlite3DbFree(db, pList);
  86195. }
  86196. /*
  86197. ** This routine is called by the parser to add a new term to the
  86198. ** end of a growing FROM clause. The "p" parameter is the part of
  86199. ** the FROM clause that has already been constructed. "p" is NULL
  86200. ** if this is the first term of the FROM clause. pTable and pDatabase
  86201. ** are the name of the table and database named in the FROM clause term.
  86202. ** pDatabase is NULL if the database name qualifier is missing - the
  86203. ** usual case. If the term has an alias, then pAlias points to the
  86204. ** alias token. If the term is a subquery, then pSubquery is the
  86205. ** SELECT statement that the subquery encodes. The pTable and
  86206. ** pDatabase parameters are NULL for subqueries. The pOn and pUsing
  86207. ** parameters are the content of the ON and USING clauses.
  86208. **
  86209. ** Return a new SrcList which encodes is the FROM with the new
  86210. ** term added.
  86211. */
  86212. SQLITE_PRIVATE SrcList *sqlite3SrcListAppendFromTerm(
  86213. Parse *pParse, /* Parsing context */
  86214. SrcList *p, /* The left part of the FROM clause already seen */
  86215. Token *pTable, /* Name of the table to add to the FROM clause */
  86216. Token *pDatabase, /* Name of the database containing pTable */
  86217. Token *pAlias, /* The right-hand side of the AS subexpression */
  86218. Select *pSubquery, /* A subquery used in place of a table name */
  86219. Expr *pOn, /* The ON clause of a join */
  86220. IdList *pUsing /* The USING clause of a join */
  86221. ){
  86222. struct SrcList_item *pItem;
  86223. sqlite3 *db = pParse->db;
  86224. if( !p && (pOn || pUsing) ){
  86225. sqlite3ErrorMsg(pParse, "a JOIN clause is required before %s",
  86226. (pOn ? "ON" : "USING")
  86227. );
  86228. goto append_from_error;
  86229. }
  86230. p = sqlite3SrcListAppend(db, p, pTable, pDatabase);
  86231. if( p==0 || NEVER(p->nSrc==0) ){
  86232. goto append_from_error;
  86233. }
  86234. pItem = &p->a[p->nSrc-1];
  86235. assert( pAlias!=0 );
  86236. if( pAlias->n ){
  86237. pItem->zAlias = sqlite3NameFromToken(db, pAlias);
  86238. }
  86239. pItem->pSelect = pSubquery;
  86240. pItem->pOn = pOn;
  86241. pItem->pUsing = pUsing;
  86242. return p;
  86243. append_from_error:
  86244. assert( p==0 );
  86245. sqlite3ExprDelete(db, pOn);
  86246. sqlite3IdListDelete(db, pUsing);
  86247. sqlite3SelectDelete(db, pSubquery);
  86248. return 0;
  86249. }
  86250. /*
  86251. ** Add an INDEXED BY or NOT INDEXED clause to the most recently added
  86252. ** element of the source-list passed as the second argument.
  86253. */
  86254. SQLITE_PRIVATE void sqlite3SrcListIndexedBy(Parse *pParse, SrcList *p, Token *pIndexedBy){
  86255. assert( pIndexedBy!=0 );
  86256. if( p && ALWAYS(p->nSrc>0) ){
  86257. struct SrcList_item *pItem = &p->a[p->nSrc-1];
  86258. assert( pItem->notIndexed==0 && pItem->zIndex==0 );
  86259. if( pIndexedBy->n==1 && !pIndexedBy->z ){
  86260. /* A "NOT INDEXED" clause was supplied. See parse.y
  86261. ** construct "indexed_opt" for details. */
  86262. pItem->notIndexed = 1;
  86263. }else{
  86264. pItem->zIndex = sqlite3NameFromToken(pParse->db, pIndexedBy);
  86265. }
  86266. }
  86267. }
  86268. /*
  86269. ** When building up a FROM clause in the parser, the join operator
  86270. ** is initially attached to the left operand. But the code generator
  86271. ** expects the join operator to be on the right operand. This routine
  86272. ** Shifts all join operators from left to right for an entire FROM
  86273. ** clause.
  86274. **
  86275. ** Example: Suppose the join is like this:
  86276. **
  86277. ** A natural cross join B
  86278. **
  86279. ** The operator is "natural cross join". The A and B operands are stored
  86280. ** in p->a[0] and p->a[1], respectively. The parser initially stores the
  86281. ** operator with A. This routine shifts that operator over to B.
  86282. */
  86283. SQLITE_PRIVATE void sqlite3SrcListShiftJoinType(SrcList *p){
  86284. if( p ){
  86285. int i;
  86286. assert( p->a || p->nSrc==0 );
  86287. for(i=p->nSrc-1; i>0; i--){
  86288. p->a[i].jointype = p->a[i-1].jointype;
  86289. }
  86290. p->a[0].jointype = 0;
  86291. }
  86292. }
  86293. /*
  86294. ** Begin a transaction
  86295. */
  86296. SQLITE_PRIVATE void sqlite3BeginTransaction(Parse *pParse, int type){
  86297. sqlite3 *db;
  86298. Vdbe *v;
  86299. int i;
  86300. assert( pParse!=0 );
  86301. db = pParse->db;
  86302. assert( db!=0 );
  86303. /* if( db->aDb[0].pBt==0 ) return; */
  86304. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "BEGIN", 0, 0) ){
  86305. return;
  86306. }
  86307. v = sqlite3GetVdbe(pParse);
  86308. if( !v ) return;
  86309. if( type!=TK_DEFERRED ){
  86310. for(i=0; i<db->nDb; i++){
  86311. sqlite3VdbeAddOp2(v, OP_Transaction, i, (type==TK_EXCLUSIVE)+1);
  86312. sqlite3VdbeUsesBtree(v, i);
  86313. }
  86314. }
  86315. sqlite3VdbeAddOp2(v, OP_AutoCommit, 0, 0);
  86316. }
  86317. /*
  86318. ** Commit a transaction
  86319. */
  86320. SQLITE_PRIVATE void sqlite3CommitTransaction(Parse *pParse){
  86321. Vdbe *v;
  86322. assert( pParse!=0 );
  86323. assert( pParse->db!=0 );
  86324. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "COMMIT", 0, 0) ){
  86325. return;
  86326. }
  86327. v = sqlite3GetVdbe(pParse);
  86328. if( v ){
  86329. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 0);
  86330. }
  86331. }
  86332. /*
  86333. ** Rollback a transaction
  86334. */
  86335. SQLITE_PRIVATE void sqlite3RollbackTransaction(Parse *pParse){
  86336. Vdbe *v;
  86337. assert( pParse!=0 );
  86338. assert( pParse->db!=0 );
  86339. if( sqlite3AuthCheck(pParse, SQLITE_TRANSACTION, "ROLLBACK", 0, 0) ){
  86340. return;
  86341. }
  86342. v = sqlite3GetVdbe(pParse);
  86343. if( v ){
  86344. sqlite3VdbeAddOp2(v, OP_AutoCommit, 1, 1);
  86345. }
  86346. }
  86347. /*
  86348. ** This function is called by the parser when it parses a command to create,
  86349. ** release or rollback an SQL savepoint.
  86350. */
  86351. SQLITE_PRIVATE void sqlite3Savepoint(Parse *pParse, int op, Token *pName){
  86352. char *zName = sqlite3NameFromToken(pParse->db, pName);
  86353. if( zName ){
  86354. Vdbe *v = sqlite3GetVdbe(pParse);
  86355. #ifndef SQLITE_OMIT_AUTHORIZATION
  86356. static const char * const az[] = { "BEGIN", "RELEASE", "ROLLBACK" };
  86357. assert( !SAVEPOINT_BEGIN && SAVEPOINT_RELEASE==1 && SAVEPOINT_ROLLBACK==2 );
  86358. #endif
  86359. if( !v || sqlite3AuthCheck(pParse, SQLITE_SAVEPOINT, az[op], zName, 0) ){
  86360. sqlite3DbFree(pParse->db, zName);
  86361. return;
  86362. }
  86363. sqlite3VdbeAddOp4(v, OP_Savepoint, op, 0, 0, zName, P4_DYNAMIC);
  86364. }
  86365. }
  86366. /*
  86367. ** Make sure the TEMP database is open and available for use. Return
  86368. ** the number of errors. Leave any error messages in the pParse structure.
  86369. */
  86370. SQLITE_PRIVATE int sqlite3OpenTempDatabase(Parse *pParse){
  86371. sqlite3 *db = pParse->db;
  86372. if( db->aDb[1].pBt==0 && !pParse->explain ){
  86373. int rc;
  86374. Btree *pBt;
  86375. static const int flags =
  86376. SQLITE_OPEN_READWRITE |
  86377. SQLITE_OPEN_CREATE |
  86378. SQLITE_OPEN_EXCLUSIVE |
  86379. SQLITE_OPEN_DELETEONCLOSE |
  86380. SQLITE_OPEN_TEMP_DB;
  86381. rc = sqlite3BtreeOpen(db->pVfs, 0, db, &pBt, 0, flags);
  86382. if( rc!=SQLITE_OK ){
  86383. sqlite3ErrorMsg(pParse, "unable to open a temporary database "
  86384. "file for storing temporary tables");
  86385. pParse->rc = rc;
  86386. return 1;
  86387. }
  86388. db->aDb[1].pBt = pBt;
  86389. assert( db->aDb[1].pSchema );
  86390. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize, -1, 0) ){
  86391. db->mallocFailed = 1;
  86392. return 1;
  86393. }
  86394. }
  86395. return 0;
  86396. }
  86397. /*
  86398. ** Record the fact that the schema cookie will need to be verified
  86399. ** for database iDb. The code to actually verify the schema cookie
  86400. ** will occur at the end of the top-level VDBE and will be generated
  86401. ** later, by sqlite3FinishCoding().
  86402. */
  86403. SQLITE_PRIVATE void sqlite3CodeVerifySchema(Parse *pParse, int iDb){
  86404. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86405. sqlite3 *db = pToplevel->db;
  86406. assert( iDb>=0 && iDb<db->nDb );
  86407. assert( db->aDb[iDb].pBt!=0 || iDb==1 );
  86408. assert( iDb<SQLITE_MAX_ATTACHED+2 );
  86409. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  86410. if( DbMaskTest(pToplevel->cookieMask, iDb)==0 ){
  86411. DbMaskSet(pToplevel->cookieMask, iDb);
  86412. pToplevel->cookieValue[iDb] = db->aDb[iDb].pSchema->schema_cookie;
  86413. if( !OMIT_TEMPDB && iDb==1 ){
  86414. sqlite3OpenTempDatabase(pToplevel);
  86415. }
  86416. }
  86417. }
  86418. /*
  86419. ** If argument zDb is NULL, then call sqlite3CodeVerifySchema() for each
  86420. ** attached database. Otherwise, invoke it for the database named zDb only.
  86421. */
  86422. SQLITE_PRIVATE void sqlite3CodeVerifyNamedSchema(Parse *pParse, const char *zDb){
  86423. sqlite3 *db = pParse->db;
  86424. int i;
  86425. for(i=0; i<db->nDb; i++){
  86426. Db *pDb = &db->aDb[i];
  86427. if( pDb->pBt && (!zDb || 0==sqlite3StrICmp(zDb, pDb->zName)) ){
  86428. sqlite3CodeVerifySchema(pParse, i);
  86429. }
  86430. }
  86431. }
  86432. /*
  86433. ** Generate VDBE code that prepares for doing an operation that
  86434. ** might change the database.
  86435. **
  86436. ** This routine starts a new transaction if we are not already within
  86437. ** a transaction. If we are already within a transaction, then a checkpoint
  86438. ** is set if the setStatement parameter is true. A checkpoint should
  86439. ** be set for operations that might fail (due to a constraint) part of
  86440. ** the way through and which will need to undo some writes without having to
  86441. ** rollback the whole transaction. For operations where all constraints
  86442. ** can be checked before any changes are made to the database, it is never
  86443. ** necessary to undo a write and the checkpoint should not be set.
  86444. */
  86445. SQLITE_PRIVATE void sqlite3BeginWriteOperation(Parse *pParse, int setStatement, int iDb){
  86446. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86447. sqlite3CodeVerifySchema(pParse, iDb);
  86448. DbMaskSet(pToplevel->writeMask, iDb);
  86449. pToplevel->isMultiWrite |= setStatement;
  86450. }
  86451. /*
  86452. ** Indicate that the statement currently under construction might write
  86453. ** more than one entry (example: deleting one row then inserting another,
  86454. ** inserting multiple rows in a table, or inserting a row and index entries.)
  86455. ** If an abort occurs after some of these writes have completed, then it will
  86456. ** be necessary to undo the completed writes.
  86457. */
  86458. SQLITE_PRIVATE void sqlite3MultiWrite(Parse *pParse){
  86459. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86460. pToplevel->isMultiWrite = 1;
  86461. }
  86462. /*
  86463. ** The code generator calls this routine if is discovers that it is
  86464. ** possible to abort a statement prior to completion. In order to
  86465. ** perform this abort without corrupting the database, we need to make
  86466. ** sure that the statement is protected by a statement transaction.
  86467. **
  86468. ** Technically, we only need to set the mayAbort flag if the
  86469. ** isMultiWrite flag was previously set. There is a time dependency
  86470. ** such that the abort must occur after the multiwrite. This makes
  86471. ** some statements involving the REPLACE conflict resolution algorithm
  86472. ** go a little faster. But taking advantage of this time dependency
  86473. ** makes it more difficult to prove that the code is correct (in
  86474. ** particular, it prevents us from writing an effective
  86475. ** implementation of sqlite3AssertMayAbort()) and so we have chosen
  86476. ** to take the safe route and skip the optimization.
  86477. */
  86478. SQLITE_PRIVATE void sqlite3MayAbort(Parse *pParse){
  86479. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  86480. pToplevel->mayAbort = 1;
  86481. }
  86482. /*
  86483. ** Code an OP_Halt that causes the vdbe to return an SQLITE_CONSTRAINT
  86484. ** error. The onError parameter determines which (if any) of the statement
  86485. ** and/or current transaction is rolled back.
  86486. */
  86487. SQLITE_PRIVATE void sqlite3HaltConstraint(
  86488. Parse *pParse, /* Parsing context */
  86489. int errCode, /* extended error code */
  86490. int onError, /* Constraint type */
  86491. char *p4, /* Error message */
  86492. i8 p4type, /* P4_STATIC or P4_TRANSIENT */
  86493. u8 p5Errmsg /* P5_ErrMsg type */
  86494. ){
  86495. Vdbe *v = sqlite3GetVdbe(pParse);
  86496. assert( (errCode&0xff)==SQLITE_CONSTRAINT );
  86497. if( onError==OE_Abort ){
  86498. sqlite3MayAbort(pParse);
  86499. }
  86500. sqlite3VdbeAddOp4(v, OP_Halt, errCode, onError, 0, p4, p4type);
  86501. if( p5Errmsg ) sqlite3VdbeChangeP5(v, p5Errmsg);
  86502. }
  86503. /*
  86504. ** Code an OP_Halt due to UNIQUE or PRIMARY KEY constraint violation.
  86505. */
  86506. SQLITE_PRIVATE void sqlite3UniqueConstraint(
  86507. Parse *pParse, /* Parsing context */
  86508. int onError, /* Constraint type */
  86509. Index *pIdx /* The index that triggers the constraint */
  86510. ){
  86511. char *zErr;
  86512. int j;
  86513. StrAccum errMsg;
  86514. Table *pTab = pIdx->pTable;
  86515. sqlite3StrAccumInit(&errMsg, 0, 0, 200);
  86516. errMsg.db = pParse->db;
  86517. for(j=0; j<pIdx->nKeyCol; j++){
  86518. char *zCol = pTab->aCol[pIdx->aiColumn[j]].zName;
  86519. if( j ) sqlite3StrAccumAppend(&errMsg, ", ", 2);
  86520. sqlite3StrAccumAppendAll(&errMsg, pTab->zName);
  86521. sqlite3StrAccumAppend(&errMsg, ".", 1);
  86522. sqlite3StrAccumAppendAll(&errMsg, zCol);
  86523. }
  86524. zErr = sqlite3StrAccumFinish(&errMsg);
  86525. sqlite3HaltConstraint(pParse,
  86526. IsPrimaryKeyIndex(pIdx) ? SQLITE_CONSTRAINT_PRIMARYKEY
  86527. : SQLITE_CONSTRAINT_UNIQUE,
  86528. onError, zErr, P4_DYNAMIC, P5_ConstraintUnique);
  86529. }
  86530. /*
  86531. ** Code an OP_Halt due to non-unique rowid.
  86532. */
  86533. SQLITE_PRIVATE void sqlite3RowidConstraint(
  86534. Parse *pParse, /* Parsing context */
  86535. int onError, /* Conflict resolution algorithm */
  86536. Table *pTab /* The table with the non-unique rowid */
  86537. ){
  86538. char *zMsg;
  86539. int rc;
  86540. if( pTab->iPKey>=0 ){
  86541. zMsg = sqlite3MPrintf(pParse->db, "%s.%s", pTab->zName,
  86542. pTab->aCol[pTab->iPKey].zName);
  86543. rc = SQLITE_CONSTRAINT_PRIMARYKEY;
  86544. }else{
  86545. zMsg = sqlite3MPrintf(pParse->db, "%s.rowid", pTab->zName);
  86546. rc = SQLITE_CONSTRAINT_ROWID;
  86547. }
  86548. sqlite3HaltConstraint(pParse, rc, onError, zMsg, P4_DYNAMIC,
  86549. P5_ConstraintUnique);
  86550. }
  86551. /*
  86552. ** Check to see if pIndex uses the collating sequence pColl. Return
  86553. ** true if it does and false if it does not.
  86554. */
  86555. #ifndef SQLITE_OMIT_REINDEX
  86556. static int collationMatch(const char *zColl, Index *pIndex){
  86557. int i;
  86558. assert( zColl!=0 );
  86559. for(i=0; i<pIndex->nColumn; i++){
  86560. const char *z = pIndex->azColl[i];
  86561. assert( z!=0 || pIndex->aiColumn[i]<0 );
  86562. if( pIndex->aiColumn[i]>=0 && 0==sqlite3StrICmp(z, zColl) ){
  86563. return 1;
  86564. }
  86565. }
  86566. return 0;
  86567. }
  86568. #endif
  86569. /*
  86570. ** Recompute all indices of pTab that use the collating sequence pColl.
  86571. ** If pColl==0 then recompute all indices of pTab.
  86572. */
  86573. #ifndef SQLITE_OMIT_REINDEX
  86574. static void reindexTable(Parse *pParse, Table *pTab, char const *zColl){
  86575. Index *pIndex; /* An index associated with pTab */
  86576. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  86577. if( zColl==0 || collationMatch(zColl, pIndex) ){
  86578. int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  86579. sqlite3BeginWriteOperation(pParse, 0, iDb);
  86580. sqlite3RefillIndex(pParse, pIndex, -1);
  86581. }
  86582. }
  86583. }
  86584. #endif
  86585. /*
  86586. ** Recompute all indices of all tables in all databases where the
  86587. ** indices use the collating sequence pColl. If pColl==0 then recompute
  86588. ** all indices everywhere.
  86589. */
  86590. #ifndef SQLITE_OMIT_REINDEX
  86591. static void reindexDatabases(Parse *pParse, char const *zColl){
  86592. Db *pDb; /* A single database */
  86593. int iDb; /* The database index number */
  86594. sqlite3 *db = pParse->db; /* The database connection */
  86595. HashElem *k; /* For looping over tables in pDb */
  86596. Table *pTab; /* A table in the database */
  86597. assert( sqlite3BtreeHoldsAllMutexes(db) ); /* Needed for schema access */
  86598. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  86599. assert( pDb!=0 );
  86600. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  86601. pTab = (Table*)sqliteHashData(k);
  86602. reindexTable(pParse, pTab, zColl);
  86603. }
  86604. }
  86605. }
  86606. #endif
  86607. /*
  86608. ** Generate code for the REINDEX command.
  86609. **
  86610. ** REINDEX -- 1
  86611. ** REINDEX <collation> -- 2
  86612. ** REINDEX ?<database>.?<tablename> -- 3
  86613. ** REINDEX ?<database>.?<indexname> -- 4
  86614. **
  86615. ** Form 1 causes all indices in all attached databases to be rebuilt.
  86616. ** Form 2 rebuilds all indices in all databases that use the named
  86617. ** collating function. Forms 3 and 4 rebuild the named index or all
  86618. ** indices associated with the named table.
  86619. */
  86620. #ifndef SQLITE_OMIT_REINDEX
  86621. SQLITE_PRIVATE void sqlite3Reindex(Parse *pParse, Token *pName1, Token *pName2){
  86622. CollSeq *pColl; /* Collating sequence to be reindexed, or NULL */
  86623. char *z; /* Name of a table or index */
  86624. const char *zDb; /* Name of the database */
  86625. Table *pTab; /* A table in the database */
  86626. Index *pIndex; /* An index associated with pTab */
  86627. int iDb; /* The database index number */
  86628. sqlite3 *db = pParse->db; /* The database connection */
  86629. Token *pObjName; /* Name of the table or index to be reindexed */
  86630. /* Read the database schema. If an error occurs, leave an error message
  86631. ** and code in pParse and return NULL. */
  86632. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  86633. return;
  86634. }
  86635. if( pName1==0 ){
  86636. reindexDatabases(pParse, 0);
  86637. return;
  86638. }else if( NEVER(pName2==0) || pName2->z==0 ){
  86639. char *zColl;
  86640. assert( pName1->z );
  86641. zColl = sqlite3NameFromToken(pParse->db, pName1);
  86642. if( !zColl ) return;
  86643. pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
  86644. if( pColl ){
  86645. reindexDatabases(pParse, zColl);
  86646. sqlite3DbFree(db, zColl);
  86647. return;
  86648. }
  86649. sqlite3DbFree(db, zColl);
  86650. }
  86651. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pObjName);
  86652. if( iDb<0 ) return;
  86653. z = sqlite3NameFromToken(db, pObjName);
  86654. if( z==0 ) return;
  86655. zDb = db->aDb[iDb].zName;
  86656. pTab = sqlite3FindTable(db, z, zDb);
  86657. if( pTab ){
  86658. reindexTable(pParse, pTab, 0);
  86659. sqlite3DbFree(db, z);
  86660. return;
  86661. }
  86662. pIndex = sqlite3FindIndex(db, z, zDb);
  86663. sqlite3DbFree(db, z);
  86664. if( pIndex ){
  86665. sqlite3BeginWriteOperation(pParse, 0, iDb);
  86666. sqlite3RefillIndex(pParse, pIndex, -1);
  86667. return;
  86668. }
  86669. sqlite3ErrorMsg(pParse, "unable to identify the object to be reindexed");
  86670. }
  86671. #endif
  86672. /*
  86673. ** Return a KeyInfo structure that is appropriate for the given Index.
  86674. **
  86675. ** The KeyInfo structure for an index is cached in the Index object.
  86676. ** So there might be multiple references to the returned pointer. The
  86677. ** caller should not try to modify the KeyInfo object.
  86678. **
  86679. ** The caller should invoke sqlite3KeyInfoUnref() on the returned object
  86680. ** when it has finished using it.
  86681. */
  86682. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoOfIndex(Parse *pParse, Index *pIdx){
  86683. if( pParse->nErr ) return 0;
  86684. #ifndef SQLITE_OMIT_SHARED_CACHE
  86685. if( pIdx->pKeyInfo && pIdx->pKeyInfo->db!=pParse->db ){
  86686. sqlite3KeyInfoUnref(pIdx->pKeyInfo);
  86687. pIdx->pKeyInfo = 0;
  86688. }
  86689. #endif
  86690. if( pIdx->pKeyInfo==0 ){
  86691. int i;
  86692. int nCol = pIdx->nColumn;
  86693. int nKey = pIdx->nKeyCol;
  86694. KeyInfo *pKey;
  86695. if( pIdx->uniqNotNull ){
  86696. pKey = sqlite3KeyInfoAlloc(pParse->db, nKey, nCol-nKey);
  86697. }else{
  86698. pKey = sqlite3KeyInfoAlloc(pParse->db, nCol, 0);
  86699. }
  86700. if( pKey ){
  86701. assert( sqlite3KeyInfoIsWriteable(pKey) );
  86702. for(i=0; i<nCol; i++){
  86703. char *zColl = pIdx->azColl[i];
  86704. assert( zColl!=0 );
  86705. pKey->aColl[i] = strcmp(zColl,"BINARY")==0 ? 0 :
  86706. sqlite3LocateCollSeq(pParse, zColl);
  86707. pKey->aSortOrder[i] = pIdx->aSortOrder[i];
  86708. }
  86709. if( pParse->nErr ){
  86710. sqlite3KeyInfoUnref(pKey);
  86711. }else{
  86712. pIdx->pKeyInfo = pKey;
  86713. }
  86714. }
  86715. }
  86716. return sqlite3KeyInfoRef(pIdx->pKeyInfo);
  86717. }
  86718. #ifndef SQLITE_OMIT_CTE
  86719. /*
  86720. ** This routine is invoked once per CTE by the parser while parsing a
  86721. ** WITH clause.
  86722. */
  86723. SQLITE_PRIVATE With *sqlite3WithAdd(
  86724. Parse *pParse, /* Parsing context */
  86725. With *pWith, /* Existing WITH clause, or NULL */
  86726. Token *pName, /* Name of the common-table */
  86727. ExprList *pArglist, /* Optional column name list for the table */
  86728. Select *pQuery /* Query used to initialize the table */
  86729. ){
  86730. sqlite3 *db = pParse->db;
  86731. With *pNew;
  86732. char *zName;
  86733. /* Check that the CTE name is unique within this WITH clause. If
  86734. ** not, store an error in the Parse structure. */
  86735. zName = sqlite3NameFromToken(pParse->db, pName);
  86736. if( zName && pWith ){
  86737. int i;
  86738. for(i=0; i<pWith->nCte; i++){
  86739. if( sqlite3StrICmp(zName, pWith->a[i].zName)==0 ){
  86740. sqlite3ErrorMsg(pParse, "duplicate WITH table name: %s", zName);
  86741. }
  86742. }
  86743. }
  86744. if( pWith ){
  86745. int nByte = sizeof(*pWith) + (sizeof(pWith->a[1]) * pWith->nCte);
  86746. pNew = sqlite3DbRealloc(db, pWith, nByte);
  86747. }else{
  86748. pNew = sqlite3DbMallocZero(db, sizeof(*pWith));
  86749. }
  86750. assert( zName!=0 || pNew==0 );
  86751. assert( db->mallocFailed==0 || pNew==0 );
  86752. if( pNew==0 ){
  86753. sqlite3ExprListDelete(db, pArglist);
  86754. sqlite3SelectDelete(db, pQuery);
  86755. sqlite3DbFree(db, zName);
  86756. pNew = pWith;
  86757. }else{
  86758. pNew->a[pNew->nCte].pSelect = pQuery;
  86759. pNew->a[pNew->nCte].pCols = pArglist;
  86760. pNew->a[pNew->nCte].zName = zName;
  86761. pNew->a[pNew->nCte].zErr = 0;
  86762. pNew->nCte++;
  86763. }
  86764. return pNew;
  86765. }
  86766. /*
  86767. ** Free the contents of the With object passed as the second argument.
  86768. */
  86769. SQLITE_PRIVATE void sqlite3WithDelete(sqlite3 *db, With *pWith){
  86770. if( pWith ){
  86771. int i;
  86772. for(i=0; i<pWith->nCte; i++){
  86773. struct Cte *pCte = &pWith->a[i];
  86774. sqlite3ExprListDelete(db, pCte->pCols);
  86775. sqlite3SelectDelete(db, pCte->pSelect);
  86776. sqlite3DbFree(db, pCte->zName);
  86777. }
  86778. sqlite3DbFree(db, pWith);
  86779. }
  86780. }
  86781. #endif /* !defined(SQLITE_OMIT_CTE) */
  86782. /************** End of build.c ***********************************************/
  86783. /************** Begin file callback.c ****************************************/
  86784. /*
  86785. ** 2005 May 23
  86786. **
  86787. ** The author disclaims copyright to this source code. In place of
  86788. ** a legal notice, here is a blessing:
  86789. **
  86790. ** May you do good and not evil.
  86791. ** May you find forgiveness for yourself and forgive others.
  86792. ** May you share freely, never taking more than you give.
  86793. **
  86794. *************************************************************************
  86795. **
  86796. ** This file contains functions used to access the internal hash tables
  86797. ** of user defined functions and collation sequences.
  86798. */
  86799. /*
  86800. ** Invoke the 'collation needed' callback to request a collation sequence
  86801. ** in the encoding enc of name zName, length nName.
  86802. */
  86803. static void callCollNeeded(sqlite3 *db, int enc, const char *zName){
  86804. assert( !db->xCollNeeded || !db->xCollNeeded16 );
  86805. if( db->xCollNeeded ){
  86806. char *zExternal = sqlite3DbStrDup(db, zName);
  86807. if( !zExternal ) return;
  86808. db->xCollNeeded(db->pCollNeededArg, db, enc, zExternal);
  86809. sqlite3DbFree(db, zExternal);
  86810. }
  86811. #ifndef SQLITE_OMIT_UTF16
  86812. if( db->xCollNeeded16 ){
  86813. char const *zExternal;
  86814. sqlite3_value *pTmp = sqlite3ValueNew(db);
  86815. sqlite3ValueSetStr(pTmp, -1, zName, SQLITE_UTF8, SQLITE_STATIC);
  86816. zExternal = sqlite3ValueText(pTmp, SQLITE_UTF16NATIVE);
  86817. if( zExternal ){
  86818. db->xCollNeeded16(db->pCollNeededArg, db, (int)ENC(db), zExternal);
  86819. }
  86820. sqlite3ValueFree(pTmp);
  86821. }
  86822. #endif
  86823. }
  86824. /*
  86825. ** This routine is called if the collation factory fails to deliver a
  86826. ** collation function in the best encoding but there may be other versions
  86827. ** of this collation function (for other text encodings) available. Use one
  86828. ** of these instead if they exist. Avoid a UTF-8 <-> UTF-16 conversion if
  86829. ** possible.
  86830. */
  86831. static int synthCollSeq(sqlite3 *db, CollSeq *pColl){
  86832. CollSeq *pColl2;
  86833. char *z = pColl->zName;
  86834. int i;
  86835. static const u8 aEnc[] = { SQLITE_UTF16BE, SQLITE_UTF16LE, SQLITE_UTF8 };
  86836. for(i=0; i<3; i++){
  86837. pColl2 = sqlite3FindCollSeq(db, aEnc[i], z, 0);
  86838. if( pColl2->xCmp!=0 ){
  86839. memcpy(pColl, pColl2, sizeof(CollSeq));
  86840. pColl->xDel = 0; /* Do not copy the destructor */
  86841. return SQLITE_OK;
  86842. }
  86843. }
  86844. return SQLITE_ERROR;
  86845. }
  86846. /*
  86847. ** This function is responsible for invoking the collation factory callback
  86848. ** or substituting a collation sequence of a different encoding when the
  86849. ** requested collation sequence is not available in the desired encoding.
  86850. **
  86851. ** If it is not NULL, then pColl must point to the database native encoding
  86852. ** collation sequence with name zName, length nName.
  86853. **
  86854. ** The return value is either the collation sequence to be used in database
  86855. ** db for collation type name zName, length nName, or NULL, if no collation
  86856. ** sequence can be found. If no collation is found, leave an error message.
  86857. **
  86858. ** See also: sqlite3LocateCollSeq(), sqlite3FindCollSeq()
  86859. */
  86860. SQLITE_PRIVATE CollSeq *sqlite3GetCollSeq(
  86861. Parse *pParse, /* Parsing context */
  86862. u8 enc, /* The desired encoding for the collating sequence */
  86863. CollSeq *pColl, /* Collating sequence with native encoding, or NULL */
  86864. const char *zName /* Collating sequence name */
  86865. ){
  86866. CollSeq *p;
  86867. sqlite3 *db = pParse->db;
  86868. p = pColl;
  86869. if( !p ){
  86870. p = sqlite3FindCollSeq(db, enc, zName, 0);
  86871. }
  86872. if( !p || !p->xCmp ){
  86873. /* No collation sequence of this type for this encoding is registered.
  86874. ** Call the collation factory to see if it can supply us with one.
  86875. */
  86876. callCollNeeded(db, enc, zName);
  86877. p = sqlite3FindCollSeq(db, enc, zName, 0);
  86878. }
  86879. if( p && !p->xCmp && synthCollSeq(db, p) ){
  86880. p = 0;
  86881. }
  86882. assert( !p || p->xCmp );
  86883. if( p==0 ){
  86884. sqlite3ErrorMsg(pParse, "no such collation sequence: %s", zName);
  86885. }
  86886. return p;
  86887. }
  86888. /*
  86889. ** This routine is called on a collation sequence before it is used to
  86890. ** check that it is defined. An undefined collation sequence exists when
  86891. ** a database is loaded that contains references to collation sequences
  86892. ** that have not been defined by sqlite3_create_collation() etc.
  86893. **
  86894. ** If required, this routine calls the 'collation needed' callback to
  86895. ** request a definition of the collating sequence. If this doesn't work,
  86896. ** an equivalent collating sequence that uses a text encoding different
  86897. ** from the main database is substituted, if one is available.
  86898. */
  86899. SQLITE_PRIVATE int sqlite3CheckCollSeq(Parse *pParse, CollSeq *pColl){
  86900. if( pColl ){
  86901. const char *zName = pColl->zName;
  86902. sqlite3 *db = pParse->db;
  86903. CollSeq *p = sqlite3GetCollSeq(pParse, ENC(db), pColl, zName);
  86904. if( !p ){
  86905. return SQLITE_ERROR;
  86906. }
  86907. assert( p==pColl );
  86908. }
  86909. return SQLITE_OK;
  86910. }
  86911. /*
  86912. ** Locate and return an entry from the db.aCollSeq hash table. If the entry
  86913. ** specified by zName and nName is not found and parameter 'create' is
  86914. ** true, then create a new entry. Otherwise return NULL.
  86915. **
  86916. ** Each pointer stored in the sqlite3.aCollSeq hash table contains an
  86917. ** array of three CollSeq structures. The first is the collation sequence
  86918. ** preferred for UTF-8, the second UTF-16le, and the third UTF-16be.
  86919. **
  86920. ** Stored immediately after the three collation sequences is a copy of
  86921. ** the collation sequence name. A pointer to this string is stored in
  86922. ** each collation sequence structure.
  86923. */
  86924. static CollSeq *findCollSeqEntry(
  86925. sqlite3 *db, /* Database connection */
  86926. const char *zName, /* Name of the collating sequence */
  86927. int create /* Create a new entry if true */
  86928. ){
  86929. CollSeq *pColl;
  86930. pColl = sqlite3HashFind(&db->aCollSeq, zName);
  86931. if( 0==pColl && create ){
  86932. int nName = sqlite3Strlen30(zName);
  86933. pColl = sqlite3DbMallocZero(db, 3*sizeof(*pColl) + nName + 1);
  86934. if( pColl ){
  86935. CollSeq *pDel = 0;
  86936. pColl[0].zName = (char*)&pColl[3];
  86937. pColl[0].enc = SQLITE_UTF8;
  86938. pColl[1].zName = (char*)&pColl[3];
  86939. pColl[1].enc = SQLITE_UTF16LE;
  86940. pColl[2].zName = (char*)&pColl[3];
  86941. pColl[2].enc = SQLITE_UTF16BE;
  86942. memcpy(pColl[0].zName, zName, nName);
  86943. pColl[0].zName[nName] = 0;
  86944. pDel = sqlite3HashInsert(&db->aCollSeq, pColl[0].zName, pColl);
  86945. /* If a malloc() failure occurred in sqlite3HashInsert(), it will
  86946. ** return the pColl pointer to be deleted (because it wasn't added
  86947. ** to the hash table).
  86948. */
  86949. assert( pDel==0 || pDel==pColl );
  86950. if( pDel!=0 ){
  86951. db->mallocFailed = 1;
  86952. sqlite3DbFree(db, pDel);
  86953. pColl = 0;
  86954. }
  86955. }
  86956. }
  86957. return pColl;
  86958. }
  86959. /*
  86960. ** Parameter zName points to a UTF-8 encoded string nName bytes long.
  86961. ** Return the CollSeq* pointer for the collation sequence named zName
  86962. ** for the encoding 'enc' from the database 'db'.
  86963. **
  86964. ** If the entry specified is not found and 'create' is true, then create a
  86965. ** new entry. Otherwise return NULL.
  86966. **
  86967. ** A separate function sqlite3LocateCollSeq() is a wrapper around
  86968. ** this routine. sqlite3LocateCollSeq() invokes the collation factory
  86969. ** if necessary and generates an error message if the collating sequence
  86970. ** cannot be found.
  86971. **
  86972. ** See also: sqlite3LocateCollSeq(), sqlite3GetCollSeq()
  86973. */
  86974. SQLITE_PRIVATE CollSeq *sqlite3FindCollSeq(
  86975. sqlite3 *db,
  86976. u8 enc,
  86977. const char *zName,
  86978. int create
  86979. ){
  86980. CollSeq *pColl;
  86981. if( zName ){
  86982. pColl = findCollSeqEntry(db, zName, create);
  86983. }else{
  86984. pColl = db->pDfltColl;
  86985. }
  86986. assert( SQLITE_UTF8==1 && SQLITE_UTF16LE==2 && SQLITE_UTF16BE==3 );
  86987. assert( enc>=SQLITE_UTF8 && enc<=SQLITE_UTF16BE );
  86988. if( pColl ) pColl += enc-1;
  86989. return pColl;
  86990. }
  86991. /* During the search for the best function definition, this procedure
  86992. ** is called to test how well the function passed as the first argument
  86993. ** matches the request for a function with nArg arguments in a system
  86994. ** that uses encoding enc. The value returned indicates how well the
  86995. ** request is matched. A higher value indicates a better match.
  86996. **
  86997. ** If nArg is -1 that means to only return a match (non-zero) if p->nArg
  86998. ** is also -1. In other words, we are searching for a function that
  86999. ** takes a variable number of arguments.
  87000. **
  87001. ** If nArg is -2 that means that we are searching for any function
  87002. ** regardless of the number of arguments it uses, so return a positive
  87003. ** match score for any
  87004. **
  87005. ** The returned value is always between 0 and 6, as follows:
  87006. **
  87007. ** 0: Not a match.
  87008. ** 1: UTF8/16 conversion required and function takes any number of arguments.
  87009. ** 2: UTF16 byte order change required and function takes any number of args.
  87010. ** 3: encoding matches and function takes any number of arguments
  87011. ** 4: UTF8/16 conversion required - argument count matches exactly
  87012. ** 5: UTF16 byte order conversion required - argument count matches exactly
  87013. ** 6: Perfect match: encoding and argument count match exactly.
  87014. **
  87015. ** If nArg==(-2) then any function with a non-null xStep or xFunc is
  87016. ** a perfect match and any function with both xStep and xFunc NULL is
  87017. ** a non-match.
  87018. */
  87019. #define FUNC_PERFECT_MATCH 6 /* The score for a perfect match */
  87020. static int matchQuality(
  87021. FuncDef *p, /* The function we are evaluating for match quality */
  87022. int nArg, /* Desired number of arguments. (-1)==any */
  87023. u8 enc /* Desired text encoding */
  87024. ){
  87025. int match;
  87026. /* nArg of -2 is a special case */
  87027. if( nArg==(-2) ) return (p->xFunc==0 && p->xStep==0) ? 0 : FUNC_PERFECT_MATCH;
  87028. /* Wrong number of arguments means "no match" */
  87029. if( p->nArg!=nArg && p->nArg>=0 ) return 0;
  87030. /* Give a better score to a function with a specific number of arguments
  87031. ** than to function that accepts any number of arguments. */
  87032. if( p->nArg==nArg ){
  87033. match = 4;
  87034. }else{
  87035. match = 1;
  87036. }
  87037. /* Bonus points if the text encoding matches */
  87038. if( enc==(p->funcFlags & SQLITE_FUNC_ENCMASK) ){
  87039. match += 2; /* Exact encoding match */
  87040. }else if( (enc & p->funcFlags & 2)!=0 ){
  87041. match += 1; /* Both are UTF16, but with different byte orders */
  87042. }
  87043. return match;
  87044. }
  87045. /*
  87046. ** Search a FuncDefHash for a function with the given name. Return
  87047. ** a pointer to the matching FuncDef if found, or 0 if there is no match.
  87048. */
  87049. static FuncDef *functionSearch(
  87050. FuncDefHash *pHash, /* Hash table to search */
  87051. int h, /* Hash of the name */
  87052. const char *zFunc, /* Name of function */
  87053. int nFunc /* Number of bytes in zFunc */
  87054. ){
  87055. FuncDef *p;
  87056. for(p=pHash->a[h]; p; p=p->pHash){
  87057. if( sqlite3StrNICmp(p->zName, zFunc, nFunc)==0 && p->zName[nFunc]==0 ){
  87058. return p;
  87059. }
  87060. }
  87061. return 0;
  87062. }
  87063. /*
  87064. ** Insert a new FuncDef into a FuncDefHash hash table.
  87065. */
  87066. SQLITE_PRIVATE void sqlite3FuncDefInsert(
  87067. FuncDefHash *pHash, /* The hash table into which to insert */
  87068. FuncDef *pDef /* The function definition to insert */
  87069. ){
  87070. FuncDef *pOther;
  87071. int nName = sqlite3Strlen30(pDef->zName);
  87072. u8 c1 = (u8)pDef->zName[0];
  87073. int h = (sqlite3UpperToLower[c1] + nName) % ArraySize(pHash->a);
  87074. pOther = functionSearch(pHash, h, pDef->zName, nName);
  87075. if( pOther ){
  87076. assert( pOther!=pDef && pOther->pNext!=pDef );
  87077. pDef->pNext = pOther->pNext;
  87078. pOther->pNext = pDef;
  87079. }else{
  87080. pDef->pNext = 0;
  87081. pDef->pHash = pHash->a[h];
  87082. pHash->a[h] = pDef;
  87083. }
  87084. }
  87085. /*
  87086. ** Locate a user function given a name, a number of arguments and a flag
  87087. ** indicating whether the function prefers UTF-16 over UTF-8. Return a
  87088. ** pointer to the FuncDef structure that defines that function, or return
  87089. ** NULL if the function does not exist.
  87090. **
  87091. ** If the createFlag argument is true, then a new (blank) FuncDef
  87092. ** structure is created and liked into the "db" structure if a
  87093. ** no matching function previously existed.
  87094. **
  87095. ** If nArg is -2, then the first valid function found is returned. A
  87096. ** function is valid if either xFunc or xStep is non-zero. The nArg==(-2)
  87097. ** case is used to see if zName is a valid function name for some number
  87098. ** of arguments. If nArg is -2, then createFlag must be 0.
  87099. **
  87100. ** If createFlag is false, then a function with the required name and
  87101. ** number of arguments may be returned even if the eTextRep flag does not
  87102. ** match that requested.
  87103. */
  87104. SQLITE_PRIVATE FuncDef *sqlite3FindFunction(
  87105. sqlite3 *db, /* An open database */
  87106. const char *zName, /* Name of the function. Not null-terminated */
  87107. int nName, /* Number of characters in the name */
  87108. int nArg, /* Number of arguments. -1 means any number */
  87109. u8 enc, /* Preferred text encoding */
  87110. u8 createFlag /* Create new entry if true and does not otherwise exist */
  87111. ){
  87112. FuncDef *p; /* Iterator variable */
  87113. FuncDef *pBest = 0; /* Best match found so far */
  87114. int bestScore = 0; /* Score of best match */
  87115. int h; /* Hash value */
  87116. assert( nArg>=(-2) );
  87117. assert( nArg>=(-1) || createFlag==0 );
  87118. h = (sqlite3UpperToLower[(u8)zName[0]] + nName) % ArraySize(db->aFunc.a);
  87119. /* First search for a match amongst the application-defined functions.
  87120. */
  87121. p = functionSearch(&db->aFunc, h, zName, nName);
  87122. while( p ){
  87123. int score = matchQuality(p, nArg, enc);
  87124. if( score>bestScore ){
  87125. pBest = p;
  87126. bestScore = score;
  87127. }
  87128. p = p->pNext;
  87129. }
  87130. /* If no match is found, search the built-in functions.
  87131. **
  87132. ** If the SQLITE_PreferBuiltin flag is set, then search the built-in
  87133. ** functions even if a prior app-defined function was found. And give
  87134. ** priority to built-in functions.
  87135. **
  87136. ** Except, if createFlag is true, that means that we are trying to
  87137. ** install a new function. Whatever FuncDef structure is returned it will
  87138. ** have fields overwritten with new information appropriate for the
  87139. ** new function. But the FuncDefs for built-in functions are read-only.
  87140. ** So we must not search for built-ins when creating a new function.
  87141. */
  87142. if( !createFlag && (pBest==0 || (db->flags & SQLITE_PreferBuiltin)!=0) ){
  87143. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  87144. bestScore = 0;
  87145. p = functionSearch(pHash, h, zName, nName);
  87146. while( p ){
  87147. int score = matchQuality(p, nArg, enc);
  87148. if( score>bestScore ){
  87149. pBest = p;
  87150. bestScore = score;
  87151. }
  87152. p = p->pNext;
  87153. }
  87154. }
  87155. /* If the createFlag parameter is true and the search did not reveal an
  87156. ** exact match for the name, number of arguments and encoding, then add a
  87157. ** new entry to the hash table and return it.
  87158. */
  87159. if( createFlag && bestScore<FUNC_PERFECT_MATCH &&
  87160. (pBest = sqlite3DbMallocZero(db, sizeof(*pBest)+nName+1))!=0 ){
  87161. pBest->zName = (char *)&pBest[1];
  87162. pBest->nArg = (u16)nArg;
  87163. pBest->funcFlags = enc;
  87164. memcpy(pBest->zName, zName, nName);
  87165. pBest->zName[nName] = 0;
  87166. sqlite3FuncDefInsert(&db->aFunc, pBest);
  87167. }
  87168. if( pBest && (pBest->xStep || pBest->xFunc || createFlag) ){
  87169. return pBest;
  87170. }
  87171. return 0;
  87172. }
  87173. /*
  87174. ** Free all resources held by the schema structure. The void* argument points
  87175. ** at a Schema struct. This function does not call sqlite3DbFree(db, ) on the
  87176. ** pointer itself, it just cleans up subsidiary resources (i.e. the contents
  87177. ** of the schema hash tables).
  87178. **
  87179. ** The Schema.cache_size variable is not cleared.
  87180. */
  87181. SQLITE_PRIVATE void sqlite3SchemaClear(void *p){
  87182. Hash temp1;
  87183. Hash temp2;
  87184. HashElem *pElem;
  87185. Schema *pSchema = (Schema *)p;
  87186. temp1 = pSchema->tblHash;
  87187. temp2 = pSchema->trigHash;
  87188. sqlite3HashInit(&pSchema->trigHash);
  87189. sqlite3HashClear(&pSchema->idxHash);
  87190. for(pElem=sqliteHashFirst(&temp2); pElem; pElem=sqliteHashNext(pElem)){
  87191. sqlite3DeleteTrigger(0, (Trigger*)sqliteHashData(pElem));
  87192. }
  87193. sqlite3HashClear(&temp2);
  87194. sqlite3HashInit(&pSchema->tblHash);
  87195. for(pElem=sqliteHashFirst(&temp1); pElem; pElem=sqliteHashNext(pElem)){
  87196. Table *pTab = sqliteHashData(pElem);
  87197. sqlite3DeleteTable(0, pTab);
  87198. }
  87199. sqlite3HashClear(&temp1);
  87200. sqlite3HashClear(&pSchema->fkeyHash);
  87201. pSchema->pSeqTab = 0;
  87202. if( pSchema->schemaFlags & DB_SchemaLoaded ){
  87203. pSchema->iGeneration++;
  87204. pSchema->schemaFlags &= ~DB_SchemaLoaded;
  87205. }
  87206. }
  87207. /*
  87208. ** Find and return the schema associated with a BTree. Create
  87209. ** a new one if necessary.
  87210. */
  87211. SQLITE_PRIVATE Schema *sqlite3SchemaGet(sqlite3 *db, Btree *pBt){
  87212. Schema * p;
  87213. if( pBt ){
  87214. p = (Schema *)sqlite3BtreeSchema(pBt, sizeof(Schema), sqlite3SchemaClear);
  87215. }else{
  87216. p = (Schema *)sqlite3DbMallocZero(0, sizeof(Schema));
  87217. }
  87218. if( !p ){
  87219. db->mallocFailed = 1;
  87220. }else if ( 0==p->file_format ){
  87221. sqlite3HashInit(&p->tblHash);
  87222. sqlite3HashInit(&p->idxHash);
  87223. sqlite3HashInit(&p->trigHash);
  87224. sqlite3HashInit(&p->fkeyHash);
  87225. p->enc = SQLITE_UTF8;
  87226. }
  87227. return p;
  87228. }
  87229. /************** End of callback.c ********************************************/
  87230. /************** Begin file delete.c ******************************************/
  87231. /*
  87232. ** 2001 September 15
  87233. **
  87234. ** The author disclaims copyright to this source code. In place of
  87235. ** a legal notice, here is a blessing:
  87236. **
  87237. ** May you do good and not evil.
  87238. ** May you find forgiveness for yourself and forgive others.
  87239. ** May you share freely, never taking more than you give.
  87240. **
  87241. *************************************************************************
  87242. ** This file contains C code routines that are called by the parser
  87243. ** in order to generate code for DELETE FROM statements.
  87244. */
  87245. /*
  87246. ** While a SrcList can in general represent multiple tables and subqueries
  87247. ** (as in the FROM clause of a SELECT statement) in this case it contains
  87248. ** the name of a single table, as one might find in an INSERT, DELETE,
  87249. ** or UPDATE statement. Look up that table in the symbol table and
  87250. ** return a pointer. Set an error message and return NULL if the table
  87251. ** name is not found or if any other error occurs.
  87252. **
  87253. ** The following fields are initialized appropriate in pSrc:
  87254. **
  87255. ** pSrc->a[0].pTab Pointer to the Table object
  87256. ** pSrc->a[0].pIndex Pointer to the INDEXED BY index, if there is one
  87257. **
  87258. */
  87259. SQLITE_PRIVATE Table *sqlite3SrcListLookup(Parse *pParse, SrcList *pSrc){
  87260. struct SrcList_item *pItem = pSrc->a;
  87261. Table *pTab;
  87262. assert( pItem && pSrc->nSrc==1 );
  87263. pTab = sqlite3LocateTableItem(pParse, 0, pItem);
  87264. sqlite3DeleteTable(pParse->db, pItem->pTab);
  87265. pItem->pTab = pTab;
  87266. if( pTab ){
  87267. pTab->nRef++;
  87268. }
  87269. if( sqlite3IndexedByLookup(pParse, pItem) ){
  87270. pTab = 0;
  87271. }
  87272. return pTab;
  87273. }
  87274. /*
  87275. ** Check to make sure the given table is writable. If it is not
  87276. ** writable, generate an error message and return 1. If it is
  87277. ** writable return 0;
  87278. */
  87279. SQLITE_PRIVATE int sqlite3IsReadOnly(Parse *pParse, Table *pTab, int viewOk){
  87280. /* A table is not writable under the following circumstances:
  87281. **
  87282. ** 1) It is a virtual table and no implementation of the xUpdate method
  87283. ** has been provided, or
  87284. ** 2) It is a system table (i.e. sqlite_master), this call is not
  87285. ** part of a nested parse and writable_schema pragma has not
  87286. ** been specified.
  87287. **
  87288. ** In either case leave an error message in pParse and return non-zero.
  87289. */
  87290. if( ( IsVirtual(pTab)
  87291. && sqlite3GetVTable(pParse->db, pTab)->pMod->pModule->xUpdate==0 )
  87292. || ( (pTab->tabFlags & TF_Readonly)!=0
  87293. && (pParse->db->flags & SQLITE_WriteSchema)==0
  87294. && pParse->nested==0 )
  87295. ){
  87296. sqlite3ErrorMsg(pParse, "table %s may not be modified", pTab->zName);
  87297. return 1;
  87298. }
  87299. #ifndef SQLITE_OMIT_VIEW
  87300. if( !viewOk && pTab->pSelect ){
  87301. sqlite3ErrorMsg(pParse,"cannot modify %s because it is a view",pTab->zName);
  87302. return 1;
  87303. }
  87304. #endif
  87305. return 0;
  87306. }
  87307. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  87308. /*
  87309. ** Evaluate a view and store its result in an ephemeral table. The
  87310. ** pWhere argument is an optional WHERE clause that restricts the
  87311. ** set of rows in the view that are to be added to the ephemeral table.
  87312. */
  87313. SQLITE_PRIVATE void sqlite3MaterializeView(
  87314. Parse *pParse, /* Parsing context */
  87315. Table *pView, /* View definition */
  87316. Expr *pWhere, /* Optional WHERE clause to be added */
  87317. int iCur /* Cursor number for ephemeral table */
  87318. ){
  87319. SelectDest dest;
  87320. Select *pSel;
  87321. SrcList *pFrom;
  87322. sqlite3 *db = pParse->db;
  87323. int iDb = sqlite3SchemaToIndex(db, pView->pSchema);
  87324. pWhere = sqlite3ExprDup(db, pWhere, 0);
  87325. pFrom = sqlite3SrcListAppend(db, 0, 0, 0);
  87326. if( pFrom ){
  87327. assert( pFrom->nSrc==1 );
  87328. pFrom->a[0].zName = sqlite3DbStrDup(db, pView->zName);
  87329. pFrom->a[0].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  87330. assert( pFrom->a[0].pOn==0 );
  87331. assert( pFrom->a[0].pUsing==0 );
  87332. }
  87333. pSel = sqlite3SelectNew(pParse, 0, pFrom, pWhere, 0, 0, 0, 0, 0, 0);
  87334. sqlite3SelectDestInit(&dest, SRT_EphemTab, iCur);
  87335. sqlite3Select(pParse, pSel, &dest);
  87336. sqlite3SelectDelete(db, pSel);
  87337. }
  87338. #endif /* !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER) */
  87339. #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
  87340. /*
  87341. ** Generate an expression tree to implement the WHERE, ORDER BY,
  87342. ** and LIMIT/OFFSET portion of DELETE and UPDATE statements.
  87343. **
  87344. ** DELETE FROM table_wxyz WHERE a<5 ORDER BY a LIMIT 1;
  87345. ** \__________________________/
  87346. ** pLimitWhere (pInClause)
  87347. */
  87348. SQLITE_PRIVATE Expr *sqlite3LimitWhere(
  87349. Parse *pParse, /* The parser context */
  87350. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  87351. Expr *pWhere, /* The WHERE clause. May be null */
  87352. ExprList *pOrderBy, /* The ORDER BY clause. May be null */
  87353. Expr *pLimit, /* The LIMIT clause. May be null */
  87354. Expr *pOffset, /* The OFFSET clause. May be null */
  87355. char *zStmtType /* Either DELETE or UPDATE. For err msgs. */
  87356. ){
  87357. Expr *pWhereRowid = NULL; /* WHERE rowid .. */
  87358. Expr *pInClause = NULL; /* WHERE rowid IN ( select ) */
  87359. Expr *pSelectRowid = NULL; /* SELECT rowid ... */
  87360. ExprList *pEList = NULL; /* Expression list contaning only pSelectRowid */
  87361. SrcList *pSelectSrc = NULL; /* SELECT rowid FROM x ... (dup of pSrc) */
  87362. Select *pSelect = NULL; /* Complete SELECT tree */
  87363. /* Check that there isn't an ORDER BY without a LIMIT clause.
  87364. */
  87365. if( pOrderBy && (pLimit == 0) ) {
  87366. sqlite3ErrorMsg(pParse, "ORDER BY without LIMIT on %s", zStmtType);
  87367. goto limit_where_cleanup_2;
  87368. }
  87369. /* We only need to generate a select expression if there
  87370. ** is a limit/offset term to enforce.
  87371. */
  87372. if( pLimit == 0 ) {
  87373. /* if pLimit is null, pOffset will always be null as well. */
  87374. assert( pOffset == 0 );
  87375. return pWhere;
  87376. }
  87377. /* Generate a select expression tree to enforce the limit/offset
  87378. ** term for the DELETE or UPDATE statement. For example:
  87379. ** DELETE FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  87380. ** becomes:
  87381. ** DELETE FROM table_a WHERE rowid IN (
  87382. ** SELECT rowid FROM table_a WHERE col1=1 ORDER BY col2 LIMIT 1 OFFSET 1
  87383. ** );
  87384. */
  87385. pSelectRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  87386. if( pSelectRowid == 0 ) goto limit_where_cleanup_2;
  87387. pEList = sqlite3ExprListAppend(pParse, 0, pSelectRowid);
  87388. if( pEList == 0 ) goto limit_where_cleanup_2;
  87389. /* duplicate the FROM clause as it is needed by both the DELETE/UPDATE tree
  87390. ** and the SELECT subtree. */
  87391. pSelectSrc = sqlite3SrcListDup(pParse->db, pSrc, 0);
  87392. if( pSelectSrc == 0 ) {
  87393. sqlite3ExprListDelete(pParse->db, pEList);
  87394. goto limit_where_cleanup_2;
  87395. }
  87396. /* generate the SELECT expression tree. */
  87397. pSelect = sqlite3SelectNew(pParse,pEList,pSelectSrc,pWhere,0,0,
  87398. pOrderBy,0,pLimit,pOffset);
  87399. if( pSelect == 0 ) return 0;
  87400. /* now generate the new WHERE rowid IN clause for the DELETE/UDPATE */
  87401. pWhereRowid = sqlite3PExpr(pParse, TK_ROW, 0, 0, 0);
  87402. if( pWhereRowid == 0 ) goto limit_where_cleanup_1;
  87403. pInClause = sqlite3PExpr(pParse, TK_IN, pWhereRowid, 0, 0);
  87404. if( pInClause == 0 ) goto limit_where_cleanup_1;
  87405. pInClause->x.pSelect = pSelect;
  87406. pInClause->flags |= EP_xIsSelect;
  87407. sqlite3ExprSetHeight(pParse, pInClause);
  87408. return pInClause;
  87409. /* something went wrong. clean up anything allocated. */
  87410. limit_where_cleanup_1:
  87411. sqlite3SelectDelete(pParse->db, pSelect);
  87412. return 0;
  87413. limit_where_cleanup_2:
  87414. sqlite3ExprDelete(pParse->db, pWhere);
  87415. sqlite3ExprListDelete(pParse->db, pOrderBy);
  87416. sqlite3ExprDelete(pParse->db, pLimit);
  87417. sqlite3ExprDelete(pParse->db, pOffset);
  87418. return 0;
  87419. }
  87420. #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) */
  87421. /* && !defined(SQLITE_OMIT_SUBQUERY) */
  87422. /*
  87423. ** Generate code for a DELETE FROM statement.
  87424. **
  87425. ** DELETE FROM table_wxyz WHERE a<5 AND b NOT NULL;
  87426. ** \________/ \________________/
  87427. ** pTabList pWhere
  87428. */
  87429. SQLITE_PRIVATE void sqlite3DeleteFrom(
  87430. Parse *pParse, /* The parser context */
  87431. SrcList *pTabList, /* The table from which we should delete things */
  87432. Expr *pWhere /* The WHERE clause. May be null */
  87433. ){
  87434. Vdbe *v; /* The virtual database engine */
  87435. Table *pTab; /* The table from which records will be deleted */
  87436. const char *zDb; /* Name of database holding pTab */
  87437. int i; /* Loop counter */
  87438. WhereInfo *pWInfo; /* Information about the WHERE clause */
  87439. Index *pIdx; /* For looping over indices of the table */
  87440. int iTabCur; /* Cursor number for the table */
  87441. int iDataCur; /* VDBE cursor for the canonical data source */
  87442. int iIdxCur; /* Cursor number of the first index */
  87443. int nIdx; /* Number of indices */
  87444. sqlite3 *db; /* Main database structure */
  87445. AuthContext sContext; /* Authorization context */
  87446. NameContext sNC; /* Name context to resolve expressions in */
  87447. int iDb; /* Database number */
  87448. int memCnt = -1; /* Memory cell used for change counting */
  87449. int rcauth; /* Value returned by authorization callback */
  87450. int okOnePass; /* True for one-pass algorithm without the FIFO */
  87451. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  87452. u8 *aToOpen = 0; /* Open cursor iTabCur+j if aToOpen[j] is true */
  87453. Index *pPk; /* The PRIMARY KEY index on the table */
  87454. int iPk = 0; /* First of nPk registers holding PRIMARY KEY value */
  87455. i16 nPk = 1; /* Number of columns in the PRIMARY KEY */
  87456. int iKey; /* Memory cell holding key of row to be deleted */
  87457. i16 nKey; /* Number of memory cells in the row key */
  87458. int iEphCur = 0; /* Ephemeral table holding all primary key values */
  87459. int iRowSet = 0; /* Register for rowset of rows to delete */
  87460. int addrBypass = 0; /* Address of jump over the delete logic */
  87461. int addrLoop = 0; /* Top of the delete loop */
  87462. int addrDelete = 0; /* Jump directly to the delete logic */
  87463. int addrEphOpen = 0; /* Instruction to open the Ephemeral table */
  87464. #ifndef SQLITE_OMIT_TRIGGER
  87465. int isView; /* True if attempting to delete from a view */
  87466. Trigger *pTrigger; /* List of table triggers, if required */
  87467. #endif
  87468. memset(&sContext, 0, sizeof(sContext));
  87469. db = pParse->db;
  87470. if( pParse->nErr || db->mallocFailed ){
  87471. goto delete_from_cleanup;
  87472. }
  87473. assert( pTabList->nSrc==1 );
  87474. /* Locate the table which we want to delete. This table has to be
  87475. ** put in an SrcList structure because some of the subroutines we
  87476. ** will be calling are designed to work with multiple tables and expect
  87477. ** an SrcList* parameter instead of just a Table* parameter.
  87478. */
  87479. pTab = sqlite3SrcListLookup(pParse, pTabList);
  87480. if( pTab==0 ) goto delete_from_cleanup;
  87481. /* Figure out if we have any triggers and if the table being
  87482. ** deleted from is a view
  87483. */
  87484. #ifndef SQLITE_OMIT_TRIGGER
  87485. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  87486. isView = pTab->pSelect!=0;
  87487. #else
  87488. # define pTrigger 0
  87489. # define isView 0
  87490. #endif
  87491. #ifdef SQLITE_OMIT_VIEW
  87492. # undef isView
  87493. # define isView 0
  87494. #endif
  87495. /* If pTab is really a view, make sure it has been initialized.
  87496. */
  87497. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  87498. goto delete_from_cleanup;
  87499. }
  87500. if( sqlite3IsReadOnly(pParse, pTab, (pTrigger?1:0)) ){
  87501. goto delete_from_cleanup;
  87502. }
  87503. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  87504. assert( iDb<db->nDb );
  87505. zDb = db->aDb[iDb].zName;
  87506. rcauth = sqlite3AuthCheck(pParse, SQLITE_DELETE, pTab->zName, 0, zDb);
  87507. assert( rcauth==SQLITE_OK || rcauth==SQLITE_DENY || rcauth==SQLITE_IGNORE );
  87508. if( rcauth==SQLITE_DENY ){
  87509. goto delete_from_cleanup;
  87510. }
  87511. assert(!isView || pTrigger);
  87512. /* Assign cursor numbers to the table and all its indices.
  87513. */
  87514. assert( pTabList->nSrc==1 );
  87515. iTabCur = pTabList->a[0].iCursor = pParse->nTab++;
  87516. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  87517. pParse->nTab++;
  87518. }
  87519. /* Start the view context
  87520. */
  87521. if( isView ){
  87522. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  87523. }
  87524. /* Begin generating code.
  87525. */
  87526. v = sqlite3GetVdbe(pParse);
  87527. if( v==0 ){
  87528. goto delete_from_cleanup;
  87529. }
  87530. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  87531. sqlite3BeginWriteOperation(pParse, 1, iDb);
  87532. /* If we are trying to delete from a view, realize that view into
  87533. ** an ephemeral table.
  87534. */
  87535. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  87536. if( isView ){
  87537. sqlite3MaterializeView(pParse, pTab, pWhere, iTabCur);
  87538. iDataCur = iIdxCur = iTabCur;
  87539. }
  87540. #endif
  87541. /* Resolve the column names in the WHERE clause.
  87542. */
  87543. memset(&sNC, 0, sizeof(sNC));
  87544. sNC.pParse = pParse;
  87545. sNC.pSrcList = pTabList;
  87546. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  87547. goto delete_from_cleanup;
  87548. }
  87549. /* Initialize the counter of the number of rows deleted, if
  87550. ** we are counting rows.
  87551. */
  87552. if( db->flags & SQLITE_CountRows ){
  87553. memCnt = ++pParse->nMem;
  87554. sqlite3VdbeAddOp2(v, OP_Integer, 0, memCnt);
  87555. }
  87556. #ifndef SQLITE_OMIT_TRUNCATE_OPTIMIZATION
  87557. /* Special case: A DELETE without a WHERE clause deletes everything.
  87558. ** It is easier just to erase the whole table. Prior to version 3.6.5,
  87559. ** this optimization caused the row change count (the value returned by
  87560. ** API function sqlite3_count_changes) to be set incorrectly. */
  87561. if( rcauth==SQLITE_OK && pWhere==0 && !pTrigger && !IsVirtual(pTab)
  87562. && 0==sqlite3FkRequired(pParse, pTab, 0, 0)
  87563. ){
  87564. assert( !isView );
  87565. sqlite3TableLock(pParse, iDb, pTab->tnum, 1, pTab->zName);
  87566. if( HasRowid(pTab) ){
  87567. sqlite3VdbeAddOp4(v, OP_Clear, pTab->tnum, iDb, memCnt,
  87568. pTab->zName, P4_STATIC);
  87569. }
  87570. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  87571. assert( pIdx->pSchema==pTab->pSchema );
  87572. sqlite3VdbeAddOp2(v, OP_Clear, pIdx->tnum, iDb);
  87573. }
  87574. }else
  87575. #endif /* SQLITE_OMIT_TRUNCATE_OPTIMIZATION */
  87576. {
  87577. if( HasRowid(pTab) ){
  87578. /* For a rowid table, initialize the RowSet to an empty set */
  87579. pPk = 0;
  87580. nPk = 1;
  87581. iRowSet = ++pParse->nMem;
  87582. sqlite3VdbeAddOp2(v, OP_Null, 0, iRowSet);
  87583. }else{
  87584. /* For a WITHOUT ROWID table, create an ephemeral table used to
  87585. ** hold all primary keys for rows to be deleted. */
  87586. pPk = sqlite3PrimaryKeyIndex(pTab);
  87587. assert( pPk!=0 );
  87588. nPk = pPk->nKeyCol;
  87589. iPk = pParse->nMem+1;
  87590. pParse->nMem += nPk;
  87591. iEphCur = pParse->nTab++;
  87592. addrEphOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEphCur, nPk);
  87593. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  87594. }
  87595. /* Construct a query to find the rowid or primary key for every row
  87596. ** to be deleted, based on the WHERE clause.
  87597. */
  87598. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  87599. WHERE_ONEPASS_DESIRED|WHERE_DUPLICATES_OK,
  87600. iTabCur+1);
  87601. if( pWInfo==0 ) goto delete_from_cleanup;
  87602. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  87603. /* Keep track of the number of rows to be deleted */
  87604. if( db->flags & SQLITE_CountRows ){
  87605. sqlite3VdbeAddOp2(v, OP_AddImm, memCnt, 1);
  87606. }
  87607. /* Extract the rowid or primary key for the current row */
  87608. if( pPk ){
  87609. for(i=0; i<nPk; i++){
  87610. sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
  87611. pPk->aiColumn[i], iPk+i);
  87612. }
  87613. iKey = iPk;
  87614. }else{
  87615. iKey = pParse->nMem + 1;
  87616. iKey = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iTabCur, iKey, 0);
  87617. if( iKey>pParse->nMem ) pParse->nMem = iKey;
  87618. }
  87619. if( okOnePass ){
  87620. /* For ONEPASS, no need to store the rowid/primary-key. There is only
  87621. ** one, so just keep it in its register(s) and fall through to the
  87622. ** delete code.
  87623. */
  87624. nKey = nPk; /* OP_Found will use an unpacked key */
  87625. aToOpen = sqlite3DbMallocRaw(db, nIdx+2);
  87626. if( aToOpen==0 ){
  87627. sqlite3WhereEnd(pWInfo);
  87628. goto delete_from_cleanup;
  87629. }
  87630. memset(aToOpen, 1, nIdx+1);
  87631. aToOpen[nIdx+1] = 0;
  87632. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iTabCur] = 0;
  87633. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iTabCur] = 0;
  87634. if( addrEphOpen ) sqlite3VdbeChangeToNoop(v, addrEphOpen);
  87635. addrDelete = sqlite3VdbeAddOp0(v, OP_Goto); /* Jump to DELETE logic */
  87636. }else if( pPk ){
  87637. /* Construct a composite key for the row to be deleted and remember it */
  87638. iKey = ++pParse->nMem;
  87639. nKey = 0; /* Zero tells OP_Found to use a composite key */
  87640. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, iKey,
  87641. sqlite3IndexAffinityStr(v, pPk), nPk);
  87642. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEphCur, iKey);
  87643. }else{
  87644. /* Get the rowid of the row to be deleted and remember it in the RowSet */
  87645. nKey = 1; /* OP_Seek always uses a single rowid */
  87646. sqlite3VdbeAddOp2(v, OP_RowSetAdd, iRowSet, iKey);
  87647. }
  87648. /* End of the WHERE loop */
  87649. sqlite3WhereEnd(pWInfo);
  87650. if( okOnePass ){
  87651. /* Bypass the delete logic below if the WHERE loop found zero rows */
  87652. addrBypass = sqlite3VdbeMakeLabel(v);
  87653. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBypass);
  87654. sqlite3VdbeJumpHere(v, addrDelete);
  87655. }
  87656. /* Unless this is a view, open cursors for the table we are
  87657. ** deleting from and all its indices. If this is a view, then the
  87658. ** only effect this statement has is to fire the INSTEAD OF
  87659. ** triggers.
  87660. */
  87661. if( !isView ){
  87662. testcase( IsVirtual(pTab) );
  87663. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iTabCur, aToOpen,
  87664. &iDataCur, &iIdxCur);
  87665. assert( pPk || IsVirtual(pTab) || iDataCur==iTabCur );
  87666. assert( pPk || IsVirtual(pTab) || iIdxCur==iDataCur+1 );
  87667. }
  87668. /* Set up a loop over the rowids/primary-keys that were found in the
  87669. ** where-clause loop above.
  87670. */
  87671. if( okOnePass ){
  87672. /* Just one row. Hence the top-of-loop is a no-op */
  87673. assert( nKey==nPk ); /* OP_Found will use an unpacked key */
  87674. assert( !IsVirtual(pTab) );
  87675. if( aToOpen[iDataCur-iTabCur] ){
  87676. assert( pPk!=0 || pTab->pSelect!=0 );
  87677. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, addrBypass, iKey, nKey);
  87678. VdbeCoverage(v);
  87679. }
  87680. }else if( pPk ){
  87681. addrLoop = sqlite3VdbeAddOp1(v, OP_Rewind, iEphCur); VdbeCoverage(v);
  87682. sqlite3VdbeAddOp2(v, OP_RowKey, iEphCur, iKey);
  87683. assert( nKey==0 ); /* OP_Found will use a composite key */
  87684. }else{
  87685. addrLoop = sqlite3VdbeAddOp3(v, OP_RowSetRead, iRowSet, 0, iKey);
  87686. VdbeCoverage(v);
  87687. assert( nKey==1 );
  87688. }
  87689. /* Delete the row */
  87690. #ifndef SQLITE_OMIT_VIRTUALTABLE
  87691. if( IsVirtual(pTab) ){
  87692. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  87693. sqlite3VtabMakeWritable(pParse, pTab);
  87694. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, 1, iKey, pVTab, P4_VTAB);
  87695. sqlite3VdbeChangeP5(v, OE_Abort);
  87696. sqlite3MayAbort(pParse);
  87697. }else
  87698. #endif
  87699. {
  87700. int count = (pParse->nested==0); /* True to count changes */
  87701. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  87702. iKey, nKey, count, OE_Default, okOnePass);
  87703. }
  87704. /* End of the loop over all rowids/primary-keys. */
  87705. if( okOnePass ){
  87706. sqlite3VdbeResolveLabel(v, addrBypass);
  87707. }else if( pPk ){
  87708. sqlite3VdbeAddOp2(v, OP_Next, iEphCur, addrLoop+1); VdbeCoverage(v);
  87709. sqlite3VdbeJumpHere(v, addrLoop);
  87710. }else{
  87711. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrLoop);
  87712. sqlite3VdbeJumpHere(v, addrLoop);
  87713. }
  87714. /* Close the cursors open on the table and its indexes. */
  87715. if( !isView && !IsVirtual(pTab) ){
  87716. if( !pPk ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  87717. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  87718. sqlite3VdbeAddOp1(v, OP_Close, iIdxCur + i);
  87719. }
  87720. }
  87721. } /* End non-truncate path */
  87722. /* Update the sqlite_sequence table by storing the content of the
  87723. ** maximum rowid counter values recorded while inserting into
  87724. ** autoincrement tables.
  87725. */
  87726. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  87727. sqlite3AutoincrementEnd(pParse);
  87728. }
  87729. /* Return the number of rows that were deleted. If this routine is
  87730. ** generating code because of a call to sqlite3NestedParse(), do not
  87731. ** invoke the callback function.
  87732. */
  87733. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  87734. sqlite3VdbeAddOp2(v, OP_ResultRow, memCnt, 1);
  87735. sqlite3VdbeSetNumCols(v, 1);
  87736. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows deleted", SQLITE_STATIC);
  87737. }
  87738. delete_from_cleanup:
  87739. sqlite3AuthContextPop(&sContext);
  87740. sqlite3SrcListDelete(db, pTabList);
  87741. sqlite3ExprDelete(db, pWhere);
  87742. sqlite3DbFree(db, aToOpen);
  87743. return;
  87744. }
  87745. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  87746. ** they may interfere with compilation of other functions in this file
  87747. ** (or in another file, if this file becomes part of the amalgamation). */
  87748. #ifdef isView
  87749. #undef isView
  87750. #endif
  87751. #ifdef pTrigger
  87752. #undef pTrigger
  87753. #endif
  87754. /*
  87755. ** This routine generates VDBE code that causes a single row of a
  87756. ** single table to be deleted. Both the original table entry and
  87757. ** all indices are removed.
  87758. **
  87759. ** Preconditions:
  87760. **
  87761. ** 1. iDataCur is an open cursor on the btree that is the canonical data
  87762. ** store for the table. (This will be either the table itself,
  87763. ** in the case of a rowid table, or the PRIMARY KEY index in the case
  87764. ** of a WITHOUT ROWID table.)
  87765. **
  87766. ** 2. Read/write cursors for all indices of pTab must be open as
  87767. ** cursor number iIdxCur+i for the i-th index.
  87768. **
  87769. ** 3. The primary key for the row to be deleted must be stored in a
  87770. ** sequence of nPk memory cells starting at iPk. If nPk==0 that means
  87771. ** that a search record formed from OP_MakeRecord is contained in the
  87772. ** single memory location iPk.
  87773. */
  87774. SQLITE_PRIVATE void sqlite3GenerateRowDelete(
  87775. Parse *pParse, /* Parsing context */
  87776. Table *pTab, /* Table containing the row to be deleted */
  87777. Trigger *pTrigger, /* List of triggers to (potentially) fire */
  87778. int iDataCur, /* Cursor from which column data is extracted */
  87779. int iIdxCur, /* First index cursor */
  87780. int iPk, /* First memory cell containing the PRIMARY KEY */
  87781. i16 nPk, /* Number of PRIMARY KEY memory cells */
  87782. u8 count, /* If non-zero, increment the row change counter */
  87783. u8 onconf, /* Default ON CONFLICT policy for triggers */
  87784. u8 bNoSeek /* iDataCur is already pointing to the row to delete */
  87785. ){
  87786. Vdbe *v = pParse->pVdbe; /* Vdbe */
  87787. int iOld = 0; /* First register in OLD.* array */
  87788. int iLabel; /* Label resolved to end of generated code */
  87789. u8 opSeek; /* Seek opcode */
  87790. /* Vdbe is guaranteed to have been allocated by this stage. */
  87791. assert( v );
  87792. VdbeModuleComment((v, "BEGIN: GenRowDel(%d,%d,%d,%d)",
  87793. iDataCur, iIdxCur, iPk, (int)nPk));
  87794. /* Seek cursor iCur to the row to delete. If this row no longer exists
  87795. ** (this can happen if a trigger program has already deleted it), do
  87796. ** not attempt to delete it or fire any DELETE triggers. */
  87797. iLabel = sqlite3VdbeMakeLabel(v);
  87798. opSeek = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
  87799. if( !bNoSeek ){
  87800. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  87801. VdbeCoverageIf(v, opSeek==OP_NotExists);
  87802. VdbeCoverageIf(v, opSeek==OP_NotFound);
  87803. }
  87804. /* If there are any triggers to fire, allocate a range of registers to
  87805. ** use for the old.* references in the triggers. */
  87806. if( sqlite3FkRequired(pParse, pTab, 0, 0) || pTrigger ){
  87807. u32 mask; /* Mask of OLD.* columns in use */
  87808. int iCol; /* Iterator used while populating OLD.* */
  87809. int addrStart; /* Start of BEFORE trigger programs */
  87810. /* TODO: Could use temporary registers here. Also could attempt to
  87811. ** avoid copying the contents of the rowid register. */
  87812. mask = sqlite3TriggerColmask(
  87813. pParse, pTrigger, 0, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onconf
  87814. );
  87815. mask |= sqlite3FkOldmask(pParse, pTab);
  87816. iOld = pParse->nMem+1;
  87817. pParse->nMem += (1 + pTab->nCol);
  87818. /* Populate the OLD.* pseudo-table register array. These values will be
  87819. ** used by any BEFORE and AFTER triggers that exist. */
  87820. sqlite3VdbeAddOp2(v, OP_Copy, iPk, iOld);
  87821. for(iCol=0; iCol<pTab->nCol; iCol++){
  87822. testcase( mask!=0xffffffff && iCol==31 );
  87823. testcase( mask!=0xffffffff && iCol==32 );
  87824. if( mask==0xffffffff || (iCol<=31 && (mask & MASKBIT32(iCol))!=0) ){
  87825. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, iCol, iOld+iCol+1);
  87826. }
  87827. }
  87828. /* Invoke BEFORE DELETE trigger programs. */
  87829. addrStart = sqlite3VdbeCurrentAddr(v);
  87830. sqlite3CodeRowTrigger(pParse, pTrigger,
  87831. TK_DELETE, 0, TRIGGER_BEFORE, pTab, iOld, onconf, iLabel
  87832. );
  87833. /* If any BEFORE triggers were coded, then seek the cursor to the
  87834. ** row to be deleted again. It may be that the BEFORE triggers moved
  87835. ** the cursor or of already deleted the row that the cursor was
  87836. ** pointing to.
  87837. */
  87838. if( addrStart<sqlite3VdbeCurrentAddr(v) ){
  87839. sqlite3VdbeAddOp4Int(v, opSeek, iDataCur, iLabel, iPk, nPk);
  87840. VdbeCoverageIf(v, opSeek==OP_NotExists);
  87841. VdbeCoverageIf(v, opSeek==OP_NotFound);
  87842. }
  87843. /* Do FK processing. This call checks that any FK constraints that
  87844. ** refer to this table (i.e. constraints attached to other tables)
  87845. ** are not violated by deleting this row. */
  87846. sqlite3FkCheck(pParse, pTab, iOld, 0, 0, 0);
  87847. }
  87848. /* Delete the index and table entries. Skip this step if pTab is really
  87849. ** a view (in which case the only effect of the DELETE statement is to
  87850. ** fire the INSTEAD OF triggers). */
  87851. if( pTab->pSelect==0 ){
  87852. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
  87853. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, (count?OPFLAG_NCHANGE:0));
  87854. if( count ){
  87855. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  87856. }
  87857. }
  87858. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  87859. ** handle rows (possibly in other tables) that refer via a foreign key
  87860. ** to the row just deleted. */
  87861. sqlite3FkActions(pParse, pTab, 0, iOld, 0, 0);
  87862. /* Invoke AFTER DELETE trigger programs. */
  87863. sqlite3CodeRowTrigger(pParse, pTrigger,
  87864. TK_DELETE, 0, TRIGGER_AFTER, pTab, iOld, onconf, iLabel
  87865. );
  87866. /* Jump here if the row had already been deleted before any BEFORE
  87867. ** trigger programs were invoked. Or if a trigger program throws a
  87868. ** RAISE(IGNORE) exception. */
  87869. sqlite3VdbeResolveLabel(v, iLabel);
  87870. VdbeModuleComment((v, "END: GenRowDel()"));
  87871. }
  87872. /*
  87873. ** This routine generates VDBE code that causes the deletion of all
  87874. ** index entries associated with a single row of a single table, pTab
  87875. **
  87876. ** Preconditions:
  87877. **
  87878. ** 1. A read/write cursor "iDataCur" must be open on the canonical storage
  87879. ** btree for the table pTab. (This will be either the table itself
  87880. ** for rowid tables or to the primary key index for WITHOUT ROWID
  87881. ** tables.)
  87882. **
  87883. ** 2. Read/write cursors for all indices of pTab must be open as
  87884. ** cursor number iIdxCur+i for the i-th index. (The pTab->pIndex
  87885. ** index is the 0-th index.)
  87886. **
  87887. ** 3. The "iDataCur" cursor must be already be positioned on the row
  87888. ** that is to be deleted.
  87889. */
  87890. SQLITE_PRIVATE void sqlite3GenerateRowIndexDelete(
  87891. Parse *pParse, /* Parsing and code generating context */
  87892. Table *pTab, /* Table containing the row to be deleted */
  87893. int iDataCur, /* Cursor of table holding data. */
  87894. int iIdxCur, /* First index cursor */
  87895. int *aRegIdx /* Only delete if aRegIdx!=0 && aRegIdx[i]>0 */
  87896. ){
  87897. int i; /* Index loop counter */
  87898. int r1 = -1; /* Register holding an index key */
  87899. int iPartIdxLabel; /* Jump destination for skipping partial index entries */
  87900. Index *pIdx; /* Current index */
  87901. Index *pPrior = 0; /* Prior index */
  87902. Vdbe *v; /* The prepared statement under construction */
  87903. Index *pPk; /* PRIMARY KEY index, or NULL for rowid tables */
  87904. v = pParse->pVdbe;
  87905. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  87906. for(i=0, pIdx=pTab->pIndex; pIdx; i++, pIdx=pIdx->pNext){
  87907. assert( iIdxCur+i!=iDataCur || pPk==pIdx );
  87908. if( aRegIdx!=0 && aRegIdx[i]==0 ) continue;
  87909. if( pIdx==pPk ) continue;
  87910. VdbeModuleComment((v, "GenRowIdxDel for %s", pIdx->zName));
  87911. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 1,
  87912. &iPartIdxLabel, pPrior, r1);
  87913. sqlite3VdbeAddOp3(v, OP_IdxDelete, iIdxCur+i, r1,
  87914. pIdx->uniqNotNull ? pIdx->nKeyCol : pIdx->nColumn);
  87915. sqlite3ResolvePartIdxLabel(pParse, iPartIdxLabel);
  87916. pPrior = pIdx;
  87917. }
  87918. }
  87919. /*
  87920. ** Generate code that will assemble an index key and stores it in register
  87921. ** regOut. The key with be for index pIdx which is an index on pTab.
  87922. ** iCur is the index of a cursor open on the pTab table and pointing to
  87923. ** the entry that needs indexing. If pTab is a WITHOUT ROWID table, then
  87924. ** iCur must be the cursor of the PRIMARY KEY index.
  87925. **
  87926. ** Return a register number which is the first in a block of
  87927. ** registers that holds the elements of the index key. The
  87928. ** block of registers has already been deallocated by the time
  87929. ** this routine returns.
  87930. **
  87931. ** If *piPartIdxLabel is not NULL, fill it in with a label and jump
  87932. ** to that label if pIdx is a partial index that should be skipped.
  87933. ** The label should be resolved using sqlite3ResolvePartIdxLabel().
  87934. ** A partial index should be skipped if its WHERE clause evaluates
  87935. ** to false or null. If pIdx is not a partial index, *piPartIdxLabel
  87936. ** will be set to zero which is an empty label that is ignored by
  87937. ** sqlite3ResolvePartIdxLabel().
  87938. **
  87939. ** The pPrior and regPrior parameters are used to implement a cache to
  87940. ** avoid unnecessary register loads. If pPrior is not NULL, then it is
  87941. ** a pointer to a different index for which an index key has just been
  87942. ** computed into register regPrior. If the current pIdx index is generating
  87943. ** its key into the same sequence of registers and if pPrior and pIdx share
  87944. ** a column in common, then the register corresponding to that column already
  87945. ** holds the correct value and the loading of that register is skipped.
  87946. ** This optimization is helpful when doing a DELETE or an INTEGRITY_CHECK
  87947. ** on a table with multiple indices, and especially with the ROWID or
  87948. ** PRIMARY KEY columns of the index.
  87949. */
  87950. SQLITE_PRIVATE int sqlite3GenerateIndexKey(
  87951. Parse *pParse, /* Parsing context */
  87952. Index *pIdx, /* The index for which to generate a key */
  87953. int iDataCur, /* Cursor number from which to take column data */
  87954. int regOut, /* Put the new key into this register if not 0 */
  87955. int prefixOnly, /* Compute only a unique prefix of the key */
  87956. int *piPartIdxLabel, /* OUT: Jump to this label to skip partial index */
  87957. Index *pPrior, /* Previously generated index key */
  87958. int regPrior /* Register holding previous generated key */
  87959. ){
  87960. Vdbe *v = pParse->pVdbe;
  87961. int j;
  87962. Table *pTab = pIdx->pTable;
  87963. int regBase;
  87964. int nCol;
  87965. if( piPartIdxLabel ){
  87966. if( pIdx->pPartIdxWhere ){
  87967. *piPartIdxLabel = sqlite3VdbeMakeLabel(v);
  87968. pParse->iPartIdxTab = iDataCur;
  87969. sqlite3ExprCachePush(pParse);
  87970. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, *piPartIdxLabel,
  87971. SQLITE_JUMPIFNULL);
  87972. }else{
  87973. *piPartIdxLabel = 0;
  87974. }
  87975. }
  87976. nCol = (prefixOnly && pIdx->uniqNotNull) ? pIdx->nKeyCol : pIdx->nColumn;
  87977. regBase = sqlite3GetTempRange(pParse, nCol);
  87978. if( pPrior && (regBase!=regPrior || pPrior->pPartIdxWhere) ) pPrior = 0;
  87979. for(j=0; j<nCol; j++){
  87980. if( pPrior && pPrior->aiColumn[j]==pIdx->aiColumn[j] ) continue;
  87981. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pIdx->aiColumn[j],
  87982. regBase+j);
  87983. /* If the column affinity is REAL but the number is an integer, then it
  87984. ** might be stored in the table as an integer (using a compact
  87985. ** representation) then converted to REAL by an OP_RealAffinity opcode.
  87986. ** But we are getting ready to store this value back into an index, where
  87987. ** it should be converted by to INTEGER again. So omit the OP_RealAffinity
  87988. ** opcode if it is present */
  87989. sqlite3VdbeDeletePriorOpcode(v, OP_RealAffinity);
  87990. }
  87991. if( regOut ){
  87992. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regOut);
  87993. }
  87994. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  87995. return regBase;
  87996. }
  87997. /*
  87998. ** If a prior call to sqlite3GenerateIndexKey() generated a jump-over label
  87999. ** because it was a partial index, then this routine should be called to
  88000. ** resolve that label.
  88001. */
  88002. SQLITE_PRIVATE void sqlite3ResolvePartIdxLabel(Parse *pParse, int iLabel){
  88003. if( iLabel ){
  88004. sqlite3VdbeResolveLabel(pParse->pVdbe, iLabel);
  88005. sqlite3ExprCachePop(pParse);
  88006. }
  88007. }
  88008. /************** End of delete.c **********************************************/
  88009. /************** Begin file func.c ********************************************/
  88010. /*
  88011. ** 2002 February 23
  88012. **
  88013. ** The author disclaims copyright to this source code. In place of
  88014. ** a legal notice, here is a blessing:
  88015. **
  88016. ** May you do good and not evil.
  88017. ** May you find forgiveness for yourself and forgive others.
  88018. ** May you share freely, never taking more than you give.
  88019. **
  88020. *************************************************************************
  88021. ** This file contains the C-language implementations for many of the SQL
  88022. ** functions of SQLite. (Some function, and in particular the date and
  88023. ** time functions, are implemented separately.)
  88024. */
  88025. /* #include <stdlib.h> */
  88026. /* #include <assert.h> */
  88027. /*
  88028. ** Return the collating function associated with a function.
  88029. */
  88030. static CollSeq *sqlite3GetFuncCollSeq(sqlite3_context *context){
  88031. VdbeOp *pOp = &context->pVdbe->aOp[context->iOp-1];
  88032. assert( pOp->opcode==OP_CollSeq );
  88033. assert( pOp->p4type==P4_COLLSEQ );
  88034. return pOp->p4.pColl;
  88035. }
  88036. /*
  88037. ** Indicate that the accumulator load should be skipped on this
  88038. ** iteration of the aggregate loop.
  88039. */
  88040. static void sqlite3SkipAccumulatorLoad(sqlite3_context *context){
  88041. context->skipFlag = 1;
  88042. }
  88043. /*
  88044. ** Implementation of the non-aggregate min() and max() functions
  88045. */
  88046. static void minmaxFunc(
  88047. sqlite3_context *context,
  88048. int argc,
  88049. sqlite3_value **argv
  88050. ){
  88051. int i;
  88052. int mask; /* 0 for min() or 0xffffffff for max() */
  88053. int iBest;
  88054. CollSeq *pColl;
  88055. assert( argc>1 );
  88056. mask = sqlite3_user_data(context)==0 ? 0 : -1;
  88057. pColl = sqlite3GetFuncCollSeq(context);
  88058. assert( pColl );
  88059. assert( mask==-1 || mask==0 );
  88060. iBest = 0;
  88061. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  88062. for(i=1; i<argc; i++){
  88063. if( sqlite3_value_type(argv[i])==SQLITE_NULL ) return;
  88064. if( (sqlite3MemCompare(argv[iBest], argv[i], pColl)^mask)>=0 ){
  88065. testcase( mask==0 );
  88066. iBest = i;
  88067. }
  88068. }
  88069. sqlite3_result_value(context, argv[iBest]);
  88070. }
  88071. /*
  88072. ** Return the type of the argument.
  88073. */
  88074. static void typeofFunc(
  88075. sqlite3_context *context,
  88076. int NotUsed,
  88077. sqlite3_value **argv
  88078. ){
  88079. const char *z = 0;
  88080. UNUSED_PARAMETER(NotUsed);
  88081. switch( sqlite3_value_type(argv[0]) ){
  88082. case SQLITE_INTEGER: z = "integer"; break;
  88083. case SQLITE_TEXT: z = "text"; break;
  88084. case SQLITE_FLOAT: z = "real"; break;
  88085. case SQLITE_BLOB: z = "blob"; break;
  88086. default: z = "null"; break;
  88087. }
  88088. sqlite3_result_text(context, z, -1, SQLITE_STATIC);
  88089. }
  88090. /*
  88091. ** Implementation of the length() function
  88092. */
  88093. static void lengthFunc(
  88094. sqlite3_context *context,
  88095. int argc,
  88096. sqlite3_value **argv
  88097. ){
  88098. int len;
  88099. assert( argc==1 );
  88100. UNUSED_PARAMETER(argc);
  88101. switch( sqlite3_value_type(argv[0]) ){
  88102. case SQLITE_BLOB:
  88103. case SQLITE_INTEGER:
  88104. case SQLITE_FLOAT: {
  88105. sqlite3_result_int(context, sqlite3_value_bytes(argv[0]));
  88106. break;
  88107. }
  88108. case SQLITE_TEXT: {
  88109. const unsigned char *z = sqlite3_value_text(argv[0]);
  88110. if( z==0 ) return;
  88111. len = 0;
  88112. while( *z ){
  88113. len++;
  88114. SQLITE_SKIP_UTF8(z);
  88115. }
  88116. sqlite3_result_int(context, len);
  88117. break;
  88118. }
  88119. default: {
  88120. sqlite3_result_null(context);
  88121. break;
  88122. }
  88123. }
  88124. }
  88125. /*
  88126. ** Implementation of the abs() function.
  88127. **
  88128. ** IMP: R-23979-26855 The abs(X) function returns the absolute value of
  88129. ** the numeric argument X.
  88130. */
  88131. static void absFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88132. assert( argc==1 );
  88133. UNUSED_PARAMETER(argc);
  88134. switch( sqlite3_value_type(argv[0]) ){
  88135. case SQLITE_INTEGER: {
  88136. i64 iVal = sqlite3_value_int64(argv[0]);
  88137. if( iVal<0 ){
  88138. if( iVal==SMALLEST_INT64 ){
  88139. /* IMP: R-31676-45509 If X is the integer -9223372036854775808
  88140. ** then abs(X) throws an integer overflow error since there is no
  88141. ** equivalent positive 64-bit two complement value. */
  88142. sqlite3_result_error(context, "integer overflow", -1);
  88143. return;
  88144. }
  88145. iVal = -iVal;
  88146. }
  88147. sqlite3_result_int64(context, iVal);
  88148. break;
  88149. }
  88150. case SQLITE_NULL: {
  88151. /* IMP: R-37434-19929 Abs(X) returns NULL if X is NULL. */
  88152. sqlite3_result_null(context);
  88153. break;
  88154. }
  88155. default: {
  88156. /* Because sqlite3_value_double() returns 0.0 if the argument is not
  88157. ** something that can be converted into a number, we have:
  88158. ** IMP: R-57326-31541 Abs(X) return 0.0 if X is a string or blob that
  88159. ** cannot be converted to a numeric value.
  88160. */
  88161. double rVal = sqlite3_value_double(argv[0]);
  88162. if( rVal<0 ) rVal = -rVal;
  88163. sqlite3_result_double(context, rVal);
  88164. break;
  88165. }
  88166. }
  88167. }
  88168. /*
  88169. ** Implementation of the instr() function.
  88170. **
  88171. ** instr(haystack,needle) finds the first occurrence of needle
  88172. ** in haystack and returns the number of previous characters plus 1,
  88173. ** or 0 if needle does not occur within haystack.
  88174. **
  88175. ** If both haystack and needle are BLOBs, then the result is one more than
  88176. ** the number of bytes in haystack prior to the first occurrence of needle,
  88177. ** or 0 if needle never occurs in haystack.
  88178. */
  88179. static void instrFunc(
  88180. sqlite3_context *context,
  88181. int argc,
  88182. sqlite3_value **argv
  88183. ){
  88184. const unsigned char *zHaystack;
  88185. const unsigned char *zNeedle;
  88186. int nHaystack;
  88187. int nNeedle;
  88188. int typeHaystack, typeNeedle;
  88189. int N = 1;
  88190. int isText;
  88191. UNUSED_PARAMETER(argc);
  88192. typeHaystack = sqlite3_value_type(argv[0]);
  88193. typeNeedle = sqlite3_value_type(argv[1]);
  88194. if( typeHaystack==SQLITE_NULL || typeNeedle==SQLITE_NULL ) return;
  88195. nHaystack = sqlite3_value_bytes(argv[0]);
  88196. nNeedle = sqlite3_value_bytes(argv[1]);
  88197. if( typeHaystack==SQLITE_BLOB && typeNeedle==SQLITE_BLOB ){
  88198. zHaystack = sqlite3_value_blob(argv[0]);
  88199. zNeedle = sqlite3_value_blob(argv[1]);
  88200. isText = 0;
  88201. }else{
  88202. zHaystack = sqlite3_value_text(argv[0]);
  88203. zNeedle = sqlite3_value_text(argv[1]);
  88204. isText = 1;
  88205. }
  88206. while( nNeedle<=nHaystack && memcmp(zHaystack, zNeedle, nNeedle)!=0 ){
  88207. N++;
  88208. do{
  88209. nHaystack--;
  88210. zHaystack++;
  88211. }while( isText && (zHaystack[0]&0xc0)==0x80 );
  88212. }
  88213. if( nNeedle>nHaystack ) N = 0;
  88214. sqlite3_result_int(context, N);
  88215. }
  88216. /*
  88217. ** Implementation of the printf() function.
  88218. */
  88219. static void printfFunc(
  88220. sqlite3_context *context,
  88221. int argc,
  88222. sqlite3_value **argv
  88223. ){
  88224. PrintfArguments x;
  88225. StrAccum str;
  88226. const char *zFormat;
  88227. int n;
  88228. if( argc>=1 && (zFormat = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  88229. x.nArg = argc-1;
  88230. x.nUsed = 0;
  88231. x.apArg = argv+1;
  88232. sqlite3StrAccumInit(&str, 0, 0, SQLITE_MAX_LENGTH);
  88233. str.db = sqlite3_context_db_handle(context);
  88234. sqlite3XPrintf(&str, SQLITE_PRINTF_SQLFUNC, zFormat, &x);
  88235. n = str.nChar;
  88236. sqlite3_result_text(context, sqlite3StrAccumFinish(&str), n,
  88237. SQLITE_DYNAMIC);
  88238. }
  88239. }
  88240. /*
  88241. ** Implementation of the substr() function.
  88242. **
  88243. ** substr(x,p1,p2) returns p2 characters of x[] beginning with p1.
  88244. ** p1 is 1-indexed. So substr(x,1,1) returns the first character
  88245. ** of x. If x is text, then we actually count UTF-8 characters.
  88246. ** If x is a blob, then we count bytes.
  88247. **
  88248. ** If p1 is negative, then we begin abs(p1) from the end of x[].
  88249. **
  88250. ** If p2 is negative, return the p2 characters preceding p1.
  88251. */
  88252. static void substrFunc(
  88253. sqlite3_context *context,
  88254. int argc,
  88255. sqlite3_value **argv
  88256. ){
  88257. const unsigned char *z;
  88258. const unsigned char *z2;
  88259. int len;
  88260. int p0type;
  88261. i64 p1, p2;
  88262. int negP2 = 0;
  88263. assert( argc==3 || argc==2 );
  88264. if( sqlite3_value_type(argv[1])==SQLITE_NULL
  88265. || (argc==3 && sqlite3_value_type(argv[2])==SQLITE_NULL)
  88266. ){
  88267. return;
  88268. }
  88269. p0type = sqlite3_value_type(argv[0]);
  88270. p1 = sqlite3_value_int(argv[1]);
  88271. if( p0type==SQLITE_BLOB ){
  88272. len = sqlite3_value_bytes(argv[0]);
  88273. z = sqlite3_value_blob(argv[0]);
  88274. if( z==0 ) return;
  88275. assert( len==sqlite3_value_bytes(argv[0]) );
  88276. }else{
  88277. z = sqlite3_value_text(argv[0]);
  88278. if( z==0 ) return;
  88279. len = 0;
  88280. if( p1<0 ){
  88281. for(z2=z; *z2; len++){
  88282. SQLITE_SKIP_UTF8(z2);
  88283. }
  88284. }
  88285. }
  88286. if( argc==3 ){
  88287. p2 = sqlite3_value_int(argv[2]);
  88288. if( p2<0 ){
  88289. p2 = -p2;
  88290. negP2 = 1;
  88291. }
  88292. }else{
  88293. p2 = sqlite3_context_db_handle(context)->aLimit[SQLITE_LIMIT_LENGTH];
  88294. }
  88295. if( p1<0 ){
  88296. p1 += len;
  88297. if( p1<0 ){
  88298. p2 += p1;
  88299. if( p2<0 ) p2 = 0;
  88300. p1 = 0;
  88301. }
  88302. }else if( p1>0 ){
  88303. p1--;
  88304. }else if( p2>0 ){
  88305. p2--;
  88306. }
  88307. if( negP2 ){
  88308. p1 -= p2;
  88309. if( p1<0 ){
  88310. p2 += p1;
  88311. p1 = 0;
  88312. }
  88313. }
  88314. assert( p1>=0 && p2>=0 );
  88315. if( p0type!=SQLITE_BLOB ){
  88316. while( *z && p1 ){
  88317. SQLITE_SKIP_UTF8(z);
  88318. p1--;
  88319. }
  88320. for(z2=z; *z2 && p2; p2--){
  88321. SQLITE_SKIP_UTF8(z2);
  88322. }
  88323. sqlite3_result_text64(context, (char*)z, z2-z, SQLITE_TRANSIENT,
  88324. SQLITE_UTF8);
  88325. }else{
  88326. if( p1+p2>len ){
  88327. p2 = len-p1;
  88328. if( p2<0 ) p2 = 0;
  88329. }
  88330. sqlite3_result_blob64(context, (char*)&z[p1], (u64)p2, SQLITE_TRANSIENT);
  88331. }
  88332. }
  88333. /*
  88334. ** Implementation of the round() function
  88335. */
  88336. #ifndef SQLITE_OMIT_FLOATING_POINT
  88337. static void roundFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88338. int n = 0;
  88339. double r;
  88340. char *zBuf;
  88341. assert( argc==1 || argc==2 );
  88342. if( argc==2 ){
  88343. if( SQLITE_NULL==sqlite3_value_type(argv[1]) ) return;
  88344. n = sqlite3_value_int(argv[1]);
  88345. if( n>30 ) n = 30;
  88346. if( n<0 ) n = 0;
  88347. }
  88348. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  88349. r = sqlite3_value_double(argv[0]);
  88350. /* If Y==0 and X will fit in a 64-bit int,
  88351. ** handle the rounding directly,
  88352. ** otherwise use printf.
  88353. */
  88354. if( n==0 && r>=0 && r<LARGEST_INT64-1 ){
  88355. r = (double)((sqlite_int64)(r+0.5));
  88356. }else if( n==0 && r<0 && (-r)<LARGEST_INT64-1 ){
  88357. r = -(double)((sqlite_int64)((-r)+0.5));
  88358. }else{
  88359. zBuf = sqlite3_mprintf("%.*f",n,r);
  88360. if( zBuf==0 ){
  88361. sqlite3_result_error_nomem(context);
  88362. return;
  88363. }
  88364. sqlite3AtoF(zBuf, &r, sqlite3Strlen30(zBuf), SQLITE_UTF8);
  88365. sqlite3_free(zBuf);
  88366. }
  88367. sqlite3_result_double(context, r);
  88368. }
  88369. #endif
  88370. /*
  88371. ** Allocate nByte bytes of space using sqlite3_malloc(). If the
  88372. ** allocation fails, call sqlite3_result_error_nomem() to notify
  88373. ** the database handle that malloc() has failed and return NULL.
  88374. ** If nByte is larger than the maximum string or blob length, then
  88375. ** raise an SQLITE_TOOBIG exception and return NULL.
  88376. */
  88377. static void *contextMalloc(sqlite3_context *context, i64 nByte){
  88378. char *z;
  88379. sqlite3 *db = sqlite3_context_db_handle(context);
  88380. assert( nByte>0 );
  88381. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH] );
  88382. testcase( nByte==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  88383. if( nByte>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  88384. sqlite3_result_error_toobig(context);
  88385. z = 0;
  88386. }else{
  88387. z = sqlite3Malloc(nByte);
  88388. if( !z ){
  88389. sqlite3_result_error_nomem(context);
  88390. }
  88391. }
  88392. return z;
  88393. }
  88394. /*
  88395. ** Implementation of the upper() and lower() SQL functions.
  88396. */
  88397. static void upperFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88398. char *z1;
  88399. const char *z2;
  88400. int i, n;
  88401. UNUSED_PARAMETER(argc);
  88402. z2 = (char*)sqlite3_value_text(argv[0]);
  88403. n = sqlite3_value_bytes(argv[0]);
  88404. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  88405. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  88406. if( z2 ){
  88407. z1 = contextMalloc(context, ((i64)n)+1);
  88408. if( z1 ){
  88409. for(i=0; i<n; i++){
  88410. z1[i] = (char)sqlite3Toupper(z2[i]);
  88411. }
  88412. sqlite3_result_text(context, z1, n, sqlite3_free);
  88413. }
  88414. }
  88415. }
  88416. static void lowerFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88417. char *z1;
  88418. const char *z2;
  88419. int i, n;
  88420. UNUSED_PARAMETER(argc);
  88421. z2 = (char*)sqlite3_value_text(argv[0]);
  88422. n = sqlite3_value_bytes(argv[0]);
  88423. /* Verify that the call to _bytes() does not invalidate the _text() pointer */
  88424. assert( z2==(char*)sqlite3_value_text(argv[0]) );
  88425. if( z2 ){
  88426. z1 = contextMalloc(context, ((i64)n)+1);
  88427. if( z1 ){
  88428. for(i=0; i<n; i++){
  88429. z1[i] = sqlite3Tolower(z2[i]);
  88430. }
  88431. sqlite3_result_text(context, z1, n, sqlite3_free);
  88432. }
  88433. }
  88434. }
  88435. /*
  88436. ** Some functions like COALESCE() and IFNULL() and UNLIKELY() are implemented
  88437. ** as VDBE code so that unused argument values do not have to be computed.
  88438. ** However, we still need some kind of function implementation for this
  88439. ** routines in the function table. The noopFunc macro provides this.
  88440. ** noopFunc will never be called so it doesn't matter what the implementation
  88441. ** is. We might as well use the "version()" function as a substitute.
  88442. */
  88443. #define noopFunc versionFunc /* Substitute function - never called */
  88444. /*
  88445. ** Implementation of random(). Return a random integer.
  88446. */
  88447. static void randomFunc(
  88448. sqlite3_context *context,
  88449. int NotUsed,
  88450. sqlite3_value **NotUsed2
  88451. ){
  88452. sqlite_int64 r;
  88453. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88454. sqlite3_randomness(sizeof(r), &r);
  88455. if( r<0 ){
  88456. /* We need to prevent a random number of 0x8000000000000000
  88457. ** (or -9223372036854775808) since when you do abs() of that
  88458. ** number of you get the same value back again. To do this
  88459. ** in a way that is testable, mask the sign bit off of negative
  88460. ** values, resulting in a positive value. Then take the
  88461. ** 2s complement of that positive value. The end result can
  88462. ** therefore be no less than -9223372036854775807.
  88463. */
  88464. r = -(r & LARGEST_INT64);
  88465. }
  88466. sqlite3_result_int64(context, r);
  88467. }
  88468. /*
  88469. ** Implementation of randomblob(N). Return a random blob
  88470. ** that is N bytes long.
  88471. */
  88472. static void randomBlob(
  88473. sqlite3_context *context,
  88474. int argc,
  88475. sqlite3_value **argv
  88476. ){
  88477. int n;
  88478. unsigned char *p;
  88479. assert( argc==1 );
  88480. UNUSED_PARAMETER(argc);
  88481. n = sqlite3_value_int(argv[0]);
  88482. if( n<1 ){
  88483. n = 1;
  88484. }
  88485. p = contextMalloc(context, n);
  88486. if( p ){
  88487. sqlite3_randomness(n, p);
  88488. sqlite3_result_blob(context, (char*)p, n, sqlite3_free);
  88489. }
  88490. }
  88491. /*
  88492. ** Implementation of the last_insert_rowid() SQL function. The return
  88493. ** value is the same as the sqlite3_last_insert_rowid() API function.
  88494. */
  88495. static void last_insert_rowid(
  88496. sqlite3_context *context,
  88497. int NotUsed,
  88498. sqlite3_value **NotUsed2
  88499. ){
  88500. sqlite3 *db = sqlite3_context_db_handle(context);
  88501. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88502. /* IMP: R-51513-12026 The last_insert_rowid() SQL function is a
  88503. ** wrapper around the sqlite3_last_insert_rowid() C/C++ interface
  88504. ** function. */
  88505. sqlite3_result_int64(context, sqlite3_last_insert_rowid(db));
  88506. }
  88507. /*
  88508. ** Implementation of the changes() SQL function.
  88509. **
  88510. ** IMP: R-62073-11209 The changes() SQL function is a wrapper
  88511. ** around the sqlite3_changes() C/C++ function and hence follows the same
  88512. ** rules for counting changes.
  88513. */
  88514. static void changes(
  88515. sqlite3_context *context,
  88516. int NotUsed,
  88517. sqlite3_value **NotUsed2
  88518. ){
  88519. sqlite3 *db = sqlite3_context_db_handle(context);
  88520. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88521. sqlite3_result_int(context, sqlite3_changes(db));
  88522. }
  88523. /*
  88524. ** Implementation of the total_changes() SQL function. The return value is
  88525. ** the same as the sqlite3_total_changes() API function.
  88526. */
  88527. static void total_changes(
  88528. sqlite3_context *context,
  88529. int NotUsed,
  88530. sqlite3_value **NotUsed2
  88531. ){
  88532. sqlite3 *db = sqlite3_context_db_handle(context);
  88533. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88534. /* IMP: R-52756-41993 This function is a wrapper around the
  88535. ** sqlite3_total_changes() C/C++ interface. */
  88536. sqlite3_result_int(context, sqlite3_total_changes(db));
  88537. }
  88538. /*
  88539. ** A structure defining how to do GLOB-style comparisons.
  88540. */
  88541. struct compareInfo {
  88542. u8 matchAll;
  88543. u8 matchOne;
  88544. u8 matchSet;
  88545. u8 noCase;
  88546. };
  88547. /*
  88548. ** For LIKE and GLOB matching on EBCDIC machines, assume that every
  88549. ** character is exactly one byte in size. Also, all characters are
  88550. ** able to participate in upper-case-to-lower-case mappings in EBCDIC
  88551. ** whereas only characters less than 0x80 do in ASCII.
  88552. */
  88553. #if defined(SQLITE_EBCDIC)
  88554. # define sqlite3Utf8Read(A) (*((*A)++))
  88555. # define GlobUpperToLower(A) A = sqlite3UpperToLower[A]
  88556. # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
  88557. #else
  88558. # define GlobUpperToLower(A) if( A<=0x7f ){ A = sqlite3UpperToLower[A]; }
  88559. # define GlobUpperToLowerAscii(A) A = sqlite3UpperToLower[A]
  88560. #endif
  88561. static const struct compareInfo globInfo = { '*', '?', '[', 0 };
  88562. /* The correct SQL-92 behavior is for the LIKE operator to ignore
  88563. ** case. Thus 'a' LIKE 'A' would be true. */
  88564. static const struct compareInfo likeInfoNorm = { '%', '_', 0, 1 };
  88565. /* If SQLITE_CASE_SENSITIVE_LIKE is defined, then the LIKE operator
  88566. ** is case sensitive causing 'a' LIKE 'A' to be false */
  88567. static const struct compareInfo likeInfoAlt = { '%', '_', 0, 0 };
  88568. /*
  88569. ** Compare two UTF-8 strings for equality where the first string can
  88570. ** potentially be a "glob" or "like" expression. Return true (1) if they
  88571. ** are the same and false (0) if they are different.
  88572. **
  88573. ** Globbing rules:
  88574. **
  88575. ** '*' Matches any sequence of zero or more characters.
  88576. **
  88577. ** '?' Matches exactly one character.
  88578. **
  88579. ** [...] Matches one character from the enclosed list of
  88580. ** characters.
  88581. **
  88582. ** [^...] Matches one character not in the enclosed list.
  88583. **
  88584. ** With the [...] and [^...] matching, a ']' character can be included
  88585. ** in the list by making it the first character after '[' or '^'. A
  88586. ** range of characters can be specified using '-'. Example:
  88587. ** "[a-z]" matches any single lower-case letter. To match a '-', make
  88588. ** it the last character in the list.
  88589. **
  88590. ** Like matching rules:
  88591. **
  88592. ** '%' Matches any sequence of zero or more characters
  88593. **
  88594. *** '_' Matches any one character
  88595. **
  88596. ** Ec Where E is the "esc" character and c is any other
  88597. ** character, including '%', '_', and esc, match exactly c.
  88598. **
  88599. ** The comments through this routine usually assume glob matching.
  88600. **
  88601. ** This routine is usually quick, but can be N**2 in the worst case.
  88602. */
  88603. static int patternCompare(
  88604. const u8 *zPattern, /* The glob pattern */
  88605. const u8 *zString, /* The string to compare against the glob */
  88606. const struct compareInfo *pInfo, /* Information about how to do the compare */
  88607. u32 esc /* The escape character */
  88608. ){
  88609. u32 c, c2; /* Next pattern and input string chars */
  88610. u32 matchOne = pInfo->matchOne; /* "?" or "_" */
  88611. u32 matchAll = pInfo->matchAll; /* "*" or "%" */
  88612. u32 matchOther; /* "[" or the escape character */
  88613. u8 noCase = pInfo->noCase; /* True if uppercase==lowercase */
  88614. const u8 *zEscaped = 0; /* One past the last escaped input char */
  88615. /* The GLOB operator does not have an ESCAPE clause. And LIKE does not
  88616. ** have the matchSet operator. So we either have to look for one or
  88617. ** the other, never both. Hence the single variable matchOther is used
  88618. ** to store the one we have to look for.
  88619. */
  88620. matchOther = esc ? esc : pInfo->matchSet;
  88621. while( (c = sqlite3Utf8Read(&zPattern))!=0 ){
  88622. if( c==matchAll ){ /* Match "*" */
  88623. /* Skip over multiple "*" characters in the pattern. If there
  88624. ** are also "?" characters, skip those as well, but consume a
  88625. ** single character of the input string for each "?" skipped */
  88626. while( (c=sqlite3Utf8Read(&zPattern)) == matchAll
  88627. || c == matchOne ){
  88628. if( c==matchOne && sqlite3Utf8Read(&zString)==0 ){
  88629. return 0;
  88630. }
  88631. }
  88632. if( c==0 ){
  88633. return 1; /* "*" at the end of the pattern matches */
  88634. }else if( c==matchOther ){
  88635. if( esc ){
  88636. c = sqlite3Utf8Read(&zPattern);
  88637. if( c==0 ) return 0;
  88638. }else{
  88639. /* "[...]" immediately follows the "*". We have to do a slow
  88640. ** recursive search in this case, but it is an unusual case. */
  88641. assert( matchOther<0x80 ); /* '[' is a single-byte character */
  88642. while( *zString
  88643. && patternCompare(&zPattern[-1],zString,pInfo,esc)==0 ){
  88644. SQLITE_SKIP_UTF8(zString);
  88645. }
  88646. return *zString!=0;
  88647. }
  88648. }
  88649. /* At this point variable c contains the first character of the
  88650. ** pattern string past the "*". Search in the input string for the
  88651. ** first matching character and recursively contine the match from
  88652. ** that point.
  88653. **
  88654. ** For a case-insensitive search, set variable cx to be the same as
  88655. ** c but in the other case and search the input string for either
  88656. ** c or cx.
  88657. */
  88658. if( c<=0x80 ){
  88659. u32 cx;
  88660. if( noCase ){
  88661. cx = sqlite3Toupper(c);
  88662. c = sqlite3Tolower(c);
  88663. }else{
  88664. cx = c;
  88665. }
  88666. while( (c2 = *(zString++))!=0 ){
  88667. if( c2!=c && c2!=cx ) continue;
  88668. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  88669. }
  88670. }else{
  88671. while( (c2 = sqlite3Utf8Read(&zString))!=0 ){
  88672. if( c2!=c ) continue;
  88673. if( patternCompare(zPattern,zString,pInfo,esc) ) return 1;
  88674. }
  88675. }
  88676. return 0;
  88677. }
  88678. if( c==matchOther ){
  88679. if( esc ){
  88680. c = sqlite3Utf8Read(&zPattern);
  88681. if( c==0 ) return 0;
  88682. zEscaped = zPattern;
  88683. }else{
  88684. u32 prior_c = 0;
  88685. int seen = 0;
  88686. int invert = 0;
  88687. c = sqlite3Utf8Read(&zString);
  88688. if( c==0 ) return 0;
  88689. c2 = sqlite3Utf8Read(&zPattern);
  88690. if( c2=='^' ){
  88691. invert = 1;
  88692. c2 = sqlite3Utf8Read(&zPattern);
  88693. }
  88694. if( c2==']' ){
  88695. if( c==']' ) seen = 1;
  88696. c2 = sqlite3Utf8Read(&zPattern);
  88697. }
  88698. while( c2 && c2!=']' ){
  88699. if( c2=='-' && zPattern[0]!=']' && zPattern[0]!=0 && prior_c>0 ){
  88700. c2 = sqlite3Utf8Read(&zPattern);
  88701. if( c>=prior_c && c<=c2 ) seen = 1;
  88702. prior_c = 0;
  88703. }else{
  88704. if( c==c2 ){
  88705. seen = 1;
  88706. }
  88707. prior_c = c2;
  88708. }
  88709. c2 = sqlite3Utf8Read(&zPattern);
  88710. }
  88711. if( c2==0 || (seen ^ invert)==0 ){
  88712. return 0;
  88713. }
  88714. continue;
  88715. }
  88716. }
  88717. c2 = sqlite3Utf8Read(&zString);
  88718. if( c==c2 ) continue;
  88719. if( noCase && c<0x80 && c2<0x80 && sqlite3Tolower(c)==sqlite3Tolower(c2) ){
  88720. continue;
  88721. }
  88722. if( c==matchOne && zPattern!=zEscaped && c2!=0 ) continue;
  88723. return 0;
  88724. }
  88725. return *zString==0;
  88726. }
  88727. /*
  88728. ** The sqlite3_strglob() interface.
  88729. */
  88730. SQLITE_API int sqlite3_strglob(const char *zGlobPattern, const char *zString){
  88731. return patternCompare((u8*)zGlobPattern, (u8*)zString, &globInfo, 0)==0;
  88732. }
  88733. /*
  88734. ** Count the number of times that the LIKE operator (or GLOB which is
  88735. ** just a variation of LIKE) gets called. This is used for testing
  88736. ** only.
  88737. */
  88738. #ifdef SQLITE_TEST
  88739. SQLITE_API int sqlite3_like_count = 0;
  88740. #endif
  88741. /*
  88742. ** Implementation of the like() SQL function. This function implements
  88743. ** the build-in LIKE operator. The first argument to the function is the
  88744. ** pattern and the second argument is the string. So, the SQL statements:
  88745. **
  88746. ** A LIKE B
  88747. **
  88748. ** is implemented as like(B,A).
  88749. **
  88750. ** This same function (with a different compareInfo structure) computes
  88751. ** the GLOB operator.
  88752. */
  88753. static void likeFunc(
  88754. sqlite3_context *context,
  88755. int argc,
  88756. sqlite3_value **argv
  88757. ){
  88758. const unsigned char *zA, *zB;
  88759. u32 escape = 0;
  88760. int nPat;
  88761. sqlite3 *db = sqlite3_context_db_handle(context);
  88762. zB = sqlite3_value_text(argv[0]);
  88763. zA = sqlite3_value_text(argv[1]);
  88764. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  88765. ** of deep recursion and N*N behavior in patternCompare().
  88766. */
  88767. nPat = sqlite3_value_bytes(argv[0]);
  88768. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] );
  88769. testcase( nPat==db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]+1 );
  88770. if( nPat > db->aLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH] ){
  88771. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  88772. return;
  88773. }
  88774. assert( zB==sqlite3_value_text(argv[0]) ); /* Encoding did not change */
  88775. if( argc==3 ){
  88776. /* The escape character string must consist of a single UTF-8 character.
  88777. ** Otherwise, return an error.
  88778. */
  88779. const unsigned char *zEsc = sqlite3_value_text(argv[2]);
  88780. if( zEsc==0 ) return;
  88781. if( sqlite3Utf8CharLen((char*)zEsc, -1)!=1 ){
  88782. sqlite3_result_error(context,
  88783. "ESCAPE expression must be a single character", -1);
  88784. return;
  88785. }
  88786. escape = sqlite3Utf8Read(&zEsc);
  88787. }
  88788. if( zA && zB ){
  88789. struct compareInfo *pInfo = sqlite3_user_data(context);
  88790. #ifdef SQLITE_TEST
  88791. sqlite3_like_count++;
  88792. #endif
  88793. sqlite3_result_int(context, patternCompare(zB, zA, pInfo, escape));
  88794. }
  88795. }
  88796. /*
  88797. ** Implementation of the NULLIF(x,y) function. The result is the first
  88798. ** argument if the arguments are different. The result is NULL if the
  88799. ** arguments are equal to each other.
  88800. */
  88801. static void nullifFunc(
  88802. sqlite3_context *context,
  88803. int NotUsed,
  88804. sqlite3_value **argv
  88805. ){
  88806. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  88807. UNUSED_PARAMETER(NotUsed);
  88808. if( sqlite3MemCompare(argv[0], argv[1], pColl)!=0 ){
  88809. sqlite3_result_value(context, argv[0]);
  88810. }
  88811. }
  88812. /*
  88813. ** Implementation of the sqlite_version() function. The result is the version
  88814. ** of the SQLite library that is running.
  88815. */
  88816. static void versionFunc(
  88817. sqlite3_context *context,
  88818. int NotUsed,
  88819. sqlite3_value **NotUsed2
  88820. ){
  88821. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88822. /* IMP: R-48699-48617 This function is an SQL wrapper around the
  88823. ** sqlite3_libversion() C-interface. */
  88824. sqlite3_result_text(context, sqlite3_libversion(), -1, SQLITE_STATIC);
  88825. }
  88826. /*
  88827. ** Implementation of the sqlite_source_id() function. The result is a string
  88828. ** that identifies the particular version of the source code used to build
  88829. ** SQLite.
  88830. */
  88831. static void sourceidFunc(
  88832. sqlite3_context *context,
  88833. int NotUsed,
  88834. sqlite3_value **NotUsed2
  88835. ){
  88836. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  88837. /* IMP: R-24470-31136 This function is an SQL wrapper around the
  88838. ** sqlite3_sourceid() C interface. */
  88839. sqlite3_result_text(context, sqlite3_sourceid(), -1, SQLITE_STATIC);
  88840. }
  88841. /*
  88842. ** Implementation of the sqlite_log() function. This is a wrapper around
  88843. ** sqlite3_log(). The return value is NULL. The function exists purely for
  88844. ** its side-effects.
  88845. */
  88846. static void errlogFunc(
  88847. sqlite3_context *context,
  88848. int argc,
  88849. sqlite3_value **argv
  88850. ){
  88851. UNUSED_PARAMETER(argc);
  88852. UNUSED_PARAMETER(context);
  88853. sqlite3_log(sqlite3_value_int(argv[0]), "%s", sqlite3_value_text(argv[1]));
  88854. }
  88855. /*
  88856. ** Implementation of the sqlite_compileoption_used() function.
  88857. ** The result is an integer that identifies if the compiler option
  88858. ** was used to build SQLite.
  88859. */
  88860. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  88861. static void compileoptionusedFunc(
  88862. sqlite3_context *context,
  88863. int argc,
  88864. sqlite3_value **argv
  88865. ){
  88866. const char *zOptName;
  88867. assert( argc==1 );
  88868. UNUSED_PARAMETER(argc);
  88869. /* IMP: R-39564-36305 The sqlite_compileoption_used() SQL
  88870. ** function is a wrapper around the sqlite3_compileoption_used() C/C++
  88871. ** function.
  88872. */
  88873. if( (zOptName = (const char*)sqlite3_value_text(argv[0]))!=0 ){
  88874. sqlite3_result_int(context, sqlite3_compileoption_used(zOptName));
  88875. }
  88876. }
  88877. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  88878. /*
  88879. ** Implementation of the sqlite_compileoption_get() function.
  88880. ** The result is a string that identifies the compiler options
  88881. ** used to build SQLite.
  88882. */
  88883. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  88884. static void compileoptiongetFunc(
  88885. sqlite3_context *context,
  88886. int argc,
  88887. sqlite3_value **argv
  88888. ){
  88889. int n;
  88890. assert( argc==1 );
  88891. UNUSED_PARAMETER(argc);
  88892. /* IMP: R-04922-24076 The sqlite_compileoption_get() SQL function
  88893. ** is a wrapper around the sqlite3_compileoption_get() C/C++ function.
  88894. */
  88895. n = sqlite3_value_int(argv[0]);
  88896. sqlite3_result_text(context, sqlite3_compileoption_get(n), -1, SQLITE_STATIC);
  88897. }
  88898. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  88899. /* Array for converting from half-bytes (nybbles) into ASCII hex
  88900. ** digits. */
  88901. static const char hexdigits[] = {
  88902. '0', '1', '2', '3', '4', '5', '6', '7',
  88903. '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  88904. };
  88905. /*
  88906. ** Implementation of the QUOTE() function. This function takes a single
  88907. ** argument. If the argument is numeric, the return value is the same as
  88908. ** the argument. If the argument is NULL, the return value is the string
  88909. ** "NULL". Otherwise, the argument is enclosed in single quotes with
  88910. ** single-quote escapes.
  88911. */
  88912. static void quoteFunc(sqlite3_context *context, int argc, sqlite3_value **argv){
  88913. assert( argc==1 );
  88914. UNUSED_PARAMETER(argc);
  88915. switch( sqlite3_value_type(argv[0]) ){
  88916. case SQLITE_FLOAT: {
  88917. double r1, r2;
  88918. char zBuf[50];
  88919. r1 = sqlite3_value_double(argv[0]);
  88920. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.15g", r1);
  88921. sqlite3AtoF(zBuf, &r2, 20, SQLITE_UTF8);
  88922. if( r1!=r2 ){
  88923. sqlite3_snprintf(sizeof(zBuf), zBuf, "%!.20e", r1);
  88924. }
  88925. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  88926. break;
  88927. }
  88928. case SQLITE_INTEGER: {
  88929. sqlite3_result_value(context, argv[0]);
  88930. break;
  88931. }
  88932. case SQLITE_BLOB: {
  88933. char *zText = 0;
  88934. char const *zBlob = sqlite3_value_blob(argv[0]);
  88935. int nBlob = sqlite3_value_bytes(argv[0]);
  88936. assert( zBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  88937. zText = (char *)contextMalloc(context, (2*(i64)nBlob)+4);
  88938. if( zText ){
  88939. int i;
  88940. for(i=0; i<nBlob; i++){
  88941. zText[(i*2)+2] = hexdigits[(zBlob[i]>>4)&0x0F];
  88942. zText[(i*2)+3] = hexdigits[(zBlob[i])&0x0F];
  88943. }
  88944. zText[(nBlob*2)+2] = '\'';
  88945. zText[(nBlob*2)+3] = '\0';
  88946. zText[0] = 'X';
  88947. zText[1] = '\'';
  88948. sqlite3_result_text(context, zText, -1, SQLITE_TRANSIENT);
  88949. sqlite3_free(zText);
  88950. }
  88951. break;
  88952. }
  88953. case SQLITE_TEXT: {
  88954. int i,j;
  88955. u64 n;
  88956. const unsigned char *zArg = sqlite3_value_text(argv[0]);
  88957. char *z;
  88958. if( zArg==0 ) return;
  88959. for(i=0, n=0; zArg[i]; i++){ if( zArg[i]=='\'' ) n++; }
  88960. z = contextMalloc(context, ((i64)i)+((i64)n)+3);
  88961. if( z ){
  88962. z[0] = '\'';
  88963. for(i=0, j=1; zArg[i]; i++){
  88964. z[j++] = zArg[i];
  88965. if( zArg[i]=='\'' ){
  88966. z[j++] = '\'';
  88967. }
  88968. }
  88969. z[j++] = '\'';
  88970. z[j] = 0;
  88971. sqlite3_result_text(context, z, j, sqlite3_free);
  88972. }
  88973. break;
  88974. }
  88975. default: {
  88976. assert( sqlite3_value_type(argv[0])==SQLITE_NULL );
  88977. sqlite3_result_text(context, "NULL", 4, SQLITE_STATIC);
  88978. break;
  88979. }
  88980. }
  88981. }
  88982. /*
  88983. ** The unicode() function. Return the integer unicode code-point value
  88984. ** for the first character of the input string.
  88985. */
  88986. static void unicodeFunc(
  88987. sqlite3_context *context,
  88988. int argc,
  88989. sqlite3_value **argv
  88990. ){
  88991. const unsigned char *z = sqlite3_value_text(argv[0]);
  88992. (void)argc;
  88993. if( z && z[0] ) sqlite3_result_int(context, sqlite3Utf8Read(&z));
  88994. }
  88995. /*
  88996. ** The char() function takes zero or more arguments, each of which is
  88997. ** an integer. It constructs a string where each character of the string
  88998. ** is the unicode character for the corresponding integer argument.
  88999. */
  89000. static void charFunc(
  89001. sqlite3_context *context,
  89002. int argc,
  89003. sqlite3_value **argv
  89004. ){
  89005. unsigned char *z, *zOut;
  89006. int i;
  89007. zOut = z = sqlite3_malloc( argc*4+1 );
  89008. if( z==0 ){
  89009. sqlite3_result_error_nomem(context);
  89010. return;
  89011. }
  89012. for(i=0; i<argc; i++){
  89013. sqlite3_int64 x;
  89014. unsigned c;
  89015. x = sqlite3_value_int64(argv[i]);
  89016. if( x<0 || x>0x10ffff ) x = 0xfffd;
  89017. c = (unsigned)(x & 0x1fffff);
  89018. if( c<0x00080 ){
  89019. *zOut++ = (u8)(c&0xFF);
  89020. }else if( c<0x00800 ){
  89021. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F);
  89022. *zOut++ = 0x80 + (u8)(c & 0x3F);
  89023. }else if( c<0x10000 ){
  89024. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F);
  89025. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  89026. *zOut++ = 0x80 + (u8)(c & 0x3F);
  89027. }else{
  89028. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07);
  89029. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F);
  89030. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F);
  89031. *zOut++ = 0x80 + (u8)(c & 0x3F);
  89032. } \
  89033. }
  89034. sqlite3_result_text64(context, (char*)z, zOut-z, sqlite3_free, SQLITE_UTF8);
  89035. }
  89036. /*
  89037. ** The hex() function. Interpret the argument as a blob. Return
  89038. ** a hexadecimal rendering as text.
  89039. */
  89040. static void hexFunc(
  89041. sqlite3_context *context,
  89042. int argc,
  89043. sqlite3_value **argv
  89044. ){
  89045. int i, n;
  89046. const unsigned char *pBlob;
  89047. char *zHex, *z;
  89048. assert( argc==1 );
  89049. UNUSED_PARAMETER(argc);
  89050. pBlob = sqlite3_value_blob(argv[0]);
  89051. n = sqlite3_value_bytes(argv[0]);
  89052. assert( pBlob==sqlite3_value_blob(argv[0]) ); /* No encoding change */
  89053. z = zHex = contextMalloc(context, ((i64)n)*2 + 1);
  89054. if( zHex ){
  89055. for(i=0; i<n; i++, pBlob++){
  89056. unsigned char c = *pBlob;
  89057. *(z++) = hexdigits[(c>>4)&0xf];
  89058. *(z++) = hexdigits[c&0xf];
  89059. }
  89060. *z = 0;
  89061. sqlite3_result_text(context, zHex, n*2, sqlite3_free);
  89062. }
  89063. }
  89064. /*
  89065. ** The zeroblob(N) function returns a zero-filled blob of size N bytes.
  89066. */
  89067. static void zeroblobFunc(
  89068. sqlite3_context *context,
  89069. int argc,
  89070. sqlite3_value **argv
  89071. ){
  89072. i64 n;
  89073. sqlite3 *db = sqlite3_context_db_handle(context);
  89074. assert( argc==1 );
  89075. UNUSED_PARAMETER(argc);
  89076. n = sqlite3_value_int64(argv[0]);
  89077. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH] );
  89078. testcase( n==db->aLimit[SQLITE_LIMIT_LENGTH]+1 );
  89079. if( n>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  89080. sqlite3_result_error_toobig(context);
  89081. }else{
  89082. sqlite3_result_zeroblob(context, (int)n); /* IMP: R-00293-64994 */
  89083. }
  89084. }
  89085. /*
  89086. ** The replace() function. Three arguments are all strings: call
  89087. ** them A, B, and C. The result is also a string which is derived
  89088. ** from A by replacing every occurrence of B with C. The match
  89089. ** must be exact. Collating sequences are not used.
  89090. */
  89091. static void replaceFunc(
  89092. sqlite3_context *context,
  89093. int argc,
  89094. sqlite3_value **argv
  89095. ){
  89096. const unsigned char *zStr; /* The input string A */
  89097. const unsigned char *zPattern; /* The pattern string B */
  89098. const unsigned char *zRep; /* The replacement string C */
  89099. unsigned char *zOut; /* The output */
  89100. int nStr; /* Size of zStr */
  89101. int nPattern; /* Size of zPattern */
  89102. int nRep; /* Size of zRep */
  89103. i64 nOut; /* Maximum size of zOut */
  89104. int loopLimit; /* Last zStr[] that might match zPattern[] */
  89105. int i, j; /* Loop counters */
  89106. assert( argc==3 );
  89107. UNUSED_PARAMETER(argc);
  89108. zStr = sqlite3_value_text(argv[0]);
  89109. if( zStr==0 ) return;
  89110. nStr = sqlite3_value_bytes(argv[0]);
  89111. assert( zStr==sqlite3_value_text(argv[0]) ); /* No encoding change */
  89112. zPattern = sqlite3_value_text(argv[1]);
  89113. if( zPattern==0 ){
  89114. assert( sqlite3_value_type(argv[1])==SQLITE_NULL
  89115. || sqlite3_context_db_handle(context)->mallocFailed );
  89116. return;
  89117. }
  89118. if( zPattern[0]==0 ){
  89119. assert( sqlite3_value_type(argv[1])!=SQLITE_NULL );
  89120. sqlite3_result_value(context, argv[0]);
  89121. return;
  89122. }
  89123. nPattern = sqlite3_value_bytes(argv[1]);
  89124. assert( zPattern==sqlite3_value_text(argv[1]) ); /* No encoding change */
  89125. zRep = sqlite3_value_text(argv[2]);
  89126. if( zRep==0 ) return;
  89127. nRep = sqlite3_value_bytes(argv[2]);
  89128. assert( zRep==sqlite3_value_text(argv[2]) );
  89129. nOut = nStr + 1;
  89130. assert( nOut<SQLITE_MAX_LENGTH );
  89131. zOut = contextMalloc(context, (i64)nOut);
  89132. if( zOut==0 ){
  89133. return;
  89134. }
  89135. loopLimit = nStr - nPattern;
  89136. for(i=j=0; i<=loopLimit; i++){
  89137. if( zStr[i]!=zPattern[0] || memcmp(&zStr[i], zPattern, nPattern) ){
  89138. zOut[j++] = zStr[i];
  89139. }else{
  89140. u8 *zOld;
  89141. sqlite3 *db = sqlite3_context_db_handle(context);
  89142. nOut += nRep - nPattern;
  89143. testcase( nOut-1==db->aLimit[SQLITE_LIMIT_LENGTH] );
  89144. testcase( nOut-2==db->aLimit[SQLITE_LIMIT_LENGTH] );
  89145. if( nOut-1>db->aLimit[SQLITE_LIMIT_LENGTH] ){
  89146. sqlite3_result_error_toobig(context);
  89147. sqlite3_free(zOut);
  89148. return;
  89149. }
  89150. zOld = zOut;
  89151. zOut = sqlite3_realloc(zOut, (int)nOut);
  89152. if( zOut==0 ){
  89153. sqlite3_result_error_nomem(context);
  89154. sqlite3_free(zOld);
  89155. return;
  89156. }
  89157. memcpy(&zOut[j], zRep, nRep);
  89158. j += nRep;
  89159. i += nPattern-1;
  89160. }
  89161. }
  89162. assert( j+nStr-i+1==nOut );
  89163. memcpy(&zOut[j], &zStr[i], nStr-i);
  89164. j += nStr - i;
  89165. assert( j<=nOut );
  89166. zOut[j] = 0;
  89167. sqlite3_result_text(context, (char*)zOut, j, sqlite3_free);
  89168. }
  89169. /*
  89170. ** Implementation of the TRIM(), LTRIM(), and RTRIM() functions.
  89171. ** The userdata is 0x1 for left trim, 0x2 for right trim, 0x3 for both.
  89172. */
  89173. static void trimFunc(
  89174. sqlite3_context *context,
  89175. int argc,
  89176. sqlite3_value **argv
  89177. ){
  89178. const unsigned char *zIn; /* Input string */
  89179. const unsigned char *zCharSet; /* Set of characters to trim */
  89180. int nIn; /* Number of bytes in input */
  89181. int flags; /* 1: trimleft 2: trimright 3: trim */
  89182. int i; /* Loop counter */
  89183. unsigned char *aLen = 0; /* Length of each character in zCharSet */
  89184. unsigned char **azChar = 0; /* Individual characters in zCharSet */
  89185. int nChar; /* Number of characters in zCharSet */
  89186. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  89187. return;
  89188. }
  89189. zIn = sqlite3_value_text(argv[0]);
  89190. if( zIn==0 ) return;
  89191. nIn = sqlite3_value_bytes(argv[0]);
  89192. assert( zIn==sqlite3_value_text(argv[0]) );
  89193. if( argc==1 ){
  89194. static const unsigned char lenOne[] = { 1 };
  89195. static unsigned char * const azOne[] = { (u8*)" " };
  89196. nChar = 1;
  89197. aLen = (u8*)lenOne;
  89198. azChar = (unsigned char **)azOne;
  89199. zCharSet = 0;
  89200. }else if( (zCharSet = sqlite3_value_text(argv[1]))==0 ){
  89201. return;
  89202. }else{
  89203. const unsigned char *z;
  89204. for(z=zCharSet, nChar=0; *z; nChar++){
  89205. SQLITE_SKIP_UTF8(z);
  89206. }
  89207. if( nChar>0 ){
  89208. azChar = contextMalloc(context, ((i64)nChar)*(sizeof(char*)+1));
  89209. if( azChar==0 ){
  89210. return;
  89211. }
  89212. aLen = (unsigned char*)&azChar[nChar];
  89213. for(z=zCharSet, nChar=0; *z; nChar++){
  89214. azChar[nChar] = (unsigned char *)z;
  89215. SQLITE_SKIP_UTF8(z);
  89216. aLen[nChar] = (u8)(z - azChar[nChar]);
  89217. }
  89218. }
  89219. }
  89220. if( nChar>0 ){
  89221. flags = SQLITE_PTR_TO_INT(sqlite3_user_data(context));
  89222. if( flags & 1 ){
  89223. while( nIn>0 ){
  89224. int len = 0;
  89225. for(i=0; i<nChar; i++){
  89226. len = aLen[i];
  89227. if( len<=nIn && memcmp(zIn, azChar[i], len)==0 ) break;
  89228. }
  89229. if( i>=nChar ) break;
  89230. zIn += len;
  89231. nIn -= len;
  89232. }
  89233. }
  89234. if( flags & 2 ){
  89235. while( nIn>0 ){
  89236. int len = 0;
  89237. for(i=0; i<nChar; i++){
  89238. len = aLen[i];
  89239. if( len<=nIn && memcmp(&zIn[nIn-len],azChar[i],len)==0 ) break;
  89240. }
  89241. if( i>=nChar ) break;
  89242. nIn -= len;
  89243. }
  89244. }
  89245. if( zCharSet ){
  89246. sqlite3_free(azChar);
  89247. }
  89248. }
  89249. sqlite3_result_text(context, (char*)zIn, nIn, SQLITE_TRANSIENT);
  89250. }
  89251. /* IMP: R-25361-16150 This function is omitted from SQLite by default. It
  89252. ** is only available if the SQLITE_SOUNDEX compile-time option is used
  89253. ** when SQLite is built.
  89254. */
  89255. #ifdef SQLITE_SOUNDEX
  89256. /*
  89257. ** Compute the soundex encoding of a word.
  89258. **
  89259. ** IMP: R-59782-00072 The soundex(X) function returns a string that is the
  89260. ** soundex encoding of the string X.
  89261. */
  89262. static void soundexFunc(
  89263. sqlite3_context *context,
  89264. int argc,
  89265. sqlite3_value **argv
  89266. ){
  89267. char zResult[8];
  89268. const u8 *zIn;
  89269. int i, j;
  89270. static const unsigned char iCode[] = {
  89271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  89275. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  89276. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  89277. 0, 0, 1, 2, 3, 0, 1, 2, 0, 0, 2, 2, 4, 5, 5, 0,
  89278. 1, 2, 6, 2, 3, 0, 1, 0, 2, 0, 2, 0, 0, 0, 0, 0,
  89279. };
  89280. assert( argc==1 );
  89281. zIn = (u8*)sqlite3_value_text(argv[0]);
  89282. if( zIn==0 ) zIn = (u8*)"";
  89283. for(i=0; zIn[i] && !sqlite3Isalpha(zIn[i]); i++){}
  89284. if( zIn[i] ){
  89285. u8 prevcode = iCode[zIn[i]&0x7f];
  89286. zResult[0] = sqlite3Toupper(zIn[i]);
  89287. for(j=1; j<4 && zIn[i]; i++){
  89288. int code = iCode[zIn[i]&0x7f];
  89289. if( code>0 ){
  89290. if( code!=prevcode ){
  89291. prevcode = code;
  89292. zResult[j++] = code + '0';
  89293. }
  89294. }else{
  89295. prevcode = 0;
  89296. }
  89297. }
  89298. while( j<4 ){
  89299. zResult[j++] = '0';
  89300. }
  89301. zResult[j] = 0;
  89302. sqlite3_result_text(context, zResult, 4, SQLITE_TRANSIENT);
  89303. }else{
  89304. /* IMP: R-64894-50321 The string "?000" is returned if the argument
  89305. ** is NULL or contains no ASCII alphabetic characters. */
  89306. sqlite3_result_text(context, "?000", 4, SQLITE_STATIC);
  89307. }
  89308. }
  89309. #endif /* SQLITE_SOUNDEX */
  89310. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  89311. /*
  89312. ** A function that loads a shared-library extension then returns NULL.
  89313. */
  89314. static void loadExt(sqlite3_context *context, int argc, sqlite3_value **argv){
  89315. const char *zFile = (const char *)sqlite3_value_text(argv[0]);
  89316. const char *zProc;
  89317. sqlite3 *db = sqlite3_context_db_handle(context);
  89318. char *zErrMsg = 0;
  89319. if( argc==2 ){
  89320. zProc = (const char *)sqlite3_value_text(argv[1]);
  89321. }else{
  89322. zProc = 0;
  89323. }
  89324. if( zFile && sqlite3_load_extension(db, zFile, zProc, &zErrMsg) ){
  89325. sqlite3_result_error(context, zErrMsg, -1);
  89326. sqlite3_free(zErrMsg);
  89327. }
  89328. }
  89329. #endif
  89330. /*
  89331. ** An instance of the following structure holds the context of a
  89332. ** sum() or avg() aggregate computation.
  89333. */
  89334. typedef struct SumCtx SumCtx;
  89335. struct SumCtx {
  89336. double rSum; /* Floating point sum */
  89337. i64 iSum; /* Integer sum */
  89338. i64 cnt; /* Number of elements summed */
  89339. u8 overflow; /* True if integer overflow seen */
  89340. u8 approx; /* True if non-integer value was input to the sum */
  89341. };
  89342. /*
  89343. ** Routines used to compute the sum, average, and total.
  89344. **
  89345. ** The SUM() function follows the (broken) SQL standard which means
  89346. ** that it returns NULL if it sums over no inputs. TOTAL returns
  89347. ** 0.0 in that case. In addition, TOTAL always returns a float where
  89348. ** SUM might return an integer if it never encounters a floating point
  89349. ** value. TOTAL never fails, but SUM might through an exception if
  89350. ** it overflows an integer.
  89351. */
  89352. static void sumStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  89353. SumCtx *p;
  89354. int type;
  89355. assert( argc==1 );
  89356. UNUSED_PARAMETER(argc);
  89357. p = sqlite3_aggregate_context(context, sizeof(*p));
  89358. type = sqlite3_value_numeric_type(argv[0]);
  89359. if( p && type!=SQLITE_NULL ){
  89360. p->cnt++;
  89361. if( type==SQLITE_INTEGER ){
  89362. i64 v = sqlite3_value_int64(argv[0]);
  89363. p->rSum += v;
  89364. if( (p->approx|p->overflow)==0 && sqlite3AddInt64(&p->iSum, v) ){
  89365. p->overflow = 1;
  89366. }
  89367. }else{
  89368. p->rSum += sqlite3_value_double(argv[0]);
  89369. p->approx = 1;
  89370. }
  89371. }
  89372. }
  89373. static void sumFinalize(sqlite3_context *context){
  89374. SumCtx *p;
  89375. p = sqlite3_aggregate_context(context, 0);
  89376. if( p && p->cnt>0 ){
  89377. if( p->overflow ){
  89378. sqlite3_result_error(context,"integer overflow",-1);
  89379. }else if( p->approx ){
  89380. sqlite3_result_double(context, p->rSum);
  89381. }else{
  89382. sqlite3_result_int64(context, p->iSum);
  89383. }
  89384. }
  89385. }
  89386. static void avgFinalize(sqlite3_context *context){
  89387. SumCtx *p;
  89388. p = sqlite3_aggregate_context(context, 0);
  89389. if( p && p->cnt>0 ){
  89390. sqlite3_result_double(context, p->rSum/(double)p->cnt);
  89391. }
  89392. }
  89393. static void totalFinalize(sqlite3_context *context){
  89394. SumCtx *p;
  89395. p = sqlite3_aggregate_context(context, 0);
  89396. /* (double)0 In case of SQLITE_OMIT_FLOATING_POINT... */
  89397. sqlite3_result_double(context, p ? p->rSum : (double)0);
  89398. }
  89399. /*
  89400. ** The following structure keeps track of state information for the
  89401. ** count() aggregate function.
  89402. */
  89403. typedef struct CountCtx CountCtx;
  89404. struct CountCtx {
  89405. i64 n;
  89406. };
  89407. /*
  89408. ** Routines to implement the count() aggregate function.
  89409. */
  89410. static void countStep(sqlite3_context *context, int argc, sqlite3_value **argv){
  89411. CountCtx *p;
  89412. p = sqlite3_aggregate_context(context, sizeof(*p));
  89413. if( (argc==0 || SQLITE_NULL!=sqlite3_value_type(argv[0])) && p ){
  89414. p->n++;
  89415. }
  89416. #ifndef SQLITE_OMIT_DEPRECATED
  89417. /* The sqlite3_aggregate_count() function is deprecated. But just to make
  89418. ** sure it still operates correctly, verify that its count agrees with our
  89419. ** internal count when using count(*) and when the total count can be
  89420. ** expressed as a 32-bit integer. */
  89421. assert( argc==1 || p==0 || p->n>0x7fffffff
  89422. || p->n==sqlite3_aggregate_count(context) );
  89423. #endif
  89424. }
  89425. static void countFinalize(sqlite3_context *context){
  89426. CountCtx *p;
  89427. p = sqlite3_aggregate_context(context, 0);
  89428. sqlite3_result_int64(context, p ? p->n : 0);
  89429. }
  89430. /*
  89431. ** Routines to implement min() and max() aggregate functions.
  89432. */
  89433. static void minmaxStep(
  89434. sqlite3_context *context,
  89435. int NotUsed,
  89436. sqlite3_value **argv
  89437. ){
  89438. Mem *pArg = (Mem *)argv[0];
  89439. Mem *pBest;
  89440. UNUSED_PARAMETER(NotUsed);
  89441. pBest = (Mem *)sqlite3_aggregate_context(context, sizeof(*pBest));
  89442. if( !pBest ) return;
  89443. if( sqlite3_value_type(argv[0])==SQLITE_NULL ){
  89444. if( pBest->flags ) sqlite3SkipAccumulatorLoad(context);
  89445. }else if( pBest->flags ){
  89446. int max;
  89447. int cmp;
  89448. CollSeq *pColl = sqlite3GetFuncCollSeq(context);
  89449. /* This step function is used for both the min() and max() aggregates,
  89450. ** the only difference between the two being that the sense of the
  89451. ** comparison is inverted. For the max() aggregate, the
  89452. ** sqlite3_user_data() function returns (void *)-1. For min() it
  89453. ** returns (void *)db, where db is the sqlite3* database pointer.
  89454. ** Therefore the next statement sets variable 'max' to 1 for the max()
  89455. ** aggregate, or 0 for min().
  89456. */
  89457. max = sqlite3_user_data(context)!=0;
  89458. cmp = sqlite3MemCompare(pBest, pArg, pColl);
  89459. if( (max && cmp<0) || (!max && cmp>0) ){
  89460. sqlite3VdbeMemCopy(pBest, pArg);
  89461. }else{
  89462. sqlite3SkipAccumulatorLoad(context);
  89463. }
  89464. }else{
  89465. pBest->db = sqlite3_context_db_handle(context);
  89466. sqlite3VdbeMemCopy(pBest, pArg);
  89467. }
  89468. }
  89469. static void minMaxFinalize(sqlite3_context *context){
  89470. sqlite3_value *pRes;
  89471. pRes = (sqlite3_value *)sqlite3_aggregate_context(context, 0);
  89472. if( pRes ){
  89473. if( pRes->flags ){
  89474. sqlite3_result_value(context, pRes);
  89475. }
  89476. sqlite3VdbeMemRelease(pRes);
  89477. }
  89478. }
  89479. /*
  89480. ** group_concat(EXPR, ?SEPARATOR?)
  89481. */
  89482. static void groupConcatStep(
  89483. sqlite3_context *context,
  89484. int argc,
  89485. sqlite3_value **argv
  89486. ){
  89487. const char *zVal;
  89488. StrAccum *pAccum;
  89489. const char *zSep;
  89490. int nVal, nSep;
  89491. assert( argc==1 || argc==2 );
  89492. if( sqlite3_value_type(argv[0])==SQLITE_NULL ) return;
  89493. pAccum = (StrAccum*)sqlite3_aggregate_context(context, sizeof(*pAccum));
  89494. if( pAccum ){
  89495. sqlite3 *db = sqlite3_context_db_handle(context);
  89496. int firstTerm = pAccum->useMalloc==0;
  89497. pAccum->useMalloc = 2;
  89498. pAccum->mxAlloc = db->aLimit[SQLITE_LIMIT_LENGTH];
  89499. if( !firstTerm ){
  89500. if( argc==2 ){
  89501. zSep = (char*)sqlite3_value_text(argv[1]);
  89502. nSep = sqlite3_value_bytes(argv[1]);
  89503. }else{
  89504. zSep = ",";
  89505. nSep = 1;
  89506. }
  89507. if( nSep ) sqlite3StrAccumAppend(pAccum, zSep, nSep);
  89508. }
  89509. zVal = (char*)sqlite3_value_text(argv[0]);
  89510. nVal = sqlite3_value_bytes(argv[0]);
  89511. if( zVal ) sqlite3StrAccumAppend(pAccum, zVal, nVal);
  89512. }
  89513. }
  89514. static void groupConcatFinalize(sqlite3_context *context){
  89515. StrAccum *pAccum;
  89516. pAccum = sqlite3_aggregate_context(context, 0);
  89517. if( pAccum ){
  89518. if( pAccum->accError==STRACCUM_TOOBIG ){
  89519. sqlite3_result_error_toobig(context);
  89520. }else if( pAccum->accError==STRACCUM_NOMEM ){
  89521. sqlite3_result_error_nomem(context);
  89522. }else{
  89523. sqlite3_result_text(context, sqlite3StrAccumFinish(pAccum), -1,
  89524. sqlite3_free);
  89525. }
  89526. }
  89527. }
  89528. /*
  89529. ** This routine does per-connection function registration. Most
  89530. ** of the built-in functions above are part of the global function set.
  89531. ** This routine only deals with those that are not global.
  89532. */
  89533. SQLITE_PRIVATE void sqlite3RegisterBuiltinFunctions(sqlite3 *db){
  89534. int rc = sqlite3_overload_function(db, "MATCH", 2);
  89535. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  89536. if( rc==SQLITE_NOMEM ){
  89537. db->mallocFailed = 1;
  89538. }
  89539. }
  89540. /*
  89541. ** Set the LIKEOPT flag on the 2-argument function with the given name.
  89542. */
  89543. static void setLikeOptFlag(sqlite3 *db, const char *zName, u8 flagVal){
  89544. FuncDef *pDef;
  89545. pDef = sqlite3FindFunction(db, zName, sqlite3Strlen30(zName),
  89546. 2, SQLITE_UTF8, 0);
  89547. if( ALWAYS(pDef) ){
  89548. pDef->funcFlags |= flagVal;
  89549. }
  89550. }
  89551. /*
  89552. ** Register the built-in LIKE and GLOB functions. The caseSensitive
  89553. ** parameter determines whether or not the LIKE operator is case
  89554. ** sensitive. GLOB is always case sensitive.
  89555. */
  89556. SQLITE_PRIVATE void sqlite3RegisterLikeFunctions(sqlite3 *db, int caseSensitive){
  89557. struct compareInfo *pInfo;
  89558. if( caseSensitive ){
  89559. pInfo = (struct compareInfo*)&likeInfoAlt;
  89560. }else{
  89561. pInfo = (struct compareInfo*)&likeInfoNorm;
  89562. }
  89563. sqlite3CreateFunc(db, "like", 2, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  89564. sqlite3CreateFunc(db, "like", 3, SQLITE_UTF8, pInfo, likeFunc, 0, 0, 0);
  89565. sqlite3CreateFunc(db, "glob", 2, SQLITE_UTF8,
  89566. (struct compareInfo*)&globInfo, likeFunc, 0, 0, 0);
  89567. setLikeOptFlag(db, "glob", SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE);
  89568. setLikeOptFlag(db, "like",
  89569. caseSensitive ? (SQLITE_FUNC_LIKE | SQLITE_FUNC_CASE) : SQLITE_FUNC_LIKE);
  89570. }
  89571. /*
  89572. ** pExpr points to an expression which implements a function. If
  89573. ** it is appropriate to apply the LIKE optimization to that function
  89574. ** then set aWc[0] through aWc[2] to the wildcard characters and
  89575. ** return TRUE. If the function is not a LIKE-style function then
  89576. ** return FALSE.
  89577. */
  89578. SQLITE_PRIVATE int sqlite3IsLikeFunction(sqlite3 *db, Expr *pExpr, int *pIsNocase, char *aWc){
  89579. FuncDef *pDef;
  89580. if( pExpr->op!=TK_FUNCTION
  89581. || !pExpr->x.pList
  89582. || pExpr->x.pList->nExpr!=2
  89583. ){
  89584. return 0;
  89585. }
  89586. assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
  89587. pDef = sqlite3FindFunction(db, pExpr->u.zToken,
  89588. sqlite3Strlen30(pExpr->u.zToken),
  89589. 2, SQLITE_UTF8, 0);
  89590. if( NEVER(pDef==0) || (pDef->funcFlags & SQLITE_FUNC_LIKE)==0 ){
  89591. return 0;
  89592. }
  89593. /* The memcpy() statement assumes that the wildcard characters are
  89594. ** the first three statements in the compareInfo structure. The
  89595. ** asserts() that follow verify that assumption
  89596. */
  89597. memcpy(aWc, pDef->pUserData, 3);
  89598. assert( (char*)&likeInfoAlt == (char*)&likeInfoAlt.matchAll );
  89599. assert( &((char*)&likeInfoAlt)[1] == (char*)&likeInfoAlt.matchOne );
  89600. assert( &((char*)&likeInfoAlt)[2] == (char*)&likeInfoAlt.matchSet );
  89601. *pIsNocase = (pDef->funcFlags & SQLITE_FUNC_CASE)==0;
  89602. return 1;
  89603. }
  89604. /*
  89605. ** All of the FuncDef structures in the aBuiltinFunc[] array above
  89606. ** to the global function hash table. This occurs at start-time (as
  89607. ** a consequence of calling sqlite3_initialize()).
  89608. **
  89609. ** After this routine runs
  89610. */
  89611. SQLITE_PRIVATE void sqlite3RegisterGlobalFunctions(void){
  89612. /*
  89613. ** The following array holds FuncDef structures for all of the functions
  89614. ** defined in this file.
  89615. **
  89616. ** The array cannot be constant since changes are made to the
  89617. ** FuncDef.pHash elements at start-time. The elements of this array
  89618. ** are read-only after initialization is complete.
  89619. */
  89620. static SQLITE_WSD FuncDef aBuiltinFunc[] = {
  89621. FUNCTION(ltrim, 1, 1, 0, trimFunc ),
  89622. FUNCTION(ltrim, 2, 1, 0, trimFunc ),
  89623. FUNCTION(rtrim, 1, 2, 0, trimFunc ),
  89624. FUNCTION(rtrim, 2, 2, 0, trimFunc ),
  89625. FUNCTION(trim, 1, 3, 0, trimFunc ),
  89626. FUNCTION(trim, 2, 3, 0, trimFunc ),
  89627. FUNCTION(min, -1, 0, 1, minmaxFunc ),
  89628. FUNCTION(min, 0, 0, 1, 0 ),
  89629. AGGREGATE2(min, 1, 0, 1, minmaxStep, minMaxFinalize,
  89630. SQLITE_FUNC_MINMAX ),
  89631. FUNCTION(max, -1, 1, 1, minmaxFunc ),
  89632. FUNCTION(max, 0, 1, 1, 0 ),
  89633. AGGREGATE2(max, 1, 1, 1, minmaxStep, minMaxFinalize,
  89634. SQLITE_FUNC_MINMAX ),
  89635. FUNCTION2(typeof, 1, 0, 0, typeofFunc, SQLITE_FUNC_TYPEOF),
  89636. FUNCTION2(length, 1, 0, 0, lengthFunc, SQLITE_FUNC_LENGTH),
  89637. FUNCTION(instr, 2, 0, 0, instrFunc ),
  89638. FUNCTION(substr, 2, 0, 0, substrFunc ),
  89639. FUNCTION(substr, 3, 0, 0, substrFunc ),
  89640. FUNCTION(printf, -1, 0, 0, printfFunc ),
  89641. FUNCTION(unicode, 1, 0, 0, unicodeFunc ),
  89642. FUNCTION(char, -1, 0, 0, charFunc ),
  89643. FUNCTION(abs, 1, 0, 0, absFunc ),
  89644. #ifndef SQLITE_OMIT_FLOATING_POINT
  89645. FUNCTION(round, 1, 0, 0, roundFunc ),
  89646. FUNCTION(round, 2, 0, 0, roundFunc ),
  89647. #endif
  89648. FUNCTION(upper, 1, 0, 0, upperFunc ),
  89649. FUNCTION(lower, 1, 0, 0, lowerFunc ),
  89650. FUNCTION(coalesce, 1, 0, 0, 0 ),
  89651. FUNCTION(coalesce, 0, 0, 0, 0 ),
  89652. FUNCTION2(coalesce, -1, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  89653. FUNCTION(hex, 1, 0, 0, hexFunc ),
  89654. FUNCTION2(ifnull, 2, 0, 0, noopFunc, SQLITE_FUNC_COALESCE),
  89655. FUNCTION2(unlikely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  89656. FUNCTION2(likelihood, 2, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  89657. FUNCTION2(likely, 1, 0, 0, noopFunc, SQLITE_FUNC_UNLIKELY),
  89658. VFUNCTION(random, 0, 0, 0, randomFunc ),
  89659. VFUNCTION(randomblob, 1, 0, 0, randomBlob ),
  89660. FUNCTION(nullif, 2, 0, 1, nullifFunc ),
  89661. FUNCTION(sqlite_version, 0, 0, 0, versionFunc ),
  89662. FUNCTION(sqlite_source_id, 0, 0, 0, sourceidFunc ),
  89663. FUNCTION(sqlite_log, 2, 0, 0, errlogFunc ),
  89664. #if SQLITE_USER_AUTHENTICATION
  89665. FUNCTION(sqlite_crypt, 2, 0, 0, sqlite3CryptFunc ),
  89666. #endif
  89667. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  89668. FUNCTION(sqlite_compileoption_used,1, 0, 0, compileoptionusedFunc ),
  89669. FUNCTION(sqlite_compileoption_get, 1, 0, 0, compileoptiongetFunc ),
  89670. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  89671. FUNCTION(quote, 1, 0, 0, quoteFunc ),
  89672. VFUNCTION(last_insert_rowid, 0, 0, 0, last_insert_rowid),
  89673. VFUNCTION(changes, 0, 0, 0, changes ),
  89674. VFUNCTION(total_changes, 0, 0, 0, total_changes ),
  89675. FUNCTION(replace, 3, 0, 0, replaceFunc ),
  89676. FUNCTION(zeroblob, 1, 0, 0, zeroblobFunc ),
  89677. #ifdef SQLITE_SOUNDEX
  89678. FUNCTION(soundex, 1, 0, 0, soundexFunc ),
  89679. #endif
  89680. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  89681. FUNCTION(load_extension, 1, 0, 0, loadExt ),
  89682. FUNCTION(load_extension, 2, 0, 0, loadExt ),
  89683. #endif
  89684. AGGREGATE(sum, 1, 0, 0, sumStep, sumFinalize ),
  89685. AGGREGATE(total, 1, 0, 0, sumStep, totalFinalize ),
  89686. AGGREGATE(avg, 1, 0, 0, sumStep, avgFinalize ),
  89687. AGGREGATE2(count, 0, 0, 0, countStep, countFinalize,
  89688. SQLITE_FUNC_COUNT ),
  89689. AGGREGATE(count, 1, 0, 0, countStep, countFinalize ),
  89690. AGGREGATE(group_concat, 1, 0, 0, groupConcatStep, groupConcatFinalize),
  89691. AGGREGATE(group_concat, 2, 0, 0, groupConcatStep, groupConcatFinalize),
  89692. LIKEFUNC(glob, 2, &globInfo, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  89693. #ifdef SQLITE_CASE_SENSITIVE_LIKE
  89694. LIKEFUNC(like, 2, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  89695. LIKEFUNC(like, 3, &likeInfoAlt, SQLITE_FUNC_LIKE|SQLITE_FUNC_CASE),
  89696. #else
  89697. LIKEFUNC(like, 2, &likeInfoNorm, SQLITE_FUNC_LIKE),
  89698. LIKEFUNC(like, 3, &likeInfoNorm, SQLITE_FUNC_LIKE),
  89699. #endif
  89700. };
  89701. int i;
  89702. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  89703. FuncDef *aFunc = (FuncDef*)&GLOBAL(FuncDef, aBuiltinFunc);
  89704. for(i=0; i<ArraySize(aBuiltinFunc); i++){
  89705. sqlite3FuncDefInsert(pHash, &aFunc[i]);
  89706. }
  89707. sqlite3RegisterDateTimeFunctions();
  89708. #ifndef SQLITE_OMIT_ALTERTABLE
  89709. sqlite3AlterFunctions();
  89710. #endif
  89711. #if defined(SQLITE_ENABLE_STAT3) || defined(SQLITE_ENABLE_STAT4)
  89712. sqlite3AnalyzeFunctions();
  89713. #endif
  89714. }
  89715. /************** End of func.c ************************************************/
  89716. /************** Begin file fkey.c ********************************************/
  89717. /*
  89718. **
  89719. ** The author disclaims copyright to this source code. In place of
  89720. ** a legal notice, here is a blessing:
  89721. **
  89722. ** May you do good and not evil.
  89723. ** May you find forgiveness for yourself and forgive others.
  89724. ** May you share freely, never taking more than you give.
  89725. **
  89726. *************************************************************************
  89727. ** This file contains code used by the compiler to add foreign key
  89728. ** support to compiled SQL statements.
  89729. */
  89730. #ifndef SQLITE_OMIT_FOREIGN_KEY
  89731. #ifndef SQLITE_OMIT_TRIGGER
  89732. /*
  89733. ** Deferred and Immediate FKs
  89734. ** --------------------------
  89735. **
  89736. ** Foreign keys in SQLite come in two flavours: deferred and immediate.
  89737. ** If an immediate foreign key constraint is violated,
  89738. ** SQLITE_CONSTRAINT_FOREIGNKEY is returned and the current
  89739. ** statement transaction rolled back. If a
  89740. ** deferred foreign key constraint is violated, no action is taken
  89741. ** immediately. However if the application attempts to commit the
  89742. ** transaction before fixing the constraint violation, the attempt fails.
  89743. **
  89744. ** Deferred constraints are implemented using a simple counter associated
  89745. ** with the database handle. The counter is set to zero each time a
  89746. ** database transaction is opened. Each time a statement is executed
  89747. ** that causes a foreign key violation, the counter is incremented. Each
  89748. ** time a statement is executed that removes an existing violation from
  89749. ** the database, the counter is decremented. When the transaction is
  89750. ** committed, the commit fails if the current value of the counter is
  89751. ** greater than zero. This scheme has two big drawbacks:
  89752. **
  89753. ** * When a commit fails due to a deferred foreign key constraint,
  89754. ** there is no way to tell which foreign constraint is not satisfied,
  89755. ** or which row it is not satisfied for.
  89756. **
  89757. ** * If the database contains foreign key violations when the
  89758. ** transaction is opened, this may cause the mechanism to malfunction.
  89759. **
  89760. ** Despite these problems, this approach is adopted as it seems simpler
  89761. ** than the alternatives.
  89762. **
  89763. ** INSERT operations:
  89764. **
  89765. ** I.1) For each FK for which the table is the child table, search
  89766. ** the parent table for a match. If none is found increment the
  89767. ** constraint counter.
  89768. **
  89769. ** I.2) For each FK for which the table is the parent table,
  89770. ** search the child table for rows that correspond to the new
  89771. ** row in the parent table. Decrement the counter for each row
  89772. ** found (as the constraint is now satisfied).
  89773. **
  89774. ** DELETE operations:
  89775. **
  89776. ** D.1) For each FK for which the table is the child table,
  89777. ** search the parent table for a row that corresponds to the
  89778. ** deleted row in the child table. If such a row is not found,
  89779. ** decrement the counter.
  89780. **
  89781. ** D.2) For each FK for which the table is the parent table, search
  89782. ** the child table for rows that correspond to the deleted row
  89783. ** in the parent table. For each found increment the counter.
  89784. **
  89785. ** UPDATE operations:
  89786. **
  89787. ** An UPDATE command requires that all 4 steps above are taken, but only
  89788. ** for FK constraints for which the affected columns are actually
  89789. ** modified (values must be compared at runtime).
  89790. **
  89791. ** Note that I.1 and D.1 are very similar operations, as are I.2 and D.2.
  89792. ** This simplifies the implementation a bit.
  89793. **
  89794. ** For the purposes of immediate FK constraints, the OR REPLACE conflict
  89795. ** resolution is considered to delete rows before the new row is inserted.
  89796. ** If a delete caused by OR REPLACE violates an FK constraint, an exception
  89797. ** is thrown, even if the FK constraint would be satisfied after the new
  89798. ** row is inserted.
  89799. **
  89800. ** Immediate constraints are usually handled similarly. The only difference
  89801. ** is that the counter used is stored as part of each individual statement
  89802. ** object (struct Vdbe). If, after the statement has run, its immediate
  89803. ** constraint counter is greater than zero,
  89804. ** it returns SQLITE_CONSTRAINT_FOREIGNKEY
  89805. ** and the statement transaction is rolled back. An exception is an INSERT
  89806. ** statement that inserts a single row only (no triggers). In this case,
  89807. ** instead of using a counter, an exception is thrown immediately if the
  89808. ** INSERT violates a foreign key constraint. This is necessary as such
  89809. ** an INSERT does not open a statement transaction.
  89810. **
  89811. ** TODO: How should dropping a table be handled? How should renaming a
  89812. ** table be handled?
  89813. **
  89814. **
  89815. ** Query API Notes
  89816. ** ---------------
  89817. **
  89818. ** Before coding an UPDATE or DELETE row operation, the code-generator
  89819. ** for those two operations needs to know whether or not the operation
  89820. ** requires any FK processing and, if so, which columns of the original
  89821. ** row are required by the FK processing VDBE code (i.e. if FKs were
  89822. ** implemented using triggers, which of the old.* columns would be
  89823. ** accessed). No information is required by the code-generator before
  89824. ** coding an INSERT operation. The functions used by the UPDATE/DELETE
  89825. ** generation code to query for this information are:
  89826. **
  89827. ** sqlite3FkRequired() - Test to see if FK processing is required.
  89828. ** sqlite3FkOldmask() - Query for the set of required old.* columns.
  89829. **
  89830. **
  89831. ** Externally accessible module functions
  89832. ** --------------------------------------
  89833. **
  89834. ** sqlite3FkCheck() - Check for foreign key violations.
  89835. ** sqlite3FkActions() - Code triggers for ON UPDATE/ON DELETE actions.
  89836. ** sqlite3FkDelete() - Delete an FKey structure.
  89837. */
  89838. /*
  89839. ** VDBE Calling Convention
  89840. ** -----------------------
  89841. **
  89842. ** Example:
  89843. **
  89844. ** For the following INSERT statement:
  89845. **
  89846. ** CREATE TABLE t1(a, b INTEGER PRIMARY KEY, c);
  89847. ** INSERT INTO t1 VALUES(1, 2, 3.1);
  89848. **
  89849. ** Register (x): 2 (type integer)
  89850. ** Register (x+1): 1 (type integer)
  89851. ** Register (x+2): NULL (type NULL)
  89852. ** Register (x+3): 3.1 (type real)
  89853. */
  89854. /*
  89855. ** A foreign key constraint requires that the key columns in the parent
  89856. ** table are collectively subject to a UNIQUE or PRIMARY KEY constraint.
  89857. ** Given that pParent is the parent table for foreign key constraint pFKey,
  89858. ** search the schema for a unique index on the parent key columns.
  89859. **
  89860. ** If successful, zero is returned. If the parent key is an INTEGER PRIMARY
  89861. ** KEY column, then output variable *ppIdx is set to NULL. Otherwise, *ppIdx
  89862. ** is set to point to the unique index.
  89863. **
  89864. ** If the parent key consists of a single column (the foreign key constraint
  89865. ** is not a composite foreign key), output variable *paiCol is set to NULL.
  89866. ** Otherwise, it is set to point to an allocated array of size N, where
  89867. ** N is the number of columns in the parent key. The first element of the
  89868. ** array is the index of the child table column that is mapped by the FK
  89869. ** constraint to the parent table column stored in the left-most column
  89870. ** of index *ppIdx. The second element of the array is the index of the
  89871. ** child table column that corresponds to the second left-most column of
  89872. ** *ppIdx, and so on.
  89873. **
  89874. ** If the required index cannot be found, either because:
  89875. **
  89876. ** 1) The named parent key columns do not exist, or
  89877. **
  89878. ** 2) The named parent key columns do exist, but are not subject to a
  89879. ** UNIQUE or PRIMARY KEY constraint, or
  89880. **
  89881. ** 3) No parent key columns were provided explicitly as part of the
  89882. ** foreign key definition, and the parent table does not have a
  89883. ** PRIMARY KEY, or
  89884. **
  89885. ** 4) No parent key columns were provided explicitly as part of the
  89886. ** foreign key definition, and the PRIMARY KEY of the parent table
  89887. ** consists of a different number of columns to the child key in
  89888. ** the child table.
  89889. **
  89890. ** then non-zero is returned, and a "foreign key mismatch" error loaded
  89891. ** into pParse. If an OOM error occurs, non-zero is returned and the
  89892. ** pParse->db->mallocFailed flag is set.
  89893. */
  89894. SQLITE_PRIVATE int sqlite3FkLocateIndex(
  89895. Parse *pParse, /* Parse context to store any error in */
  89896. Table *pParent, /* Parent table of FK constraint pFKey */
  89897. FKey *pFKey, /* Foreign key to find index for */
  89898. Index **ppIdx, /* OUT: Unique index on parent table */
  89899. int **paiCol /* OUT: Map of index columns in pFKey */
  89900. ){
  89901. Index *pIdx = 0; /* Value to return via *ppIdx */
  89902. int *aiCol = 0; /* Value to return via *paiCol */
  89903. int nCol = pFKey->nCol; /* Number of columns in parent key */
  89904. char *zKey = pFKey->aCol[0].zCol; /* Name of left-most parent key column */
  89905. /* The caller is responsible for zeroing output parameters. */
  89906. assert( ppIdx && *ppIdx==0 );
  89907. assert( !paiCol || *paiCol==0 );
  89908. assert( pParse );
  89909. /* If this is a non-composite (single column) foreign key, check if it
  89910. ** maps to the INTEGER PRIMARY KEY of table pParent. If so, leave *ppIdx
  89911. ** and *paiCol set to zero and return early.
  89912. **
  89913. ** Otherwise, for a composite foreign key (more than one column), allocate
  89914. ** space for the aiCol array (returned via output parameter *paiCol).
  89915. ** Non-composite foreign keys do not require the aiCol array.
  89916. */
  89917. if( nCol==1 ){
  89918. /* The FK maps to the IPK if any of the following are true:
  89919. **
  89920. ** 1) There is an INTEGER PRIMARY KEY column and the FK is implicitly
  89921. ** mapped to the primary key of table pParent, or
  89922. ** 2) The FK is explicitly mapped to a column declared as INTEGER
  89923. ** PRIMARY KEY.
  89924. */
  89925. if( pParent->iPKey>=0 ){
  89926. if( !zKey ) return 0;
  89927. if( !sqlite3StrICmp(pParent->aCol[pParent->iPKey].zName, zKey) ) return 0;
  89928. }
  89929. }else if( paiCol ){
  89930. assert( nCol>1 );
  89931. aiCol = (int *)sqlite3DbMallocRaw(pParse->db, nCol*sizeof(int));
  89932. if( !aiCol ) return 1;
  89933. *paiCol = aiCol;
  89934. }
  89935. for(pIdx=pParent->pIndex; pIdx; pIdx=pIdx->pNext){
  89936. if( pIdx->nKeyCol==nCol && IsUniqueIndex(pIdx) ){
  89937. /* pIdx is a UNIQUE index (or a PRIMARY KEY) and has the right number
  89938. ** of columns. If each indexed column corresponds to a foreign key
  89939. ** column of pFKey, then this index is a winner. */
  89940. if( zKey==0 ){
  89941. /* If zKey is NULL, then this foreign key is implicitly mapped to
  89942. ** the PRIMARY KEY of table pParent. The PRIMARY KEY index may be
  89943. ** identified by the test. */
  89944. if( IsPrimaryKeyIndex(pIdx) ){
  89945. if( aiCol ){
  89946. int i;
  89947. for(i=0; i<nCol; i++) aiCol[i] = pFKey->aCol[i].iFrom;
  89948. }
  89949. break;
  89950. }
  89951. }else{
  89952. /* If zKey is non-NULL, then this foreign key was declared to
  89953. ** map to an explicit list of columns in table pParent. Check if this
  89954. ** index matches those columns. Also, check that the index uses
  89955. ** the default collation sequences for each column. */
  89956. int i, j;
  89957. for(i=0; i<nCol; i++){
  89958. i16 iCol = pIdx->aiColumn[i]; /* Index of column in parent tbl */
  89959. char *zDfltColl; /* Def. collation for column */
  89960. char *zIdxCol; /* Name of indexed column */
  89961. /* If the index uses a collation sequence that is different from
  89962. ** the default collation sequence for the column, this index is
  89963. ** unusable. Bail out early in this case. */
  89964. zDfltColl = pParent->aCol[iCol].zColl;
  89965. if( !zDfltColl ){
  89966. zDfltColl = "BINARY";
  89967. }
  89968. if( sqlite3StrICmp(pIdx->azColl[i], zDfltColl) ) break;
  89969. zIdxCol = pParent->aCol[iCol].zName;
  89970. for(j=0; j<nCol; j++){
  89971. if( sqlite3StrICmp(pFKey->aCol[j].zCol, zIdxCol)==0 ){
  89972. if( aiCol ) aiCol[i] = pFKey->aCol[j].iFrom;
  89973. break;
  89974. }
  89975. }
  89976. if( j==nCol ) break;
  89977. }
  89978. if( i==nCol ) break; /* pIdx is usable */
  89979. }
  89980. }
  89981. }
  89982. if( !pIdx ){
  89983. if( !pParse->disableTriggers ){
  89984. sqlite3ErrorMsg(pParse,
  89985. "foreign key mismatch - \"%w\" referencing \"%w\"",
  89986. pFKey->pFrom->zName, pFKey->zTo);
  89987. }
  89988. sqlite3DbFree(pParse->db, aiCol);
  89989. return 1;
  89990. }
  89991. *ppIdx = pIdx;
  89992. return 0;
  89993. }
  89994. /*
  89995. ** This function is called when a row is inserted into or deleted from the
  89996. ** child table of foreign key constraint pFKey. If an SQL UPDATE is executed
  89997. ** on the child table of pFKey, this function is invoked twice for each row
  89998. ** affected - once to "delete" the old row, and then again to "insert" the
  89999. ** new row.
  90000. **
  90001. ** Each time it is called, this function generates VDBE code to locate the
  90002. ** row in the parent table that corresponds to the row being inserted into
  90003. ** or deleted from the child table. If the parent row can be found, no
  90004. ** special action is taken. Otherwise, if the parent row can *not* be
  90005. ** found in the parent table:
  90006. **
  90007. ** Operation | FK type | Action taken
  90008. ** --------------------------------------------------------------------------
  90009. ** INSERT immediate Increment the "immediate constraint counter".
  90010. **
  90011. ** DELETE immediate Decrement the "immediate constraint counter".
  90012. **
  90013. ** INSERT deferred Increment the "deferred constraint counter".
  90014. **
  90015. ** DELETE deferred Decrement the "deferred constraint counter".
  90016. **
  90017. ** These operations are identified in the comment at the top of this file
  90018. ** (fkey.c) as "I.1" and "D.1".
  90019. */
  90020. static void fkLookupParent(
  90021. Parse *pParse, /* Parse context */
  90022. int iDb, /* Index of database housing pTab */
  90023. Table *pTab, /* Parent table of FK pFKey */
  90024. Index *pIdx, /* Unique index on parent key columns in pTab */
  90025. FKey *pFKey, /* Foreign key constraint */
  90026. int *aiCol, /* Map from parent key columns to child table columns */
  90027. int regData, /* Address of array containing child table row */
  90028. int nIncr, /* Increment constraint counter by this */
  90029. int isIgnore /* If true, pretend pTab contains all NULL values */
  90030. ){
  90031. int i; /* Iterator variable */
  90032. Vdbe *v = sqlite3GetVdbe(pParse); /* Vdbe to add code to */
  90033. int iCur = pParse->nTab - 1; /* Cursor number to use */
  90034. int iOk = sqlite3VdbeMakeLabel(v); /* jump here if parent key found */
  90035. /* If nIncr is less than zero, then check at runtime if there are any
  90036. ** outstanding constraints to resolve. If there are not, there is no need
  90037. ** to check if deleting this row resolves any outstanding violations.
  90038. **
  90039. ** Check if any of the key columns in the child table row are NULL. If
  90040. ** any are, then the constraint is considered satisfied. No need to
  90041. ** search for a matching row in the parent table. */
  90042. if( nIncr<0 ){
  90043. sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, iOk);
  90044. VdbeCoverage(v);
  90045. }
  90046. for(i=0; i<pFKey->nCol; i++){
  90047. int iReg = aiCol[i] + regData + 1;
  90048. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iOk); VdbeCoverage(v);
  90049. }
  90050. if( isIgnore==0 ){
  90051. if( pIdx==0 ){
  90052. /* If pIdx is NULL, then the parent key is the INTEGER PRIMARY KEY
  90053. ** column of the parent table (table pTab). */
  90054. int iMustBeInt; /* Address of MustBeInt instruction */
  90055. int regTemp = sqlite3GetTempReg(pParse);
  90056. /* Invoke MustBeInt to coerce the child key value to an integer (i.e.
  90057. ** apply the affinity of the parent key). If this fails, then there
  90058. ** is no matching parent key. Before using MustBeInt, make a copy of
  90059. ** the value. Otherwise, the value inserted into the child key column
  90060. ** will have INTEGER affinity applied to it, which may not be correct. */
  90061. sqlite3VdbeAddOp2(v, OP_SCopy, aiCol[0]+1+regData, regTemp);
  90062. iMustBeInt = sqlite3VdbeAddOp2(v, OP_MustBeInt, regTemp, 0);
  90063. VdbeCoverage(v);
  90064. /* If the parent table is the same as the child table, and we are about
  90065. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  90066. ** then check if the row being inserted matches itself. If so, do not
  90067. ** increment the constraint-counter. */
  90068. if( pTab==pFKey->pFrom && nIncr==1 ){
  90069. sqlite3VdbeAddOp3(v, OP_Eq, regData, iOk, regTemp); VdbeCoverage(v);
  90070. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  90071. }
  90072. sqlite3OpenTable(pParse, iCur, iDb, pTab, OP_OpenRead);
  90073. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, 0, regTemp); VdbeCoverage(v);
  90074. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  90075. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  90076. sqlite3VdbeJumpHere(v, iMustBeInt);
  90077. sqlite3ReleaseTempReg(pParse, regTemp);
  90078. }else{
  90079. int nCol = pFKey->nCol;
  90080. int regTemp = sqlite3GetTempRange(pParse, nCol);
  90081. int regRec = sqlite3GetTempReg(pParse);
  90082. sqlite3VdbeAddOp3(v, OP_OpenRead, iCur, pIdx->tnum, iDb);
  90083. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  90084. for(i=0; i<nCol; i++){
  90085. sqlite3VdbeAddOp2(v, OP_Copy, aiCol[i]+1+regData, regTemp+i);
  90086. }
  90087. /* If the parent table is the same as the child table, and we are about
  90088. ** to increment the constraint-counter (i.e. this is an INSERT operation),
  90089. ** then check if the row being inserted matches itself. If so, do not
  90090. ** increment the constraint-counter.
  90091. **
  90092. ** If any of the parent-key values are NULL, then the row cannot match
  90093. ** itself. So set JUMPIFNULL to make sure we do the OP_Found if any
  90094. ** of the parent-key values are NULL (at this point it is known that
  90095. ** none of the child key values are).
  90096. */
  90097. if( pTab==pFKey->pFrom && nIncr==1 ){
  90098. int iJump = sqlite3VdbeCurrentAddr(v) + nCol + 1;
  90099. for(i=0; i<nCol; i++){
  90100. int iChild = aiCol[i]+1+regData;
  90101. int iParent = pIdx->aiColumn[i]+1+regData;
  90102. assert( aiCol[i]!=pTab->iPKey );
  90103. if( pIdx->aiColumn[i]==pTab->iPKey ){
  90104. /* The parent key is a composite key that includes the IPK column */
  90105. iParent = regData;
  90106. }
  90107. sqlite3VdbeAddOp3(v, OP_Ne, iChild, iJump, iParent); VdbeCoverage(v);
  90108. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  90109. }
  90110. sqlite3VdbeAddOp2(v, OP_Goto, 0, iOk);
  90111. }
  90112. sqlite3VdbeAddOp4(v, OP_MakeRecord, regTemp, nCol, regRec,
  90113. sqlite3IndexAffinityStr(v,pIdx), nCol);
  90114. sqlite3VdbeAddOp4Int(v, OP_Found, iCur, iOk, regRec, 0); VdbeCoverage(v);
  90115. sqlite3ReleaseTempReg(pParse, regRec);
  90116. sqlite3ReleaseTempRange(pParse, regTemp, nCol);
  90117. }
  90118. }
  90119. if( !pFKey->isDeferred && !(pParse->db->flags & SQLITE_DeferFKs)
  90120. && !pParse->pToplevel
  90121. && !pParse->isMultiWrite
  90122. ){
  90123. /* Special case: If this is an INSERT statement that will insert exactly
  90124. ** one row into the table, raise a constraint immediately instead of
  90125. ** incrementing a counter. This is necessary as the VM code is being
  90126. ** generated for will not open a statement transaction. */
  90127. assert( nIncr==1 );
  90128. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  90129. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  90130. }else{
  90131. if( nIncr>0 && pFKey->isDeferred==0 ){
  90132. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  90133. }
  90134. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  90135. }
  90136. sqlite3VdbeResolveLabel(v, iOk);
  90137. sqlite3VdbeAddOp1(v, OP_Close, iCur);
  90138. }
  90139. /*
  90140. ** Return an Expr object that refers to a memory register corresponding
  90141. ** to column iCol of table pTab.
  90142. **
  90143. ** regBase is the first of an array of register that contains the data
  90144. ** for pTab. regBase itself holds the rowid. regBase+1 holds the first
  90145. ** column. regBase+2 holds the second column, and so forth.
  90146. */
  90147. static Expr *exprTableRegister(
  90148. Parse *pParse, /* Parsing and code generating context */
  90149. Table *pTab, /* The table whose content is at r[regBase]... */
  90150. int regBase, /* Contents of table pTab */
  90151. i16 iCol /* Which column of pTab is desired */
  90152. ){
  90153. Expr *pExpr;
  90154. Column *pCol;
  90155. const char *zColl;
  90156. sqlite3 *db = pParse->db;
  90157. pExpr = sqlite3Expr(db, TK_REGISTER, 0);
  90158. if( pExpr ){
  90159. if( iCol>=0 && iCol!=pTab->iPKey ){
  90160. pCol = &pTab->aCol[iCol];
  90161. pExpr->iTable = regBase + iCol + 1;
  90162. pExpr->affinity = pCol->affinity;
  90163. zColl = pCol->zColl;
  90164. if( zColl==0 ) zColl = db->pDfltColl->zName;
  90165. pExpr = sqlite3ExprAddCollateString(pParse, pExpr, zColl);
  90166. }else{
  90167. pExpr->iTable = regBase;
  90168. pExpr->affinity = SQLITE_AFF_INTEGER;
  90169. }
  90170. }
  90171. return pExpr;
  90172. }
  90173. /*
  90174. ** Return an Expr object that refers to column iCol of table pTab which
  90175. ** has cursor iCur.
  90176. */
  90177. static Expr *exprTableColumn(
  90178. sqlite3 *db, /* The database connection */
  90179. Table *pTab, /* The table whose column is desired */
  90180. int iCursor, /* The open cursor on the table */
  90181. i16 iCol /* The column that is wanted */
  90182. ){
  90183. Expr *pExpr = sqlite3Expr(db, TK_COLUMN, 0);
  90184. if( pExpr ){
  90185. pExpr->pTab = pTab;
  90186. pExpr->iTable = iCursor;
  90187. pExpr->iColumn = iCol;
  90188. }
  90189. return pExpr;
  90190. }
  90191. /*
  90192. ** This function is called to generate code executed when a row is deleted
  90193. ** from the parent table of foreign key constraint pFKey and, if pFKey is
  90194. ** deferred, when a row is inserted into the same table. When generating
  90195. ** code for an SQL UPDATE operation, this function may be called twice -
  90196. ** once to "delete" the old row and once to "insert" the new row.
  90197. **
  90198. ** The code generated by this function scans through the rows in the child
  90199. ** table that correspond to the parent table row being deleted or inserted.
  90200. ** For each child row found, one of the following actions is taken:
  90201. **
  90202. ** Operation | FK type | Action taken
  90203. ** --------------------------------------------------------------------------
  90204. ** DELETE immediate Increment the "immediate constraint counter".
  90205. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  90206. ** throw a "FOREIGN KEY constraint failed" exception.
  90207. **
  90208. ** INSERT immediate Decrement the "immediate constraint counter".
  90209. **
  90210. ** DELETE deferred Increment the "deferred constraint counter".
  90211. ** Or, if the ON (UPDATE|DELETE) action is RESTRICT,
  90212. ** throw a "FOREIGN KEY constraint failed" exception.
  90213. **
  90214. ** INSERT deferred Decrement the "deferred constraint counter".
  90215. **
  90216. ** These operations are identified in the comment at the top of this file
  90217. ** (fkey.c) as "I.2" and "D.2".
  90218. */
  90219. static void fkScanChildren(
  90220. Parse *pParse, /* Parse context */
  90221. SrcList *pSrc, /* The child table to be scanned */
  90222. Table *pTab, /* The parent table */
  90223. Index *pIdx, /* Index on parent covering the foreign key */
  90224. FKey *pFKey, /* The foreign key linking pSrc to pTab */
  90225. int *aiCol, /* Map from pIdx cols to child table cols */
  90226. int regData, /* Parent row data starts here */
  90227. int nIncr /* Amount to increment deferred counter by */
  90228. ){
  90229. sqlite3 *db = pParse->db; /* Database handle */
  90230. int i; /* Iterator variable */
  90231. Expr *pWhere = 0; /* WHERE clause to scan with */
  90232. NameContext sNameContext; /* Context used to resolve WHERE clause */
  90233. WhereInfo *pWInfo; /* Context used by sqlite3WhereXXX() */
  90234. int iFkIfZero = 0; /* Address of OP_FkIfZero */
  90235. Vdbe *v = sqlite3GetVdbe(pParse);
  90236. assert( pIdx==0 || pIdx->pTable==pTab );
  90237. assert( pIdx==0 || pIdx->nKeyCol==pFKey->nCol );
  90238. assert( pIdx!=0 || pFKey->nCol==1 );
  90239. assert( pIdx!=0 || HasRowid(pTab) );
  90240. if( nIncr<0 ){
  90241. iFkIfZero = sqlite3VdbeAddOp2(v, OP_FkIfZero, pFKey->isDeferred, 0);
  90242. VdbeCoverage(v);
  90243. }
  90244. /* Create an Expr object representing an SQL expression like:
  90245. **
  90246. ** <parent-key1> = <child-key1> AND <parent-key2> = <child-key2> ...
  90247. **
  90248. ** The collation sequence used for the comparison should be that of
  90249. ** the parent key columns. The affinity of the parent key column should
  90250. ** be applied to each child key value before the comparison takes place.
  90251. */
  90252. for(i=0; i<pFKey->nCol; i++){
  90253. Expr *pLeft; /* Value from parent table row */
  90254. Expr *pRight; /* Column ref to child table */
  90255. Expr *pEq; /* Expression (pLeft = pRight) */
  90256. i16 iCol; /* Index of column in child table */
  90257. const char *zCol; /* Name of column in child table */
  90258. iCol = pIdx ? pIdx->aiColumn[i] : -1;
  90259. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  90260. iCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  90261. assert( iCol>=0 );
  90262. zCol = pFKey->pFrom->aCol[iCol].zName;
  90263. pRight = sqlite3Expr(db, TK_ID, zCol);
  90264. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  90265. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  90266. }
  90267. /* If the child table is the same as the parent table, then add terms
  90268. ** to the WHERE clause that prevent this entry from being scanned.
  90269. ** The added WHERE clause terms are like this:
  90270. **
  90271. ** $current_rowid!=rowid
  90272. ** NOT( $current_a==a AND $current_b==b AND ... )
  90273. **
  90274. ** The first form is used for rowid tables. The second form is used
  90275. ** for WITHOUT ROWID tables. In the second form, the primary key is
  90276. ** (a,b,...)
  90277. */
  90278. if( pTab==pFKey->pFrom && nIncr>0 ){
  90279. Expr *pNe; /* Expression (pLeft != pRight) */
  90280. Expr *pLeft; /* Value from parent table row */
  90281. Expr *pRight; /* Column ref to child table */
  90282. if( HasRowid(pTab) ){
  90283. pLeft = exprTableRegister(pParse, pTab, regData, -1);
  90284. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, -1);
  90285. pNe = sqlite3PExpr(pParse, TK_NE, pLeft, pRight, 0);
  90286. }else{
  90287. Expr *pEq, *pAll = 0;
  90288. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  90289. assert( pIdx!=0 );
  90290. for(i=0; i<pPk->nKeyCol; i++){
  90291. i16 iCol = pIdx->aiColumn[i];
  90292. pLeft = exprTableRegister(pParse, pTab, regData, iCol);
  90293. pRight = exprTableColumn(db, pTab, pSrc->a[0].iCursor, iCol);
  90294. pEq = sqlite3PExpr(pParse, TK_EQ, pLeft, pRight, 0);
  90295. pAll = sqlite3ExprAnd(db, pAll, pEq);
  90296. }
  90297. pNe = sqlite3PExpr(pParse, TK_NOT, pAll, 0, 0);
  90298. }
  90299. pWhere = sqlite3ExprAnd(db, pWhere, pNe);
  90300. }
  90301. /* Resolve the references in the WHERE clause. */
  90302. memset(&sNameContext, 0, sizeof(NameContext));
  90303. sNameContext.pSrcList = pSrc;
  90304. sNameContext.pParse = pParse;
  90305. sqlite3ResolveExprNames(&sNameContext, pWhere);
  90306. /* Create VDBE to loop through the entries in pSrc that match the WHERE
  90307. ** clause. If the constraint is not deferred, throw an exception for
  90308. ** each row found. Otherwise, for deferred constraints, increment the
  90309. ** deferred constraint counter by nIncr for each row selected. */
  90310. pWInfo = sqlite3WhereBegin(pParse, pSrc, pWhere, 0, 0, 0, 0);
  90311. if( nIncr>0 && pFKey->isDeferred==0 ){
  90312. sqlite3ParseToplevel(pParse)->mayAbort = 1;
  90313. }
  90314. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, nIncr);
  90315. if( pWInfo ){
  90316. sqlite3WhereEnd(pWInfo);
  90317. }
  90318. /* Clean up the WHERE clause constructed above. */
  90319. sqlite3ExprDelete(db, pWhere);
  90320. if( iFkIfZero ){
  90321. sqlite3VdbeJumpHere(v, iFkIfZero);
  90322. }
  90323. }
  90324. /*
  90325. ** This function returns a linked list of FKey objects (connected by
  90326. ** FKey.pNextTo) holding all children of table pTab. For example,
  90327. ** given the following schema:
  90328. **
  90329. ** CREATE TABLE t1(a PRIMARY KEY);
  90330. ** CREATE TABLE t2(b REFERENCES t1(a);
  90331. **
  90332. ** Calling this function with table "t1" as an argument returns a pointer
  90333. ** to the FKey structure representing the foreign key constraint on table
  90334. ** "t2". Calling this function with "t2" as the argument would return a
  90335. ** NULL pointer (as there are no FK constraints for which t2 is the parent
  90336. ** table).
  90337. */
  90338. SQLITE_PRIVATE FKey *sqlite3FkReferences(Table *pTab){
  90339. return (FKey *)sqlite3HashFind(&pTab->pSchema->fkeyHash, pTab->zName);
  90340. }
  90341. /*
  90342. ** The second argument is a Trigger structure allocated by the
  90343. ** fkActionTrigger() routine. This function deletes the Trigger structure
  90344. ** and all of its sub-components.
  90345. **
  90346. ** The Trigger structure or any of its sub-components may be allocated from
  90347. ** the lookaside buffer belonging to database handle dbMem.
  90348. */
  90349. static void fkTriggerDelete(sqlite3 *dbMem, Trigger *p){
  90350. if( p ){
  90351. TriggerStep *pStep = p->step_list;
  90352. sqlite3ExprDelete(dbMem, pStep->pWhere);
  90353. sqlite3ExprListDelete(dbMem, pStep->pExprList);
  90354. sqlite3SelectDelete(dbMem, pStep->pSelect);
  90355. sqlite3ExprDelete(dbMem, p->pWhen);
  90356. sqlite3DbFree(dbMem, p);
  90357. }
  90358. }
  90359. /*
  90360. ** This function is called to generate code that runs when table pTab is
  90361. ** being dropped from the database. The SrcList passed as the second argument
  90362. ** to this function contains a single entry guaranteed to resolve to
  90363. ** table pTab.
  90364. **
  90365. ** Normally, no code is required. However, if either
  90366. **
  90367. ** (a) The table is the parent table of a FK constraint, or
  90368. ** (b) The table is the child table of a deferred FK constraint and it is
  90369. ** determined at runtime that there are outstanding deferred FK
  90370. ** constraint violations in the database,
  90371. **
  90372. ** then the equivalent of "DELETE FROM <tbl>" is executed before dropping
  90373. ** the table from the database. Triggers are disabled while running this
  90374. ** DELETE, but foreign key actions are not.
  90375. */
  90376. SQLITE_PRIVATE void sqlite3FkDropTable(Parse *pParse, SrcList *pName, Table *pTab){
  90377. sqlite3 *db = pParse->db;
  90378. if( (db->flags&SQLITE_ForeignKeys) && !IsVirtual(pTab) && !pTab->pSelect ){
  90379. int iSkip = 0;
  90380. Vdbe *v = sqlite3GetVdbe(pParse);
  90381. assert( v ); /* VDBE has already been allocated */
  90382. if( sqlite3FkReferences(pTab)==0 ){
  90383. /* Search for a deferred foreign key constraint for which this table
  90384. ** is the child table. If one cannot be found, return without
  90385. ** generating any VDBE code. If one can be found, then jump over
  90386. ** the entire DELETE if there are no outstanding deferred constraints
  90387. ** when this statement is run. */
  90388. FKey *p;
  90389. for(p=pTab->pFKey; p; p=p->pNextFrom){
  90390. if( p->isDeferred || (db->flags & SQLITE_DeferFKs) ) break;
  90391. }
  90392. if( !p ) return;
  90393. iSkip = sqlite3VdbeMakeLabel(v);
  90394. sqlite3VdbeAddOp2(v, OP_FkIfZero, 1, iSkip); VdbeCoverage(v);
  90395. }
  90396. pParse->disableTriggers = 1;
  90397. sqlite3DeleteFrom(pParse, sqlite3SrcListDup(db, pName, 0), 0);
  90398. pParse->disableTriggers = 0;
  90399. /* If the DELETE has generated immediate foreign key constraint
  90400. ** violations, halt the VDBE and return an error at this point, before
  90401. ** any modifications to the schema are made. This is because statement
  90402. ** transactions are not able to rollback schema changes.
  90403. **
  90404. ** If the SQLITE_DeferFKs flag is set, then this is not required, as
  90405. ** the statement transaction will not be rolled back even if FK
  90406. ** constraints are violated.
  90407. */
  90408. if( (db->flags & SQLITE_DeferFKs)==0 ){
  90409. sqlite3VdbeAddOp2(v, OP_FkIfZero, 0, sqlite3VdbeCurrentAddr(v)+2);
  90410. VdbeCoverage(v);
  90411. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_FOREIGNKEY,
  90412. OE_Abort, 0, P4_STATIC, P5_ConstraintFK);
  90413. }
  90414. if( iSkip ){
  90415. sqlite3VdbeResolveLabel(v, iSkip);
  90416. }
  90417. }
  90418. }
  90419. /*
  90420. ** The second argument points to an FKey object representing a foreign key
  90421. ** for which pTab is the child table. An UPDATE statement against pTab
  90422. ** is currently being processed. For each column of the table that is
  90423. ** actually updated, the corresponding element in the aChange[] array
  90424. ** is zero or greater (if a column is unmodified the corresponding element
  90425. ** is set to -1). If the rowid column is modified by the UPDATE statement
  90426. ** the bChngRowid argument is non-zero.
  90427. **
  90428. ** This function returns true if any of the columns that are part of the
  90429. ** child key for FK constraint *p are modified.
  90430. */
  90431. static int fkChildIsModified(
  90432. Table *pTab, /* Table being updated */
  90433. FKey *p, /* Foreign key for which pTab is the child */
  90434. int *aChange, /* Array indicating modified columns */
  90435. int bChngRowid /* True if rowid is modified by this update */
  90436. ){
  90437. int i;
  90438. for(i=0; i<p->nCol; i++){
  90439. int iChildKey = p->aCol[i].iFrom;
  90440. if( aChange[iChildKey]>=0 ) return 1;
  90441. if( iChildKey==pTab->iPKey && bChngRowid ) return 1;
  90442. }
  90443. return 0;
  90444. }
  90445. /*
  90446. ** The second argument points to an FKey object representing a foreign key
  90447. ** for which pTab is the parent table. An UPDATE statement against pTab
  90448. ** is currently being processed. For each column of the table that is
  90449. ** actually updated, the corresponding element in the aChange[] array
  90450. ** is zero or greater (if a column is unmodified the corresponding element
  90451. ** is set to -1). If the rowid column is modified by the UPDATE statement
  90452. ** the bChngRowid argument is non-zero.
  90453. **
  90454. ** This function returns true if any of the columns that are part of the
  90455. ** parent key for FK constraint *p are modified.
  90456. */
  90457. static int fkParentIsModified(
  90458. Table *pTab,
  90459. FKey *p,
  90460. int *aChange,
  90461. int bChngRowid
  90462. ){
  90463. int i;
  90464. for(i=0; i<p->nCol; i++){
  90465. char *zKey = p->aCol[i].zCol;
  90466. int iKey;
  90467. for(iKey=0; iKey<pTab->nCol; iKey++){
  90468. if( aChange[iKey]>=0 || (iKey==pTab->iPKey && bChngRowid) ){
  90469. Column *pCol = &pTab->aCol[iKey];
  90470. if( zKey ){
  90471. if( 0==sqlite3StrICmp(pCol->zName, zKey) ) return 1;
  90472. }else if( pCol->colFlags & COLFLAG_PRIMKEY ){
  90473. return 1;
  90474. }
  90475. }
  90476. }
  90477. }
  90478. return 0;
  90479. }
  90480. /*
  90481. ** This function is called when inserting, deleting or updating a row of
  90482. ** table pTab to generate VDBE code to perform foreign key constraint
  90483. ** processing for the operation.
  90484. **
  90485. ** For a DELETE operation, parameter regOld is passed the index of the
  90486. ** first register in an array of (pTab->nCol+1) registers containing the
  90487. ** rowid of the row being deleted, followed by each of the column values
  90488. ** of the row being deleted, from left to right. Parameter regNew is passed
  90489. ** zero in this case.
  90490. **
  90491. ** For an INSERT operation, regOld is passed zero and regNew is passed the
  90492. ** first register of an array of (pTab->nCol+1) registers containing the new
  90493. ** row data.
  90494. **
  90495. ** For an UPDATE operation, this function is called twice. Once before
  90496. ** the original record is deleted from the table using the calling convention
  90497. ** described for DELETE. Then again after the original record is deleted
  90498. ** but before the new record is inserted using the INSERT convention.
  90499. */
  90500. SQLITE_PRIVATE void sqlite3FkCheck(
  90501. Parse *pParse, /* Parse context */
  90502. Table *pTab, /* Row is being deleted from this table */
  90503. int regOld, /* Previous row data is stored here */
  90504. int regNew, /* New row data is stored here */
  90505. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  90506. int bChngRowid /* True if rowid is UPDATEd */
  90507. ){
  90508. sqlite3 *db = pParse->db; /* Database handle */
  90509. FKey *pFKey; /* Used to iterate through FKs */
  90510. int iDb; /* Index of database containing pTab */
  90511. const char *zDb; /* Name of database containing pTab */
  90512. int isIgnoreErrors = pParse->disableTriggers;
  90513. /* Exactly one of regOld and regNew should be non-zero. */
  90514. assert( (regOld==0)!=(regNew==0) );
  90515. /* If foreign-keys are disabled, this function is a no-op. */
  90516. if( (db->flags&SQLITE_ForeignKeys)==0 ) return;
  90517. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  90518. zDb = db->aDb[iDb].zName;
  90519. /* Loop through all the foreign key constraints for which pTab is the
  90520. ** child table (the table that the foreign key definition is part of). */
  90521. for(pFKey=pTab->pFKey; pFKey; pFKey=pFKey->pNextFrom){
  90522. Table *pTo; /* Parent table of foreign key pFKey */
  90523. Index *pIdx = 0; /* Index on key columns in pTo */
  90524. int *aiFree = 0;
  90525. int *aiCol;
  90526. int iCol;
  90527. int i;
  90528. int isIgnore = 0;
  90529. if( aChange
  90530. && sqlite3_stricmp(pTab->zName, pFKey->zTo)!=0
  90531. && fkChildIsModified(pTab, pFKey, aChange, bChngRowid)==0
  90532. ){
  90533. continue;
  90534. }
  90535. /* Find the parent table of this foreign key. Also find a unique index
  90536. ** on the parent key columns in the parent table. If either of these
  90537. ** schema items cannot be located, set an error in pParse and return
  90538. ** early. */
  90539. if( pParse->disableTriggers ){
  90540. pTo = sqlite3FindTable(db, pFKey->zTo, zDb);
  90541. }else{
  90542. pTo = sqlite3LocateTable(pParse, 0, pFKey->zTo, zDb);
  90543. }
  90544. if( !pTo || sqlite3FkLocateIndex(pParse, pTo, pFKey, &pIdx, &aiFree) ){
  90545. assert( isIgnoreErrors==0 || (regOld!=0 && regNew==0) );
  90546. if( !isIgnoreErrors || db->mallocFailed ) return;
  90547. if( pTo==0 ){
  90548. /* If isIgnoreErrors is true, then a table is being dropped. In this
  90549. ** case SQLite runs a "DELETE FROM xxx" on the table being dropped
  90550. ** before actually dropping it in order to check FK constraints.
  90551. ** If the parent table of an FK constraint on the current table is
  90552. ** missing, behave as if it is empty. i.e. decrement the relevant
  90553. ** FK counter for each row of the current table with non-NULL keys.
  90554. */
  90555. Vdbe *v = sqlite3GetVdbe(pParse);
  90556. int iJump = sqlite3VdbeCurrentAddr(v) + pFKey->nCol + 1;
  90557. for(i=0; i<pFKey->nCol; i++){
  90558. int iReg = pFKey->aCol[i].iFrom + regOld + 1;
  90559. sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iJump); VdbeCoverage(v);
  90560. }
  90561. sqlite3VdbeAddOp2(v, OP_FkCounter, pFKey->isDeferred, -1);
  90562. }
  90563. continue;
  90564. }
  90565. assert( pFKey->nCol==1 || (aiFree && pIdx) );
  90566. if( aiFree ){
  90567. aiCol = aiFree;
  90568. }else{
  90569. iCol = pFKey->aCol[0].iFrom;
  90570. aiCol = &iCol;
  90571. }
  90572. for(i=0; i<pFKey->nCol; i++){
  90573. if( aiCol[i]==pTab->iPKey ){
  90574. aiCol[i] = -1;
  90575. }
  90576. #ifndef SQLITE_OMIT_AUTHORIZATION
  90577. /* Request permission to read the parent key columns. If the
  90578. ** authorization callback returns SQLITE_IGNORE, behave as if any
  90579. ** values read from the parent table are NULL. */
  90580. if( db->xAuth ){
  90581. int rcauth;
  90582. char *zCol = pTo->aCol[pIdx ? pIdx->aiColumn[i] : pTo->iPKey].zName;
  90583. rcauth = sqlite3AuthReadCol(pParse, pTo->zName, zCol, iDb);
  90584. isIgnore = (rcauth==SQLITE_IGNORE);
  90585. }
  90586. #endif
  90587. }
  90588. /* Take a shared-cache advisory read-lock on the parent table. Allocate
  90589. ** a cursor to use to search the unique index on the parent key columns
  90590. ** in the parent table. */
  90591. sqlite3TableLock(pParse, iDb, pTo->tnum, 0, pTo->zName);
  90592. pParse->nTab++;
  90593. if( regOld!=0 ){
  90594. /* A row is being removed from the child table. Search for the parent.
  90595. ** If the parent does not exist, removing the child row resolves an
  90596. ** outstanding foreign key constraint violation. */
  90597. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regOld, -1,isIgnore);
  90598. }
  90599. if( regNew!=0 ){
  90600. /* A row is being added to the child table. If a parent row cannot
  90601. ** be found, adding the child row has violated the FK constraint. */
  90602. fkLookupParent(pParse, iDb, pTo, pIdx, pFKey, aiCol, regNew, +1,isIgnore);
  90603. }
  90604. sqlite3DbFree(db, aiFree);
  90605. }
  90606. /* Loop through all the foreign key constraints that refer to this table.
  90607. ** (the "child" constraints) */
  90608. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  90609. Index *pIdx = 0; /* Foreign key index for pFKey */
  90610. SrcList *pSrc;
  90611. int *aiCol = 0;
  90612. if( aChange && fkParentIsModified(pTab, pFKey, aChange, bChngRowid)==0 ){
  90613. continue;
  90614. }
  90615. if( !pFKey->isDeferred && !(db->flags & SQLITE_DeferFKs)
  90616. && !pParse->pToplevel && !pParse->isMultiWrite
  90617. ){
  90618. assert( regOld==0 && regNew!=0 );
  90619. /* Inserting a single row into a parent table cannot cause an immediate
  90620. ** foreign key violation. So do nothing in this case. */
  90621. continue;
  90622. }
  90623. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ){
  90624. if( !isIgnoreErrors || db->mallocFailed ) return;
  90625. continue;
  90626. }
  90627. assert( aiCol || pFKey->nCol==1 );
  90628. /* Create a SrcList structure containing the child table. We need the
  90629. ** child table as a SrcList for sqlite3WhereBegin() */
  90630. pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  90631. if( pSrc ){
  90632. struct SrcList_item *pItem = pSrc->a;
  90633. pItem->pTab = pFKey->pFrom;
  90634. pItem->zName = pFKey->pFrom->zName;
  90635. pItem->pTab->nRef++;
  90636. pItem->iCursor = pParse->nTab++;
  90637. if( regNew!=0 ){
  90638. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regNew, -1);
  90639. }
  90640. if( regOld!=0 ){
  90641. /* If there is a RESTRICT action configured for the current operation
  90642. ** on the parent table of this FK, then throw an exception
  90643. ** immediately if the FK constraint is violated, even if this is a
  90644. ** deferred trigger. That's what RESTRICT means. To defer checking
  90645. ** the constraint, the FK should specify NO ACTION (represented
  90646. ** using OE_None). NO ACTION is the default. */
  90647. fkScanChildren(pParse, pSrc, pTab, pIdx, pFKey, aiCol, regOld, 1);
  90648. }
  90649. pItem->zName = 0;
  90650. sqlite3SrcListDelete(db, pSrc);
  90651. }
  90652. sqlite3DbFree(db, aiCol);
  90653. }
  90654. }
  90655. #define COLUMN_MASK(x) (((x)>31) ? 0xffffffff : ((u32)1<<(x)))
  90656. /*
  90657. ** This function is called before generating code to update or delete a
  90658. ** row contained in table pTab.
  90659. */
  90660. SQLITE_PRIVATE u32 sqlite3FkOldmask(
  90661. Parse *pParse, /* Parse context */
  90662. Table *pTab /* Table being modified */
  90663. ){
  90664. u32 mask = 0;
  90665. if( pParse->db->flags&SQLITE_ForeignKeys ){
  90666. FKey *p;
  90667. int i;
  90668. for(p=pTab->pFKey; p; p=p->pNextFrom){
  90669. for(i=0; i<p->nCol; i++) mask |= COLUMN_MASK(p->aCol[i].iFrom);
  90670. }
  90671. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  90672. Index *pIdx = 0;
  90673. sqlite3FkLocateIndex(pParse, pTab, p, &pIdx, 0);
  90674. if( pIdx ){
  90675. for(i=0; i<pIdx->nKeyCol; i++) mask |= COLUMN_MASK(pIdx->aiColumn[i]);
  90676. }
  90677. }
  90678. }
  90679. return mask;
  90680. }
  90681. /*
  90682. ** This function is called before generating code to update or delete a
  90683. ** row contained in table pTab. If the operation is a DELETE, then
  90684. ** parameter aChange is passed a NULL value. For an UPDATE, aChange points
  90685. ** to an array of size N, where N is the number of columns in table pTab.
  90686. ** If the i'th column is not modified by the UPDATE, then the corresponding
  90687. ** entry in the aChange[] array is set to -1. If the column is modified,
  90688. ** the value is 0 or greater. Parameter chngRowid is set to true if the
  90689. ** UPDATE statement modifies the rowid fields of the table.
  90690. **
  90691. ** If any foreign key processing will be required, this function returns
  90692. ** true. If there is no foreign key related processing, this function
  90693. ** returns false.
  90694. */
  90695. SQLITE_PRIVATE int sqlite3FkRequired(
  90696. Parse *pParse, /* Parse context */
  90697. Table *pTab, /* Table being modified */
  90698. int *aChange, /* Non-NULL for UPDATE operations */
  90699. int chngRowid /* True for UPDATE that affects rowid */
  90700. ){
  90701. if( pParse->db->flags&SQLITE_ForeignKeys ){
  90702. if( !aChange ){
  90703. /* A DELETE operation. Foreign key processing is required if the
  90704. ** table in question is either the child or parent table for any
  90705. ** foreign key constraint. */
  90706. return (sqlite3FkReferences(pTab) || pTab->pFKey);
  90707. }else{
  90708. /* This is an UPDATE. Foreign key processing is only required if the
  90709. ** operation modifies one or more child or parent key columns. */
  90710. FKey *p;
  90711. /* Check if any child key columns are being modified. */
  90712. for(p=pTab->pFKey; p; p=p->pNextFrom){
  90713. if( fkChildIsModified(pTab, p, aChange, chngRowid) ) return 1;
  90714. }
  90715. /* Check if any parent key columns are being modified. */
  90716. for(p=sqlite3FkReferences(pTab); p; p=p->pNextTo){
  90717. if( fkParentIsModified(pTab, p, aChange, chngRowid) ) return 1;
  90718. }
  90719. }
  90720. }
  90721. return 0;
  90722. }
  90723. /*
  90724. ** This function is called when an UPDATE or DELETE operation is being
  90725. ** compiled on table pTab, which is the parent table of foreign-key pFKey.
  90726. ** If the current operation is an UPDATE, then the pChanges parameter is
  90727. ** passed a pointer to the list of columns being modified. If it is a
  90728. ** DELETE, pChanges is passed a NULL pointer.
  90729. **
  90730. ** It returns a pointer to a Trigger structure containing a trigger
  90731. ** equivalent to the ON UPDATE or ON DELETE action specified by pFKey.
  90732. ** If the action is "NO ACTION" or "RESTRICT", then a NULL pointer is
  90733. ** returned (these actions require no special handling by the triggers
  90734. ** sub-system, code for them is created by fkScanChildren()).
  90735. **
  90736. ** For example, if pFKey is the foreign key and pTab is table "p" in
  90737. ** the following schema:
  90738. **
  90739. ** CREATE TABLE p(pk PRIMARY KEY);
  90740. ** CREATE TABLE c(ck REFERENCES p ON DELETE CASCADE);
  90741. **
  90742. ** then the returned trigger structure is equivalent to:
  90743. **
  90744. ** CREATE TRIGGER ... DELETE ON p BEGIN
  90745. ** DELETE FROM c WHERE ck = old.pk;
  90746. ** END;
  90747. **
  90748. ** The returned pointer is cached as part of the foreign key object. It
  90749. ** is eventually freed along with the rest of the foreign key object by
  90750. ** sqlite3FkDelete().
  90751. */
  90752. static Trigger *fkActionTrigger(
  90753. Parse *pParse, /* Parse context */
  90754. Table *pTab, /* Table being updated or deleted from */
  90755. FKey *pFKey, /* Foreign key to get action for */
  90756. ExprList *pChanges /* Change-list for UPDATE, NULL for DELETE */
  90757. ){
  90758. sqlite3 *db = pParse->db; /* Database handle */
  90759. int action; /* One of OE_None, OE_Cascade etc. */
  90760. Trigger *pTrigger; /* Trigger definition to return */
  90761. int iAction = (pChanges!=0); /* 1 for UPDATE, 0 for DELETE */
  90762. action = pFKey->aAction[iAction];
  90763. pTrigger = pFKey->apTrigger[iAction];
  90764. if( action!=OE_None && !pTrigger ){
  90765. u8 enableLookaside; /* Copy of db->lookaside.bEnabled */
  90766. char const *zFrom; /* Name of child table */
  90767. int nFrom; /* Length in bytes of zFrom */
  90768. Index *pIdx = 0; /* Parent key index for this FK */
  90769. int *aiCol = 0; /* child table cols -> parent key cols */
  90770. TriggerStep *pStep = 0; /* First (only) step of trigger program */
  90771. Expr *pWhere = 0; /* WHERE clause of trigger step */
  90772. ExprList *pList = 0; /* Changes list if ON UPDATE CASCADE */
  90773. Select *pSelect = 0; /* If RESTRICT, "SELECT RAISE(...)" */
  90774. int i; /* Iterator variable */
  90775. Expr *pWhen = 0; /* WHEN clause for the trigger */
  90776. if( sqlite3FkLocateIndex(pParse, pTab, pFKey, &pIdx, &aiCol) ) return 0;
  90777. assert( aiCol || pFKey->nCol==1 );
  90778. for(i=0; i<pFKey->nCol; i++){
  90779. Token tOld = { "old", 3 }; /* Literal "old" token */
  90780. Token tNew = { "new", 3 }; /* Literal "new" token */
  90781. Token tFromCol; /* Name of column in child table */
  90782. Token tToCol; /* Name of column in parent table */
  90783. int iFromCol; /* Idx of column in child table */
  90784. Expr *pEq; /* tFromCol = OLD.tToCol */
  90785. iFromCol = aiCol ? aiCol[i] : pFKey->aCol[0].iFrom;
  90786. assert( iFromCol>=0 );
  90787. tToCol.z = pIdx ? pTab->aCol[pIdx->aiColumn[i]].zName : "oid";
  90788. tFromCol.z = pFKey->pFrom->aCol[iFromCol].zName;
  90789. tToCol.n = sqlite3Strlen30(tToCol.z);
  90790. tFromCol.n = sqlite3Strlen30(tFromCol.z);
  90791. /* Create the expression "OLD.zToCol = zFromCol". It is important
  90792. ** that the "OLD.zToCol" term is on the LHS of the = operator, so
  90793. ** that the affinity and collation sequence associated with the
  90794. ** parent table are used for the comparison. */
  90795. pEq = sqlite3PExpr(pParse, TK_EQ,
  90796. sqlite3PExpr(pParse, TK_DOT,
  90797. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  90798. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  90799. , 0),
  90800. sqlite3PExpr(pParse, TK_ID, 0, 0, &tFromCol)
  90801. , 0);
  90802. pWhere = sqlite3ExprAnd(db, pWhere, pEq);
  90803. /* For ON UPDATE, construct the next term of the WHEN clause.
  90804. ** The final WHEN clause will be like this:
  90805. **
  90806. ** WHEN NOT(old.col1 IS new.col1 AND ... AND old.colN IS new.colN)
  90807. */
  90808. if( pChanges ){
  90809. pEq = sqlite3PExpr(pParse, TK_IS,
  90810. sqlite3PExpr(pParse, TK_DOT,
  90811. sqlite3PExpr(pParse, TK_ID, 0, 0, &tOld),
  90812. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  90813. 0),
  90814. sqlite3PExpr(pParse, TK_DOT,
  90815. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  90816. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol),
  90817. 0),
  90818. 0);
  90819. pWhen = sqlite3ExprAnd(db, pWhen, pEq);
  90820. }
  90821. if( action!=OE_Restrict && (action!=OE_Cascade || pChanges) ){
  90822. Expr *pNew;
  90823. if( action==OE_Cascade ){
  90824. pNew = sqlite3PExpr(pParse, TK_DOT,
  90825. sqlite3PExpr(pParse, TK_ID, 0, 0, &tNew),
  90826. sqlite3PExpr(pParse, TK_ID, 0, 0, &tToCol)
  90827. , 0);
  90828. }else if( action==OE_SetDflt ){
  90829. Expr *pDflt = pFKey->pFrom->aCol[iFromCol].pDflt;
  90830. if( pDflt ){
  90831. pNew = sqlite3ExprDup(db, pDflt, 0);
  90832. }else{
  90833. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  90834. }
  90835. }else{
  90836. pNew = sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
  90837. }
  90838. pList = sqlite3ExprListAppend(pParse, pList, pNew);
  90839. sqlite3ExprListSetName(pParse, pList, &tFromCol, 0);
  90840. }
  90841. }
  90842. sqlite3DbFree(db, aiCol);
  90843. zFrom = pFKey->pFrom->zName;
  90844. nFrom = sqlite3Strlen30(zFrom);
  90845. if( action==OE_Restrict ){
  90846. Token tFrom;
  90847. Expr *pRaise;
  90848. tFrom.z = zFrom;
  90849. tFrom.n = nFrom;
  90850. pRaise = sqlite3Expr(db, TK_RAISE, "FOREIGN KEY constraint failed");
  90851. if( pRaise ){
  90852. pRaise->affinity = OE_Abort;
  90853. }
  90854. pSelect = sqlite3SelectNew(pParse,
  90855. sqlite3ExprListAppend(pParse, 0, pRaise),
  90856. sqlite3SrcListAppend(db, 0, &tFrom, 0),
  90857. pWhere,
  90858. 0, 0, 0, 0, 0, 0
  90859. );
  90860. pWhere = 0;
  90861. }
  90862. /* Disable lookaside memory allocation */
  90863. enableLookaside = db->lookaside.bEnabled;
  90864. db->lookaside.bEnabled = 0;
  90865. pTrigger = (Trigger *)sqlite3DbMallocZero(db,
  90866. sizeof(Trigger) + /* struct Trigger */
  90867. sizeof(TriggerStep) + /* Single step in trigger program */
  90868. nFrom + 1 /* Space for pStep->target.z */
  90869. );
  90870. if( pTrigger ){
  90871. pStep = pTrigger->step_list = (TriggerStep *)&pTrigger[1];
  90872. pStep->target.z = (char *)&pStep[1];
  90873. pStep->target.n = nFrom;
  90874. memcpy((char *)pStep->target.z, zFrom, nFrom);
  90875. pStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  90876. pStep->pExprList = sqlite3ExprListDup(db, pList, EXPRDUP_REDUCE);
  90877. pStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  90878. if( pWhen ){
  90879. pWhen = sqlite3PExpr(pParse, TK_NOT, pWhen, 0, 0);
  90880. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  90881. }
  90882. }
  90883. /* Re-enable the lookaside buffer, if it was disabled earlier. */
  90884. db->lookaside.bEnabled = enableLookaside;
  90885. sqlite3ExprDelete(db, pWhere);
  90886. sqlite3ExprDelete(db, pWhen);
  90887. sqlite3ExprListDelete(db, pList);
  90888. sqlite3SelectDelete(db, pSelect);
  90889. if( db->mallocFailed==1 ){
  90890. fkTriggerDelete(db, pTrigger);
  90891. return 0;
  90892. }
  90893. assert( pStep!=0 );
  90894. switch( action ){
  90895. case OE_Restrict:
  90896. pStep->op = TK_SELECT;
  90897. break;
  90898. case OE_Cascade:
  90899. if( !pChanges ){
  90900. pStep->op = TK_DELETE;
  90901. break;
  90902. }
  90903. default:
  90904. pStep->op = TK_UPDATE;
  90905. }
  90906. pStep->pTrig = pTrigger;
  90907. pTrigger->pSchema = pTab->pSchema;
  90908. pTrigger->pTabSchema = pTab->pSchema;
  90909. pFKey->apTrigger[iAction] = pTrigger;
  90910. pTrigger->op = (pChanges ? TK_UPDATE : TK_DELETE);
  90911. }
  90912. return pTrigger;
  90913. }
  90914. /*
  90915. ** This function is called when deleting or updating a row to implement
  90916. ** any required CASCADE, SET NULL or SET DEFAULT actions.
  90917. */
  90918. SQLITE_PRIVATE void sqlite3FkActions(
  90919. Parse *pParse, /* Parse context */
  90920. Table *pTab, /* Table being updated or deleted from */
  90921. ExprList *pChanges, /* Change-list for UPDATE, NULL for DELETE */
  90922. int regOld, /* Address of array containing old row */
  90923. int *aChange, /* Array indicating UPDATEd columns (or 0) */
  90924. int bChngRowid /* True if rowid is UPDATEd */
  90925. ){
  90926. /* If foreign-key support is enabled, iterate through all FKs that
  90927. ** refer to table pTab. If there is an action associated with the FK
  90928. ** for this operation (either update or delete), invoke the associated
  90929. ** trigger sub-program. */
  90930. if( pParse->db->flags&SQLITE_ForeignKeys ){
  90931. FKey *pFKey; /* Iterator variable */
  90932. for(pFKey = sqlite3FkReferences(pTab); pFKey; pFKey=pFKey->pNextTo){
  90933. if( aChange==0 || fkParentIsModified(pTab, pFKey, aChange, bChngRowid) ){
  90934. Trigger *pAct = fkActionTrigger(pParse, pTab, pFKey, pChanges);
  90935. if( pAct ){
  90936. sqlite3CodeRowTriggerDirect(pParse, pAct, pTab, regOld, OE_Abort, 0);
  90937. }
  90938. }
  90939. }
  90940. }
  90941. }
  90942. #endif /* ifndef SQLITE_OMIT_TRIGGER */
  90943. /*
  90944. ** Free all memory associated with foreign key definitions attached to
  90945. ** table pTab. Remove the deleted foreign keys from the Schema.fkeyHash
  90946. ** hash table.
  90947. */
  90948. SQLITE_PRIVATE void sqlite3FkDelete(sqlite3 *db, Table *pTab){
  90949. FKey *pFKey; /* Iterator variable */
  90950. FKey *pNext; /* Copy of pFKey->pNextFrom */
  90951. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, pTab->pSchema) );
  90952. for(pFKey=pTab->pFKey; pFKey; pFKey=pNext){
  90953. /* Remove the FK from the fkeyHash hash table. */
  90954. if( !db || db->pnBytesFreed==0 ){
  90955. if( pFKey->pPrevTo ){
  90956. pFKey->pPrevTo->pNextTo = pFKey->pNextTo;
  90957. }else{
  90958. void *p = (void *)pFKey->pNextTo;
  90959. const char *z = (p ? pFKey->pNextTo->zTo : pFKey->zTo);
  90960. sqlite3HashInsert(&pTab->pSchema->fkeyHash, z, p);
  90961. }
  90962. if( pFKey->pNextTo ){
  90963. pFKey->pNextTo->pPrevTo = pFKey->pPrevTo;
  90964. }
  90965. }
  90966. /* EV: R-30323-21917 Each foreign key constraint in SQLite is
  90967. ** classified as either immediate or deferred.
  90968. */
  90969. assert( pFKey->isDeferred==0 || pFKey->isDeferred==1 );
  90970. /* Delete any triggers created to implement actions for this FK. */
  90971. #ifndef SQLITE_OMIT_TRIGGER
  90972. fkTriggerDelete(db, pFKey->apTrigger[0]);
  90973. fkTriggerDelete(db, pFKey->apTrigger[1]);
  90974. #endif
  90975. pNext = pFKey->pNextFrom;
  90976. sqlite3DbFree(db, pFKey);
  90977. }
  90978. }
  90979. #endif /* ifndef SQLITE_OMIT_FOREIGN_KEY */
  90980. /************** End of fkey.c ************************************************/
  90981. /************** Begin file insert.c ******************************************/
  90982. /*
  90983. ** 2001 September 15
  90984. **
  90985. ** The author disclaims copyright to this source code. In place of
  90986. ** a legal notice, here is a blessing:
  90987. **
  90988. ** May you do good and not evil.
  90989. ** May you find forgiveness for yourself and forgive others.
  90990. ** May you share freely, never taking more than you give.
  90991. **
  90992. *************************************************************************
  90993. ** This file contains C code routines that are called by the parser
  90994. ** to handle INSERT statements in SQLite.
  90995. */
  90996. /*
  90997. ** Generate code that will
  90998. **
  90999. ** (1) acquire a lock for table pTab then
  91000. ** (2) open pTab as cursor iCur.
  91001. **
  91002. ** If pTab is a WITHOUT ROWID table, then it is the PRIMARY KEY index
  91003. ** for that table that is actually opened.
  91004. */
  91005. SQLITE_PRIVATE void sqlite3OpenTable(
  91006. Parse *pParse, /* Generate code into this VDBE */
  91007. int iCur, /* The cursor number of the table */
  91008. int iDb, /* The database index in sqlite3.aDb[] */
  91009. Table *pTab, /* The table to be opened */
  91010. int opcode /* OP_OpenRead or OP_OpenWrite */
  91011. ){
  91012. Vdbe *v;
  91013. assert( !IsVirtual(pTab) );
  91014. v = sqlite3GetVdbe(pParse);
  91015. assert( opcode==OP_OpenWrite || opcode==OP_OpenRead );
  91016. sqlite3TableLock(pParse, iDb, pTab->tnum,
  91017. (opcode==OP_OpenWrite)?1:0, pTab->zName);
  91018. if( HasRowid(pTab) ){
  91019. sqlite3VdbeAddOp4Int(v, opcode, iCur, pTab->tnum, iDb, pTab->nCol);
  91020. VdbeComment((v, "%s", pTab->zName));
  91021. }else{
  91022. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  91023. assert( pPk!=0 );
  91024. assert( pPk->tnum=pTab->tnum );
  91025. sqlite3VdbeAddOp3(v, opcode, iCur, pPk->tnum, iDb);
  91026. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  91027. VdbeComment((v, "%s", pTab->zName));
  91028. }
  91029. }
  91030. /*
  91031. ** Return a pointer to the column affinity string associated with index
  91032. ** pIdx. A column affinity string has one character for each column in
  91033. ** the table, according to the affinity of the column:
  91034. **
  91035. ** Character Column affinity
  91036. ** ------------------------------
  91037. ** 'A' NONE
  91038. ** 'B' TEXT
  91039. ** 'C' NUMERIC
  91040. ** 'D' INTEGER
  91041. ** 'F' REAL
  91042. **
  91043. ** An extra 'D' is appended to the end of the string to cover the
  91044. ** rowid that appears as the last column in every index.
  91045. **
  91046. ** Memory for the buffer containing the column index affinity string
  91047. ** is managed along with the rest of the Index structure. It will be
  91048. ** released when sqlite3DeleteIndex() is called.
  91049. */
  91050. SQLITE_PRIVATE const char *sqlite3IndexAffinityStr(Vdbe *v, Index *pIdx){
  91051. if( !pIdx->zColAff ){
  91052. /* The first time a column affinity string for a particular index is
  91053. ** required, it is allocated and populated here. It is then stored as
  91054. ** a member of the Index structure for subsequent use.
  91055. **
  91056. ** The column affinity string will eventually be deleted by
  91057. ** sqliteDeleteIndex() when the Index structure itself is cleaned
  91058. ** up.
  91059. */
  91060. int n;
  91061. Table *pTab = pIdx->pTable;
  91062. sqlite3 *db = sqlite3VdbeDb(v);
  91063. pIdx->zColAff = (char *)sqlite3DbMallocRaw(0, pIdx->nColumn+1);
  91064. if( !pIdx->zColAff ){
  91065. db->mallocFailed = 1;
  91066. return 0;
  91067. }
  91068. for(n=0; n<pIdx->nColumn; n++){
  91069. i16 x = pIdx->aiColumn[n];
  91070. pIdx->zColAff[n] = x<0 ? SQLITE_AFF_INTEGER : pTab->aCol[x].affinity;
  91071. }
  91072. pIdx->zColAff[n] = 0;
  91073. }
  91074. return pIdx->zColAff;
  91075. }
  91076. /*
  91077. ** Compute the affinity string for table pTab, if it has not already been
  91078. ** computed. As an optimization, omit trailing SQLITE_AFF_NONE affinities.
  91079. **
  91080. ** If the affinity exists (if it is no entirely SQLITE_AFF_NONE values) and
  91081. ** if iReg>0 then code an OP_Affinity opcode that will set the affinities
  91082. ** for register iReg and following. Or if affinities exists and iReg==0,
  91083. ** then just set the P4 operand of the previous opcode (which should be
  91084. ** an OP_MakeRecord) to the affinity string.
  91085. **
  91086. ** A column affinity string has one character per column:
  91087. **
  91088. ** Character Column affinity
  91089. ** ------------------------------
  91090. ** 'A' NONE
  91091. ** 'B' TEXT
  91092. ** 'C' NUMERIC
  91093. ** 'D' INTEGER
  91094. ** 'E' REAL
  91095. */
  91096. SQLITE_PRIVATE void sqlite3TableAffinity(Vdbe *v, Table *pTab, int iReg){
  91097. int i;
  91098. char *zColAff = pTab->zColAff;
  91099. if( zColAff==0 ){
  91100. sqlite3 *db = sqlite3VdbeDb(v);
  91101. zColAff = (char *)sqlite3DbMallocRaw(0, pTab->nCol+1);
  91102. if( !zColAff ){
  91103. db->mallocFailed = 1;
  91104. return;
  91105. }
  91106. for(i=0; i<pTab->nCol; i++){
  91107. zColAff[i] = pTab->aCol[i].affinity;
  91108. }
  91109. do{
  91110. zColAff[i--] = 0;
  91111. }while( i>=0 && zColAff[i]==SQLITE_AFF_NONE );
  91112. pTab->zColAff = zColAff;
  91113. }
  91114. i = sqlite3Strlen30(zColAff);
  91115. if( i ){
  91116. if( iReg ){
  91117. sqlite3VdbeAddOp4(v, OP_Affinity, iReg, i, 0, zColAff, i);
  91118. }else{
  91119. sqlite3VdbeChangeP4(v, -1, zColAff, i);
  91120. }
  91121. }
  91122. }
  91123. /*
  91124. ** Return non-zero if the table pTab in database iDb or any of its indices
  91125. ** have been opened at any point in the VDBE program. This is used to see if
  91126. ** a statement of the form "INSERT INTO <iDb, pTab> SELECT ..." can
  91127. ** run without using a temporary table for the results of the SELECT.
  91128. */
  91129. static int readsTable(Parse *p, int iDb, Table *pTab){
  91130. Vdbe *v = sqlite3GetVdbe(p);
  91131. int i;
  91132. int iEnd = sqlite3VdbeCurrentAddr(v);
  91133. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91134. VTable *pVTab = IsVirtual(pTab) ? sqlite3GetVTable(p->db, pTab) : 0;
  91135. #endif
  91136. for(i=1; i<iEnd; i++){
  91137. VdbeOp *pOp = sqlite3VdbeGetOp(v, i);
  91138. assert( pOp!=0 );
  91139. if( pOp->opcode==OP_OpenRead && pOp->p3==iDb ){
  91140. Index *pIndex;
  91141. int tnum = pOp->p2;
  91142. if( tnum==pTab->tnum ){
  91143. return 1;
  91144. }
  91145. for(pIndex=pTab->pIndex; pIndex; pIndex=pIndex->pNext){
  91146. if( tnum==pIndex->tnum ){
  91147. return 1;
  91148. }
  91149. }
  91150. }
  91151. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91152. if( pOp->opcode==OP_VOpen && pOp->p4.pVtab==pVTab ){
  91153. assert( pOp->p4.pVtab!=0 );
  91154. assert( pOp->p4type==P4_VTAB );
  91155. return 1;
  91156. }
  91157. #endif
  91158. }
  91159. return 0;
  91160. }
  91161. #ifndef SQLITE_OMIT_AUTOINCREMENT
  91162. /*
  91163. ** Locate or create an AutoincInfo structure associated with table pTab
  91164. ** which is in database iDb. Return the register number for the register
  91165. ** that holds the maximum rowid.
  91166. **
  91167. ** There is at most one AutoincInfo structure per table even if the
  91168. ** same table is autoincremented multiple times due to inserts within
  91169. ** triggers. A new AutoincInfo structure is created if this is the
  91170. ** first use of table pTab. On 2nd and subsequent uses, the original
  91171. ** AutoincInfo structure is used.
  91172. **
  91173. ** Three memory locations are allocated:
  91174. **
  91175. ** (1) Register to hold the name of the pTab table.
  91176. ** (2) Register to hold the maximum ROWID of pTab.
  91177. ** (3) Register to hold the rowid in sqlite_sequence of pTab
  91178. **
  91179. ** The 2nd register is the one that is returned. That is all the
  91180. ** insert routine needs to know about.
  91181. */
  91182. static int autoIncBegin(
  91183. Parse *pParse, /* Parsing context */
  91184. int iDb, /* Index of the database holding pTab */
  91185. Table *pTab /* The table we are writing to */
  91186. ){
  91187. int memId = 0; /* Register holding maximum rowid */
  91188. if( pTab->tabFlags & TF_Autoincrement ){
  91189. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  91190. AutoincInfo *pInfo;
  91191. pInfo = pToplevel->pAinc;
  91192. while( pInfo && pInfo->pTab!=pTab ){ pInfo = pInfo->pNext; }
  91193. if( pInfo==0 ){
  91194. pInfo = sqlite3DbMallocRaw(pParse->db, sizeof(*pInfo));
  91195. if( pInfo==0 ) return 0;
  91196. pInfo->pNext = pToplevel->pAinc;
  91197. pToplevel->pAinc = pInfo;
  91198. pInfo->pTab = pTab;
  91199. pInfo->iDb = iDb;
  91200. pToplevel->nMem++; /* Register to hold name of table */
  91201. pInfo->regCtr = ++pToplevel->nMem; /* Max rowid register */
  91202. pToplevel->nMem++; /* Rowid in sqlite_sequence */
  91203. }
  91204. memId = pInfo->regCtr;
  91205. }
  91206. return memId;
  91207. }
  91208. /*
  91209. ** This routine generates code that will initialize all of the
  91210. ** register used by the autoincrement tracker.
  91211. */
  91212. SQLITE_PRIVATE void sqlite3AutoincrementBegin(Parse *pParse){
  91213. AutoincInfo *p; /* Information about an AUTOINCREMENT */
  91214. sqlite3 *db = pParse->db; /* The database connection */
  91215. Db *pDb; /* Database only autoinc table */
  91216. int memId; /* Register holding max rowid */
  91217. int addr; /* A VDBE address */
  91218. Vdbe *v = pParse->pVdbe; /* VDBE under construction */
  91219. /* This routine is never called during trigger-generation. It is
  91220. ** only called from the top-level */
  91221. assert( pParse->pTriggerTab==0 );
  91222. assert( pParse==sqlite3ParseToplevel(pParse) );
  91223. assert( v ); /* We failed long ago if this is not so */
  91224. for(p = pParse->pAinc; p; p = p->pNext){
  91225. pDb = &db->aDb[p->iDb];
  91226. memId = p->regCtr;
  91227. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  91228. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenRead);
  91229. sqlite3VdbeAddOp3(v, OP_Null, 0, memId, memId+1);
  91230. addr = sqlite3VdbeCurrentAddr(v);
  91231. sqlite3VdbeAddOp4(v, OP_String8, 0, memId-1, 0, p->pTab->zName, 0);
  91232. sqlite3VdbeAddOp2(v, OP_Rewind, 0, addr+9); VdbeCoverage(v);
  91233. sqlite3VdbeAddOp3(v, OP_Column, 0, 0, memId);
  91234. sqlite3VdbeAddOp3(v, OP_Ne, memId-1, addr+7, memId); VdbeCoverage(v);
  91235. sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
  91236. sqlite3VdbeAddOp2(v, OP_Rowid, 0, memId+1);
  91237. sqlite3VdbeAddOp3(v, OP_Column, 0, 1, memId);
  91238. sqlite3VdbeAddOp2(v, OP_Goto, 0, addr+9);
  91239. sqlite3VdbeAddOp2(v, OP_Next, 0, addr+2); VdbeCoverage(v);
  91240. sqlite3VdbeAddOp2(v, OP_Integer, 0, memId);
  91241. sqlite3VdbeAddOp0(v, OP_Close);
  91242. }
  91243. }
  91244. /*
  91245. ** Update the maximum rowid for an autoincrement calculation.
  91246. **
  91247. ** This routine should be called when the top of the stack holds a
  91248. ** new rowid that is about to be inserted. If that new rowid is
  91249. ** larger than the maximum rowid in the memId memory cell, then the
  91250. ** memory cell is updated. The stack is unchanged.
  91251. */
  91252. static void autoIncStep(Parse *pParse, int memId, int regRowid){
  91253. if( memId>0 ){
  91254. sqlite3VdbeAddOp2(pParse->pVdbe, OP_MemMax, memId, regRowid);
  91255. }
  91256. }
  91257. /*
  91258. ** This routine generates the code needed to write autoincrement
  91259. ** maximum rowid values back into the sqlite_sequence register.
  91260. ** Every statement that might do an INSERT into an autoincrement
  91261. ** table (either directly or through triggers) needs to call this
  91262. ** routine just before the "exit" code.
  91263. */
  91264. SQLITE_PRIVATE void sqlite3AutoincrementEnd(Parse *pParse){
  91265. AutoincInfo *p;
  91266. Vdbe *v = pParse->pVdbe;
  91267. sqlite3 *db = pParse->db;
  91268. assert( v );
  91269. for(p = pParse->pAinc; p; p = p->pNext){
  91270. Db *pDb = &db->aDb[p->iDb];
  91271. int j1;
  91272. int iRec;
  91273. int memId = p->regCtr;
  91274. iRec = sqlite3GetTempReg(pParse);
  91275. assert( sqlite3SchemaMutexHeld(db, 0, pDb->pSchema) );
  91276. sqlite3OpenTable(pParse, 0, p->iDb, pDb->pSchema->pSeqTab, OP_OpenWrite);
  91277. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, memId+1); VdbeCoverage(v);
  91278. sqlite3VdbeAddOp2(v, OP_NewRowid, 0, memId+1);
  91279. sqlite3VdbeJumpHere(v, j1);
  91280. sqlite3VdbeAddOp3(v, OP_MakeRecord, memId-1, 2, iRec);
  91281. sqlite3VdbeAddOp3(v, OP_Insert, 0, iRec, memId+1);
  91282. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  91283. sqlite3VdbeAddOp0(v, OP_Close);
  91284. sqlite3ReleaseTempReg(pParse, iRec);
  91285. }
  91286. }
  91287. #else
  91288. /*
  91289. ** If SQLITE_OMIT_AUTOINCREMENT is defined, then the three routines
  91290. ** above are all no-ops
  91291. */
  91292. # define autoIncBegin(A,B,C) (0)
  91293. # define autoIncStep(A,B,C)
  91294. #endif /* SQLITE_OMIT_AUTOINCREMENT */
  91295. /* Forward declaration */
  91296. static int xferOptimization(
  91297. Parse *pParse, /* Parser context */
  91298. Table *pDest, /* The table we are inserting into */
  91299. Select *pSelect, /* A SELECT statement to use as the data source */
  91300. int onError, /* How to handle constraint errors */
  91301. int iDbDest /* The database of pDest */
  91302. );
  91303. /*
  91304. ** This routine is called to handle SQL of the following forms:
  91305. **
  91306. ** insert into TABLE (IDLIST) values(EXPRLIST)
  91307. ** insert into TABLE (IDLIST) select
  91308. **
  91309. ** The IDLIST following the table name is always optional. If omitted,
  91310. ** then a list of all columns for the table is substituted. The IDLIST
  91311. ** appears in the pColumn parameter. pColumn is NULL if IDLIST is omitted.
  91312. **
  91313. ** The pList parameter holds EXPRLIST in the first form of the INSERT
  91314. ** statement above, and pSelect is NULL. For the second form, pList is
  91315. ** NULL and pSelect is a pointer to the select statement used to generate
  91316. ** data for the insert.
  91317. **
  91318. ** The code generated follows one of four templates. For a simple
  91319. ** insert with data coming from a VALUES clause, the code executes
  91320. ** once straight down through. Pseudo-code follows (we call this
  91321. ** the "1st template"):
  91322. **
  91323. ** open write cursor to <table> and its indices
  91324. ** put VALUES clause expressions into registers
  91325. ** write the resulting record into <table>
  91326. ** cleanup
  91327. **
  91328. ** The three remaining templates assume the statement is of the form
  91329. **
  91330. ** INSERT INTO <table> SELECT ...
  91331. **
  91332. ** If the SELECT clause is of the restricted form "SELECT * FROM <table2>" -
  91333. ** in other words if the SELECT pulls all columns from a single table
  91334. ** and there is no WHERE or LIMIT or GROUP BY or ORDER BY clauses, and
  91335. ** if <table2> and <table1> are distinct tables but have identical
  91336. ** schemas, including all the same indices, then a special optimization
  91337. ** is invoked that copies raw records from <table2> over to <table1>.
  91338. ** See the xferOptimization() function for the implementation of this
  91339. ** template. This is the 2nd template.
  91340. **
  91341. ** open a write cursor to <table>
  91342. ** open read cursor on <table2>
  91343. ** transfer all records in <table2> over to <table>
  91344. ** close cursors
  91345. ** foreach index on <table>
  91346. ** open a write cursor on the <table> index
  91347. ** open a read cursor on the corresponding <table2> index
  91348. ** transfer all records from the read to the write cursors
  91349. ** close cursors
  91350. ** end foreach
  91351. **
  91352. ** The 3rd template is for when the second template does not apply
  91353. ** and the SELECT clause does not read from <table> at any time.
  91354. ** The generated code follows this template:
  91355. **
  91356. ** X <- A
  91357. ** goto B
  91358. ** A: setup for the SELECT
  91359. ** loop over the rows in the SELECT
  91360. ** load values into registers R..R+n
  91361. ** yield X
  91362. ** end loop
  91363. ** cleanup after the SELECT
  91364. ** end-coroutine X
  91365. ** B: open write cursor to <table> and its indices
  91366. ** C: yield X, at EOF goto D
  91367. ** insert the select result into <table> from R..R+n
  91368. ** goto C
  91369. ** D: cleanup
  91370. **
  91371. ** The 4th template is used if the insert statement takes its
  91372. ** values from a SELECT but the data is being inserted into a table
  91373. ** that is also read as part of the SELECT. In the third form,
  91374. ** we have to use an intermediate table to store the results of
  91375. ** the select. The template is like this:
  91376. **
  91377. ** X <- A
  91378. ** goto B
  91379. ** A: setup for the SELECT
  91380. ** loop over the tables in the SELECT
  91381. ** load value into register R..R+n
  91382. ** yield X
  91383. ** end loop
  91384. ** cleanup after the SELECT
  91385. ** end co-routine R
  91386. ** B: open temp table
  91387. ** L: yield X, at EOF goto M
  91388. ** insert row from R..R+n into temp table
  91389. ** goto L
  91390. ** M: open write cursor to <table> and its indices
  91391. ** rewind temp table
  91392. ** C: loop over rows of intermediate table
  91393. ** transfer values form intermediate table into <table>
  91394. ** end loop
  91395. ** D: cleanup
  91396. */
  91397. SQLITE_PRIVATE void sqlite3Insert(
  91398. Parse *pParse, /* Parser context */
  91399. SrcList *pTabList, /* Name of table into which we are inserting */
  91400. Select *pSelect, /* A SELECT statement to use as the data source */
  91401. IdList *pColumn, /* Column names corresponding to IDLIST. */
  91402. int onError /* How to handle constraint errors */
  91403. ){
  91404. sqlite3 *db; /* The main database structure */
  91405. Table *pTab; /* The table to insert into. aka TABLE */
  91406. char *zTab; /* Name of the table into which we are inserting */
  91407. const char *zDb; /* Name of the database holding this table */
  91408. int i, j, idx; /* Loop counters */
  91409. Vdbe *v; /* Generate code into this virtual machine */
  91410. Index *pIdx; /* For looping over indices of the table */
  91411. int nColumn; /* Number of columns in the data */
  91412. int nHidden = 0; /* Number of hidden columns if TABLE is virtual */
  91413. int iDataCur = 0; /* VDBE cursor that is the main data repository */
  91414. int iIdxCur = 0; /* First index cursor */
  91415. int ipkColumn = -1; /* Column that is the INTEGER PRIMARY KEY */
  91416. int endOfLoop; /* Label for the end of the insertion loop */
  91417. int srcTab = 0; /* Data comes from this temporary cursor if >=0 */
  91418. int addrInsTop = 0; /* Jump to label "D" */
  91419. int addrCont = 0; /* Top of insert loop. Label "C" in templates 3 and 4 */
  91420. SelectDest dest; /* Destination for SELECT on rhs of INSERT */
  91421. int iDb; /* Index of database holding TABLE */
  91422. Db *pDb; /* The database containing table being inserted into */
  91423. u8 useTempTable = 0; /* Store SELECT results in intermediate table */
  91424. u8 appendFlag = 0; /* True if the insert is likely to be an append */
  91425. u8 withoutRowid; /* 0 for normal table. 1 for WITHOUT ROWID table */
  91426. u8 bIdListInOrder = 1; /* True if IDLIST is in table order */
  91427. ExprList *pList = 0; /* List of VALUES() to be inserted */
  91428. /* Register allocations */
  91429. int regFromSelect = 0;/* Base register for data coming from SELECT */
  91430. int regAutoinc = 0; /* Register holding the AUTOINCREMENT counter */
  91431. int regRowCount = 0; /* Memory cell used for the row counter */
  91432. int regIns; /* Block of regs holding rowid+data being inserted */
  91433. int regRowid; /* registers holding insert rowid */
  91434. int regData; /* register holding first column to insert */
  91435. int *aRegIdx = 0; /* One register allocated to each index */
  91436. #ifndef SQLITE_OMIT_TRIGGER
  91437. int isView; /* True if attempting to insert into a view */
  91438. Trigger *pTrigger; /* List of triggers on pTab, if required */
  91439. int tmask; /* Mask of trigger times */
  91440. #endif
  91441. db = pParse->db;
  91442. memset(&dest, 0, sizeof(dest));
  91443. if( pParse->nErr || db->mallocFailed ){
  91444. goto insert_cleanup;
  91445. }
  91446. /* If the Select object is really just a simple VALUES() list with a
  91447. ** single row values (the common case) then keep that one row of values
  91448. ** and go ahead and discard the Select object
  91449. */
  91450. if( pSelect && (pSelect->selFlags & SF_Values)!=0 && pSelect->pPrior==0 ){
  91451. pList = pSelect->pEList;
  91452. pSelect->pEList = 0;
  91453. sqlite3SelectDelete(db, pSelect);
  91454. pSelect = 0;
  91455. }
  91456. /* Locate the table into which we will be inserting new information.
  91457. */
  91458. assert( pTabList->nSrc==1 );
  91459. zTab = pTabList->a[0].zName;
  91460. if( NEVER(zTab==0) ) goto insert_cleanup;
  91461. pTab = sqlite3SrcListLookup(pParse, pTabList);
  91462. if( pTab==0 ){
  91463. goto insert_cleanup;
  91464. }
  91465. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  91466. assert( iDb<db->nDb );
  91467. pDb = &db->aDb[iDb];
  91468. zDb = pDb->zName;
  91469. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, pTab->zName, 0, zDb) ){
  91470. goto insert_cleanup;
  91471. }
  91472. withoutRowid = !HasRowid(pTab);
  91473. /* Figure out if we have any triggers and if the table being
  91474. ** inserted into is a view
  91475. */
  91476. #ifndef SQLITE_OMIT_TRIGGER
  91477. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_INSERT, 0, &tmask);
  91478. isView = pTab->pSelect!=0;
  91479. #else
  91480. # define pTrigger 0
  91481. # define tmask 0
  91482. # define isView 0
  91483. #endif
  91484. #ifdef SQLITE_OMIT_VIEW
  91485. # undef isView
  91486. # define isView 0
  91487. #endif
  91488. assert( (pTrigger && tmask) || (pTrigger==0 && tmask==0) );
  91489. /* If pTab is really a view, make sure it has been initialized.
  91490. ** ViewGetColumnNames() is a no-op if pTab is not a view.
  91491. */
  91492. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  91493. goto insert_cleanup;
  91494. }
  91495. /* Cannot insert into a read-only table.
  91496. */
  91497. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  91498. goto insert_cleanup;
  91499. }
  91500. /* Allocate a VDBE
  91501. */
  91502. v = sqlite3GetVdbe(pParse);
  91503. if( v==0 ) goto insert_cleanup;
  91504. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  91505. sqlite3BeginWriteOperation(pParse, pSelect || pTrigger, iDb);
  91506. #ifndef SQLITE_OMIT_XFER_OPT
  91507. /* If the statement is of the form
  91508. **
  91509. ** INSERT INTO <table1> SELECT * FROM <table2>;
  91510. **
  91511. ** Then special optimizations can be applied that make the transfer
  91512. ** very fast and which reduce fragmentation of indices.
  91513. **
  91514. ** This is the 2nd template.
  91515. */
  91516. if( pColumn==0 && xferOptimization(pParse, pTab, pSelect, onError, iDb) ){
  91517. assert( !pTrigger );
  91518. assert( pList==0 );
  91519. goto insert_end;
  91520. }
  91521. #endif /* SQLITE_OMIT_XFER_OPT */
  91522. /* If this is an AUTOINCREMENT table, look up the sequence number in the
  91523. ** sqlite_sequence table and store it in memory cell regAutoinc.
  91524. */
  91525. regAutoinc = autoIncBegin(pParse, iDb, pTab);
  91526. /* Allocate registers for holding the rowid of the new row,
  91527. ** the content of the new row, and the assembled row record.
  91528. */
  91529. regRowid = regIns = pParse->nMem+1;
  91530. pParse->nMem += pTab->nCol + 1;
  91531. if( IsVirtual(pTab) ){
  91532. regRowid++;
  91533. pParse->nMem++;
  91534. }
  91535. regData = regRowid+1;
  91536. /* If the INSERT statement included an IDLIST term, then make sure
  91537. ** all elements of the IDLIST really are columns of the table and
  91538. ** remember the column indices.
  91539. **
  91540. ** If the table has an INTEGER PRIMARY KEY column and that column
  91541. ** is named in the IDLIST, then record in the ipkColumn variable
  91542. ** the index into IDLIST of the primary key column. ipkColumn is
  91543. ** the index of the primary key as it appears in IDLIST, not as
  91544. ** is appears in the original table. (The index of the INTEGER
  91545. ** PRIMARY KEY in the original table is pTab->iPKey.)
  91546. */
  91547. if( pColumn ){
  91548. for(i=0; i<pColumn->nId; i++){
  91549. pColumn->a[i].idx = -1;
  91550. }
  91551. for(i=0; i<pColumn->nId; i++){
  91552. for(j=0; j<pTab->nCol; j++){
  91553. if( sqlite3StrICmp(pColumn->a[i].zName, pTab->aCol[j].zName)==0 ){
  91554. pColumn->a[i].idx = j;
  91555. if( i!=j ) bIdListInOrder = 0;
  91556. if( j==pTab->iPKey ){
  91557. ipkColumn = i; assert( !withoutRowid );
  91558. }
  91559. break;
  91560. }
  91561. }
  91562. if( j>=pTab->nCol ){
  91563. if( sqlite3IsRowid(pColumn->a[i].zName) && !withoutRowid ){
  91564. ipkColumn = i;
  91565. bIdListInOrder = 0;
  91566. }else{
  91567. sqlite3ErrorMsg(pParse, "table %S has no column named %s",
  91568. pTabList, 0, pColumn->a[i].zName);
  91569. pParse->checkSchema = 1;
  91570. goto insert_cleanup;
  91571. }
  91572. }
  91573. }
  91574. }
  91575. /* Figure out how many columns of data are supplied. If the data
  91576. ** is coming from a SELECT statement, then generate a co-routine that
  91577. ** produces a single row of the SELECT on each invocation. The
  91578. ** co-routine is the common header to the 3rd and 4th templates.
  91579. */
  91580. if( pSelect ){
  91581. /* Data is coming from a SELECT. Generate a co-routine to run the SELECT */
  91582. int regYield; /* Register holding co-routine entry-point */
  91583. int addrTop; /* Top of the co-routine */
  91584. int rc; /* Result code */
  91585. regYield = ++pParse->nMem;
  91586. addrTop = sqlite3VdbeCurrentAddr(v) + 1;
  91587. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, addrTop);
  91588. sqlite3SelectDestInit(&dest, SRT_Coroutine, regYield);
  91589. dest.iSdst = bIdListInOrder ? regData : 0;
  91590. dest.nSdst = pTab->nCol;
  91591. rc = sqlite3Select(pParse, pSelect, &dest);
  91592. regFromSelect = dest.iSdst;
  91593. assert( pParse->nErr==0 || rc );
  91594. if( rc || db->mallocFailed ) goto insert_cleanup;
  91595. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regYield);
  91596. sqlite3VdbeJumpHere(v, addrTop - 1); /* label B: */
  91597. assert( pSelect->pEList );
  91598. nColumn = pSelect->pEList->nExpr;
  91599. /* Set useTempTable to TRUE if the result of the SELECT statement
  91600. ** should be written into a temporary table (template 4). Set to
  91601. ** FALSE if each output row of the SELECT can be written directly into
  91602. ** the destination table (template 3).
  91603. **
  91604. ** A temp table must be used if the table being updated is also one
  91605. ** of the tables being read by the SELECT statement. Also use a
  91606. ** temp table in the case of row triggers.
  91607. */
  91608. if( pTrigger || readsTable(pParse, iDb, pTab) ){
  91609. useTempTable = 1;
  91610. }
  91611. if( useTempTable ){
  91612. /* Invoke the coroutine to extract information from the SELECT
  91613. ** and add it to a transient table srcTab. The code generated
  91614. ** here is from the 4th template:
  91615. **
  91616. ** B: open temp table
  91617. ** L: yield X, goto M at EOF
  91618. ** insert row from R..R+n into temp table
  91619. ** goto L
  91620. ** M: ...
  91621. */
  91622. int regRec; /* Register to hold packed record */
  91623. int regTempRowid; /* Register to hold temp table ROWID */
  91624. int addrL; /* Label "L" */
  91625. srcTab = pParse->nTab++;
  91626. regRec = sqlite3GetTempReg(pParse);
  91627. regTempRowid = sqlite3GetTempReg(pParse);
  91628. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, srcTab, nColumn);
  91629. addrL = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm); VdbeCoverage(v);
  91630. sqlite3VdbeAddOp3(v, OP_MakeRecord, regFromSelect, nColumn, regRec);
  91631. sqlite3VdbeAddOp2(v, OP_NewRowid, srcTab, regTempRowid);
  91632. sqlite3VdbeAddOp3(v, OP_Insert, srcTab, regRec, regTempRowid);
  91633. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrL);
  91634. sqlite3VdbeJumpHere(v, addrL);
  91635. sqlite3ReleaseTempReg(pParse, regRec);
  91636. sqlite3ReleaseTempReg(pParse, regTempRowid);
  91637. }
  91638. }else{
  91639. /* This is the case if the data for the INSERT is coming from a VALUES
  91640. ** clause
  91641. */
  91642. NameContext sNC;
  91643. memset(&sNC, 0, sizeof(sNC));
  91644. sNC.pParse = pParse;
  91645. srcTab = -1;
  91646. assert( useTempTable==0 );
  91647. nColumn = pList ? pList->nExpr : 0;
  91648. for(i=0; i<nColumn; i++){
  91649. if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
  91650. goto insert_cleanup;
  91651. }
  91652. }
  91653. }
  91654. /* If there is no IDLIST term but the table has an integer primary
  91655. ** key, the set the ipkColumn variable to the integer primary key
  91656. ** column index in the original table definition.
  91657. */
  91658. if( pColumn==0 && nColumn>0 ){
  91659. ipkColumn = pTab->iPKey;
  91660. }
  91661. /* Make sure the number of columns in the source data matches the number
  91662. ** of columns to be inserted into the table.
  91663. */
  91664. if( IsVirtual(pTab) ){
  91665. for(i=0; i<pTab->nCol; i++){
  91666. nHidden += (IsHiddenColumn(&pTab->aCol[i]) ? 1 : 0);
  91667. }
  91668. }
  91669. if( pColumn==0 && nColumn && nColumn!=(pTab->nCol-nHidden) ){
  91670. sqlite3ErrorMsg(pParse,
  91671. "table %S has %d columns but %d values were supplied",
  91672. pTabList, 0, pTab->nCol-nHidden, nColumn);
  91673. goto insert_cleanup;
  91674. }
  91675. if( pColumn!=0 && nColumn!=pColumn->nId ){
  91676. sqlite3ErrorMsg(pParse, "%d values for %d columns", nColumn, pColumn->nId);
  91677. goto insert_cleanup;
  91678. }
  91679. /* Initialize the count of rows to be inserted
  91680. */
  91681. if( db->flags & SQLITE_CountRows ){
  91682. regRowCount = ++pParse->nMem;
  91683. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  91684. }
  91685. /* If this is not a view, open the table and and all indices */
  91686. if( !isView ){
  91687. int nIdx;
  91688. nIdx = sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, -1, 0,
  91689. &iDataCur, &iIdxCur);
  91690. aRegIdx = sqlite3DbMallocRaw(db, sizeof(int)*(nIdx+1));
  91691. if( aRegIdx==0 ){
  91692. goto insert_cleanup;
  91693. }
  91694. for(i=0; i<nIdx; i++){
  91695. aRegIdx[i] = ++pParse->nMem;
  91696. }
  91697. }
  91698. /* This is the top of the main insertion loop */
  91699. if( useTempTable ){
  91700. /* This block codes the top of loop only. The complete loop is the
  91701. ** following pseudocode (template 4):
  91702. **
  91703. ** rewind temp table, if empty goto D
  91704. ** C: loop over rows of intermediate table
  91705. ** transfer values form intermediate table into <table>
  91706. ** end loop
  91707. ** D: ...
  91708. */
  91709. addrInsTop = sqlite3VdbeAddOp1(v, OP_Rewind, srcTab); VdbeCoverage(v);
  91710. addrCont = sqlite3VdbeCurrentAddr(v);
  91711. }else if( pSelect ){
  91712. /* This block codes the top of loop only. The complete loop is the
  91713. ** following pseudocode (template 3):
  91714. **
  91715. ** C: yield X, at EOF goto D
  91716. ** insert the select result into <table> from R..R+n
  91717. ** goto C
  91718. ** D: ...
  91719. */
  91720. addrInsTop = addrCont = sqlite3VdbeAddOp1(v, OP_Yield, dest.iSDParm);
  91721. VdbeCoverage(v);
  91722. }
  91723. /* Run the BEFORE and INSTEAD OF triggers, if there are any
  91724. */
  91725. endOfLoop = sqlite3VdbeMakeLabel(v);
  91726. if( tmask & TRIGGER_BEFORE ){
  91727. int regCols = sqlite3GetTempRange(pParse, pTab->nCol+1);
  91728. /* build the NEW.* reference row. Note that if there is an INTEGER
  91729. ** PRIMARY KEY into which a NULL is being inserted, that NULL will be
  91730. ** translated into a unique ID for the row. But on a BEFORE trigger,
  91731. ** we do not know what the unique ID will be (because the insert has
  91732. ** not happened yet) so we substitute a rowid of -1
  91733. */
  91734. if( ipkColumn<0 ){
  91735. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  91736. }else{
  91737. int j1;
  91738. assert( !withoutRowid );
  91739. if( useTempTable ){
  91740. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regCols);
  91741. }else{
  91742. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  91743. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regCols);
  91744. }
  91745. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regCols); VdbeCoverage(v);
  91746. sqlite3VdbeAddOp2(v, OP_Integer, -1, regCols);
  91747. sqlite3VdbeJumpHere(v, j1);
  91748. sqlite3VdbeAddOp1(v, OP_MustBeInt, regCols); VdbeCoverage(v);
  91749. }
  91750. /* Cannot have triggers on a virtual table. If it were possible,
  91751. ** this block would have to account for hidden column.
  91752. */
  91753. assert( !IsVirtual(pTab) );
  91754. /* Create the new column data
  91755. */
  91756. for(i=0; i<pTab->nCol; i++){
  91757. if( pColumn==0 ){
  91758. j = i;
  91759. }else{
  91760. for(j=0; j<pColumn->nId; j++){
  91761. if( pColumn->a[j].idx==i ) break;
  91762. }
  91763. }
  91764. if( (!useTempTable && !pList) || (pColumn && j>=pColumn->nId) ){
  91765. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regCols+i+1);
  91766. }else if( useTempTable ){
  91767. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, regCols+i+1);
  91768. }else{
  91769. assert( pSelect==0 ); /* Otherwise useTempTable is true */
  91770. sqlite3ExprCodeAndCache(pParse, pList->a[j].pExpr, regCols+i+1);
  91771. }
  91772. }
  91773. /* If this is an INSERT on a view with an INSTEAD OF INSERT trigger,
  91774. ** do not attempt any conversions before assembling the record.
  91775. ** If this is a real table, attempt conversions as required by the
  91776. ** table column affinities.
  91777. */
  91778. if( !isView ){
  91779. sqlite3TableAffinity(v, pTab, regCols+1);
  91780. }
  91781. /* Fire BEFORE or INSTEAD OF triggers */
  91782. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_BEFORE,
  91783. pTab, regCols-pTab->nCol-1, onError, endOfLoop);
  91784. sqlite3ReleaseTempRange(pParse, regCols, pTab->nCol+1);
  91785. }
  91786. /* Compute the content of the next row to insert into a range of
  91787. ** registers beginning at regIns.
  91788. */
  91789. if( !isView ){
  91790. if( IsVirtual(pTab) ){
  91791. /* The row that the VUpdate opcode will delete: none */
  91792. sqlite3VdbeAddOp2(v, OP_Null, 0, regIns);
  91793. }
  91794. if( ipkColumn>=0 ){
  91795. if( useTempTable ){
  91796. sqlite3VdbeAddOp3(v, OP_Column, srcTab, ipkColumn, regRowid);
  91797. }else if( pSelect ){
  91798. sqlite3VdbeAddOp2(v, OP_Copy, regFromSelect+ipkColumn, regRowid);
  91799. }else{
  91800. VdbeOp *pOp;
  91801. sqlite3ExprCode(pParse, pList->a[ipkColumn].pExpr, regRowid);
  91802. pOp = sqlite3VdbeGetOp(v, -1);
  91803. if( ALWAYS(pOp) && pOp->opcode==OP_Null && !IsVirtual(pTab) ){
  91804. appendFlag = 1;
  91805. pOp->opcode = OP_NewRowid;
  91806. pOp->p1 = iDataCur;
  91807. pOp->p2 = regRowid;
  91808. pOp->p3 = regAutoinc;
  91809. }
  91810. }
  91811. /* If the PRIMARY KEY expression is NULL, then use OP_NewRowid
  91812. ** to generate a unique primary key value.
  91813. */
  91814. if( !appendFlag ){
  91815. int j1;
  91816. if( !IsVirtual(pTab) ){
  91817. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regRowid); VdbeCoverage(v);
  91818. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  91819. sqlite3VdbeJumpHere(v, j1);
  91820. }else{
  91821. j1 = sqlite3VdbeCurrentAddr(v);
  91822. sqlite3VdbeAddOp2(v, OP_IsNull, regRowid, j1+2); VdbeCoverage(v);
  91823. }
  91824. sqlite3VdbeAddOp1(v, OP_MustBeInt, regRowid); VdbeCoverage(v);
  91825. }
  91826. }else if( IsVirtual(pTab) || withoutRowid ){
  91827. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowid);
  91828. }else{
  91829. sqlite3VdbeAddOp3(v, OP_NewRowid, iDataCur, regRowid, regAutoinc);
  91830. appendFlag = 1;
  91831. }
  91832. autoIncStep(pParse, regAutoinc, regRowid);
  91833. /* Compute data for all columns of the new entry, beginning
  91834. ** with the first column.
  91835. */
  91836. nHidden = 0;
  91837. for(i=0; i<pTab->nCol; i++){
  91838. int iRegStore = regRowid+1+i;
  91839. if( i==pTab->iPKey ){
  91840. /* The value of the INTEGER PRIMARY KEY column is always a NULL.
  91841. ** Whenever this column is read, the rowid will be substituted
  91842. ** in its place. Hence, fill this column with a NULL to avoid
  91843. ** taking up data space with information that will never be used.
  91844. ** As there may be shallow copies of this value, make it a soft-NULL */
  91845. sqlite3VdbeAddOp1(v, OP_SoftNull, iRegStore);
  91846. continue;
  91847. }
  91848. if( pColumn==0 ){
  91849. if( IsHiddenColumn(&pTab->aCol[i]) ){
  91850. assert( IsVirtual(pTab) );
  91851. j = -1;
  91852. nHidden++;
  91853. }else{
  91854. j = i - nHidden;
  91855. }
  91856. }else{
  91857. for(j=0; j<pColumn->nId; j++){
  91858. if( pColumn->a[j].idx==i ) break;
  91859. }
  91860. }
  91861. if( j<0 || nColumn==0 || (pColumn && j>=pColumn->nId) ){
  91862. sqlite3ExprCodeFactorable(pParse, pTab->aCol[i].pDflt, iRegStore);
  91863. }else if( useTempTable ){
  91864. sqlite3VdbeAddOp3(v, OP_Column, srcTab, j, iRegStore);
  91865. }else if( pSelect ){
  91866. if( regFromSelect!=regData ){
  91867. sqlite3VdbeAddOp2(v, OP_SCopy, regFromSelect+j, iRegStore);
  91868. }
  91869. }else{
  91870. sqlite3ExprCode(pParse, pList->a[j].pExpr, iRegStore);
  91871. }
  91872. }
  91873. /* Generate code to check constraints and generate index keys and
  91874. ** do the insertion.
  91875. */
  91876. #ifndef SQLITE_OMIT_VIRTUALTABLE
  91877. if( IsVirtual(pTab) ){
  91878. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  91879. sqlite3VtabMakeWritable(pParse, pTab);
  91880. sqlite3VdbeAddOp4(v, OP_VUpdate, 1, pTab->nCol+2, regIns, pVTab, P4_VTAB);
  91881. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  91882. sqlite3MayAbort(pParse);
  91883. }else
  91884. #endif
  91885. {
  91886. int isReplace; /* Set to true if constraints may cause a replace */
  91887. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  91888. regIns, 0, ipkColumn>=0, onError, endOfLoop, &isReplace
  91889. );
  91890. sqlite3FkCheck(pParse, pTab, 0, regIns, 0, 0);
  91891. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  91892. regIns, aRegIdx, 0, appendFlag, isReplace==0);
  91893. }
  91894. }
  91895. /* Update the count of rows that are inserted
  91896. */
  91897. if( (db->flags & SQLITE_CountRows)!=0 ){
  91898. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  91899. }
  91900. if( pTrigger ){
  91901. /* Code AFTER triggers */
  91902. sqlite3CodeRowTrigger(pParse, pTrigger, TK_INSERT, 0, TRIGGER_AFTER,
  91903. pTab, regData-2-pTab->nCol, onError, endOfLoop);
  91904. }
  91905. /* The bottom of the main insertion loop, if the data source
  91906. ** is a SELECT statement.
  91907. */
  91908. sqlite3VdbeResolveLabel(v, endOfLoop);
  91909. if( useTempTable ){
  91910. sqlite3VdbeAddOp2(v, OP_Next, srcTab, addrCont); VdbeCoverage(v);
  91911. sqlite3VdbeJumpHere(v, addrInsTop);
  91912. sqlite3VdbeAddOp1(v, OP_Close, srcTab);
  91913. }else if( pSelect ){
  91914. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrCont);
  91915. sqlite3VdbeJumpHere(v, addrInsTop);
  91916. }
  91917. if( !IsVirtual(pTab) && !isView ){
  91918. /* Close all tables opened */
  91919. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp1(v, OP_Close, iDataCur);
  91920. for(idx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, idx++){
  91921. sqlite3VdbeAddOp1(v, OP_Close, idx+iIdxCur);
  91922. }
  91923. }
  91924. insert_end:
  91925. /* Update the sqlite_sequence table by storing the content of the
  91926. ** maximum rowid counter values recorded while inserting into
  91927. ** autoincrement tables.
  91928. */
  91929. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  91930. sqlite3AutoincrementEnd(pParse);
  91931. }
  91932. /*
  91933. ** Return the number of rows inserted. If this routine is
  91934. ** generating code because of a call to sqlite3NestedParse(), do not
  91935. ** invoke the callback function.
  91936. */
  91937. if( (db->flags&SQLITE_CountRows) && !pParse->nested && !pParse->pTriggerTab ){
  91938. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  91939. sqlite3VdbeSetNumCols(v, 1);
  91940. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows inserted", SQLITE_STATIC);
  91941. }
  91942. insert_cleanup:
  91943. sqlite3SrcListDelete(db, pTabList);
  91944. sqlite3ExprListDelete(db, pList);
  91945. sqlite3SelectDelete(db, pSelect);
  91946. sqlite3IdListDelete(db, pColumn);
  91947. sqlite3DbFree(db, aRegIdx);
  91948. }
  91949. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  91950. ** they may interfere with compilation of other functions in this file
  91951. ** (or in another file, if this file becomes part of the amalgamation). */
  91952. #ifdef isView
  91953. #undef isView
  91954. #endif
  91955. #ifdef pTrigger
  91956. #undef pTrigger
  91957. #endif
  91958. #ifdef tmask
  91959. #undef tmask
  91960. #endif
  91961. /*
  91962. ** Generate code to do constraint checks prior to an INSERT or an UPDATE
  91963. ** on table pTab.
  91964. **
  91965. ** The regNewData parameter is the first register in a range that contains
  91966. ** the data to be inserted or the data after the update. There will be
  91967. ** pTab->nCol+1 registers in this range. The first register (the one
  91968. ** that regNewData points to) will contain the new rowid, or NULL in the
  91969. ** case of a WITHOUT ROWID table. The second register in the range will
  91970. ** contain the content of the first table column. The third register will
  91971. ** contain the content of the second table column. And so forth.
  91972. **
  91973. ** The regOldData parameter is similar to regNewData except that it contains
  91974. ** the data prior to an UPDATE rather than afterwards. regOldData is zero
  91975. ** for an INSERT. This routine can distinguish between UPDATE and INSERT by
  91976. ** checking regOldData for zero.
  91977. **
  91978. ** For an UPDATE, the pkChng boolean is true if the true primary key (the
  91979. ** rowid for a normal table or the PRIMARY KEY for a WITHOUT ROWID table)
  91980. ** might be modified by the UPDATE. If pkChng is false, then the key of
  91981. ** the iDataCur content table is guaranteed to be unchanged by the UPDATE.
  91982. **
  91983. ** For an INSERT, the pkChng boolean indicates whether or not the rowid
  91984. ** was explicitly specified as part of the INSERT statement. If pkChng
  91985. ** is zero, it means that the either rowid is computed automatically or
  91986. ** that the table is a WITHOUT ROWID table and has no rowid. On an INSERT,
  91987. ** pkChng will only be true if the INSERT statement provides an integer
  91988. ** value for either the rowid column or its INTEGER PRIMARY KEY alias.
  91989. **
  91990. ** The code generated by this routine will store new index entries into
  91991. ** registers identified by aRegIdx[]. No index entry is created for
  91992. ** indices where aRegIdx[i]==0. The order of indices in aRegIdx[] is
  91993. ** the same as the order of indices on the linked list of indices
  91994. ** at pTab->pIndex.
  91995. **
  91996. ** The caller must have already opened writeable cursors on the main
  91997. ** table and all applicable indices (that is to say, all indices for which
  91998. ** aRegIdx[] is not zero). iDataCur is the cursor for the main table when
  91999. ** inserting or updating a rowid table, or the cursor for the PRIMARY KEY
  92000. ** index when operating on a WITHOUT ROWID table. iIdxCur is the cursor
  92001. ** for the first index in the pTab->pIndex list. Cursors for other indices
  92002. ** are at iIdxCur+N for the N-th element of the pTab->pIndex list.
  92003. **
  92004. ** This routine also generates code to check constraints. NOT NULL,
  92005. ** CHECK, and UNIQUE constraints are all checked. If a constraint fails,
  92006. ** then the appropriate action is performed. There are five possible
  92007. ** actions: ROLLBACK, ABORT, FAIL, REPLACE, and IGNORE.
  92008. **
  92009. ** Constraint type Action What Happens
  92010. ** --------------- ---------- ----------------------------------------
  92011. ** any ROLLBACK The current transaction is rolled back and
  92012. ** sqlite3_step() returns immediately with a
  92013. ** return code of SQLITE_CONSTRAINT.
  92014. **
  92015. ** any ABORT Back out changes from the current command
  92016. ** only (do not do a complete rollback) then
  92017. ** cause sqlite3_step() to return immediately
  92018. ** with SQLITE_CONSTRAINT.
  92019. **
  92020. ** any FAIL Sqlite3_step() returns immediately with a
  92021. ** return code of SQLITE_CONSTRAINT. The
  92022. ** transaction is not rolled back and any
  92023. ** changes to prior rows are retained.
  92024. **
  92025. ** any IGNORE The attempt in insert or update the current
  92026. ** row is skipped, without throwing an error.
  92027. ** Processing continues with the next row.
  92028. ** (There is an immediate jump to ignoreDest.)
  92029. **
  92030. ** NOT NULL REPLACE The NULL value is replace by the default
  92031. ** value for that column. If the default value
  92032. ** is NULL, the action is the same as ABORT.
  92033. **
  92034. ** UNIQUE REPLACE The other row that conflicts with the row
  92035. ** being inserted is removed.
  92036. **
  92037. ** CHECK REPLACE Illegal. The results in an exception.
  92038. **
  92039. ** Which action to take is determined by the overrideError parameter.
  92040. ** Or if overrideError==OE_Default, then the pParse->onError parameter
  92041. ** is used. Or if pParse->onError==OE_Default then the onError value
  92042. ** for the constraint is used.
  92043. */
  92044. SQLITE_PRIVATE void sqlite3GenerateConstraintChecks(
  92045. Parse *pParse, /* The parser context */
  92046. Table *pTab, /* The table being inserted or updated */
  92047. int *aRegIdx, /* Use register aRegIdx[i] for index i. 0 for unused */
  92048. int iDataCur, /* Canonical data cursor (main table or PK index) */
  92049. int iIdxCur, /* First index cursor */
  92050. int regNewData, /* First register in a range holding values to insert */
  92051. int regOldData, /* Previous content. 0 for INSERTs */
  92052. u8 pkChng, /* Non-zero if the rowid or PRIMARY KEY changed */
  92053. u8 overrideError, /* Override onError to this if not OE_Default */
  92054. int ignoreDest, /* Jump to this label on an OE_Ignore resolution */
  92055. int *pbMayReplace /* OUT: Set to true if constraint may cause a replace */
  92056. ){
  92057. Vdbe *v; /* VDBE under constrution */
  92058. Index *pIdx; /* Pointer to one of the indices */
  92059. Index *pPk = 0; /* The PRIMARY KEY index */
  92060. sqlite3 *db; /* Database connection */
  92061. int i; /* loop counter */
  92062. int ix; /* Index loop counter */
  92063. int nCol; /* Number of columns */
  92064. int onError; /* Conflict resolution strategy */
  92065. int j1; /* Address of jump instruction */
  92066. int seenReplace = 0; /* True if REPLACE is used to resolve INT PK conflict */
  92067. int nPkField; /* Number of fields in PRIMARY KEY. 1 for ROWID tables */
  92068. int ipkTop = 0; /* Top of the rowid change constraint check */
  92069. int ipkBottom = 0; /* Bottom of the rowid change constraint check */
  92070. u8 isUpdate; /* True if this is an UPDATE operation */
  92071. u8 bAffinityDone = 0; /* True if the OP_Affinity operation has been run */
  92072. int regRowid = -1; /* Register holding ROWID value */
  92073. isUpdate = regOldData!=0;
  92074. db = pParse->db;
  92075. v = sqlite3GetVdbe(pParse);
  92076. assert( v!=0 );
  92077. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  92078. nCol = pTab->nCol;
  92079. /* pPk is the PRIMARY KEY index for WITHOUT ROWID tables and NULL for
  92080. ** normal rowid tables. nPkField is the number of key fields in the
  92081. ** pPk index or 1 for a rowid table. In other words, nPkField is the
  92082. ** number of fields in the true primary key of the table. */
  92083. if( HasRowid(pTab) ){
  92084. pPk = 0;
  92085. nPkField = 1;
  92086. }else{
  92087. pPk = sqlite3PrimaryKeyIndex(pTab);
  92088. nPkField = pPk->nKeyCol;
  92089. }
  92090. /* Record that this module has started */
  92091. VdbeModuleComment((v, "BEGIN: GenCnstCks(%d,%d,%d,%d,%d)",
  92092. iDataCur, iIdxCur, regNewData, regOldData, pkChng));
  92093. /* Test all NOT NULL constraints.
  92094. */
  92095. for(i=0; i<nCol; i++){
  92096. if( i==pTab->iPKey ){
  92097. continue;
  92098. }
  92099. onError = pTab->aCol[i].notNull;
  92100. if( onError==OE_None ) continue;
  92101. if( overrideError!=OE_Default ){
  92102. onError = overrideError;
  92103. }else if( onError==OE_Default ){
  92104. onError = OE_Abort;
  92105. }
  92106. if( onError==OE_Replace && pTab->aCol[i].pDflt==0 ){
  92107. onError = OE_Abort;
  92108. }
  92109. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  92110. || onError==OE_Ignore || onError==OE_Replace );
  92111. switch( onError ){
  92112. case OE_Abort:
  92113. sqlite3MayAbort(pParse);
  92114. /* Fall through */
  92115. case OE_Rollback:
  92116. case OE_Fail: {
  92117. char *zMsg = sqlite3MPrintf(db, "%s.%s", pTab->zName,
  92118. pTab->aCol[i].zName);
  92119. sqlite3VdbeAddOp4(v, OP_HaltIfNull, SQLITE_CONSTRAINT_NOTNULL, onError,
  92120. regNewData+1+i, zMsg, P4_DYNAMIC);
  92121. sqlite3VdbeChangeP5(v, P5_ConstraintNotNull);
  92122. VdbeCoverage(v);
  92123. break;
  92124. }
  92125. case OE_Ignore: {
  92126. sqlite3VdbeAddOp2(v, OP_IsNull, regNewData+1+i, ignoreDest);
  92127. VdbeCoverage(v);
  92128. break;
  92129. }
  92130. default: {
  92131. assert( onError==OE_Replace );
  92132. j1 = sqlite3VdbeAddOp1(v, OP_NotNull, regNewData+1+i); VdbeCoverage(v);
  92133. sqlite3ExprCode(pParse, pTab->aCol[i].pDflt, regNewData+1+i);
  92134. sqlite3VdbeJumpHere(v, j1);
  92135. break;
  92136. }
  92137. }
  92138. }
  92139. /* Test all CHECK constraints
  92140. */
  92141. #ifndef SQLITE_OMIT_CHECK
  92142. if( pTab->pCheck && (db->flags & SQLITE_IgnoreChecks)==0 ){
  92143. ExprList *pCheck = pTab->pCheck;
  92144. pParse->ckBase = regNewData+1;
  92145. onError = overrideError!=OE_Default ? overrideError : OE_Abort;
  92146. for(i=0; i<pCheck->nExpr; i++){
  92147. int allOk = sqlite3VdbeMakeLabel(v);
  92148. sqlite3ExprIfTrue(pParse, pCheck->a[i].pExpr, allOk, SQLITE_JUMPIFNULL);
  92149. if( onError==OE_Ignore ){
  92150. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  92151. }else{
  92152. char *zName = pCheck->a[i].zName;
  92153. if( zName==0 ) zName = pTab->zName;
  92154. if( onError==OE_Replace ) onError = OE_Abort; /* IMP: R-15569-63625 */
  92155. sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_CHECK,
  92156. onError, zName, P4_TRANSIENT,
  92157. P5_ConstraintCheck);
  92158. }
  92159. sqlite3VdbeResolveLabel(v, allOk);
  92160. }
  92161. }
  92162. #endif /* !defined(SQLITE_OMIT_CHECK) */
  92163. /* If rowid is changing, make sure the new rowid does not previously
  92164. ** exist in the table.
  92165. */
  92166. if( pkChng && pPk==0 ){
  92167. int addrRowidOk = sqlite3VdbeMakeLabel(v);
  92168. /* Figure out what action to take in case of a rowid collision */
  92169. onError = pTab->keyConf;
  92170. if( overrideError!=OE_Default ){
  92171. onError = overrideError;
  92172. }else if( onError==OE_Default ){
  92173. onError = OE_Abort;
  92174. }
  92175. if( isUpdate ){
  92176. /* pkChng!=0 does not mean that the rowid has change, only that
  92177. ** it might have changed. Skip the conflict logic below if the rowid
  92178. ** is unchanged. */
  92179. sqlite3VdbeAddOp3(v, OP_Eq, regNewData, addrRowidOk, regOldData);
  92180. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  92181. VdbeCoverage(v);
  92182. }
  92183. /* If the response to a rowid conflict is REPLACE but the response
  92184. ** to some other UNIQUE constraint is FAIL or IGNORE, then we need
  92185. ** to defer the running of the rowid conflict checking until after
  92186. ** the UNIQUE constraints have run.
  92187. */
  92188. if( onError==OE_Replace && overrideError!=OE_Replace ){
  92189. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  92190. if( pIdx->onError==OE_Ignore || pIdx->onError==OE_Fail ){
  92191. ipkTop = sqlite3VdbeAddOp0(v, OP_Goto);
  92192. break;
  92193. }
  92194. }
  92195. }
  92196. /* Check to see if the new rowid already exists in the table. Skip
  92197. ** the following conflict logic if it does not. */
  92198. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, addrRowidOk, regNewData);
  92199. VdbeCoverage(v);
  92200. /* Generate code that deals with a rowid collision */
  92201. switch( onError ){
  92202. default: {
  92203. onError = OE_Abort;
  92204. /* Fall thru into the next case */
  92205. }
  92206. case OE_Rollback:
  92207. case OE_Abort:
  92208. case OE_Fail: {
  92209. sqlite3RowidConstraint(pParse, onError, pTab);
  92210. break;
  92211. }
  92212. case OE_Replace: {
  92213. /* If there are DELETE triggers on this table and the
  92214. ** recursive-triggers flag is set, call GenerateRowDelete() to
  92215. ** remove the conflicting row from the table. This will fire
  92216. ** the triggers and remove both the table and index b-tree entries.
  92217. **
  92218. ** Otherwise, if there are no triggers or the recursive-triggers
  92219. ** flag is not set, but the table has one or more indexes, call
  92220. ** GenerateRowIndexDelete(). This removes the index b-tree entries
  92221. ** only. The table b-tree entry will be replaced by the new entry
  92222. ** when it is inserted.
  92223. **
  92224. ** If either GenerateRowDelete() or GenerateRowIndexDelete() is called,
  92225. ** also invoke MultiWrite() to indicate that this VDBE may require
  92226. ** statement rollback (if the statement is aborted after the delete
  92227. ** takes place). Earlier versions called sqlite3MultiWrite() regardless,
  92228. ** but being more selective here allows statements like:
  92229. **
  92230. ** REPLACE INTO t(rowid) VALUES($newrowid)
  92231. **
  92232. ** to run without a statement journal if there are no indexes on the
  92233. ** table.
  92234. */
  92235. Trigger *pTrigger = 0;
  92236. if( db->flags&SQLITE_RecTriggers ){
  92237. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  92238. }
  92239. if( pTrigger || sqlite3FkRequired(pParse, pTab, 0, 0) ){
  92240. sqlite3MultiWrite(pParse);
  92241. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  92242. regNewData, 1, 0, OE_Replace, 1);
  92243. }else if( pTab->pIndex ){
  92244. sqlite3MultiWrite(pParse);
  92245. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, 0);
  92246. }
  92247. seenReplace = 1;
  92248. break;
  92249. }
  92250. case OE_Ignore: {
  92251. /*assert( seenReplace==0 );*/
  92252. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  92253. break;
  92254. }
  92255. }
  92256. sqlite3VdbeResolveLabel(v, addrRowidOk);
  92257. if( ipkTop ){
  92258. ipkBottom = sqlite3VdbeAddOp0(v, OP_Goto);
  92259. sqlite3VdbeJumpHere(v, ipkTop);
  92260. }
  92261. }
  92262. /* Test all UNIQUE constraints by creating entries for each UNIQUE
  92263. ** index and making sure that duplicate entries do not already exist.
  92264. ** Compute the revised record entries for indices as we go.
  92265. **
  92266. ** This loop also handles the case of the PRIMARY KEY index for a
  92267. ** WITHOUT ROWID table.
  92268. */
  92269. for(ix=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, ix++){
  92270. int regIdx; /* Range of registers hold conent for pIdx */
  92271. int regR; /* Range of registers holding conflicting PK */
  92272. int iThisCur; /* Cursor for this UNIQUE index */
  92273. int addrUniqueOk; /* Jump here if the UNIQUE constraint is satisfied */
  92274. if( aRegIdx[ix]==0 ) continue; /* Skip indices that do not change */
  92275. if( bAffinityDone==0 ){
  92276. sqlite3TableAffinity(v, pTab, regNewData+1);
  92277. bAffinityDone = 1;
  92278. }
  92279. iThisCur = iIdxCur+ix;
  92280. addrUniqueOk = sqlite3VdbeMakeLabel(v);
  92281. /* Skip partial indices for which the WHERE clause is not true */
  92282. if( pIdx->pPartIdxWhere ){
  92283. sqlite3VdbeAddOp2(v, OP_Null, 0, aRegIdx[ix]);
  92284. pParse->ckBase = regNewData+1;
  92285. sqlite3ExprIfFalse(pParse, pIdx->pPartIdxWhere, addrUniqueOk,
  92286. SQLITE_JUMPIFNULL);
  92287. pParse->ckBase = 0;
  92288. }
  92289. /* Create a record for this index entry as it should appear after
  92290. ** the insert or update. Store that record in the aRegIdx[ix] register
  92291. */
  92292. regIdx = sqlite3GetTempRange(pParse, pIdx->nColumn);
  92293. for(i=0; i<pIdx->nColumn; i++){
  92294. int iField = pIdx->aiColumn[i];
  92295. int x;
  92296. if( iField<0 || iField==pTab->iPKey ){
  92297. if( regRowid==regIdx+i ) continue; /* ROWID already in regIdx+i */
  92298. x = regNewData;
  92299. regRowid = pIdx->pPartIdxWhere ? -1 : regIdx+i;
  92300. }else{
  92301. x = iField + regNewData + 1;
  92302. }
  92303. sqlite3VdbeAddOp2(v, OP_SCopy, x, regIdx+i);
  92304. VdbeComment((v, "%s", iField<0 ? "rowid" : pTab->aCol[iField].zName));
  92305. }
  92306. sqlite3VdbeAddOp3(v, OP_MakeRecord, regIdx, pIdx->nColumn, aRegIdx[ix]);
  92307. VdbeComment((v, "for %s", pIdx->zName));
  92308. sqlite3ExprCacheAffinityChange(pParse, regIdx, pIdx->nColumn);
  92309. /* In an UPDATE operation, if this index is the PRIMARY KEY index
  92310. ** of a WITHOUT ROWID table and there has been no change the
  92311. ** primary key, then no collision is possible. The collision detection
  92312. ** logic below can all be skipped. */
  92313. if( isUpdate && pPk==pIdx && pkChng==0 ){
  92314. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  92315. continue;
  92316. }
  92317. /* Find out what action to take in case there is a uniqueness conflict */
  92318. onError = pIdx->onError;
  92319. if( onError==OE_None ){
  92320. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  92321. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  92322. continue; /* pIdx is not a UNIQUE index */
  92323. }
  92324. if( overrideError!=OE_Default ){
  92325. onError = overrideError;
  92326. }else if( onError==OE_Default ){
  92327. onError = OE_Abort;
  92328. }
  92329. /* Check to see if the new index entry will be unique */
  92330. sqlite3VdbeAddOp4Int(v, OP_NoConflict, iThisCur, addrUniqueOk,
  92331. regIdx, pIdx->nKeyCol); VdbeCoverage(v);
  92332. /* Generate code to handle collisions */
  92333. regR = (pIdx==pPk) ? regIdx : sqlite3GetTempRange(pParse, nPkField);
  92334. if( isUpdate || onError==OE_Replace ){
  92335. if( HasRowid(pTab) ){
  92336. sqlite3VdbeAddOp2(v, OP_IdxRowid, iThisCur, regR);
  92337. /* Conflict only if the rowid of the existing index entry
  92338. ** is different from old-rowid */
  92339. if( isUpdate ){
  92340. sqlite3VdbeAddOp3(v, OP_Eq, regR, addrUniqueOk, regOldData);
  92341. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  92342. VdbeCoverage(v);
  92343. }
  92344. }else{
  92345. int x;
  92346. /* Extract the PRIMARY KEY from the end of the index entry and
  92347. ** store it in registers regR..regR+nPk-1 */
  92348. if( pIdx!=pPk ){
  92349. for(i=0; i<pPk->nKeyCol; i++){
  92350. x = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[i]);
  92351. sqlite3VdbeAddOp3(v, OP_Column, iThisCur, x, regR+i);
  92352. VdbeComment((v, "%s.%s", pTab->zName,
  92353. pTab->aCol[pPk->aiColumn[i]].zName));
  92354. }
  92355. }
  92356. if( isUpdate ){
  92357. /* If currently processing the PRIMARY KEY of a WITHOUT ROWID
  92358. ** table, only conflict if the new PRIMARY KEY values are actually
  92359. ** different from the old.
  92360. **
  92361. ** For a UNIQUE index, only conflict if the PRIMARY KEY values
  92362. ** of the matched index row are different from the original PRIMARY
  92363. ** KEY values of this row before the update. */
  92364. int addrJump = sqlite3VdbeCurrentAddr(v)+pPk->nKeyCol;
  92365. int op = OP_Ne;
  92366. int regCmp = (IsPrimaryKeyIndex(pIdx) ? regIdx : regR);
  92367. for(i=0; i<pPk->nKeyCol; i++){
  92368. char *p4 = (char*)sqlite3LocateCollSeq(pParse, pPk->azColl[i]);
  92369. x = pPk->aiColumn[i];
  92370. if( i==(pPk->nKeyCol-1) ){
  92371. addrJump = addrUniqueOk;
  92372. op = OP_Eq;
  92373. }
  92374. sqlite3VdbeAddOp4(v, op,
  92375. regOldData+1+x, addrJump, regCmp+i, p4, P4_COLLSEQ
  92376. );
  92377. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  92378. VdbeCoverageIf(v, op==OP_Eq);
  92379. VdbeCoverageIf(v, op==OP_Ne);
  92380. }
  92381. }
  92382. }
  92383. }
  92384. /* Generate code that executes if the new index entry is not unique */
  92385. assert( onError==OE_Rollback || onError==OE_Abort || onError==OE_Fail
  92386. || onError==OE_Ignore || onError==OE_Replace );
  92387. switch( onError ){
  92388. case OE_Rollback:
  92389. case OE_Abort:
  92390. case OE_Fail: {
  92391. sqlite3UniqueConstraint(pParse, onError, pIdx);
  92392. break;
  92393. }
  92394. case OE_Ignore: {
  92395. sqlite3VdbeAddOp2(v, OP_Goto, 0, ignoreDest);
  92396. break;
  92397. }
  92398. default: {
  92399. Trigger *pTrigger = 0;
  92400. assert( onError==OE_Replace );
  92401. sqlite3MultiWrite(pParse);
  92402. if( db->flags&SQLITE_RecTriggers ){
  92403. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_DELETE, 0, 0);
  92404. }
  92405. sqlite3GenerateRowDelete(pParse, pTab, pTrigger, iDataCur, iIdxCur,
  92406. regR, nPkField, 0, OE_Replace, pIdx==pPk);
  92407. seenReplace = 1;
  92408. break;
  92409. }
  92410. }
  92411. sqlite3VdbeResolveLabel(v, addrUniqueOk);
  92412. sqlite3ReleaseTempRange(pParse, regIdx, pIdx->nColumn);
  92413. if( regR!=regIdx ) sqlite3ReleaseTempRange(pParse, regR, nPkField);
  92414. }
  92415. if( ipkTop ){
  92416. sqlite3VdbeAddOp2(v, OP_Goto, 0, ipkTop+1);
  92417. sqlite3VdbeJumpHere(v, ipkBottom);
  92418. }
  92419. *pbMayReplace = seenReplace;
  92420. VdbeModuleComment((v, "END: GenCnstCks(%d)", seenReplace));
  92421. }
  92422. /*
  92423. ** This routine generates code to finish the INSERT or UPDATE operation
  92424. ** that was started by a prior call to sqlite3GenerateConstraintChecks.
  92425. ** A consecutive range of registers starting at regNewData contains the
  92426. ** rowid and the content to be inserted.
  92427. **
  92428. ** The arguments to this routine should be the same as the first six
  92429. ** arguments to sqlite3GenerateConstraintChecks.
  92430. */
  92431. SQLITE_PRIVATE void sqlite3CompleteInsertion(
  92432. Parse *pParse, /* The parser context */
  92433. Table *pTab, /* the table into which we are inserting */
  92434. int iDataCur, /* Cursor of the canonical data source */
  92435. int iIdxCur, /* First index cursor */
  92436. int regNewData, /* Range of content */
  92437. int *aRegIdx, /* Register used by each index. 0 for unused indices */
  92438. int isUpdate, /* True for UPDATE, False for INSERT */
  92439. int appendBias, /* True if this is likely to be an append */
  92440. int useSeekResult /* True to set the USESEEKRESULT flag on OP_[Idx]Insert */
  92441. ){
  92442. Vdbe *v; /* Prepared statements under construction */
  92443. Index *pIdx; /* An index being inserted or updated */
  92444. u8 pik_flags; /* flag values passed to the btree insert */
  92445. int regData; /* Content registers (after the rowid) */
  92446. int regRec; /* Register holding assembled record for the table */
  92447. int i; /* Loop counter */
  92448. u8 bAffinityDone = 0; /* True if OP_Affinity has been run already */
  92449. v = sqlite3GetVdbe(pParse);
  92450. assert( v!=0 );
  92451. assert( pTab->pSelect==0 ); /* This table is not a VIEW */
  92452. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  92453. if( aRegIdx[i]==0 ) continue;
  92454. bAffinityDone = 1;
  92455. if( pIdx->pPartIdxWhere ){
  92456. sqlite3VdbeAddOp2(v, OP_IsNull, aRegIdx[i], sqlite3VdbeCurrentAddr(v)+2);
  92457. VdbeCoverage(v);
  92458. }
  92459. sqlite3VdbeAddOp2(v, OP_IdxInsert, iIdxCur+i, aRegIdx[i]);
  92460. pik_flags = 0;
  92461. if( useSeekResult ) pik_flags = OPFLAG_USESEEKRESULT;
  92462. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
  92463. assert( pParse->nested==0 );
  92464. pik_flags |= OPFLAG_NCHANGE;
  92465. }
  92466. if( pik_flags ) sqlite3VdbeChangeP5(v, pik_flags);
  92467. }
  92468. if( !HasRowid(pTab) ) return;
  92469. regData = regNewData + 1;
  92470. regRec = sqlite3GetTempReg(pParse);
  92471. sqlite3VdbeAddOp3(v, OP_MakeRecord, regData, pTab->nCol, regRec);
  92472. if( !bAffinityDone ) sqlite3TableAffinity(v, pTab, 0);
  92473. sqlite3ExprCacheAffinityChange(pParse, regData, pTab->nCol);
  92474. if( pParse->nested ){
  92475. pik_flags = 0;
  92476. }else{
  92477. pik_flags = OPFLAG_NCHANGE;
  92478. pik_flags |= (isUpdate?OPFLAG_ISUPDATE:OPFLAG_LASTROWID);
  92479. }
  92480. if( appendBias ){
  92481. pik_flags |= OPFLAG_APPEND;
  92482. }
  92483. if( useSeekResult ){
  92484. pik_flags |= OPFLAG_USESEEKRESULT;
  92485. }
  92486. sqlite3VdbeAddOp3(v, OP_Insert, iDataCur, regRec, regNewData);
  92487. if( !pParse->nested ){
  92488. sqlite3VdbeChangeP4(v, -1, pTab->zName, P4_TRANSIENT);
  92489. }
  92490. sqlite3VdbeChangeP5(v, pik_flags);
  92491. }
  92492. /*
  92493. ** Allocate cursors for the pTab table and all its indices and generate
  92494. ** code to open and initialized those cursors.
  92495. **
  92496. ** The cursor for the object that contains the complete data (normally
  92497. ** the table itself, but the PRIMARY KEY index in the case of a WITHOUT
  92498. ** ROWID table) is returned in *piDataCur. The first index cursor is
  92499. ** returned in *piIdxCur. The number of indices is returned.
  92500. **
  92501. ** Use iBase as the first cursor (either the *piDataCur for rowid tables
  92502. ** or the first index for WITHOUT ROWID tables) if it is non-negative.
  92503. ** If iBase is negative, then allocate the next available cursor.
  92504. **
  92505. ** For a rowid table, *piDataCur will be exactly one less than *piIdxCur.
  92506. ** For a WITHOUT ROWID table, *piDataCur will be somewhere in the range
  92507. ** of *piIdxCurs, depending on where the PRIMARY KEY index appears on the
  92508. ** pTab->pIndex list.
  92509. **
  92510. ** If pTab is a virtual table, then this routine is a no-op and the
  92511. ** *piDataCur and *piIdxCur values are left uninitialized.
  92512. */
  92513. SQLITE_PRIVATE int sqlite3OpenTableAndIndices(
  92514. Parse *pParse, /* Parsing context */
  92515. Table *pTab, /* Table to be opened */
  92516. int op, /* OP_OpenRead or OP_OpenWrite */
  92517. int iBase, /* Use this for the table cursor, if there is one */
  92518. u8 *aToOpen, /* If not NULL: boolean for each table and index */
  92519. int *piDataCur, /* Write the database source cursor number here */
  92520. int *piIdxCur /* Write the first index cursor number here */
  92521. ){
  92522. int i;
  92523. int iDb;
  92524. int iDataCur;
  92525. Index *pIdx;
  92526. Vdbe *v;
  92527. assert( op==OP_OpenRead || op==OP_OpenWrite );
  92528. if( IsVirtual(pTab) ){
  92529. /* This routine is a no-op for virtual tables. Leave the output
  92530. ** variables *piDataCur and *piIdxCur uninitialized so that valgrind
  92531. ** can detect if they are used by mistake in the caller. */
  92532. return 0;
  92533. }
  92534. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  92535. v = sqlite3GetVdbe(pParse);
  92536. assert( v!=0 );
  92537. if( iBase<0 ) iBase = pParse->nTab;
  92538. iDataCur = iBase++;
  92539. if( piDataCur ) *piDataCur = iDataCur;
  92540. if( HasRowid(pTab) && (aToOpen==0 || aToOpen[0]) ){
  92541. sqlite3OpenTable(pParse, iDataCur, iDb, pTab, op);
  92542. }else{
  92543. sqlite3TableLock(pParse, iDb, pTab->tnum, op==OP_OpenWrite, pTab->zName);
  92544. }
  92545. if( piIdxCur ) *piIdxCur = iBase;
  92546. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  92547. int iIdxCur = iBase++;
  92548. assert( pIdx->pSchema==pTab->pSchema );
  92549. if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) && piDataCur ){
  92550. *piDataCur = iIdxCur;
  92551. }
  92552. if( aToOpen==0 || aToOpen[i+1] ){
  92553. sqlite3VdbeAddOp3(v, op, iIdxCur, pIdx->tnum, iDb);
  92554. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  92555. VdbeComment((v, "%s", pIdx->zName));
  92556. }
  92557. }
  92558. if( iBase>pParse->nTab ) pParse->nTab = iBase;
  92559. return i;
  92560. }
  92561. #ifdef SQLITE_TEST
  92562. /*
  92563. ** The following global variable is incremented whenever the
  92564. ** transfer optimization is used. This is used for testing
  92565. ** purposes only - to make sure the transfer optimization really
  92566. ** is happening when it is supposed to.
  92567. */
  92568. SQLITE_API int sqlite3_xferopt_count;
  92569. #endif /* SQLITE_TEST */
  92570. #ifndef SQLITE_OMIT_XFER_OPT
  92571. /*
  92572. ** Check to collation names to see if they are compatible.
  92573. */
  92574. static int xferCompatibleCollation(const char *z1, const char *z2){
  92575. if( z1==0 ){
  92576. return z2==0;
  92577. }
  92578. if( z2==0 ){
  92579. return 0;
  92580. }
  92581. return sqlite3StrICmp(z1, z2)==0;
  92582. }
  92583. /*
  92584. ** Check to see if index pSrc is compatible as a source of data
  92585. ** for index pDest in an insert transfer optimization. The rules
  92586. ** for a compatible index:
  92587. **
  92588. ** * The index is over the same set of columns
  92589. ** * The same DESC and ASC markings occurs on all columns
  92590. ** * The same onError processing (OE_Abort, OE_Ignore, etc)
  92591. ** * The same collating sequence on each column
  92592. ** * The index has the exact same WHERE clause
  92593. */
  92594. static int xferCompatibleIndex(Index *pDest, Index *pSrc){
  92595. int i;
  92596. assert( pDest && pSrc );
  92597. assert( pDest->pTable!=pSrc->pTable );
  92598. if( pDest->nKeyCol!=pSrc->nKeyCol ){
  92599. return 0; /* Different number of columns */
  92600. }
  92601. if( pDest->onError!=pSrc->onError ){
  92602. return 0; /* Different conflict resolution strategies */
  92603. }
  92604. for(i=0; i<pSrc->nKeyCol; i++){
  92605. if( pSrc->aiColumn[i]!=pDest->aiColumn[i] ){
  92606. return 0; /* Different columns indexed */
  92607. }
  92608. if( pSrc->aSortOrder[i]!=pDest->aSortOrder[i] ){
  92609. return 0; /* Different sort orders */
  92610. }
  92611. if( !xferCompatibleCollation(pSrc->azColl[i],pDest->azColl[i]) ){
  92612. return 0; /* Different collating sequences */
  92613. }
  92614. }
  92615. if( sqlite3ExprCompare(pSrc->pPartIdxWhere, pDest->pPartIdxWhere, -1) ){
  92616. return 0; /* Different WHERE clauses */
  92617. }
  92618. /* If no test above fails then the indices must be compatible */
  92619. return 1;
  92620. }
  92621. /*
  92622. ** Attempt the transfer optimization on INSERTs of the form
  92623. **
  92624. ** INSERT INTO tab1 SELECT * FROM tab2;
  92625. **
  92626. ** The xfer optimization transfers raw records from tab2 over to tab1.
  92627. ** Columns are not decoded and reassembled, which greatly improves
  92628. ** performance. Raw index records are transferred in the same way.
  92629. **
  92630. ** The xfer optimization is only attempted if tab1 and tab2 are compatible.
  92631. ** There are lots of rules for determining compatibility - see comments
  92632. ** embedded in the code for details.
  92633. **
  92634. ** This routine returns TRUE if the optimization is guaranteed to be used.
  92635. ** Sometimes the xfer optimization will only work if the destination table
  92636. ** is empty - a factor that can only be determined at run-time. In that
  92637. ** case, this routine generates code for the xfer optimization but also
  92638. ** does a test to see if the destination table is empty and jumps over the
  92639. ** xfer optimization code if the test fails. In that case, this routine
  92640. ** returns FALSE so that the caller will know to go ahead and generate
  92641. ** an unoptimized transfer. This routine also returns FALSE if there
  92642. ** is no chance that the xfer optimization can be applied.
  92643. **
  92644. ** This optimization is particularly useful at making VACUUM run faster.
  92645. */
  92646. static int xferOptimization(
  92647. Parse *pParse, /* Parser context */
  92648. Table *pDest, /* The table we are inserting into */
  92649. Select *pSelect, /* A SELECT statement to use as the data source */
  92650. int onError, /* How to handle constraint errors */
  92651. int iDbDest /* The database of pDest */
  92652. ){
  92653. ExprList *pEList; /* The result set of the SELECT */
  92654. Table *pSrc; /* The table in the FROM clause of SELECT */
  92655. Index *pSrcIdx, *pDestIdx; /* Source and destination indices */
  92656. struct SrcList_item *pItem; /* An element of pSelect->pSrc */
  92657. int i; /* Loop counter */
  92658. int iDbSrc; /* The database of pSrc */
  92659. int iSrc, iDest; /* Cursors from source and destination */
  92660. int addr1, addr2; /* Loop addresses */
  92661. int emptyDestTest = 0; /* Address of test for empty pDest */
  92662. int emptySrcTest = 0; /* Address of test for empty pSrc */
  92663. Vdbe *v; /* The VDBE we are building */
  92664. int regAutoinc; /* Memory register used by AUTOINC */
  92665. int destHasUniqueIdx = 0; /* True if pDest has a UNIQUE index */
  92666. int regData, regRowid; /* Registers holding data and rowid */
  92667. if( pSelect==0 ){
  92668. return 0; /* Must be of the form INSERT INTO ... SELECT ... */
  92669. }
  92670. if( pParse->pWith || pSelect->pWith ){
  92671. /* Do not attempt to process this query if there are an WITH clauses
  92672. ** attached to it. Proceeding may generate a false "no such table: xxx"
  92673. ** error if pSelect reads from a CTE named "xxx". */
  92674. return 0;
  92675. }
  92676. if( sqlite3TriggerList(pParse, pDest) ){
  92677. return 0; /* tab1 must not have triggers */
  92678. }
  92679. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92680. if( pDest->tabFlags & TF_Virtual ){
  92681. return 0; /* tab1 must not be a virtual table */
  92682. }
  92683. #endif
  92684. if( onError==OE_Default ){
  92685. if( pDest->iPKey>=0 ) onError = pDest->keyConf;
  92686. if( onError==OE_Default ) onError = OE_Abort;
  92687. }
  92688. assert(pSelect->pSrc); /* allocated even if there is no FROM clause */
  92689. if( pSelect->pSrc->nSrc!=1 ){
  92690. return 0; /* FROM clause must have exactly one term */
  92691. }
  92692. if( pSelect->pSrc->a[0].pSelect ){
  92693. return 0; /* FROM clause cannot contain a subquery */
  92694. }
  92695. if( pSelect->pWhere ){
  92696. return 0; /* SELECT may not have a WHERE clause */
  92697. }
  92698. if( pSelect->pOrderBy ){
  92699. return 0; /* SELECT may not have an ORDER BY clause */
  92700. }
  92701. /* Do not need to test for a HAVING clause. If HAVING is present but
  92702. ** there is no ORDER BY, we will get an error. */
  92703. if( pSelect->pGroupBy ){
  92704. return 0; /* SELECT may not have a GROUP BY clause */
  92705. }
  92706. if( pSelect->pLimit ){
  92707. return 0; /* SELECT may not have a LIMIT clause */
  92708. }
  92709. assert( pSelect->pOffset==0 ); /* Must be so if pLimit==0 */
  92710. if( pSelect->pPrior ){
  92711. return 0; /* SELECT may not be a compound query */
  92712. }
  92713. if( pSelect->selFlags & SF_Distinct ){
  92714. return 0; /* SELECT may not be DISTINCT */
  92715. }
  92716. pEList = pSelect->pEList;
  92717. assert( pEList!=0 );
  92718. if( pEList->nExpr!=1 ){
  92719. return 0; /* The result set must have exactly one column */
  92720. }
  92721. assert( pEList->a[0].pExpr );
  92722. if( pEList->a[0].pExpr->op!=TK_ALL ){
  92723. return 0; /* The result set must be the special operator "*" */
  92724. }
  92725. /* At this point we have established that the statement is of the
  92726. ** correct syntactic form to participate in this optimization. Now
  92727. ** we have to check the semantics.
  92728. */
  92729. pItem = pSelect->pSrc->a;
  92730. pSrc = sqlite3LocateTableItem(pParse, 0, pItem);
  92731. if( pSrc==0 ){
  92732. return 0; /* FROM clause does not contain a real table */
  92733. }
  92734. if( pSrc==pDest ){
  92735. return 0; /* tab1 and tab2 may not be the same table */
  92736. }
  92737. if( HasRowid(pDest)!=HasRowid(pSrc) ){
  92738. return 0; /* source and destination must both be WITHOUT ROWID or not */
  92739. }
  92740. #ifndef SQLITE_OMIT_VIRTUALTABLE
  92741. if( pSrc->tabFlags & TF_Virtual ){
  92742. return 0; /* tab2 must not be a virtual table */
  92743. }
  92744. #endif
  92745. if( pSrc->pSelect ){
  92746. return 0; /* tab2 may not be a view */
  92747. }
  92748. if( pDest->nCol!=pSrc->nCol ){
  92749. return 0; /* Number of columns must be the same in tab1 and tab2 */
  92750. }
  92751. if( pDest->iPKey!=pSrc->iPKey ){
  92752. return 0; /* Both tables must have the same INTEGER PRIMARY KEY */
  92753. }
  92754. for(i=0; i<pDest->nCol; i++){
  92755. Column *pDestCol = &pDest->aCol[i];
  92756. Column *pSrcCol = &pSrc->aCol[i];
  92757. if( pDestCol->affinity!=pSrcCol->affinity ){
  92758. return 0; /* Affinity must be the same on all columns */
  92759. }
  92760. if( !xferCompatibleCollation(pDestCol->zColl, pSrcCol->zColl) ){
  92761. return 0; /* Collating sequence must be the same on all columns */
  92762. }
  92763. if( pDestCol->notNull && !pSrcCol->notNull ){
  92764. return 0; /* tab2 must be NOT NULL if tab1 is */
  92765. }
  92766. /* Default values for second and subsequent columns need to match. */
  92767. if( i>0
  92768. && ((pDestCol->zDflt==0)!=(pSrcCol->zDflt==0)
  92769. || (pDestCol->zDflt && strcmp(pDestCol->zDflt, pSrcCol->zDflt)!=0))
  92770. ){
  92771. return 0; /* Default values must be the same for all columns */
  92772. }
  92773. }
  92774. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  92775. if( IsUniqueIndex(pDestIdx) ){
  92776. destHasUniqueIdx = 1;
  92777. }
  92778. for(pSrcIdx=pSrc->pIndex; pSrcIdx; pSrcIdx=pSrcIdx->pNext){
  92779. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  92780. }
  92781. if( pSrcIdx==0 ){
  92782. return 0; /* pDestIdx has no corresponding index in pSrc */
  92783. }
  92784. }
  92785. #ifndef SQLITE_OMIT_CHECK
  92786. if( pDest->pCheck && sqlite3ExprListCompare(pSrc->pCheck,pDest->pCheck,-1) ){
  92787. return 0; /* Tables have different CHECK constraints. Ticket #2252 */
  92788. }
  92789. #endif
  92790. #ifndef SQLITE_OMIT_FOREIGN_KEY
  92791. /* Disallow the transfer optimization if the destination table constains
  92792. ** any foreign key constraints. This is more restrictive than necessary.
  92793. ** But the main beneficiary of the transfer optimization is the VACUUM
  92794. ** command, and the VACUUM command disables foreign key constraints. So
  92795. ** the extra complication to make this rule less restrictive is probably
  92796. ** not worth the effort. Ticket [6284df89debdfa61db8073e062908af0c9b6118e]
  92797. */
  92798. if( (pParse->db->flags & SQLITE_ForeignKeys)!=0 && pDest->pFKey!=0 ){
  92799. return 0;
  92800. }
  92801. #endif
  92802. if( (pParse->db->flags & SQLITE_CountRows)!=0 ){
  92803. return 0; /* xfer opt does not play well with PRAGMA count_changes */
  92804. }
  92805. /* If we get this far, it means that the xfer optimization is at
  92806. ** least a possibility, though it might only work if the destination
  92807. ** table (tab1) is initially empty.
  92808. */
  92809. #ifdef SQLITE_TEST
  92810. sqlite3_xferopt_count++;
  92811. #endif
  92812. iDbSrc = sqlite3SchemaToIndex(pParse->db, pSrc->pSchema);
  92813. v = sqlite3GetVdbe(pParse);
  92814. sqlite3CodeVerifySchema(pParse, iDbSrc);
  92815. iSrc = pParse->nTab++;
  92816. iDest = pParse->nTab++;
  92817. regAutoinc = autoIncBegin(pParse, iDbDest, pDest);
  92818. regData = sqlite3GetTempReg(pParse);
  92819. regRowid = sqlite3GetTempReg(pParse);
  92820. sqlite3OpenTable(pParse, iDest, iDbDest, pDest, OP_OpenWrite);
  92821. assert( HasRowid(pDest) || destHasUniqueIdx );
  92822. if( (pDest->iPKey<0 && pDest->pIndex!=0) /* (1) */
  92823. || destHasUniqueIdx /* (2) */
  92824. || (onError!=OE_Abort && onError!=OE_Rollback) /* (3) */
  92825. ){
  92826. /* In some circumstances, we are able to run the xfer optimization
  92827. ** only if the destination table is initially empty. This code makes
  92828. ** that determination. Conditions under which the destination must
  92829. ** be empty:
  92830. **
  92831. ** (1) There is no INTEGER PRIMARY KEY but there are indices.
  92832. ** (If the destination is not initially empty, the rowid fields
  92833. ** of index entries might need to change.)
  92834. **
  92835. ** (2) The destination has a unique index. (The xfer optimization
  92836. ** is unable to test uniqueness.)
  92837. **
  92838. ** (3) onError is something other than OE_Abort and OE_Rollback.
  92839. */
  92840. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iDest, 0); VdbeCoverage(v);
  92841. emptyDestTest = sqlite3VdbeAddOp2(v, OP_Goto, 0, 0);
  92842. sqlite3VdbeJumpHere(v, addr1);
  92843. }
  92844. if( HasRowid(pSrc) ){
  92845. sqlite3OpenTable(pParse, iSrc, iDbSrc, pSrc, OP_OpenRead);
  92846. emptySrcTest = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  92847. if( pDest->iPKey>=0 ){
  92848. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  92849. addr2 = sqlite3VdbeAddOp3(v, OP_NotExists, iDest, 0, regRowid);
  92850. VdbeCoverage(v);
  92851. sqlite3RowidConstraint(pParse, onError, pDest);
  92852. sqlite3VdbeJumpHere(v, addr2);
  92853. autoIncStep(pParse, regAutoinc, regRowid);
  92854. }else if( pDest->pIndex==0 ){
  92855. addr1 = sqlite3VdbeAddOp2(v, OP_NewRowid, iDest, regRowid);
  92856. }else{
  92857. addr1 = sqlite3VdbeAddOp2(v, OP_Rowid, iSrc, regRowid);
  92858. assert( (pDest->tabFlags & TF_Autoincrement)==0 );
  92859. }
  92860. sqlite3VdbeAddOp2(v, OP_RowData, iSrc, regData);
  92861. sqlite3VdbeAddOp3(v, OP_Insert, iDest, regData, regRowid);
  92862. sqlite3VdbeChangeP5(v, OPFLAG_NCHANGE|OPFLAG_LASTROWID|OPFLAG_APPEND);
  92863. sqlite3VdbeChangeP4(v, -1, pDest->zName, 0);
  92864. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1); VdbeCoverage(v);
  92865. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  92866. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  92867. }else{
  92868. sqlite3TableLock(pParse, iDbDest, pDest->tnum, 1, pDest->zName);
  92869. sqlite3TableLock(pParse, iDbSrc, pSrc->tnum, 0, pSrc->zName);
  92870. }
  92871. for(pDestIdx=pDest->pIndex; pDestIdx; pDestIdx=pDestIdx->pNext){
  92872. for(pSrcIdx=pSrc->pIndex; ALWAYS(pSrcIdx); pSrcIdx=pSrcIdx->pNext){
  92873. if( xferCompatibleIndex(pDestIdx, pSrcIdx) ) break;
  92874. }
  92875. assert( pSrcIdx );
  92876. sqlite3VdbeAddOp3(v, OP_OpenRead, iSrc, pSrcIdx->tnum, iDbSrc);
  92877. sqlite3VdbeSetP4KeyInfo(pParse, pSrcIdx);
  92878. VdbeComment((v, "%s", pSrcIdx->zName));
  92879. sqlite3VdbeAddOp3(v, OP_OpenWrite, iDest, pDestIdx->tnum, iDbDest);
  92880. sqlite3VdbeSetP4KeyInfo(pParse, pDestIdx);
  92881. sqlite3VdbeChangeP5(v, OPFLAG_BULKCSR);
  92882. VdbeComment((v, "%s", pDestIdx->zName));
  92883. addr1 = sqlite3VdbeAddOp2(v, OP_Rewind, iSrc, 0); VdbeCoverage(v);
  92884. sqlite3VdbeAddOp2(v, OP_RowKey, iSrc, regData);
  92885. sqlite3VdbeAddOp3(v, OP_IdxInsert, iDest, regData, 1);
  92886. sqlite3VdbeAddOp2(v, OP_Next, iSrc, addr1+1); VdbeCoverage(v);
  92887. sqlite3VdbeJumpHere(v, addr1);
  92888. sqlite3VdbeAddOp2(v, OP_Close, iSrc, 0);
  92889. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  92890. }
  92891. if( emptySrcTest ) sqlite3VdbeJumpHere(v, emptySrcTest);
  92892. sqlite3ReleaseTempReg(pParse, regRowid);
  92893. sqlite3ReleaseTempReg(pParse, regData);
  92894. if( emptyDestTest ){
  92895. sqlite3VdbeAddOp2(v, OP_Halt, SQLITE_OK, 0);
  92896. sqlite3VdbeJumpHere(v, emptyDestTest);
  92897. sqlite3VdbeAddOp2(v, OP_Close, iDest, 0);
  92898. return 0;
  92899. }else{
  92900. return 1;
  92901. }
  92902. }
  92903. #endif /* SQLITE_OMIT_XFER_OPT */
  92904. /************** End of insert.c **********************************************/
  92905. /************** Begin file legacy.c ******************************************/
  92906. /*
  92907. ** 2001 September 15
  92908. **
  92909. ** The author disclaims copyright to this source code. In place of
  92910. ** a legal notice, here is a blessing:
  92911. **
  92912. ** May you do good and not evil.
  92913. ** May you find forgiveness for yourself and forgive others.
  92914. ** May you share freely, never taking more than you give.
  92915. **
  92916. *************************************************************************
  92917. ** Main file for the SQLite library. The routines in this file
  92918. ** implement the programmer interface to the library. Routines in
  92919. ** other files are for internal use by SQLite and should not be
  92920. ** accessed by users of the library.
  92921. */
  92922. /*
  92923. ** Execute SQL code. Return one of the SQLITE_ success/failure
  92924. ** codes. Also write an error message into memory obtained from
  92925. ** malloc() and make *pzErrMsg point to that message.
  92926. **
  92927. ** If the SQL is a query, then for each row in the query result
  92928. ** the xCallback() function is called. pArg becomes the first
  92929. ** argument to xCallback(). If xCallback=NULL then no callback
  92930. ** is invoked, even for queries.
  92931. */
  92932. SQLITE_API int sqlite3_exec(
  92933. sqlite3 *db, /* The database on which the SQL executes */
  92934. const char *zSql, /* The SQL to be executed */
  92935. sqlite3_callback xCallback, /* Invoke this callback routine */
  92936. void *pArg, /* First argument to xCallback() */
  92937. char **pzErrMsg /* Write error messages here */
  92938. ){
  92939. int rc = SQLITE_OK; /* Return code */
  92940. const char *zLeftover; /* Tail of unprocessed SQL */
  92941. sqlite3_stmt *pStmt = 0; /* The current SQL statement */
  92942. char **azCols = 0; /* Names of result columns */
  92943. int callbackIsInit; /* True if callback data is initialized */
  92944. if( !sqlite3SafetyCheckOk(db) ) return SQLITE_MISUSE_BKPT;
  92945. if( zSql==0 ) zSql = "";
  92946. sqlite3_mutex_enter(db->mutex);
  92947. sqlite3Error(db, SQLITE_OK);
  92948. while( rc==SQLITE_OK && zSql[0] ){
  92949. int nCol;
  92950. char **azVals = 0;
  92951. pStmt = 0;
  92952. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, &zLeftover);
  92953. assert( rc==SQLITE_OK || pStmt==0 );
  92954. if( rc!=SQLITE_OK ){
  92955. continue;
  92956. }
  92957. if( !pStmt ){
  92958. /* this happens for a comment or white-space */
  92959. zSql = zLeftover;
  92960. continue;
  92961. }
  92962. callbackIsInit = 0;
  92963. nCol = sqlite3_column_count(pStmt);
  92964. while( 1 ){
  92965. int i;
  92966. rc = sqlite3_step(pStmt);
  92967. /* Invoke the callback function if required */
  92968. if( xCallback && (SQLITE_ROW==rc ||
  92969. (SQLITE_DONE==rc && !callbackIsInit
  92970. && db->flags&SQLITE_NullCallback)) ){
  92971. if( !callbackIsInit ){
  92972. azCols = sqlite3DbMallocZero(db, 2*nCol*sizeof(const char*) + 1);
  92973. if( azCols==0 ){
  92974. goto exec_out;
  92975. }
  92976. for(i=0; i<nCol; i++){
  92977. azCols[i] = (char *)sqlite3_column_name(pStmt, i);
  92978. /* sqlite3VdbeSetColName() installs column names as UTF8
  92979. ** strings so there is no way for sqlite3_column_name() to fail. */
  92980. assert( azCols[i]!=0 );
  92981. }
  92982. callbackIsInit = 1;
  92983. }
  92984. if( rc==SQLITE_ROW ){
  92985. azVals = &azCols[nCol];
  92986. for(i=0; i<nCol; i++){
  92987. azVals[i] = (char *)sqlite3_column_text(pStmt, i);
  92988. if( !azVals[i] && sqlite3_column_type(pStmt, i)!=SQLITE_NULL ){
  92989. db->mallocFailed = 1;
  92990. goto exec_out;
  92991. }
  92992. }
  92993. }
  92994. if( xCallback(pArg, nCol, azVals, azCols) ){
  92995. /* EVIDENCE-OF: R-38229-40159 If the callback function to
  92996. ** sqlite3_exec() returns non-zero, then sqlite3_exec() will
  92997. ** return SQLITE_ABORT. */
  92998. rc = SQLITE_ABORT;
  92999. sqlite3VdbeFinalize((Vdbe *)pStmt);
  93000. pStmt = 0;
  93001. sqlite3Error(db, SQLITE_ABORT);
  93002. goto exec_out;
  93003. }
  93004. }
  93005. if( rc!=SQLITE_ROW ){
  93006. rc = sqlite3VdbeFinalize((Vdbe *)pStmt);
  93007. pStmt = 0;
  93008. zSql = zLeftover;
  93009. while( sqlite3Isspace(zSql[0]) ) zSql++;
  93010. break;
  93011. }
  93012. }
  93013. sqlite3DbFree(db, azCols);
  93014. azCols = 0;
  93015. }
  93016. exec_out:
  93017. if( pStmt ) sqlite3VdbeFinalize((Vdbe *)pStmt);
  93018. sqlite3DbFree(db, azCols);
  93019. rc = sqlite3ApiExit(db, rc);
  93020. if( rc!=SQLITE_OK && pzErrMsg ){
  93021. int nErrMsg = 1 + sqlite3Strlen30(sqlite3_errmsg(db));
  93022. *pzErrMsg = sqlite3Malloc(nErrMsg);
  93023. if( *pzErrMsg ){
  93024. memcpy(*pzErrMsg, sqlite3_errmsg(db), nErrMsg);
  93025. }else{
  93026. rc = SQLITE_NOMEM;
  93027. sqlite3Error(db, SQLITE_NOMEM);
  93028. }
  93029. }else if( pzErrMsg ){
  93030. *pzErrMsg = 0;
  93031. }
  93032. assert( (rc&db->errMask)==rc );
  93033. sqlite3_mutex_leave(db->mutex);
  93034. return rc;
  93035. }
  93036. /************** End of legacy.c **********************************************/
  93037. /************** Begin file loadext.c *****************************************/
  93038. /*
  93039. ** 2006 June 7
  93040. **
  93041. ** The author disclaims copyright to this source code. In place of
  93042. ** a legal notice, here is a blessing:
  93043. **
  93044. ** May you do good and not evil.
  93045. ** May you find forgiveness for yourself and forgive others.
  93046. ** May you share freely, never taking more than you give.
  93047. **
  93048. *************************************************************************
  93049. ** This file contains code used to dynamically load extensions into
  93050. ** the SQLite library.
  93051. */
  93052. #ifndef SQLITE_CORE
  93053. #define SQLITE_CORE 1 /* Disable the API redefinition in sqlite3ext.h */
  93054. #endif
  93055. /************** Include sqlite3ext.h in the middle of loadext.c **************/
  93056. /************** Begin file sqlite3ext.h **************************************/
  93057. /*
  93058. ** 2006 June 7
  93059. **
  93060. ** The author disclaims copyright to this source code. In place of
  93061. ** a legal notice, here is a blessing:
  93062. **
  93063. ** May you do good and not evil.
  93064. ** May you find forgiveness for yourself and forgive others.
  93065. ** May you share freely, never taking more than you give.
  93066. **
  93067. *************************************************************************
  93068. ** This header file defines the SQLite interface for use by
  93069. ** shared libraries that want to be imported as extensions into
  93070. ** an SQLite instance. Shared libraries that intend to be loaded
  93071. ** as extensions by SQLite should #include this file instead of
  93072. ** sqlite3.h.
  93073. */
  93074. #ifndef _SQLITE3EXT_H_
  93075. #define _SQLITE3EXT_H_
  93076. typedef struct sqlite3_api_routines sqlite3_api_routines;
  93077. /*
  93078. ** The following structure holds pointers to all of the SQLite API
  93079. ** routines.
  93080. **
  93081. ** WARNING: In order to maintain backwards compatibility, add new
  93082. ** interfaces to the end of this structure only. If you insert new
  93083. ** interfaces in the middle of this structure, then older different
  93084. ** versions of SQLite will not be able to load each other's shared
  93085. ** libraries!
  93086. */
  93087. struct sqlite3_api_routines {
  93088. void * (*aggregate_context)(sqlite3_context*,int nBytes);
  93089. int (*aggregate_count)(sqlite3_context*);
  93090. int (*bind_blob)(sqlite3_stmt*,int,const void*,int n,void(*)(void*));
  93091. int (*bind_double)(sqlite3_stmt*,int,double);
  93092. int (*bind_int)(sqlite3_stmt*,int,int);
  93093. int (*bind_int64)(sqlite3_stmt*,int,sqlite_int64);
  93094. int (*bind_null)(sqlite3_stmt*,int);
  93095. int (*bind_parameter_count)(sqlite3_stmt*);
  93096. int (*bind_parameter_index)(sqlite3_stmt*,const char*zName);
  93097. const char * (*bind_parameter_name)(sqlite3_stmt*,int);
  93098. int (*bind_text)(sqlite3_stmt*,int,const char*,int n,void(*)(void*));
  93099. int (*bind_text16)(sqlite3_stmt*,int,const void*,int,void(*)(void*));
  93100. int (*bind_value)(sqlite3_stmt*,int,const sqlite3_value*);
  93101. int (*busy_handler)(sqlite3*,int(*)(void*,int),void*);
  93102. int (*busy_timeout)(sqlite3*,int ms);
  93103. int (*changes)(sqlite3*);
  93104. int (*close)(sqlite3*);
  93105. int (*collation_needed)(sqlite3*,void*,void(*)(void*,sqlite3*,
  93106. int eTextRep,const char*));
  93107. int (*collation_needed16)(sqlite3*,void*,void(*)(void*,sqlite3*,
  93108. int eTextRep,const void*));
  93109. const void * (*column_blob)(sqlite3_stmt*,int iCol);
  93110. int (*column_bytes)(sqlite3_stmt*,int iCol);
  93111. int (*column_bytes16)(sqlite3_stmt*,int iCol);
  93112. int (*column_count)(sqlite3_stmt*pStmt);
  93113. const char * (*column_database_name)(sqlite3_stmt*,int);
  93114. const void * (*column_database_name16)(sqlite3_stmt*,int);
  93115. const char * (*column_decltype)(sqlite3_stmt*,int i);
  93116. const void * (*column_decltype16)(sqlite3_stmt*,int);
  93117. double (*column_double)(sqlite3_stmt*,int iCol);
  93118. int (*column_int)(sqlite3_stmt*,int iCol);
  93119. sqlite_int64 (*column_int64)(sqlite3_stmt*,int iCol);
  93120. const char * (*column_name)(sqlite3_stmt*,int);
  93121. const void * (*column_name16)(sqlite3_stmt*,int);
  93122. const char * (*column_origin_name)(sqlite3_stmt*,int);
  93123. const void * (*column_origin_name16)(sqlite3_stmt*,int);
  93124. const char * (*column_table_name)(sqlite3_stmt*,int);
  93125. const void * (*column_table_name16)(sqlite3_stmt*,int);
  93126. const unsigned char * (*column_text)(sqlite3_stmt*,int iCol);
  93127. const void * (*column_text16)(sqlite3_stmt*,int iCol);
  93128. int (*column_type)(sqlite3_stmt*,int iCol);
  93129. sqlite3_value* (*column_value)(sqlite3_stmt*,int iCol);
  93130. void * (*commit_hook)(sqlite3*,int(*)(void*),void*);
  93131. int (*complete)(const char*sql);
  93132. int (*complete16)(const void*sql);
  93133. int (*create_collation)(sqlite3*,const char*,int,void*,
  93134. int(*)(void*,int,const void*,int,const void*));
  93135. int (*create_collation16)(sqlite3*,const void*,int,void*,
  93136. int(*)(void*,int,const void*,int,const void*));
  93137. int (*create_function)(sqlite3*,const char*,int,int,void*,
  93138. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  93139. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  93140. void (*xFinal)(sqlite3_context*));
  93141. int (*create_function16)(sqlite3*,const void*,int,int,void*,
  93142. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  93143. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  93144. void (*xFinal)(sqlite3_context*));
  93145. int (*create_module)(sqlite3*,const char*,const sqlite3_module*,void*);
  93146. int (*data_count)(sqlite3_stmt*pStmt);
  93147. sqlite3 * (*db_handle)(sqlite3_stmt*);
  93148. int (*declare_vtab)(sqlite3*,const char*);
  93149. int (*enable_shared_cache)(int);
  93150. int (*errcode)(sqlite3*db);
  93151. const char * (*errmsg)(sqlite3*);
  93152. const void * (*errmsg16)(sqlite3*);
  93153. int (*exec)(sqlite3*,const char*,sqlite3_callback,void*,char**);
  93154. int (*expired)(sqlite3_stmt*);
  93155. int (*finalize)(sqlite3_stmt*pStmt);
  93156. void (*free)(void*);
  93157. void (*free_table)(char**result);
  93158. int (*get_autocommit)(sqlite3*);
  93159. void * (*get_auxdata)(sqlite3_context*,int);
  93160. int (*get_table)(sqlite3*,const char*,char***,int*,int*,char**);
  93161. int (*global_recover)(void);
  93162. void (*interruptx)(sqlite3*);
  93163. sqlite_int64 (*last_insert_rowid)(sqlite3*);
  93164. const char * (*libversion)(void);
  93165. int (*libversion_number)(void);
  93166. void *(*malloc)(int);
  93167. char * (*mprintf)(const char*,...);
  93168. int (*open)(const char*,sqlite3**);
  93169. int (*open16)(const void*,sqlite3**);
  93170. int (*prepare)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  93171. int (*prepare16)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  93172. void * (*profile)(sqlite3*,void(*)(void*,const char*,sqlite_uint64),void*);
  93173. void (*progress_handler)(sqlite3*,int,int(*)(void*),void*);
  93174. void *(*realloc)(void*,int);
  93175. int (*reset)(sqlite3_stmt*pStmt);
  93176. void (*result_blob)(sqlite3_context*,const void*,int,void(*)(void*));
  93177. void (*result_double)(sqlite3_context*,double);
  93178. void (*result_error)(sqlite3_context*,const char*,int);
  93179. void (*result_error16)(sqlite3_context*,const void*,int);
  93180. void (*result_int)(sqlite3_context*,int);
  93181. void (*result_int64)(sqlite3_context*,sqlite_int64);
  93182. void (*result_null)(sqlite3_context*);
  93183. void (*result_text)(sqlite3_context*,const char*,int,void(*)(void*));
  93184. void (*result_text16)(sqlite3_context*,const void*,int,void(*)(void*));
  93185. void (*result_text16be)(sqlite3_context*,const void*,int,void(*)(void*));
  93186. void (*result_text16le)(sqlite3_context*,const void*,int,void(*)(void*));
  93187. void (*result_value)(sqlite3_context*,sqlite3_value*);
  93188. void * (*rollback_hook)(sqlite3*,void(*)(void*),void*);
  93189. int (*set_authorizer)(sqlite3*,int(*)(void*,int,const char*,const char*,
  93190. const char*,const char*),void*);
  93191. void (*set_auxdata)(sqlite3_context*,int,void*,void (*)(void*));
  93192. char * (*snprintf)(int,char*,const char*,...);
  93193. int (*step)(sqlite3_stmt*);
  93194. int (*table_column_metadata)(sqlite3*,const char*,const char*,const char*,
  93195. char const**,char const**,int*,int*,int*);
  93196. void (*thread_cleanup)(void);
  93197. int (*total_changes)(sqlite3*);
  93198. void * (*trace)(sqlite3*,void(*xTrace)(void*,const char*),void*);
  93199. int (*transfer_bindings)(sqlite3_stmt*,sqlite3_stmt*);
  93200. void * (*update_hook)(sqlite3*,void(*)(void*,int ,char const*,char const*,
  93201. sqlite_int64),void*);
  93202. void * (*user_data)(sqlite3_context*);
  93203. const void * (*value_blob)(sqlite3_value*);
  93204. int (*value_bytes)(sqlite3_value*);
  93205. int (*value_bytes16)(sqlite3_value*);
  93206. double (*value_double)(sqlite3_value*);
  93207. int (*value_int)(sqlite3_value*);
  93208. sqlite_int64 (*value_int64)(sqlite3_value*);
  93209. int (*value_numeric_type)(sqlite3_value*);
  93210. const unsigned char * (*value_text)(sqlite3_value*);
  93211. const void * (*value_text16)(sqlite3_value*);
  93212. const void * (*value_text16be)(sqlite3_value*);
  93213. const void * (*value_text16le)(sqlite3_value*);
  93214. int (*value_type)(sqlite3_value*);
  93215. char *(*vmprintf)(const char*,va_list);
  93216. /* Added ??? */
  93217. int (*overload_function)(sqlite3*, const char *zFuncName, int nArg);
  93218. /* Added by 3.3.13 */
  93219. int (*prepare_v2)(sqlite3*,const char*,int,sqlite3_stmt**,const char**);
  93220. int (*prepare16_v2)(sqlite3*,const void*,int,sqlite3_stmt**,const void**);
  93221. int (*clear_bindings)(sqlite3_stmt*);
  93222. /* Added by 3.4.1 */
  93223. int (*create_module_v2)(sqlite3*,const char*,const sqlite3_module*,void*,
  93224. void (*xDestroy)(void *));
  93225. /* Added by 3.5.0 */
  93226. int (*bind_zeroblob)(sqlite3_stmt*,int,int);
  93227. int (*blob_bytes)(sqlite3_blob*);
  93228. int (*blob_close)(sqlite3_blob*);
  93229. int (*blob_open)(sqlite3*,const char*,const char*,const char*,sqlite3_int64,
  93230. int,sqlite3_blob**);
  93231. int (*blob_read)(sqlite3_blob*,void*,int,int);
  93232. int (*blob_write)(sqlite3_blob*,const void*,int,int);
  93233. int (*create_collation_v2)(sqlite3*,const char*,int,void*,
  93234. int(*)(void*,int,const void*,int,const void*),
  93235. void(*)(void*));
  93236. int (*file_control)(sqlite3*,const char*,int,void*);
  93237. sqlite3_int64 (*memory_highwater)(int);
  93238. sqlite3_int64 (*memory_used)(void);
  93239. sqlite3_mutex *(*mutex_alloc)(int);
  93240. void (*mutex_enter)(sqlite3_mutex*);
  93241. void (*mutex_free)(sqlite3_mutex*);
  93242. void (*mutex_leave)(sqlite3_mutex*);
  93243. int (*mutex_try)(sqlite3_mutex*);
  93244. int (*open_v2)(const char*,sqlite3**,int,const char*);
  93245. int (*release_memory)(int);
  93246. void (*result_error_nomem)(sqlite3_context*);
  93247. void (*result_error_toobig)(sqlite3_context*);
  93248. int (*sleep)(int);
  93249. void (*soft_heap_limit)(int);
  93250. sqlite3_vfs *(*vfs_find)(const char*);
  93251. int (*vfs_register)(sqlite3_vfs*,int);
  93252. int (*vfs_unregister)(sqlite3_vfs*);
  93253. int (*xthreadsafe)(void);
  93254. void (*result_zeroblob)(sqlite3_context*,int);
  93255. void (*result_error_code)(sqlite3_context*,int);
  93256. int (*test_control)(int, ...);
  93257. void (*randomness)(int,void*);
  93258. sqlite3 *(*context_db_handle)(sqlite3_context*);
  93259. int (*extended_result_codes)(sqlite3*,int);
  93260. int (*limit)(sqlite3*,int,int);
  93261. sqlite3_stmt *(*next_stmt)(sqlite3*,sqlite3_stmt*);
  93262. const char *(*sql)(sqlite3_stmt*);
  93263. int (*status)(int,int*,int*,int);
  93264. int (*backup_finish)(sqlite3_backup*);
  93265. sqlite3_backup *(*backup_init)(sqlite3*,const char*,sqlite3*,const char*);
  93266. int (*backup_pagecount)(sqlite3_backup*);
  93267. int (*backup_remaining)(sqlite3_backup*);
  93268. int (*backup_step)(sqlite3_backup*,int);
  93269. const char *(*compileoption_get)(int);
  93270. int (*compileoption_used)(const char*);
  93271. int (*create_function_v2)(sqlite3*,const char*,int,int,void*,
  93272. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  93273. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  93274. void (*xFinal)(sqlite3_context*),
  93275. void(*xDestroy)(void*));
  93276. int (*db_config)(sqlite3*,int,...);
  93277. sqlite3_mutex *(*db_mutex)(sqlite3*);
  93278. int (*db_status)(sqlite3*,int,int*,int*,int);
  93279. int (*extended_errcode)(sqlite3*);
  93280. void (*log)(int,const char*,...);
  93281. sqlite3_int64 (*soft_heap_limit64)(sqlite3_int64);
  93282. const char *(*sourceid)(void);
  93283. int (*stmt_status)(sqlite3_stmt*,int,int);
  93284. int (*strnicmp)(const char*,const char*,int);
  93285. int (*unlock_notify)(sqlite3*,void(*)(void**,int),void*);
  93286. int (*wal_autocheckpoint)(sqlite3*,int);
  93287. int (*wal_checkpoint)(sqlite3*,const char*);
  93288. void *(*wal_hook)(sqlite3*,int(*)(void*,sqlite3*,const char*,int),void*);
  93289. int (*blob_reopen)(sqlite3_blob*,sqlite3_int64);
  93290. int (*vtab_config)(sqlite3*,int op,...);
  93291. int (*vtab_on_conflict)(sqlite3*);
  93292. /* Version 3.7.16 and later */
  93293. int (*close_v2)(sqlite3*);
  93294. const char *(*db_filename)(sqlite3*,const char*);
  93295. int (*db_readonly)(sqlite3*,const char*);
  93296. int (*db_release_memory)(sqlite3*);
  93297. const char *(*errstr)(int);
  93298. int (*stmt_busy)(sqlite3_stmt*);
  93299. int (*stmt_readonly)(sqlite3_stmt*);
  93300. int (*stricmp)(const char*,const char*);
  93301. int (*uri_boolean)(const char*,const char*,int);
  93302. sqlite3_int64 (*uri_int64)(const char*,const char*,sqlite3_int64);
  93303. const char *(*uri_parameter)(const char*,const char*);
  93304. char *(*vsnprintf)(int,char*,const char*,va_list);
  93305. int (*wal_checkpoint_v2)(sqlite3*,const char*,int,int*,int*);
  93306. /* Version 3.8.7 and later */
  93307. int (*auto_extension)(void(*)(void));
  93308. int (*bind_blob64)(sqlite3_stmt*,int,const void*,sqlite3_uint64,
  93309. void(*)(void*));
  93310. int (*bind_text64)(sqlite3_stmt*,int,const char*,sqlite3_uint64,
  93311. void(*)(void*),unsigned char);
  93312. int (*cancel_auto_extension)(void(*)(void));
  93313. int (*load_extension)(sqlite3*,const char*,const char*,char**);
  93314. void *(*malloc64)(sqlite3_uint64);
  93315. sqlite3_uint64 (*msize)(void*);
  93316. void *(*realloc64)(void*,sqlite3_uint64);
  93317. void (*reset_auto_extension)(void);
  93318. void (*result_blob64)(sqlite3_context*,const void*,sqlite3_uint64,
  93319. void(*)(void*));
  93320. void (*result_text64)(sqlite3_context*,const char*,sqlite3_uint64,
  93321. void(*)(void*), unsigned char);
  93322. int (*strglob)(const char*,const char*);
  93323. };
  93324. /*
  93325. ** The following macros redefine the API routines so that they are
  93326. ** redirected through the global sqlite3_api structure.
  93327. **
  93328. ** This header file is also used by the loadext.c source file
  93329. ** (part of the main SQLite library - not an extension) so that
  93330. ** it can get access to the sqlite3_api_routines structure
  93331. ** definition. But the main library does not want to redefine
  93332. ** the API. So the redefinition macros are only valid if the
  93333. ** SQLITE_CORE macros is undefined.
  93334. */
  93335. #ifndef SQLITE_CORE
  93336. #define sqlite3_aggregate_context sqlite3_api->aggregate_context
  93337. #ifndef SQLITE_OMIT_DEPRECATED
  93338. #define sqlite3_aggregate_count sqlite3_api->aggregate_count
  93339. #endif
  93340. #define sqlite3_bind_blob sqlite3_api->bind_blob
  93341. #define sqlite3_bind_double sqlite3_api->bind_double
  93342. #define sqlite3_bind_int sqlite3_api->bind_int
  93343. #define sqlite3_bind_int64 sqlite3_api->bind_int64
  93344. #define sqlite3_bind_null sqlite3_api->bind_null
  93345. #define sqlite3_bind_parameter_count sqlite3_api->bind_parameter_count
  93346. #define sqlite3_bind_parameter_index sqlite3_api->bind_parameter_index
  93347. #define sqlite3_bind_parameter_name sqlite3_api->bind_parameter_name
  93348. #define sqlite3_bind_text sqlite3_api->bind_text
  93349. #define sqlite3_bind_text16 sqlite3_api->bind_text16
  93350. #define sqlite3_bind_value sqlite3_api->bind_value
  93351. #define sqlite3_busy_handler sqlite3_api->busy_handler
  93352. #define sqlite3_busy_timeout sqlite3_api->busy_timeout
  93353. #define sqlite3_changes sqlite3_api->changes
  93354. #define sqlite3_close sqlite3_api->close
  93355. #define sqlite3_collation_needed sqlite3_api->collation_needed
  93356. #define sqlite3_collation_needed16 sqlite3_api->collation_needed16
  93357. #define sqlite3_column_blob sqlite3_api->column_blob
  93358. #define sqlite3_column_bytes sqlite3_api->column_bytes
  93359. #define sqlite3_column_bytes16 sqlite3_api->column_bytes16
  93360. #define sqlite3_column_count sqlite3_api->column_count
  93361. #define sqlite3_column_database_name sqlite3_api->column_database_name
  93362. #define sqlite3_column_database_name16 sqlite3_api->column_database_name16
  93363. #define sqlite3_column_decltype sqlite3_api->column_decltype
  93364. #define sqlite3_column_decltype16 sqlite3_api->column_decltype16
  93365. #define sqlite3_column_double sqlite3_api->column_double
  93366. #define sqlite3_column_int sqlite3_api->column_int
  93367. #define sqlite3_column_int64 sqlite3_api->column_int64
  93368. #define sqlite3_column_name sqlite3_api->column_name
  93369. #define sqlite3_column_name16 sqlite3_api->column_name16
  93370. #define sqlite3_column_origin_name sqlite3_api->column_origin_name
  93371. #define sqlite3_column_origin_name16 sqlite3_api->column_origin_name16
  93372. #define sqlite3_column_table_name sqlite3_api->column_table_name
  93373. #define sqlite3_column_table_name16 sqlite3_api->column_table_name16
  93374. #define sqlite3_column_text sqlite3_api->column_text
  93375. #define sqlite3_column_text16 sqlite3_api->column_text16
  93376. #define sqlite3_column_type sqlite3_api->column_type
  93377. #define sqlite3_column_value sqlite3_api->column_value
  93378. #define sqlite3_commit_hook sqlite3_api->commit_hook
  93379. #define sqlite3_complete sqlite3_api->complete
  93380. #define sqlite3_complete16 sqlite3_api->complete16
  93381. #define sqlite3_create_collation sqlite3_api->create_collation
  93382. #define sqlite3_create_collation16 sqlite3_api->create_collation16
  93383. #define sqlite3_create_function sqlite3_api->create_function
  93384. #define sqlite3_create_function16 sqlite3_api->create_function16
  93385. #define sqlite3_create_module sqlite3_api->create_module
  93386. #define sqlite3_create_module_v2 sqlite3_api->create_module_v2
  93387. #define sqlite3_data_count sqlite3_api->data_count
  93388. #define sqlite3_db_handle sqlite3_api->db_handle
  93389. #define sqlite3_declare_vtab sqlite3_api->declare_vtab
  93390. #define sqlite3_enable_shared_cache sqlite3_api->enable_shared_cache
  93391. #define sqlite3_errcode sqlite3_api->errcode
  93392. #define sqlite3_errmsg sqlite3_api->errmsg
  93393. #define sqlite3_errmsg16 sqlite3_api->errmsg16
  93394. #define sqlite3_exec sqlite3_api->exec
  93395. #ifndef SQLITE_OMIT_DEPRECATED
  93396. #define sqlite3_expired sqlite3_api->expired
  93397. #endif
  93398. #define sqlite3_finalize sqlite3_api->finalize
  93399. #define sqlite3_free sqlite3_api->free
  93400. #define sqlite3_free_table sqlite3_api->free_table
  93401. #define sqlite3_get_autocommit sqlite3_api->get_autocommit
  93402. #define sqlite3_get_auxdata sqlite3_api->get_auxdata
  93403. #define sqlite3_get_table sqlite3_api->get_table
  93404. #ifndef SQLITE_OMIT_DEPRECATED
  93405. #define sqlite3_global_recover sqlite3_api->global_recover
  93406. #endif
  93407. #define sqlite3_interrupt sqlite3_api->interruptx
  93408. #define sqlite3_last_insert_rowid sqlite3_api->last_insert_rowid
  93409. #define sqlite3_libversion sqlite3_api->libversion
  93410. #define sqlite3_libversion_number sqlite3_api->libversion_number
  93411. #define sqlite3_malloc sqlite3_api->malloc
  93412. #define sqlite3_mprintf sqlite3_api->mprintf
  93413. #define sqlite3_open sqlite3_api->open
  93414. #define sqlite3_open16 sqlite3_api->open16
  93415. #define sqlite3_prepare sqlite3_api->prepare
  93416. #define sqlite3_prepare16 sqlite3_api->prepare16
  93417. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  93418. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  93419. #define sqlite3_profile sqlite3_api->profile
  93420. #define sqlite3_progress_handler sqlite3_api->progress_handler
  93421. #define sqlite3_realloc sqlite3_api->realloc
  93422. #define sqlite3_reset sqlite3_api->reset
  93423. #define sqlite3_result_blob sqlite3_api->result_blob
  93424. #define sqlite3_result_double sqlite3_api->result_double
  93425. #define sqlite3_result_error sqlite3_api->result_error
  93426. #define sqlite3_result_error16 sqlite3_api->result_error16
  93427. #define sqlite3_result_int sqlite3_api->result_int
  93428. #define sqlite3_result_int64 sqlite3_api->result_int64
  93429. #define sqlite3_result_null sqlite3_api->result_null
  93430. #define sqlite3_result_text sqlite3_api->result_text
  93431. #define sqlite3_result_text16 sqlite3_api->result_text16
  93432. #define sqlite3_result_text16be sqlite3_api->result_text16be
  93433. #define sqlite3_result_text16le sqlite3_api->result_text16le
  93434. #define sqlite3_result_value sqlite3_api->result_value
  93435. #define sqlite3_rollback_hook sqlite3_api->rollback_hook
  93436. #define sqlite3_set_authorizer sqlite3_api->set_authorizer
  93437. #define sqlite3_set_auxdata sqlite3_api->set_auxdata
  93438. #define sqlite3_snprintf sqlite3_api->snprintf
  93439. #define sqlite3_step sqlite3_api->step
  93440. #define sqlite3_table_column_metadata sqlite3_api->table_column_metadata
  93441. #define sqlite3_thread_cleanup sqlite3_api->thread_cleanup
  93442. #define sqlite3_total_changes sqlite3_api->total_changes
  93443. #define sqlite3_trace sqlite3_api->trace
  93444. #ifndef SQLITE_OMIT_DEPRECATED
  93445. #define sqlite3_transfer_bindings sqlite3_api->transfer_bindings
  93446. #endif
  93447. #define sqlite3_update_hook sqlite3_api->update_hook
  93448. #define sqlite3_user_data sqlite3_api->user_data
  93449. #define sqlite3_value_blob sqlite3_api->value_blob
  93450. #define sqlite3_value_bytes sqlite3_api->value_bytes
  93451. #define sqlite3_value_bytes16 sqlite3_api->value_bytes16
  93452. #define sqlite3_value_double sqlite3_api->value_double
  93453. #define sqlite3_value_int sqlite3_api->value_int
  93454. #define sqlite3_value_int64 sqlite3_api->value_int64
  93455. #define sqlite3_value_numeric_type sqlite3_api->value_numeric_type
  93456. #define sqlite3_value_text sqlite3_api->value_text
  93457. #define sqlite3_value_text16 sqlite3_api->value_text16
  93458. #define sqlite3_value_text16be sqlite3_api->value_text16be
  93459. #define sqlite3_value_text16le sqlite3_api->value_text16le
  93460. #define sqlite3_value_type sqlite3_api->value_type
  93461. #define sqlite3_vmprintf sqlite3_api->vmprintf
  93462. #define sqlite3_overload_function sqlite3_api->overload_function
  93463. #define sqlite3_prepare_v2 sqlite3_api->prepare_v2
  93464. #define sqlite3_prepare16_v2 sqlite3_api->prepare16_v2
  93465. #define sqlite3_clear_bindings sqlite3_api->clear_bindings
  93466. #define sqlite3_bind_zeroblob sqlite3_api->bind_zeroblob
  93467. #define sqlite3_blob_bytes sqlite3_api->blob_bytes
  93468. #define sqlite3_blob_close sqlite3_api->blob_close
  93469. #define sqlite3_blob_open sqlite3_api->blob_open
  93470. #define sqlite3_blob_read sqlite3_api->blob_read
  93471. #define sqlite3_blob_write sqlite3_api->blob_write
  93472. #define sqlite3_create_collation_v2 sqlite3_api->create_collation_v2
  93473. #define sqlite3_file_control sqlite3_api->file_control
  93474. #define sqlite3_memory_highwater sqlite3_api->memory_highwater
  93475. #define sqlite3_memory_used sqlite3_api->memory_used
  93476. #define sqlite3_mutex_alloc sqlite3_api->mutex_alloc
  93477. #define sqlite3_mutex_enter sqlite3_api->mutex_enter
  93478. #define sqlite3_mutex_free sqlite3_api->mutex_free
  93479. #define sqlite3_mutex_leave sqlite3_api->mutex_leave
  93480. #define sqlite3_mutex_try sqlite3_api->mutex_try
  93481. #define sqlite3_open_v2 sqlite3_api->open_v2
  93482. #define sqlite3_release_memory sqlite3_api->release_memory
  93483. #define sqlite3_result_error_nomem sqlite3_api->result_error_nomem
  93484. #define sqlite3_result_error_toobig sqlite3_api->result_error_toobig
  93485. #define sqlite3_sleep sqlite3_api->sleep
  93486. #define sqlite3_soft_heap_limit sqlite3_api->soft_heap_limit
  93487. #define sqlite3_vfs_find sqlite3_api->vfs_find
  93488. #define sqlite3_vfs_register sqlite3_api->vfs_register
  93489. #define sqlite3_vfs_unregister sqlite3_api->vfs_unregister
  93490. #define sqlite3_threadsafe sqlite3_api->xthreadsafe
  93491. #define sqlite3_result_zeroblob sqlite3_api->result_zeroblob
  93492. #define sqlite3_result_error_code sqlite3_api->result_error_code
  93493. #define sqlite3_test_control sqlite3_api->test_control
  93494. #define sqlite3_randomness sqlite3_api->randomness
  93495. #define sqlite3_context_db_handle sqlite3_api->context_db_handle
  93496. #define sqlite3_extended_result_codes sqlite3_api->extended_result_codes
  93497. #define sqlite3_limit sqlite3_api->limit
  93498. #define sqlite3_next_stmt sqlite3_api->next_stmt
  93499. #define sqlite3_sql sqlite3_api->sql
  93500. #define sqlite3_status sqlite3_api->status
  93501. #define sqlite3_backup_finish sqlite3_api->backup_finish
  93502. #define sqlite3_backup_init sqlite3_api->backup_init
  93503. #define sqlite3_backup_pagecount sqlite3_api->backup_pagecount
  93504. #define sqlite3_backup_remaining sqlite3_api->backup_remaining
  93505. #define sqlite3_backup_step sqlite3_api->backup_step
  93506. #define sqlite3_compileoption_get sqlite3_api->compileoption_get
  93507. #define sqlite3_compileoption_used sqlite3_api->compileoption_used
  93508. #define sqlite3_create_function_v2 sqlite3_api->create_function_v2
  93509. #define sqlite3_db_config sqlite3_api->db_config
  93510. #define sqlite3_db_mutex sqlite3_api->db_mutex
  93511. #define sqlite3_db_status sqlite3_api->db_status
  93512. #define sqlite3_extended_errcode sqlite3_api->extended_errcode
  93513. #define sqlite3_log sqlite3_api->log
  93514. #define sqlite3_soft_heap_limit64 sqlite3_api->soft_heap_limit64
  93515. #define sqlite3_sourceid sqlite3_api->sourceid
  93516. #define sqlite3_stmt_status sqlite3_api->stmt_status
  93517. #define sqlite3_strnicmp sqlite3_api->strnicmp
  93518. #define sqlite3_unlock_notify sqlite3_api->unlock_notify
  93519. #define sqlite3_wal_autocheckpoint sqlite3_api->wal_autocheckpoint
  93520. #define sqlite3_wal_checkpoint sqlite3_api->wal_checkpoint
  93521. #define sqlite3_wal_hook sqlite3_api->wal_hook
  93522. #define sqlite3_blob_reopen sqlite3_api->blob_reopen
  93523. #define sqlite3_vtab_config sqlite3_api->vtab_config
  93524. #define sqlite3_vtab_on_conflict sqlite3_api->vtab_on_conflict
  93525. /* Version 3.7.16 and later */
  93526. #define sqlite3_close_v2 sqlite3_api->close_v2
  93527. #define sqlite3_db_filename sqlite3_api->db_filename
  93528. #define sqlite3_db_readonly sqlite3_api->db_readonly
  93529. #define sqlite3_db_release_memory sqlite3_api->db_release_memory
  93530. #define sqlite3_errstr sqlite3_api->errstr
  93531. #define sqlite3_stmt_busy sqlite3_api->stmt_busy
  93532. #define sqlite3_stmt_readonly sqlite3_api->stmt_readonly
  93533. #define sqlite3_stricmp sqlite3_api->stricmp
  93534. #define sqlite3_uri_boolean sqlite3_api->uri_boolean
  93535. #define sqlite3_uri_int64 sqlite3_api->uri_int64
  93536. #define sqlite3_uri_parameter sqlite3_api->uri_parameter
  93537. #define sqlite3_uri_vsnprintf sqlite3_api->vsnprintf
  93538. #define sqlite3_wal_checkpoint_v2 sqlite3_api->wal_checkpoint_v2
  93539. /* Version 3.8.7 and later */
  93540. #define sqlite3_auto_extension sqlite3_api->auto_extension
  93541. #define sqlite3_bind_blob64 sqlite3_api->bind_blob64
  93542. #define sqlite3_bind_text64 sqlite3_api->bind_text64
  93543. #define sqlite3_cancel_auto_extension sqlite3_api->cancel_auto_extension
  93544. #define sqlite3_load_extension sqlite3_api->load_extension
  93545. #define sqlite3_malloc64 sqlite3_api->malloc64
  93546. #define sqlite3_msize sqlite3_api->msize
  93547. #define sqlite3_realloc64 sqlite3_api->realloc64
  93548. #define sqlite3_reset_auto_extension sqlite3_api->reset_auto_extension
  93549. #define sqlite3_result_blob64 sqlite3_api->result_blob64
  93550. #define sqlite3_result_text64 sqlite3_api->result_text64
  93551. #define sqlite3_strglob sqlite3_api->strglob
  93552. #endif /* SQLITE_CORE */
  93553. #ifndef SQLITE_CORE
  93554. /* This case when the file really is being compiled as a loadable
  93555. ** extension */
  93556. # define SQLITE_EXTENSION_INIT1 const sqlite3_api_routines *sqlite3_api=0;
  93557. # define SQLITE_EXTENSION_INIT2(v) sqlite3_api=v;
  93558. # define SQLITE_EXTENSION_INIT3 \
  93559. extern const sqlite3_api_routines *sqlite3_api;
  93560. #else
  93561. /* This case when the file is being statically linked into the
  93562. ** application */
  93563. # define SQLITE_EXTENSION_INIT1 /*no-op*/
  93564. # define SQLITE_EXTENSION_INIT2(v) (void)v; /* unused parameter */
  93565. # define SQLITE_EXTENSION_INIT3 /*no-op*/
  93566. #endif
  93567. #endif /* _SQLITE3EXT_H_ */
  93568. /************** End of sqlite3ext.h ******************************************/
  93569. /************** Continuing where we left off in loadext.c ********************/
  93570. /* #include <string.h> */
  93571. #ifndef SQLITE_OMIT_LOAD_EXTENSION
  93572. /*
  93573. ** Some API routines are omitted when various features are
  93574. ** excluded from a build of SQLite. Substitute a NULL pointer
  93575. ** for any missing APIs.
  93576. */
  93577. #ifndef SQLITE_ENABLE_COLUMN_METADATA
  93578. # define sqlite3_column_database_name 0
  93579. # define sqlite3_column_database_name16 0
  93580. # define sqlite3_column_table_name 0
  93581. # define sqlite3_column_table_name16 0
  93582. # define sqlite3_column_origin_name 0
  93583. # define sqlite3_column_origin_name16 0
  93584. # define sqlite3_table_column_metadata 0
  93585. #endif
  93586. #ifdef SQLITE_OMIT_AUTHORIZATION
  93587. # define sqlite3_set_authorizer 0
  93588. #endif
  93589. #ifdef SQLITE_OMIT_UTF16
  93590. # define sqlite3_bind_text16 0
  93591. # define sqlite3_collation_needed16 0
  93592. # define sqlite3_column_decltype16 0
  93593. # define sqlite3_column_name16 0
  93594. # define sqlite3_column_text16 0
  93595. # define sqlite3_complete16 0
  93596. # define sqlite3_create_collation16 0
  93597. # define sqlite3_create_function16 0
  93598. # define sqlite3_errmsg16 0
  93599. # define sqlite3_open16 0
  93600. # define sqlite3_prepare16 0
  93601. # define sqlite3_prepare16_v2 0
  93602. # define sqlite3_result_error16 0
  93603. # define sqlite3_result_text16 0
  93604. # define sqlite3_result_text16be 0
  93605. # define sqlite3_result_text16le 0
  93606. # define sqlite3_value_text16 0
  93607. # define sqlite3_value_text16be 0
  93608. # define sqlite3_value_text16le 0
  93609. # define sqlite3_column_database_name16 0
  93610. # define sqlite3_column_table_name16 0
  93611. # define sqlite3_column_origin_name16 0
  93612. #endif
  93613. #ifdef SQLITE_OMIT_COMPLETE
  93614. # define sqlite3_complete 0
  93615. # define sqlite3_complete16 0
  93616. #endif
  93617. #ifdef SQLITE_OMIT_DECLTYPE
  93618. # define sqlite3_column_decltype16 0
  93619. # define sqlite3_column_decltype 0
  93620. #endif
  93621. #ifdef SQLITE_OMIT_PROGRESS_CALLBACK
  93622. # define sqlite3_progress_handler 0
  93623. #endif
  93624. #ifdef SQLITE_OMIT_VIRTUALTABLE
  93625. # define sqlite3_create_module 0
  93626. # define sqlite3_create_module_v2 0
  93627. # define sqlite3_declare_vtab 0
  93628. # define sqlite3_vtab_config 0
  93629. # define sqlite3_vtab_on_conflict 0
  93630. #endif
  93631. #ifdef SQLITE_OMIT_SHARED_CACHE
  93632. # define sqlite3_enable_shared_cache 0
  93633. #endif
  93634. #ifdef SQLITE_OMIT_TRACE
  93635. # define sqlite3_profile 0
  93636. # define sqlite3_trace 0
  93637. #endif
  93638. #ifdef SQLITE_OMIT_GET_TABLE
  93639. # define sqlite3_free_table 0
  93640. # define sqlite3_get_table 0
  93641. #endif
  93642. #ifdef SQLITE_OMIT_INCRBLOB
  93643. #define sqlite3_bind_zeroblob 0
  93644. #define sqlite3_blob_bytes 0
  93645. #define sqlite3_blob_close 0
  93646. #define sqlite3_blob_open 0
  93647. #define sqlite3_blob_read 0
  93648. #define sqlite3_blob_write 0
  93649. #define sqlite3_blob_reopen 0
  93650. #endif
  93651. /*
  93652. ** The following structure contains pointers to all SQLite API routines.
  93653. ** A pointer to this structure is passed into extensions when they are
  93654. ** loaded so that the extension can make calls back into the SQLite
  93655. ** library.
  93656. **
  93657. ** When adding new APIs, add them to the bottom of this structure
  93658. ** in order to preserve backwards compatibility.
  93659. **
  93660. ** Extensions that use newer APIs should first call the
  93661. ** sqlite3_libversion_number() to make sure that the API they
  93662. ** intend to use is supported by the library. Extensions should
  93663. ** also check to make sure that the pointer to the function is
  93664. ** not NULL before calling it.
  93665. */
  93666. static const sqlite3_api_routines sqlite3Apis = {
  93667. sqlite3_aggregate_context,
  93668. #ifndef SQLITE_OMIT_DEPRECATED
  93669. sqlite3_aggregate_count,
  93670. #else
  93671. 0,
  93672. #endif
  93673. sqlite3_bind_blob,
  93674. sqlite3_bind_double,
  93675. sqlite3_bind_int,
  93676. sqlite3_bind_int64,
  93677. sqlite3_bind_null,
  93678. sqlite3_bind_parameter_count,
  93679. sqlite3_bind_parameter_index,
  93680. sqlite3_bind_parameter_name,
  93681. sqlite3_bind_text,
  93682. sqlite3_bind_text16,
  93683. sqlite3_bind_value,
  93684. sqlite3_busy_handler,
  93685. sqlite3_busy_timeout,
  93686. sqlite3_changes,
  93687. sqlite3_close,
  93688. sqlite3_collation_needed,
  93689. sqlite3_collation_needed16,
  93690. sqlite3_column_blob,
  93691. sqlite3_column_bytes,
  93692. sqlite3_column_bytes16,
  93693. sqlite3_column_count,
  93694. sqlite3_column_database_name,
  93695. sqlite3_column_database_name16,
  93696. sqlite3_column_decltype,
  93697. sqlite3_column_decltype16,
  93698. sqlite3_column_double,
  93699. sqlite3_column_int,
  93700. sqlite3_column_int64,
  93701. sqlite3_column_name,
  93702. sqlite3_column_name16,
  93703. sqlite3_column_origin_name,
  93704. sqlite3_column_origin_name16,
  93705. sqlite3_column_table_name,
  93706. sqlite3_column_table_name16,
  93707. sqlite3_column_text,
  93708. sqlite3_column_text16,
  93709. sqlite3_column_type,
  93710. sqlite3_column_value,
  93711. sqlite3_commit_hook,
  93712. sqlite3_complete,
  93713. sqlite3_complete16,
  93714. sqlite3_create_collation,
  93715. sqlite3_create_collation16,
  93716. sqlite3_create_function,
  93717. sqlite3_create_function16,
  93718. sqlite3_create_module,
  93719. sqlite3_data_count,
  93720. sqlite3_db_handle,
  93721. sqlite3_declare_vtab,
  93722. sqlite3_enable_shared_cache,
  93723. sqlite3_errcode,
  93724. sqlite3_errmsg,
  93725. sqlite3_errmsg16,
  93726. sqlite3_exec,
  93727. #ifndef SQLITE_OMIT_DEPRECATED
  93728. sqlite3_expired,
  93729. #else
  93730. 0,
  93731. #endif
  93732. sqlite3_finalize,
  93733. sqlite3_free,
  93734. sqlite3_free_table,
  93735. sqlite3_get_autocommit,
  93736. sqlite3_get_auxdata,
  93737. sqlite3_get_table,
  93738. 0, /* Was sqlite3_global_recover(), but that function is deprecated */
  93739. sqlite3_interrupt,
  93740. sqlite3_last_insert_rowid,
  93741. sqlite3_libversion,
  93742. sqlite3_libversion_number,
  93743. sqlite3_malloc,
  93744. sqlite3_mprintf,
  93745. sqlite3_open,
  93746. sqlite3_open16,
  93747. sqlite3_prepare,
  93748. sqlite3_prepare16,
  93749. sqlite3_profile,
  93750. sqlite3_progress_handler,
  93751. sqlite3_realloc,
  93752. sqlite3_reset,
  93753. sqlite3_result_blob,
  93754. sqlite3_result_double,
  93755. sqlite3_result_error,
  93756. sqlite3_result_error16,
  93757. sqlite3_result_int,
  93758. sqlite3_result_int64,
  93759. sqlite3_result_null,
  93760. sqlite3_result_text,
  93761. sqlite3_result_text16,
  93762. sqlite3_result_text16be,
  93763. sqlite3_result_text16le,
  93764. sqlite3_result_value,
  93765. sqlite3_rollback_hook,
  93766. sqlite3_set_authorizer,
  93767. sqlite3_set_auxdata,
  93768. sqlite3_snprintf,
  93769. sqlite3_step,
  93770. sqlite3_table_column_metadata,
  93771. #ifndef SQLITE_OMIT_DEPRECATED
  93772. sqlite3_thread_cleanup,
  93773. #else
  93774. 0,
  93775. #endif
  93776. sqlite3_total_changes,
  93777. sqlite3_trace,
  93778. #ifndef SQLITE_OMIT_DEPRECATED
  93779. sqlite3_transfer_bindings,
  93780. #else
  93781. 0,
  93782. #endif
  93783. sqlite3_update_hook,
  93784. sqlite3_user_data,
  93785. sqlite3_value_blob,
  93786. sqlite3_value_bytes,
  93787. sqlite3_value_bytes16,
  93788. sqlite3_value_double,
  93789. sqlite3_value_int,
  93790. sqlite3_value_int64,
  93791. sqlite3_value_numeric_type,
  93792. sqlite3_value_text,
  93793. sqlite3_value_text16,
  93794. sqlite3_value_text16be,
  93795. sqlite3_value_text16le,
  93796. sqlite3_value_type,
  93797. sqlite3_vmprintf,
  93798. /*
  93799. ** The original API set ends here. All extensions can call any
  93800. ** of the APIs above provided that the pointer is not NULL. But
  93801. ** before calling APIs that follow, extension should check the
  93802. ** sqlite3_libversion_number() to make sure they are dealing with
  93803. ** a library that is new enough to support that API.
  93804. *************************************************************************
  93805. */
  93806. sqlite3_overload_function,
  93807. /*
  93808. ** Added after 3.3.13
  93809. */
  93810. sqlite3_prepare_v2,
  93811. sqlite3_prepare16_v2,
  93812. sqlite3_clear_bindings,
  93813. /*
  93814. ** Added for 3.4.1
  93815. */
  93816. sqlite3_create_module_v2,
  93817. /*
  93818. ** Added for 3.5.0
  93819. */
  93820. sqlite3_bind_zeroblob,
  93821. sqlite3_blob_bytes,
  93822. sqlite3_blob_close,
  93823. sqlite3_blob_open,
  93824. sqlite3_blob_read,
  93825. sqlite3_blob_write,
  93826. sqlite3_create_collation_v2,
  93827. sqlite3_file_control,
  93828. sqlite3_memory_highwater,
  93829. sqlite3_memory_used,
  93830. #ifdef SQLITE_MUTEX_OMIT
  93831. 0,
  93832. 0,
  93833. 0,
  93834. 0,
  93835. 0,
  93836. #else
  93837. sqlite3_mutex_alloc,
  93838. sqlite3_mutex_enter,
  93839. sqlite3_mutex_free,
  93840. sqlite3_mutex_leave,
  93841. sqlite3_mutex_try,
  93842. #endif
  93843. sqlite3_open_v2,
  93844. sqlite3_release_memory,
  93845. sqlite3_result_error_nomem,
  93846. sqlite3_result_error_toobig,
  93847. sqlite3_sleep,
  93848. sqlite3_soft_heap_limit,
  93849. sqlite3_vfs_find,
  93850. sqlite3_vfs_register,
  93851. sqlite3_vfs_unregister,
  93852. /*
  93853. ** Added for 3.5.8
  93854. */
  93855. sqlite3_threadsafe,
  93856. sqlite3_result_zeroblob,
  93857. sqlite3_result_error_code,
  93858. sqlite3_test_control,
  93859. sqlite3_randomness,
  93860. sqlite3_context_db_handle,
  93861. /*
  93862. ** Added for 3.6.0
  93863. */
  93864. sqlite3_extended_result_codes,
  93865. sqlite3_limit,
  93866. sqlite3_next_stmt,
  93867. sqlite3_sql,
  93868. sqlite3_status,
  93869. /*
  93870. ** Added for 3.7.4
  93871. */
  93872. sqlite3_backup_finish,
  93873. sqlite3_backup_init,
  93874. sqlite3_backup_pagecount,
  93875. sqlite3_backup_remaining,
  93876. sqlite3_backup_step,
  93877. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  93878. sqlite3_compileoption_get,
  93879. sqlite3_compileoption_used,
  93880. #else
  93881. 0,
  93882. 0,
  93883. #endif
  93884. sqlite3_create_function_v2,
  93885. sqlite3_db_config,
  93886. sqlite3_db_mutex,
  93887. sqlite3_db_status,
  93888. sqlite3_extended_errcode,
  93889. sqlite3_log,
  93890. sqlite3_soft_heap_limit64,
  93891. sqlite3_sourceid,
  93892. sqlite3_stmt_status,
  93893. sqlite3_strnicmp,
  93894. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  93895. sqlite3_unlock_notify,
  93896. #else
  93897. 0,
  93898. #endif
  93899. #ifndef SQLITE_OMIT_WAL
  93900. sqlite3_wal_autocheckpoint,
  93901. sqlite3_wal_checkpoint,
  93902. sqlite3_wal_hook,
  93903. #else
  93904. 0,
  93905. 0,
  93906. 0,
  93907. #endif
  93908. sqlite3_blob_reopen,
  93909. sqlite3_vtab_config,
  93910. sqlite3_vtab_on_conflict,
  93911. sqlite3_close_v2,
  93912. sqlite3_db_filename,
  93913. sqlite3_db_readonly,
  93914. sqlite3_db_release_memory,
  93915. sqlite3_errstr,
  93916. sqlite3_stmt_busy,
  93917. sqlite3_stmt_readonly,
  93918. sqlite3_stricmp,
  93919. sqlite3_uri_boolean,
  93920. sqlite3_uri_int64,
  93921. sqlite3_uri_parameter,
  93922. sqlite3_vsnprintf,
  93923. sqlite3_wal_checkpoint_v2,
  93924. /* Version 3.8.7 and later */
  93925. sqlite3_auto_extension,
  93926. sqlite3_bind_blob64,
  93927. sqlite3_bind_text64,
  93928. sqlite3_cancel_auto_extension,
  93929. sqlite3_load_extension,
  93930. sqlite3_malloc64,
  93931. sqlite3_msize,
  93932. sqlite3_realloc64,
  93933. sqlite3_reset_auto_extension,
  93934. sqlite3_result_blob64,
  93935. sqlite3_result_text64,
  93936. sqlite3_strglob
  93937. };
  93938. /*
  93939. ** Attempt to load an SQLite extension library contained in the file
  93940. ** zFile. The entry point is zProc. zProc may be 0 in which case a
  93941. ** default entry point name (sqlite3_extension_init) is used. Use
  93942. ** of the default name is recommended.
  93943. **
  93944. ** Return SQLITE_OK on success and SQLITE_ERROR if something goes wrong.
  93945. **
  93946. ** If an error occurs and pzErrMsg is not 0, then fill *pzErrMsg with
  93947. ** error message text. The calling function should free this memory
  93948. ** by calling sqlite3DbFree(db, ).
  93949. */
  93950. static int sqlite3LoadExtension(
  93951. sqlite3 *db, /* Load the extension into this database connection */
  93952. const char *zFile, /* Name of the shared library containing extension */
  93953. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  93954. char **pzErrMsg /* Put error message here if not 0 */
  93955. ){
  93956. sqlite3_vfs *pVfs = db->pVfs;
  93957. void *handle;
  93958. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  93959. char *zErrmsg = 0;
  93960. const char *zEntry;
  93961. char *zAltEntry = 0;
  93962. void **aHandle;
  93963. int nMsg = 300 + sqlite3Strlen30(zFile);
  93964. int ii;
  93965. /* Shared library endings to try if zFile cannot be loaded as written */
  93966. static const char *azEndings[] = {
  93967. #if SQLITE_OS_WIN
  93968. "dll"
  93969. #elif defined(__APPLE__)
  93970. "dylib"
  93971. #else
  93972. "so"
  93973. #endif
  93974. };
  93975. if( pzErrMsg ) *pzErrMsg = 0;
  93976. /* Ticket #1863. To avoid a creating security problems for older
  93977. ** applications that relink against newer versions of SQLite, the
  93978. ** ability to run load_extension is turned off by default. One
  93979. ** must call sqlite3_enable_load_extension() to turn on extension
  93980. ** loading. Otherwise you get the following error.
  93981. */
  93982. if( (db->flags & SQLITE_LoadExtension)==0 ){
  93983. if( pzErrMsg ){
  93984. *pzErrMsg = sqlite3_mprintf("not authorized");
  93985. }
  93986. return SQLITE_ERROR;
  93987. }
  93988. zEntry = zProc ? zProc : "sqlite3_extension_init";
  93989. handle = sqlite3OsDlOpen(pVfs, zFile);
  93990. #if SQLITE_OS_UNIX || SQLITE_OS_WIN
  93991. for(ii=0; ii<ArraySize(azEndings) && handle==0; ii++){
  93992. char *zAltFile = sqlite3_mprintf("%s.%s", zFile, azEndings[ii]);
  93993. if( zAltFile==0 ) return SQLITE_NOMEM;
  93994. handle = sqlite3OsDlOpen(pVfs, zAltFile);
  93995. sqlite3_free(zAltFile);
  93996. }
  93997. #endif
  93998. if( handle==0 ){
  93999. if( pzErrMsg ){
  94000. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  94001. if( zErrmsg ){
  94002. sqlite3_snprintf(nMsg, zErrmsg,
  94003. "unable to open shared library [%s]", zFile);
  94004. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  94005. }
  94006. }
  94007. return SQLITE_ERROR;
  94008. }
  94009. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  94010. sqlite3OsDlSym(pVfs, handle, zEntry);
  94011. /* If no entry point was specified and the default legacy
  94012. ** entry point name "sqlite3_extension_init" was not found, then
  94013. ** construct an entry point name "sqlite3_X_init" where the X is
  94014. ** replaced by the lowercase value of every ASCII alphabetic
  94015. ** character in the filename after the last "/" upto the first ".",
  94016. ** and eliding the first three characters if they are "lib".
  94017. ** Examples:
  94018. **
  94019. ** /usr/local/lib/libExample5.4.3.so ==> sqlite3_example_init
  94020. ** C:/lib/mathfuncs.dll ==> sqlite3_mathfuncs_init
  94021. */
  94022. if( xInit==0 && zProc==0 ){
  94023. int iFile, iEntry, c;
  94024. int ncFile = sqlite3Strlen30(zFile);
  94025. zAltEntry = sqlite3_malloc(ncFile+30);
  94026. if( zAltEntry==0 ){
  94027. sqlite3OsDlClose(pVfs, handle);
  94028. return SQLITE_NOMEM;
  94029. }
  94030. memcpy(zAltEntry, "sqlite3_", 8);
  94031. for(iFile=ncFile-1; iFile>=0 && zFile[iFile]!='/'; iFile--){}
  94032. iFile++;
  94033. if( sqlite3_strnicmp(zFile+iFile, "lib", 3)==0 ) iFile += 3;
  94034. for(iEntry=8; (c = zFile[iFile])!=0 && c!='.'; iFile++){
  94035. if( sqlite3Isalpha(c) ){
  94036. zAltEntry[iEntry++] = (char)sqlite3UpperToLower[(unsigned)c];
  94037. }
  94038. }
  94039. memcpy(zAltEntry+iEntry, "_init", 6);
  94040. zEntry = zAltEntry;
  94041. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  94042. sqlite3OsDlSym(pVfs, handle, zEntry);
  94043. }
  94044. if( xInit==0 ){
  94045. if( pzErrMsg ){
  94046. nMsg += sqlite3Strlen30(zEntry);
  94047. *pzErrMsg = zErrmsg = sqlite3_malloc(nMsg);
  94048. if( zErrmsg ){
  94049. sqlite3_snprintf(nMsg, zErrmsg,
  94050. "no entry point [%s] in shared library [%s]", zEntry, zFile);
  94051. sqlite3OsDlError(pVfs, nMsg-1, zErrmsg);
  94052. }
  94053. }
  94054. sqlite3OsDlClose(pVfs, handle);
  94055. sqlite3_free(zAltEntry);
  94056. return SQLITE_ERROR;
  94057. }
  94058. sqlite3_free(zAltEntry);
  94059. if( xInit(db, &zErrmsg, &sqlite3Apis) ){
  94060. if( pzErrMsg ){
  94061. *pzErrMsg = sqlite3_mprintf("error during initialization: %s", zErrmsg);
  94062. }
  94063. sqlite3_free(zErrmsg);
  94064. sqlite3OsDlClose(pVfs, handle);
  94065. return SQLITE_ERROR;
  94066. }
  94067. /* Append the new shared library handle to the db->aExtension array. */
  94068. aHandle = sqlite3DbMallocZero(db, sizeof(handle)*(db->nExtension+1));
  94069. if( aHandle==0 ){
  94070. return SQLITE_NOMEM;
  94071. }
  94072. if( db->nExtension>0 ){
  94073. memcpy(aHandle, db->aExtension, sizeof(handle)*db->nExtension);
  94074. }
  94075. sqlite3DbFree(db, db->aExtension);
  94076. db->aExtension = aHandle;
  94077. db->aExtension[db->nExtension++] = handle;
  94078. return SQLITE_OK;
  94079. }
  94080. SQLITE_API int sqlite3_load_extension(
  94081. sqlite3 *db, /* Load the extension into this database connection */
  94082. const char *zFile, /* Name of the shared library containing extension */
  94083. const char *zProc, /* Entry point. Use "sqlite3_extension_init" if 0 */
  94084. char **pzErrMsg /* Put error message here if not 0 */
  94085. ){
  94086. int rc;
  94087. sqlite3_mutex_enter(db->mutex);
  94088. rc = sqlite3LoadExtension(db, zFile, zProc, pzErrMsg);
  94089. rc = sqlite3ApiExit(db, rc);
  94090. sqlite3_mutex_leave(db->mutex);
  94091. return rc;
  94092. }
  94093. /*
  94094. ** Call this routine when the database connection is closing in order
  94095. ** to clean up loaded extensions
  94096. */
  94097. SQLITE_PRIVATE void sqlite3CloseExtensions(sqlite3 *db){
  94098. int i;
  94099. assert( sqlite3_mutex_held(db->mutex) );
  94100. for(i=0; i<db->nExtension; i++){
  94101. sqlite3OsDlClose(db->pVfs, db->aExtension[i]);
  94102. }
  94103. sqlite3DbFree(db, db->aExtension);
  94104. }
  94105. /*
  94106. ** Enable or disable extension loading. Extension loading is disabled by
  94107. ** default so as not to open security holes in older applications.
  94108. */
  94109. SQLITE_API int sqlite3_enable_load_extension(sqlite3 *db, int onoff){
  94110. sqlite3_mutex_enter(db->mutex);
  94111. if( onoff ){
  94112. db->flags |= SQLITE_LoadExtension;
  94113. }else{
  94114. db->flags &= ~SQLITE_LoadExtension;
  94115. }
  94116. sqlite3_mutex_leave(db->mutex);
  94117. return SQLITE_OK;
  94118. }
  94119. #endif /* SQLITE_OMIT_LOAD_EXTENSION */
  94120. /*
  94121. ** The auto-extension code added regardless of whether or not extension
  94122. ** loading is supported. We need a dummy sqlite3Apis pointer for that
  94123. ** code if regular extension loading is not available. This is that
  94124. ** dummy pointer.
  94125. */
  94126. #ifdef SQLITE_OMIT_LOAD_EXTENSION
  94127. static const sqlite3_api_routines sqlite3Apis = { 0 };
  94128. #endif
  94129. /*
  94130. ** The following object holds the list of automatically loaded
  94131. ** extensions.
  94132. **
  94133. ** This list is shared across threads. The SQLITE_MUTEX_STATIC_MASTER
  94134. ** mutex must be held while accessing this list.
  94135. */
  94136. typedef struct sqlite3AutoExtList sqlite3AutoExtList;
  94137. static SQLITE_WSD struct sqlite3AutoExtList {
  94138. int nExt; /* Number of entries in aExt[] */
  94139. void (**aExt)(void); /* Pointers to the extension init functions */
  94140. } sqlite3Autoext = { 0, 0 };
  94141. /* The "wsdAutoext" macro will resolve to the autoextension
  94142. ** state vector. If writable static data is unsupported on the target,
  94143. ** we have to locate the state vector at run-time. In the more common
  94144. ** case where writable static data is supported, wsdStat can refer directly
  94145. ** to the "sqlite3Autoext" state vector declared above.
  94146. */
  94147. #ifdef SQLITE_OMIT_WSD
  94148. # define wsdAutoextInit \
  94149. sqlite3AutoExtList *x = &GLOBAL(sqlite3AutoExtList,sqlite3Autoext)
  94150. # define wsdAutoext x[0]
  94151. #else
  94152. # define wsdAutoextInit
  94153. # define wsdAutoext sqlite3Autoext
  94154. #endif
  94155. /*
  94156. ** Register a statically linked extension that is automatically
  94157. ** loaded by every new database connection.
  94158. */
  94159. SQLITE_API int sqlite3_auto_extension(void (*xInit)(void)){
  94160. int rc = SQLITE_OK;
  94161. #ifndef SQLITE_OMIT_AUTOINIT
  94162. rc = sqlite3_initialize();
  94163. if( rc ){
  94164. return rc;
  94165. }else
  94166. #endif
  94167. {
  94168. int i;
  94169. #if SQLITE_THREADSAFE
  94170. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  94171. #endif
  94172. wsdAutoextInit;
  94173. sqlite3_mutex_enter(mutex);
  94174. for(i=0; i<wsdAutoext.nExt; i++){
  94175. if( wsdAutoext.aExt[i]==xInit ) break;
  94176. }
  94177. if( i==wsdAutoext.nExt ){
  94178. int nByte = (wsdAutoext.nExt+1)*sizeof(wsdAutoext.aExt[0]);
  94179. void (**aNew)(void);
  94180. aNew = sqlite3_realloc(wsdAutoext.aExt, nByte);
  94181. if( aNew==0 ){
  94182. rc = SQLITE_NOMEM;
  94183. }else{
  94184. wsdAutoext.aExt = aNew;
  94185. wsdAutoext.aExt[wsdAutoext.nExt] = xInit;
  94186. wsdAutoext.nExt++;
  94187. }
  94188. }
  94189. sqlite3_mutex_leave(mutex);
  94190. assert( (rc&0xff)==rc );
  94191. return rc;
  94192. }
  94193. }
  94194. /*
  94195. ** Cancel a prior call to sqlite3_auto_extension. Remove xInit from the
  94196. ** set of routines that is invoked for each new database connection, if it
  94197. ** is currently on the list. If xInit is not on the list, then this
  94198. ** routine is a no-op.
  94199. **
  94200. ** Return 1 if xInit was found on the list and removed. Return 0 if xInit
  94201. ** was not on the list.
  94202. */
  94203. SQLITE_API int sqlite3_cancel_auto_extension(void (*xInit)(void)){
  94204. #if SQLITE_THREADSAFE
  94205. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  94206. #endif
  94207. int i;
  94208. int n = 0;
  94209. wsdAutoextInit;
  94210. sqlite3_mutex_enter(mutex);
  94211. for(i=wsdAutoext.nExt-1; i>=0; i--){
  94212. if( wsdAutoext.aExt[i]==xInit ){
  94213. wsdAutoext.nExt--;
  94214. wsdAutoext.aExt[i] = wsdAutoext.aExt[wsdAutoext.nExt];
  94215. n++;
  94216. break;
  94217. }
  94218. }
  94219. sqlite3_mutex_leave(mutex);
  94220. return n;
  94221. }
  94222. /*
  94223. ** Reset the automatic extension loading mechanism.
  94224. */
  94225. SQLITE_API void sqlite3_reset_auto_extension(void){
  94226. #ifndef SQLITE_OMIT_AUTOINIT
  94227. if( sqlite3_initialize()==SQLITE_OK )
  94228. #endif
  94229. {
  94230. #if SQLITE_THREADSAFE
  94231. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  94232. #endif
  94233. wsdAutoextInit;
  94234. sqlite3_mutex_enter(mutex);
  94235. sqlite3_free(wsdAutoext.aExt);
  94236. wsdAutoext.aExt = 0;
  94237. wsdAutoext.nExt = 0;
  94238. sqlite3_mutex_leave(mutex);
  94239. }
  94240. }
  94241. /*
  94242. ** Load all automatic extensions.
  94243. **
  94244. ** If anything goes wrong, set an error in the database connection.
  94245. */
  94246. SQLITE_PRIVATE void sqlite3AutoLoadExtensions(sqlite3 *db){
  94247. int i;
  94248. int go = 1;
  94249. int rc;
  94250. int (*xInit)(sqlite3*,char**,const sqlite3_api_routines*);
  94251. wsdAutoextInit;
  94252. if( wsdAutoext.nExt==0 ){
  94253. /* Common case: early out without every having to acquire a mutex */
  94254. return;
  94255. }
  94256. for(i=0; go; i++){
  94257. char *zErrmsg;
  94258. #if SQLITE_THREADSAFE
  94259. sqlite3_mutex *mutex = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER);
  94260. #endif
  94261. sqlite3_mutex_enter(mutex);
  94262. if( i>=wsdAutoext.nExt ){
  94263. xInit = 0;
  94264. go = 0;
  94265. }else{
  94266. xInit = (int(*)(sqlite3*,char**,const sqlite3_api_routines*))
  94267. wsdAutoext.aExt[i];
  94268. }
  94269. sqlite3_mutex_leave(mutex);
  94270. zErrmsg = 0;
  94271. if( xInit && (rc = xInit(db, &zErrmsg, &sqlite3Apis))!=0 ){
  94272. sqlite3ErrorWithMsg(db, rc,
  94273. "automatic extension loading failed: %s", zErrmsg);
  94274. go = 0;
  94275. }
  94276. sqlite3_free(zErrmsg);
  94277. }
  94278. }
  94279. /************** End of loadext.c *********************************************/
  94280. /************** Begin file pragma.c ******************************************/
  94281. /*
  94282. ** 2003 April 6
  94283. **
  94284. ** The author disclaims copyright to this source code. In place of
  94285. ** a legal notice, here is a blessing:
  94286. **
  94287. ** May you do good and not evil.
  94288. ** May you find forgiveness for yourself and forgive others.
  94289. ** May you share freely, never taking more than you give.
  94290. **
  94291. *************************************************************************
  94292. ** This file contains code used to implement the PRAGMA command.
  94293. */
  94294. #if !defined(SQLITE_ENABLE_LOCKING_STYLE)
  94295. # if defined(__APPLE__)
  94296. # define SQLITE_ENABLE_LOCKING_STYLE 1
  94297. # else
  94298. # define SQLITE_ENABLE_LOCKING_STYLE 0
  94299. # endif
  94300. #endif
  94301. /***************************************************************************
  94302. ** The next block of code, including the PragTyp_XXXX macro definitions and
  94303. ** the aPragmaName[] object is composed of generated code. DO NOT EDIT.
  94304. **
  94305. ** To add new pragmas, edit the code in ../tool/mkpragmatab.tcl and rerun
  94306. ** that script. Then copy/paste the output in place of the following:
  94307. */
  94308. #define PragTyp_HEADER_VALUE 0
  94309. #define PragTyp_AUTO_VACUUM 1
  94310. #define PragTyp_FLAG 2
  94311. #define PragTyp_BUSY_TIMEOUT 3
  94312. #define PragTyp_CACHE_SIZE 4
  94313. #define PragTyp_CASE_SENSITIVE_LIKE 5
  94314. #define PragTyp_COLLATION_LIST 6
  94315. #define PragTyp_COMPILE_OPTIONS 7
  94316. #define PragTyp_DATA_STORE_DIRECTORY 8
  94317. #define PragTyp_DATABASE_LIST 9
  94318. #define PragTyp_DEFAULT_CACHE_SIZE 10
  94319. #define PragTyp_ENCODING 11
  94320. #define PragTyp_FOREIGN_KEY_CHECK 12
  94321. #define PragTyp_FOREIGN_KEY_LIST 13
  94322. #define PragTyp_INCREMENTAL_VACUUM 14
  94323. #define PragTyp_INDEX_INFO 15
  94324. #define PragTyp_INDEX_LIST 16
  94325. #define PragTyp_INTEGRITY_CHECK 17
  94326. #define PragTyp_JOURNAL_MODE 18
  94327. #define PragTyp_JOURNAL_SIZE_LIMIT 19
  94328. #define PragTyp_LOCK_PROXY_FILE 20
  94329. #define PragTyp_LOCKING_MODE 21
  94330. #define PragTyp_PAGE_COUNT 22
  94331. #define PragTyp_MMAP_SIZE 23
  94332. #define PragTyp_PAGE_SIZE 24
  94333. #define PragTyp_SECURE_DELETE 25
  94334. #define PragTyp_SHRINK_MEMORY 26
  94335. #define PragTyp_SOFT_HEAP_LIMIT 27
  94336. #define PragTyp_STATS 28
  94337. #define PragTyp_SYNCHRONOUS 29
  94338. #define PragTyp_TABLE_INFO 30
  94339. #define PragTyp_TEMP_STORE 31
  94340. #define PragTyp_TEMP_STORE_DIRECTORY 32
  94341. #define PragTyp_THREADS 33
  94342. #define PragTyp_WAL_AUTOCHECKPOINT 34
  94343. #define PragTyp_WAL_CHECKPOINT 35
  94344. #define PragTyp_ACTIVATE_EXTENSIONS 36
  94345. #define PragTyp_HEXKEY 37
  94346. #define PragTyp_KEY 38
  94347. #define PragTyp_REKEY 39
  94348. #define PragTyp_LOCK_STATUS 40
  94349. #define PragTyp_PARSER_TRACE 41
  94350. #define PragFlag_NeedSchema 0x01
  94351. static const struct sPragmaNames {
  94352. const char *const zName; /* Name of pragma */
  94353. u8 ePragTyp; /* PragTyp_XXX value */
  94354. u8 mPragFlag; /* Zero or more PragFlag_XXX values */
  94355. u32 iArg; /* Extra argument */
  94356. } aPragmaNames[] = {
  94357. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  94358. { /* zName: */ "activate_extensions",
  94359. /* ePragTyp: */ PragTyp_ACTIVATE_EXTENSIONS,
  94360. /* ePragFlag: */ 0,
  94361. /* iArg: */ 0 },
  94362. #endif
  94363. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  94364. { /* zName: */ "application_id",
  94365. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  94366. /* ePragFlag: */ 0,
  94367. /* iArg: */ 0 },
  94368. #endif
  94369. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  94370. { /* zName: */ "auto_vacuum",
  94371. /* ePragTyp: */ PragTyp_AUTO_VACUUM,
  94372. /* ePragFlag: */ PragFlag_NeedSchema,
  94373. /* iArg: */ 0 },
  94374. #endif
  94375. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94376. #if !defined(SQLITE_OMIT_AUTOMATIC_INDEX)
  94377. { /* zName: */ "automatic_index",
  94378. /* ePragTyp: */ PragTyp_FLAG,
  94379. /* ePragFlag: */ 0,
  94380. /* iArg: */ SQLITE_AutoIndex },
  94381. #endif
  94382. #endif
  94383. { /* zName: */ "busy_timeout",
  94384. /* ePragTyp: */ PragTyp_BUSY_TIMEOUT,
  94385. /* ePragFlag: */ 0,
  94386. /* iArg: */ 0 },
  94387. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94388. { /* zName: */ "cache_size",
  94389. /* ePragTyp: */ PragTyp_CACHE_SIZE,
  94390. /* ePragFlag: */ PragFlag_NeedSchema,
  94391. /* iArg: */ 0 },
  94392. #endif
  94393. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94394. { /* zName: */ "cache_spill",
  94395. /* ePragTyp: */ PragTyp_FLAG,
  94396. /* ePragFlag: */ 0,
  94397. /* iArg: */ SQLITE_CacheSpill },
  94398. #endif
  94399. { /* zName: */ "case_sensitive_like",
  94400. /* ePragTyp: */ PragTyp_CASE_SENSITIVE_LIKE,
  94401. /* ePragFlag: */ 0,
  94402. /* iArg: */ 0 },
  94403. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94404. { /* zName: */ "checkpoint_fullfsync",
  94405. /* ePragTyp: */ PragTyp_FLAG,
  94406. /* ePragFlag: */ 0,
  94407. /* iArg: */ SQLITE_CkptFullFSync },
  94408. #endif
  94409. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  94410. { /* zName: */ "collation_list",
  94411. /* ePragTyp: */ PragTyp_COLLATION_LIST,
  94412. /* ePragFlag: */ 0,
  94413. /* iArg: */ 0 },
  94414. #endif
  94415. #if !defined(SQLITE_OMIT_COMPILEOPTION_DIAGS)
  94416. { /* zName: */ "compile_options",
  94417. /* ePragTyp: */ PragTyp_COMPILE_OPTIONS,
  94418. /* ePragFlag: */ 0,
  94419. /* iArg: */ 0 },
  94420. #endif
  94421. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94422. { /* zName: */ "count_changes",
  94423. /* ePragTyp: */ PragTyp_FLAG,
  94424. /* ePragFlag: */ 0,
  94425. /* iArg: */ SQLITE_CountRows },
  94426. #endif
  94427. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_OS_WIN
  94428. { /* zName: */ "data_store_directory",
  94429. /* ePragTyp: */ PragTyp_DATA_STORE_DIRECTORY,
  94430. /* ePragFlag: */ 0,
  94431. /* iArg: */ 0 },
  94432. #endif
  94433. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  94434. { /* zName: */ "database_list",
  94435. /* ePragTyp: */ PragTyp_DATABASE_LIST,
  94436. /* ePragFlag: */ PragFlag_NeedSchema,
  94437. /* iArg: */ 0 },
  94438. #endif
  94439. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  94440. { /* zName: */ "default_cache_size",
  94441. /* ePragTyp: */ PragTyp_DEFAULT_CACHE_SIZE,
  94442. /* ePragFlag: */ PragFlag_NeedSchema,
  94443. /* iArg: */ 0 },
  94444. #endif
  94445. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94446. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94447. { /* zName: */ "defer_foreign_keys",
  94448. /* ePragTyp: */ PragTyp_FLAG,
  94449. /* ePragFlag: */ 0,
  94450. /* iArg: */ SQLITE_DeferFKs },
  94451. #endif
  94452. #endif
  94453. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94454. { /* zName: */ "empty_result_callbacks",
  94455. /* ePragTyp: */ PragTyp_FLAG,
  94456. /* ePragFlag: */ 0,
  94457. /* iArg: */ SQLITE_NullCallback },
  94458. #endif
  94459. #if !defined(SQLITE_OMIT_UTF16)
  94460. { /* zName: */ "encoding",
  94461. /* ePragTyp: */ PragTyp_ENCODING,
  94462. /* ePragFlag: */ 0,
  94463. /* iArg: */ 0 },
  94464. #endif
  94465. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94466. { /* zName: */ "foreign_key_check",
  94467. /* ePragTyp: */ PragTyp_FOREIGN_KEY_CHECK,
  94468. /* ePragFlag: */ PragFlag_NeedSchema,
  94469. /* iArg: */ 0 },
  94470. #endif
  94471. #if !defined(SQLITE_OMIT_FOREIGN_KEY)
  94472. { /* zName: */ "foreign_key_list",
  94473. /* ePragTyp: */ PragTyp_FOREIGN_KEY_LIST,
  94474. /* ePragFlag: */ PragFlag_NeedSchema,
  94475. /* iArg: */ 0 },
  94476. #endif
  94477. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94478. #if !defined(SQLITE_OMIT_FOREIGN_KEY) && !defined(SQLITE_OMIT_TRIGGER)
  94479. { /* zName: */ "foreign_keys",
  94480. /* ePragTyp: */ PragTyp_FLAG,
  94481. /* ePragFlag: */ 0,
  94482. /* iArg: */ SQLITE_ForeignKeys },
  94483. #endif
  94484. #endif
  94485. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  94486. { /* zName: */ "freelist_count",
  94487. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  94488. /* ePragFlag: */ 0,
  94489. /* iArg: */ 0 },
  94490. #endif
  94491. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94492. { /* zName: */ "full_column_names",
  94493. /* ePragTyp: */ PragTyp_FLAG,
  94494. /* ePragFlag: */ 0,
  94495. /* iArg: */ SQLITE_FullColNames },
  94496. { /* zName: */ "fullfsync",
  94497. /* ePragTyp: */ PragTyp_FLAG,
  94498. /* ePragFlag: */ 0,
  94499. /* iArg: */ SQLITE_FullFSync },
  94500. #endif
  94501. #if defined(SQLITE_HAS_CODEC)
  94502. { /* zName: */ "hexkey",
  94503. /* ePragTyp: */ PragTyp_HEXKEY,
  94504. /* ePragFlag: */ 0,
  94505. /* iArg: */ 0 },
  94506. { /* zName: */ "hexrekey",
  94507. /* ePragTyp: */ PragTyp_HEXKEY,
  94508. /* ePragFlag: */ 0,
  94509. /* iArg: */ 0 },
  94510. #endif
  94511. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94512. #if !defined(SQLITE_OMIT_CHECK)
  94513. { /* zName: */ "ignore_check_constraints",
  94514. /* ePragTyp: */ PragTyp_FLAG,
  94515. /* ePragFlag: */ 0,
  94516. /* iArg: */ SQLITE_IgnoreChecks },
  94517. #endif
  94518. #endif
  94519. #if !defined(SQLITE_OMIT_AUTOVACUUM)
  94520. { /* zName: */ "incremental_vacuum",
  94521. /* ePragTyp: */ PragTyp_INCREMENTAL_VACUUM,
  94522. /* ePragFlag: */ PragFlag_NeedSchema,
  94523. /* iArg: */ 0 },
  94524. #endif
  94525. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  94526. { /* zName: */ "index_info",
  94527. /* ePragTyp: */ PragTyp_INDEX_INFO,
  94528. /* ePragFlag: */ PragFlag_NeedSchema,
  94529. /* iArg: */ 0 },
  94530. { /* zName: */ "index_list",
  94531. /* ePragTyp: */ PragTyp_INDEX_LIST,
  94532. /* ePragFlag: */ PragFlag_NeedSchema,
  94533. /* iArg: */ 0 },
  94534. #endif
  94535. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  94536. { /* zName: */ "integrity_check",
  94537. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  94538. /* ePragFlag: */ PragFlag_NeedSchema,
  94539. /* iArg: */ 0 },
  94540. #endif
  94541. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94542. { /* zName: */ "journal_mode",
  94543. /* ePragTyp: */ PragTyp_JOURNAL_MODE,
  94544. /* ePragFlag: */ PragFlag_NeedSchema,
  94545. /* iArg: */ 0 },
  94546. { /* zName: */ "journal_size_limit",
  94547. /* ePragTyp: */ PragTyp_JOURNAL_SIZE_LIMIT,
  94548. /* ePragFlag: */ 0,
  94549. /* iArg: */ 0 },
  94550. #endif
  94551. #if defined(SQLITE_HAS_CODEC)
  94552. { /* zName: */ "key",
  94553. /* ePragTyp: */ PragTyp_KEY,
  94554. /* ePragFlag: */ 0,
  94555. /* iArg: */ 0 },
  94556. #endif
  94557. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94558. { /* zName: */ "legacy_file_format",
  94559. /* ePragTyp: */ PragTyp_FLAG,
  94560. /* ePragFlag: */ 0,
  94561. /* iArg: */ SQLITE_LegacyFileFmt },
  94562. #endif
  94563. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && SQLITE_ENABLE_LOCKING_STYLE
  94564. { /* zName: */ "lock_proxy_file",
  94565. /* ePragTyp: */ PragTyp_LOCK_PROXY_FILE,
  94566. /* ePragFlag: */ 0,
  94567. /* iArg: */ 0 },
  94568. #endif
  94569. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  94570. { /* zName: */ "lock_status",
  94571. /* ePragTyp: */ PragTyp_LOCK_STATUS,
  94572. /* ePragFlag: */ 0,
  94573. /* iArg: */ 0 },
  94574. #endif
  94575. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94576. { /* zName: */ "locking_mode",
  94577. /* ePragTyp: */ PragTyp_LOCKING_MODE,
  94578. /* ePragFlag: */ 0,
  94579. /* iArg: */ 0 },
  94580. { /* zName: */ "max_page_count",
  94581. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  94582. /* ePragFlag: */ PragFlag_NeedSchema,
  94583. /* iArg: */ 0 },
  94584. { /* zName: */ "mmap_size",
  94585. /* ePragTyp: */ PragTyp_MMAP_SIZE,
  94586. /* ePragFlag: */ 0,
  94587. /* iArg: */ 0 },
  94588. { /* zName: */ "page_count",
  94589. /* ePragTyp: */ PragTyp_PAGE_COUNT,
  94590. /* ePragFlag: */ PragFlag_NeedSchema,
  94591. /* iArg: */ 0 },
  94592. { /* zName: */ "page_size",
  94593. /* ePragTyp: */ PragTyp_PAGE_SIZE,
  94594. /* ePragFlag: */ 0,
  94595. /* iArg: */ 0 },
  94596. #endif
  94597. #if defined(SQLITE_DEBUG)
  94598. { /* zName: */ "parser_trace",
  94599. /* ePragTyp: */ PragTyp_PARSER_TRACE,
  94600. /* ePragFlag: */ 0,
  94601. /* iArg: */ 0 },
  94602. #endif
  94603. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94604. { /* zName: */ "query_only",
  94605. /* ePragTyp: */ PragTyp_FLAG,
  94606. /* ePragFlag: */ 0,
  94607. /* iArg: */ SQLITE_QueryOnly },
  94608. #endif
  94609. #if !defined(SQLITE_OMIT_INTEGRITY_CHECK)
  94610. { /* zName: */ "quick_check",
  94611. /* ePragTyp: */ PragTyp_INTEGRITY_CHECK,
  94612. /* ePragFlag: */ PragFlag_NeedSchema,
  94613. /* iArg: */ 0 },
  94614. #endif
  94615. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94616. { /* zName: */ "read_uncommitted",
  94617. /* ePragTyp: */ PragTyp_FLAG,
  94618. /* ePragFlag: */ 0,
  94619. /* iArg: */ SQLITE_ReadUncommitted },
  94620. { /* zName: */ "recursive_triggers",
  94621. /* ePragTyp: */ PragTyp_FLAG,
  94622. /* ePragFlag: */ 0,
  94623. /* iArg: */ SQLITE_RecTriggers },
  94624. #endif
  94625. #if defined(SQLITE_HAS_CODEC)
  94626. { /* zName: */ "rekey",
  94627. /* ePragTyp: */ PragTyp_REKEY,
  94628. /* ePragFlag: */ 0,
  94629. /* iArg: */ 0 },
  94630. #endif
  94631. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94632. { /* zName: */ "reverse_unordered_selects",
  94633. /* ePragTyp: */ PragTyp_FLAG,
  94634. /* ePragFlag: */ 0,
  94635. /* iArg: */ SQLITE_ReverseOrder },
  94636. #endif
  94637. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  94638. { /* zName: */ "schema_version",
  94639. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  94640. /* ePragFlag: */ 0,
  94641. /* iArg: */ 0 },
  94642. #endif
  94643. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94644. { /* zName: */ "secure_delete",
  94645. /* ePragTyp: */ PragTyp_SECURE_DELETE,
  94646. /* ePragFlag: */ 0,
  94647. /* iArg: */ 0 },
  94648. #endif
  94649. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94650. { /* zName: */ "short_column_names",
  94651. /* ePragTyp: */ PragTyp_FLAG,
  94652. /* ePragFlag: */ 0,
  94653. /* iArg: */ SQLITE_ShortColNames },
  94654. #endif
  94655. { /* zName: */ "shrink_memory",
  94656. /* ePragTyp: */ PragTyp_SHRINK_MEMORY,
  94657. /* ePragFlag: */ 0,
  94658. /* iArg: */ 0 },
  94659. { /* zName: */ "soft_heap_limit",
  94660. /* ePragTyp: */ PragTyp_SOFT_HEAP_LIMIT,
  94661. /* ePragFlag: */ 0,
  94662. /* iArg: */ 0 },
  94663. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94664. #if defined(SQLITE_DEBUG)
  94665. { /* zName: */ "sql_trace",
  94666. /* ePragTyp: */ PragTyp_FLAG,
  94667. /* ePragFlag: */ 0,
  94668. /* iArg: */ SQLITE_SqlTrace },
  94669. #endif
  94670. #endif
  94671. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  94672. { /* zName: */ "stats",
  94673. /* ePragTyp: */ PragTyp_STATS,
  94674. /* ePragFlag: */ PragFlag_NeedSchema,
  94675. /* iArg: */ 0 },
  94676. #endif
  94677. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94678. { /* zName: */ "synchronous",
  94679. /* ePragTyp: */ PragTyp_SYNCHRONOUS,
  94680. /* ePragFlag: */ PragFlag_NeedSchema,
  94681. /* iArg: */ 0 },
  94682. #endif
  94683. #if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS)
  94684. { /* zName: */ "table_info",
  94685. /* ePragTyp: */ PragTyp_TABLE_INFO,
  94686. /* ePragFlag: */ PragFlag_NeedSchema,
  94687. /* iArg: */ 0 },
  94688. #endif
  94689. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  94690. { /* zName: */ "temp_store",
  94691. /* ePragTyp: */ PragTyp_TEMP_STORE,
  94692. /* ePragFlag: */ 0,
  94693. /* iArg: */ 0 },
  94694. { /* zName: */ "temp_store_directory",
  94695. /* ePragTyp: */ PragTyp_TEMP_STORE_DIRECTORY,
  94696. /* ePragFlag: */ 0,
  94697. /* iArg: */ 0 },
  94698. #endif
  94699. { /* zName: */ "threads",
  94700. /* ePragTyp: */ PragTyp_THREADS,
  94701. /* ePragFlag: */ 0,
  94702. /* iArg: */ 0 },
  94703. #if !defined(SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS)
  94704. { /* zName: */ "user_version",
  94705. /* ePragTyp: */ PragTyp_HEADER_VALUE,
  94706. /* ePragFlag: */ 0,
  94707. /* iArg: */ 0 },
  94708. #endif
  94709. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94710. #if defined(SQLITE_DEBUG)
  94711. { /* zName: */ "vdbe_addoptrace",
  94712. /* ePragTyp: */ PragTyp_FLAG,
  94713. /* ePragFlag: */ 0,
  94714. /* iArg: */ SQLITE_VdbeAddopTrace },
  94715. { /* zName: */ "vdbe_debug",
  94716. /* ePragTyp: */ PragTyp_FLAG,
  94717. /* ePragFlag: */ 0,
  94718. /* iArg: */ SQLITE_SqlTrace|SQLITE_VdbeListing|SQLITE_VdbeTrace },
  94719. { /* zName: */ "vdbe_eqp",
  94720. /* ePragTyp: */ PragTyp_FLAG,
  94721. /* ePragFlag: */ 0,
  94722. /* iArg: */ SQLITE_VdbeEQP },
  94723. { /* zName: */ "vdbe_listing",
  94724. /* ePragTyp: */ PragTyp_FLAG,
  94725. /* ePragFlag: */ 0,
  94726. /* iArg: */ SQLITE_VdbeListing },
  94727. { /* zName: */ "vdbe_trace",
  94728. /* ePragTyp: */ PragTyp_FLAG,
  94729. /* ePragFlag: */ 0,
  94730. /* iArg: */ SQLITE_VdbeTrace },
  94731. #endif
  94732. #endif
  94733. #if !defined(SQLITE_OMIT_WAL)
  94734. { /* zName: */ "wal_autocheckpoint",
  94735. /* ePragTyp: */ PragTyp_WAL_AUTOCHECKPOINT,
  94736. /* ePragFlag: */ 0,
  94737. /* iArg: */ 0 },
  94738. { /* zName: */ "wal_checkpoint",
  94739. /* ePragTyp: */ PragTyp_WAL_CHECKPOINT,
  94740. /* ePragFlag: */ PragFlag_NeedSchema,
  94741. /* iArg: */ 0 },
  94742. #endif
  94743. #if !defined(SQLITE_OMIT_FLAG_PRAGMAS)
  94744. { /* zName: */ "writable_schema",
  94745. /* ePragTyp: */ PragTyp_FLAG,
  94746. /* ePragFlag: */ 0,
  94747. /* iArg: */ SQLITE_WriteSchema|SQLITE_RecoveryMode },
  94748. #endif
  94749. };
  94750. /* Number of pragmas: 57 on by default, 70 total. */
  94751. /* End of the automatically generated pragma table.
  94752. ***************************************************************************/
  94753. /*
  94754. ** Interpret the given string as a safety level. Return 0 for OFF,
  94755. ** 1 for ON or NORMAL and 2 for FULL. Return 1 for an empty or
  94756. ** unrecognized string argument. The FULL option is disallowed
  94757. ** if the omitFull parameter it 1.
  94758. **
  94759. ** Note that the values returned are one less that the values that
  94760. ** should be passed into sqlite3BtreeSetSafetyLevel(). The is done
  94761. ** to support legacy SQL code. The safety level used to be boolean
  94762. ** and older scripts may have used numbers 0 for OFF and 1 for ON.
  94763. */
  94764. static u8 getSafetyLevel(const char *z, int omitFull, u8 dflt){
  94765. /* 123456789 123456789 */
  94766. static const char zText[] = "onoffalseyestruefull";
  94767. static const u8 iOffset[] = {0, 1, 2, 4, 9, 12, 16};
  94768. static const u8 iLength[] = {2, 2, 3, 5, 3, 4, 4};
  94769. static const u8 iValue[] = {1, 0, 0, 0, 1, 1, 2};
  94770. int i, n;
  94771. if( sqlite3Isdigit(*z) ){
  94772. return (u8)sqlite3Atoi(z);
  94773. }
  94774. n = sqlite3Strlen30(z);
  94775. for(i=0; i<ArraySize(iLength)-omitFull; i++){
  94776. if( iLength[i]==n && sqlite3StrNICmp(&zText[iOffset[i]],z,n)==0 ){
  94777. return iValue[i];
  94778. }
  94779. }
  94780. return dflt;
  94781. }
  94782. /*
  94783. ** Interpret the given string as a boolean value.
  94784. */
  94785. SQLITE_PRIVATE u8 sqlite3GetBoolean(const char *z, u8 dflt){
  94786. return getSafetyLevel(z,1,dflt)!=0;
  94787. }
  94788. /* The sqlite3GetBoolean() function is used by other modules but the
  94789. ** remainder of this file is specific to PRAGMA processing. So omit
  94790. ** the rest of the file if PRAGMAs are omitted from the build.
  94791. */
  94792. #if !defined(SQLITE_OMIT_PRAGMA)
  94793. /*
  94794. ** Interpret the given string as a locking mode value.
  94795. */
  94796. static int getLockingMode(const char *z){
  94797. if( z ){
  94798. if( 0==sqlite3StrICmp(z, "exclusive") ) return PAGER_LOCKINGMODE_EXCLUSIVE;
  94799. if( 0==sqlite3StrICmp(z, "normal") ) return PAGER_LOCKINGMODE_NORMAL;
  94800. }
  94801. return PAGER_LOCKINGMODE_QUERY;
  94802. }
  94803. #ifndef SQLITE_OMIT_AUTOVACUUM
  94804. /*
  94805. ** Interpret the given string as an auto-vacuum mode value.
  94806. **
  94807. ** The following strings, "none", "full" and "incremental" are
  94808. ** acceptable, as are their numeric equivalents: 0, 1 and 2 respectively.
  94809. */
  94810. static int getAutoVacuum(const char *z){
  94811. int i;
  94812. if( 0==sqlite3StrICmp(z, "none") ) return BTREE_AUTOVACUUM_NONE;
  94813. if( 0==sqlite3StrICmp(z, "full") ) return BTREE_AUTOVACUUM_FULL;
  94814. if( 0==sqlite3StrICmp(z, "incremental") ) return BTREE_AUTOVACUUM_INCR;
  94815. i = sqlite3Atoi(z);
  94816. return (u8)((i>=0&&i<=2)?i:0);
  94817. }
  94818. #endif /* ifndef SQLITE_OMIT_AUTOVACUUM */
  94819. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  94820. /*
  94821. ** Interpret the given string as a temp db location. Return 1 for file
  94822. ** backed temporary databases, 2 for the Red-Black tree in memory database
  94823. ** and 0 to use the compile-time default.
  94824. */
  94825. static int getTempStore(const char *z){
  94826. if( z[0]>='0' && z[0]<='2' ){
  94827. return z[0] - '0';
  94828. }else if( sqlite3StrICmp(z, "file")==0 ){
  94829. return 1;
  94830. }else if( sqlite3StrICmp(z, "memory")==0 ){
  94831. return 2;
  94832. }else{
  94833. return 0;
  94834. }
  94835. }
  94836. #endif /* SQLITE_PAGER_PRAGMAS */
  94837. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  94838. /*
  94839. ** Invalidate temp storage, either when the temp storage is changed
  94840. ** from default, or when 'file' and the temp_store_directory has changed
  94841. */
  94842. static int invalidateTempStorage(Parse *pParse){
  94843. sqlite3 *db = pParse->db;
  94844. if( db->aDb[1].pBt!=0 ){
  94845. if( !db->autoCommit || sqlite3BtreeIsInReadTrans(db->aDb[1].pBt) ){
  94846. sqlite3ErrorMsg(pParse, "temporary storage cannot be changed "
  94847. "from within a transaction");
  94848. return SQLITE_ERROR;
  94849. }
  94850. sqlite3BtreeClose(db->aDb[1].pBt);
  94851. db->aDb[1].pBt = 0;
  94852. sqlite3ResetAllSchemasOfConnection(db);
  94853. }
  94854. return SQLITE_OK;
  94855. }
  94856. #endif /* SQLITE_PAGER_PRAGMAS */
  94857. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  94858. /*
  94859. ** If the TEMP database is open, close it and mark the database schema
  94860. ** as needing reloading. This must be done when using the SQLITE_TEMP_STORE
  94861. ** or DEFAULT_TEMP_STORE pragmas.
  94862. */
  94863. static int changeTempStorage(Parse *pParse, const char *zStorageType){
  94864. int ts = getTempStore(zStorageType);
  94865. sqlite3 *db = pParse->db;
  94866. if( db->temp_store==ts ) return SQLITE_OK;
  94867. if( invalidateTempStorage( pParse ) != SQLITE_OK ){
  94868. return SQLITE_ERROR;
  94869. }
  94870. db->temp_store = (u8)ts;
  94871. return SQLITE_OK;
  94872. }
  94873. #endif /* SQLITE_PAGER_PRAGMAS */
  94874. /*
  94875. ** Generate code to return a single integer value.
  94876. */
  94877. static void returnSingleInt(Parse *pParse, const char *zLabel, i64 value){
  94878. Vdbe *v = sqlite3GetVdbe(pParse);
  94879. int mem = ++pParse->nMem;
  94880. i64 *pI64 = sqlite3DbMallocRaw(pParse->db, sizeof(value));
  94881. if( pI64 ){
  94882. memcpy(pI64, &value, sizeof(value));
  94883. }
  94884. sqlite3VdbeAddOp4(v, OP_Int64, 0, mem, 0, (char*)pI64, P4_INT64);
  94885. sqlite3VdbeSetNumCols(v, 1);
  94886. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLabel, SQLITE_STATIC);
  94887. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  94888. }
  94889. /*
  94890. ** Set the safety_level and pager flags for pager iDb. Or if iDb<0
  94891. ** set these values for all pagers.
  94892. */
  94893. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  94894. static void setAllPagerFlags(sqlite3 *db){
  94895. if( db->autoCommit ){
  94896. Db *pDb = db->aDb;
  94897. int n = db->nDb;
  94898. assert( SQLITE_FullFSync==PAGER_FULLFSYNC );
  94899. assert( SQLITE_CkptFullFSync==PAGER_CKPT_FULLFSYNC );
  94900. assert( SQLITE_CacheSpill==PAGER_CACHESPILL );
  94901. assert( (PAGER_FULLFSYNC | PAGER_CKPT_FULLFSYNC | PAGER_CACHESPILL)
  94902. == PAGER_FLAGS_MASK );
  94903. assert( (pDb->safety_level & PAGER_SYNCHRONOUS_MASK)==pDb->safety_level );
  94904. while( (n--) > 0 ){
  94905. if( pDb->pBt ){
  94906. sqlite3BtreeSetPagerFlags(pDb->pBt,
  94907. pDb->safety_level | (db->flags & PAGER_FLAGS_MASK) );
  94908. }
  94909. pDb++;
  94910. }
  94911. }
  94912. }
  94913. #else
  94914. # define setAllPagerFlags(X) /* no-op */
  94915. #endif
  94916. /*
  94917. ** Return a human-readable name for a constraint resolution action.
  94918. */
  94919. #ifndef SQLITE_OMIT_FOREIGN_KEY
  94920. static const char *actionName(u8 action){
  94921. const char *zName;
  94922. switch( action ){
  94923. case OE_SetNull: zName = "SET NULL"; break;
  94924. case OE_SetDflt: zName = "SET DEFAULT"; break;
  94925. case OE_Cascade: zName = "CASCADE"; break;
  94926. case OE_Restrict: zName = "RESTRICT"; break;
  94927. default: zName = "NO ACTION";
  94928. assert( action==OE_None ); break;
  94929. }
  94930. return zName;
  94931. }
  94932. #endif
  94933. /*
  94934. ** Parameter eMode must be one of the PAGER_JOURNALMODE_XXX constants
  94935. ** defined in pager.h. This function returns the associated lowercase
  94936. ** journal-mode name.
  94937. */
  94938. SQLITE_PRIVATE const char *sqlite3JournalModename(int eMode){
  94939. static char * const azModeName[] = {
  94940. "delete", "persist", "off", "truncate", "memory"
  94941. #ifndef SQLITE_OMIT_WAL
  94942. , "wal"
  94943. #endif
  94944. };
  94945. assert( PAGER_JOURNALMODE_DELETE==0 );
  94946. assert( PAGER_JOURNALMODE_PERSIST==1 );
  94947. assert( PAGER_JOURNALMODE_OFF==2 );
  94948. assert( PAGER_JOURNALMODE_TRUNCATE==3 );
  94949. assert( PAGER_JOURNALMODE_MEMORY==4 );
  94950. assert( PAGER_JOURNALMODE_WAL==5 );
  94951. assert( eMode>=0 && eMode<=ArraySize(azModeName) );
  94952. if( eMode==ArraySize(azModeName) ) return 0;
  94953. return azModeName[eMode];
  94954. }
  94955. /*
  94956. ** Process a pragma statement.
  94957. **
  94958. ** Pragmas are of this form:
  94959. **
  94960. ** PRAGMA [database.]id [= value]
  94961. **
  94962. ** The identifier might also be a string. The value is a string, and
  94963. ** identifier, or a number. If minusFlag is true, then the value is
  94964. ** a number that was preceded by a minus sign.
  94965. **
  94966. ** If the left side is "database.id" then pId1 is the database name
  94967. ** and pId2 is the id. If the left side is just "id" then pId1 is the
  94968. ** id and pId2 is any empty string.
  94969. */
  94970. SQLITE_PRIVATE void sqlite3Pragma(
  94971. Parse *pParse,
  94972. Token *pId1, /* First part of [database.]id field */
  94973. Token *pId2, /* Second part of [database.]id field, or NULL */
  94974. Token *pValue, /* Token for <value>, or NULL */
  94975. int minusFlag /* True if a '-' sign preceded <value> */
  94976. ){
  94977. char *zLeft = 0; /* Nul-terminated UTF-8 string <id> */
  94978. char *zRight = 0; /* Nul-terminated UTF-8 string <value>, or NULL */
  94979. const char *zDb = 0; /* The database name */
  94980. Token *pId; /* Pointer to <id> token */
  94981. char *aFcntl[4]; /* Argument to SQLITE_FCNTL_PRAGMA */
  94982. int iDb; /* Database index for <database> */
  94983. int lwr, upr, mid; /* Binary search bounds */
  94984. int rc; /* return value form SQLITE_FCNTL_PRAGMA */
  94985. sqlite3 *db = pParse->db; /* The database connection */
  94986. Db *pDb; /* The specific database being pragmaed */
  94987. Vdbe *v = sqlite3GetVdbe(pParse); /* Prepared statement */
  94988. if( v==0 ) return;
  94989. sqlite3VdbeRunOnlyOnce(v);
  94990. pParse->nMem = 2;
  94991. /* Interpret the [database.] part of the pragma statement. iDb is the
  94992. ** index of the database this pragma is being applied to in db.aDb[]. */
  94993. iDb = sqlite3TwoPartName(pParse, pId1, pId2, &pId);
  94994. if( iDb<0 ) return;
  94995. pDb = &db->aDb[iDb];
  94996. /* If the temp database has been explicitly named as part of the
  94997. ** pragma, make sure it is open.
  94998. */
  94999. if( iDb==1 && sqlite3OpenTempDatabase(pParse) ){
  95000. return;
  95001. }
  95002. zLeft = sqlite3NameFromToken(db, pId);
  95003. if( !zLeft ) return;
  95004. if( minusFlag ){
  95005. zRight = sqlite3MPrintf(db, "-%T", pValue);
  95006. }else{
  95007. zRight = sqlite3NameFromToken(db, pValue);
  95008. }
  95009. assert( pId2 );
  95010. zDb = pId2->n>0 ? pDb->zName : 0;
  95011. if( sqlite3AuthCheck(pParse, SQLITE_PRAGMA, zLeft, zRight, zDb) ){
  95012. goto pragma_out;
  95013. }
  95014. /* Send an SQLITE_FCNTL_PRAGMA file-control to the underlying VFS
  95015. ** connection. If it returns SQLITE_OK, then assume that the VFS
  95016. ** handled the pragma and generate a no-op prepared statement.
  95017. */
  95018. aFcntl[0] = 0;
  95019. aFcntl[1] = zLeft;
  95020. aFcntl[2] = zRight;
  95021. aFcntl[3] = 0;
  95022. db->busyHandler.nBusy = 0;
  95023. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_PRAGMA, (void*)aFcntl);
  95024. if( rc==SQLITE_OK ){
  95025. if( aFcntl[0] ){
  95026. int mem = ++pParse->nMem;
  95027. sqlite3VdbeAddOp4(v, OP_String8, 0, mem, 0, aFcntl[0], 0);
  95028. sqlite3VdbeSetNumCols(v, 1);
  95029. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "result", SQLITE_STATIC);
  95030. sqlite3VdbeAddOp2(v, OP_ResultRow, mem, 1);
  95031. sqlite3_free(aFcntl[0]);
  95032. }
  95033. goto pragma_out;
  95034. }
  95035. if( rc!=SQLITE_NOTFOUND ){
  95036. if( aFcntl[0] ){
  95037. sqlite3ErrorMsg(pParse, "%s", aFcntl[0]);
  95038. sqlite3_free(aFcntl[0]);
  95039. }
  95040. pParse->nErr++;
  95041. pParse->rc = rc;
  95042. goto pragma_out;
  95043. }
  95044. /* Locate the pragma in the lookup table */
  95045. lwr = 0;
  95046. upr = ArraySize(aPragmaNames)-1;
  95047. while( lwr<=upr ){
  95048. mid = (lwr+upr)/2;
  95049. rc = sqlite3_stricmp(zLeft, aPragmaNames[mid].zName);
  95050. if( rc==0 ) break;
  95051. if( rc<0 ){
  95052. upr = mid - 1;
  95053. }else{
  95054. lwr = mid + 1;
  95055. }
  95056. }
  95057. if( lwr>upr ) goto pragma_out;
  95058. /* Make sure the database schema is loaded if the pragma requires that */
  95059. if( (aPragmaNames[mid].mPragFlag & PragFlag_NeedSchema)!=0 ){
  95060. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  95061. }
  95062. /* Jump to the appropriate pragma handler */
  95063. switch( aPragmaNames[mid].ePragTyp ){
  95064. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS) && !defined(SQLITE_OMIT_DEPRECATED)
  95065. /*
  95066. ** PRAGMA [database.]default_cache_size
  95067. ** PRAGMA [database.]default_cache_size=N
  95068. **
  95069. ** The first form reports the current persistent setting for the
  95070. ** page cache size. The value returned is the maximum number of
  95071. ** pages in the page cache. The second form sets both the current
  95072. ** page cache size value and the persistent page cache size value
  95073. ** stored in the database file.
  95074. **
  95075. ** Older versions of SQLite would set the default cache size to a
  95076. ** negative number to indicate synchronous=OFF. These days, synchronous
  95077. ** is always on by default regardless of the sign of the default cache
  95078. ** size. But continue to take the absolute value of the default cache
  95079. ** size of historical compatibility.
  95080. */
  95081. case PragTyp_DEFAULT_CACHE_SIZE: {
  95082. static const int iLn = VDBE_OFFSET_LINENO(2);
  95083. static const VdbeOpList getCacheSize[] = {
  95084. { OP_Transaction, 0, 0, 0}, /* 0 */
  95085. { OP_ReadCookie, 0, 1, BTREE_DEFAULT_CACHE_SIZE}, /* 1 */
  95086. { OP_IfPos, 1, 8, 0},
  95087. { OP_Integer, 0, 2, 0},
  95088. { OP_Subtract, 1, 2, 1},
  95089. { OP_IfPos, 1, 8, 0},
  95090. { OP_Integer, 0, 1, 0}, /* 6 */
  95091. { OP_Noop, 0, 0, 0},
  95092. { OP_ResultRow, 1, 1, 0},
  95093. };
  95094. int addr;
  95095. sqlite3VdbeUsesBtree(v, iDb);
  95096. if( !zRight ){
  95097. sqlite3VdbeSetNumCols(v, 1);
  95098. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cache_size", SQLITE_STATIC);
  95099. pParse->nMem += 2;
  95100. addr = sqlite3VdbeAddOpList(v, ArraySize(getCacheSize), getCacheSize,iLn);
  95101. sqlite3VdbeChangeP1(v, addr, iDb);
  95102. sqlite3VdbeChangeP1(v, addr+1, iDb);
  95103. sqlite3VdbeChangeP1(v, addr+6, SQLITE_DEFAULT_CACHE_SIZE);
  95104. }else{
  95105. int size = sqlite3AbsInt32(sqlite3Atoi(zRight));
  95106. sqlite3BeginWriteOperation(pParse, 0, iDb);
  95107. sqlite3VdbeAddOp2(v, OP_Integer, size, 1);
  95108. sqlite3VdbeAddOp3(v, OP_SetCookie, iDb, BTREE_DEFAULT_CACHE_SIZE, 1);
  95109. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95110. pDb->pSchema->cache_size = size;
  95111. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  95112. }
  95113. break;
  95114. }
  95115. #endif /* !SQLITE_OMIT_PAGER_PRAGMAS && !SQLITE_OMIT_DEPRECATED */
  95116. #if !defined(SQLITE_OMIT_PAGER_PRAGMAS)
  95117. /*
  95118. ** PRAGMA [database.]page_size
  95119. ** PRAGMA [database.]page_size=N
  95120. **
  95121. ** The first form reports the current setting for the
  95122. ** database page size in bytes. The second form sets the
  95123. ** database page size value. The value can only be set if
  95124. ** the database has not yet been created.
  95125. */
  95126. case PragTyp_PAGE_SIZE: {
  95127. Btree *pBt = pDb->pBt;
  95128. assert( pBt!=0 );
  95129. if( !zRight ){
  95130. int size = ALWAYS(pBt) ? sqlite3BtreeGetPageSize(pBt) : 0;
  95131. returnSingleInt(pParse, "page_size", size);
  95132. }else{
  95133. /* Malloc may fail when setting the page-size, as there is an internal
  95134. ** buffer that the pager module resizes using sqlite3_realloc().
  95135. */
  95136. db->nextPagesize = sqlite3Atoi(zRight);
  95137. if( SQLITE_NOMEM==sqlite3BtreeSetPageSize(pBt, db->nextPagesize,-1,0) ){
  95138. db->mallocFailed = 1;
  95139. }
  95140. }
  95141. break;
  95142. }
  95143. /*
  95144. ** PRAGMA [database.]secure_delete
  95145. ** PRAGMA [database.]secure_delete=ON/OFF
  95146. **
  95147. ** The first form reports the current setting for the
  95148. ** secure_delete flag. The second form changes the secure_delete
  95149. ** flag setting and reports thenew value.
  95150. */
  95151. case PragTyp_SECURE_DELETE: {
  95152. Btree *pBt = pDb->pBt;
  95153. int b = -1;
  95154. assert( pBt!=0 );
  95155. if( zRight ){
  95156. b = sqlite3GetBoolean(zRight, 0);
  95157. }
  95158. if( pId2->n==0 && b>=0 ){
  95159. int ii;
  95160. for(ii=0; ii<db->nDb; ii++){
  95161. sqlite3BtreeSecureDelete(db->aDb[ii].pBt, b);
  95162. }
  95163. }
  95164. b = sqlite3BtreeSecureDelete(pBt, b);
  95165. returnSingleInt(pParse, "secure_delete", b);
  95166. break;
  95167. }
  95168. /*
  95169. ** PRAGMA [database.]max_page_count
  95170. ** PRAGMA [database.]max_page_count=N
  95171. **
  95172. ** The first form reports the current setting for the
  95173. ** maximum number of pages in the database file. The
  95174. ** second form attempts to change this setting. Both
  95175. ** forms return the current setting.
  95176. **
  95177. ** The absolute value of N is used. This is undocumented and might
  95178. ** change. The only purpose is to provide an easy way to test
  95179. ** the sqlite3AbsInt32() function.
  95180. **
  95181. ** PRAGMA [database.]page_count
  95182. **
  95183. ** Return the number of pages in the specified database.
  95184. */
  95185. case PragTyp_PAGE_COUNT: {
  95186. int iReg;
  95187. sqlite3CodeVerifySchema(pParse, iDb);
  95188. iReg = ++pParse->nMem;
  95189. if( sqlite3Tolower(zLeft[0])=='p' ){
  95190. sqlite3VdbeAddOp2(v, OP_Pagecount, iDb, iReg);
  95191. }else{
  95192. sqlite3VdbeAddOp3(v, OP_MaxPgcnt, iDb, iReg,
  95193. sqlite3AbsInt32(sqlite3Atoi(zRight)));
  95194. }
  95195. sqlite3VdbeAddOp2(v, OP_ResultRow, iReg, 1);
  95196. sqlite3VdbeSetNumCols(v, 1);
  95197. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  95198. break;
  95199. }
  95200. /*
  95201. ** PRAGMA [database.]locking_mode
  95202. ** PRAGMA [database.]locking_mode = (normal|exclusive)
  95203. */
  95204. case PragTyp_LOCKING_MODE: {
  95205. const char *zRet = "normal";
  95206. int eMode = getLockingMode(zRight);
  95207. if( pId2->n==0 && eMode==PAGER_LOCKINGMODE_QUERY ){
  95208. /* Simple "PRAGMA locking_mode;" statement. This is a query for
  95209. ** the current default locking mode (which may be different to
  95210. ** the locking-mode of the main database).
  95211. */
  95212. eMode = db->dfltLockMode;
  95213. }else{
  95214. Pager *pPager;
  95215. if( pId2->n==0 ){
  95216. /* This indicates that no database name was specified as part
  95217. ** of the PRAGMA command. In this case the locking-mode must be
  95218. ** set on all attached databases, as well as the main db file.
  95219. **
  95220. ** Also, the sqlite3.dfltLockMode variable is set so that
  95221. ** any subsequently attached databases also use the specified
  95222. ** locking mode.
  95223. */
  95224. int ii;
  95225. assert(pDb==&db->aDb[0]);
  95226. for(ii=2; ii<db->nDb; ii++){
  95227. pPager = sqlite3BtreePager(db->aDb[ii].pBt);
  95228. sqlite3PagerLockingMode(pPager, eMode);
  95229. }
  95230. db->dfltLockMode = (u8)eMode;
  95231. }
  95232. pPager = sqlite3BtreePager(pDb->pBt);
  95233. eMode = sqlite3PagerLockingMode(pPager, eMode);
  95234. }
  95235. assert( eMode==PAGER_LOCKINGMODE_NORMAL
  95236. || eMode==PAGER_LOCKINGMODE_EXCLUSIVE );
  95237. if( eMode==PAGER_LOCKINGMODE_EXCLUSIVE ){
  95238. zRet = "exclusive";
  95239. }
  95240. sqlite3VdbeSetNumCols(v, 1);
  95241. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "locking_mode", SQLITE_STATIC);
  95242. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zRet, 0);
  95243. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95244. break;
  95245. }
  95246. /*
  95247. ** PRAGMA [database.]journal_mode
  95248. ** PRAGMA [database.]journal_mode =
  95249. ** (delete|persist|off|truncate|memory|wal|off)
  95250. */
  95251. case PragTyp_JOURNAL_MODE: {
  95252. int eMode; /* One of the PAGER_JOURNALMODE_XXX symbols */
  95253. int ii; /* Loop counter */
  95254. sqlite3VdbeSetNumCols(v, 1);
  95255. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "journal_mode", SQLITE_STATIC);
  95256. if( zRight==0 ){
  95257. /* If there is no "=MODE" part of the pragma, do a query for the
  95258. ** current mode */
  95259. eMode = PAGER_JOURNALMODE_QUERY;
  95260. }else{
  95261. const char *zMode;
  95262. int n = sqlite3Strlen30(zRight);
  95263. for(eMode=0; (zMode = sqlite3JournalModename(eMode))!=0; eMode++){
  95264. if( sqlite3StrNICmp(zRight, zMode, n)==0 ) break;
  95265. }
  95266. if( !zMode ){
  95267. /* If the "=MODE" part does not match any known journal mode,
  95268. ** then do a query */
  95269. eMode = PAGER_JOURNALMODE_QUERY;
  95270. }
  95271. }
  95272. if( eMode==PAGER_JOURNALMODE_QUERY && pId2->n==0 ){
  95273. /* Convert "PRAGMA journal_mode" into "PRAGMA main.journal_mode" */
  95274. iDb = 0;
  95275. pId2->n = 1;
  95276. }
  95277. for(ii=db->nDb-1; ii>=0; ii--){
  95278. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  95279. sqlite3VdbeUsesBtree(v, ii);
  95280. sqlite3VdbeAddOp3(v, OP_JournalMode, ii, 1, eMode);
  95281. }
  95282. }
  95283. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95284. break;
  95285. }
  95286. /*
  95287. ** PRAGMA [database.]journal_size_limit
  95288. ** PRAGMA [database.]journal_size_limit=N
  95289. **
  95290. ** Get or set the size limit on rollback journal files.
  95291. */
  95292. case PragTyp_JOURNAL_SIZE_LIMIT: {
  95293. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  95294. i64 iLimit = -2;
  95295. if( zRight ){
  95296. sqlite3DecOrHexToI64(zRight, &iLimit);
  95297. if( iLimit<-1 ) iLimit = -1;
  95298. }
  95299. iLimit = sqlite3PagerJournalSizeLimit(pPager, iLimit);
  95300. returnSingleInt(pParse, "journal_size_limit", iLimit);
  95301. break;
  95302. }
  95303. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  95304. /*
  95305. ** PRAGMA [database.]auto_vacuum
  95306. ** PRAGMA [database.]auto_vacuum=N
  95307. **
  95308. ** Get or set the value of the database 'auto-vacuum' parameter.
  95309. ** The value is one of: 0 NONE 1 FULL 2 INCREMENTAL
  95310. */
  95311. #ifndef SQLITE_OMIT_AUTOVACUUM
  95312. case PragTyp_AUTO_VACUUM: {
  95313. Btree *pBt = pDb->pBt;
  95314. assert( pBt!=0 );
  95315. if( !zRight ){
  95316. returnSingleInt(pParse, "auto_vacuum", sqlite3BtreeGetAutoVacuum(pBt));
  95317. }else{
  95318. int eAuto = getAutoVacuum(zRight);
  95319. assert( eAuto>=0 && eAuto<=2 );
  95320. db->nextAutovac = (u8)eAuto;
  95321. /* Call SetAutoVacuum() to set initialize the internal auto and
  95322. ** incr-vacuum flags. This is required in case this connection
  95323. ** creates the database file. It is important that it is created
  95324. ** as an auto-vacuum capable db.
  95325. */
  95326. rc = sqlite3BtreeSetAutoVacuum(pBt, eAuto);
  95327. if( rc==SQLITE_OK && (eAuto==1 || eAuto==2) ){
  95328. /* When setting the auto_vacuum mode to either "full" or
  95329. ** "incremental", write the value of meta[6] in the database
  95330. ** file. Before writing to meta[6], check that meta[3] indicates
  95331. ** that this really is an auto-vacuum capable database.
  95332. */
  95333. static const int iLn = VDBE_OFFSET_LINENO(2);
  95334. static const VdbeOpList setMeta6[] = {
  95335. { OP_Transaction, 0, 1, 0}, /* 0 */
  95336. { OP_ReadCookie, 0, 1, BTREE_LARGEST_ROOT_PAGE},
  95337. { OP_If, 1, 0, 0}, /* 2 */
  95338. { OP_Halt, SQLITE_OK, OE_Abort, 0}, /* 3 */
  95339. { OP_Integer, 0, 1, 0}, /* 4 */
  95340. { OP_SetCookie, 0, BTREE_INCR_VACUUM, 1}, /* 5 */
  95341. };
  95342. int iAddr;
  95343. iAddr = sqlite3VdbeAddOpList(v, ArraySize(setMeta6), setMeta6, iLn);
  95344. sqlite3VdbeChangeP1(v, iAddr, iDb);
  95345. sqlite3VdbeChangeP1(v, iAddr+1, iDb);
  95346. sqlite3VdbeChangeP2(v, iAddr+2, iAddr+4);
  95347. sqlite3VdbeChangeP1(v, iAddr+4, eAuto-1);
  95348. sqlite3VdbeChangeP1(v, iAddr+5, iDb);
  95349. sqlite3VdbeUsesBtree(v, iDb);
  95350. }
  95351. }
  95352. break;
  95353. }
  95354. #endif
  95355. /*
  95356. ** PRAGMA [database.]incremental_vacuum(N)
  95357. **
  95358. ** Do N steps of incremental vacuuming on a database.
  95359. */
  95360. #ifndef SQLITE_OMIT_AUTOVACUUM
  95361. case PragTyp_INCREMENTAL_VACUUM: {
  95362. int iLimit, addr;
  95363. if( zRight==0 || !sqlite3GetInt32(zRight, &iLimit) || iLimit<=0 ){
  95364. iLimit = 0x7fffffff;
  95365. }
  95366. sqlite3BeginWriteOperation(pParse, 0, iDb);
  95367. sqlite3VdbeAddOp2(v, OP_Integer, iLimit, 1);
  95368. addr = sqlite3VdbeAddOp1(v, OP_IncrVacuum, iDb); VdbeCoverage(v);
  95369. sqlite3VdbeAddOp1(v, OP_ResultRow, 1);
  95370. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  95371. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr); VdbeCoverage(v);
  95372. sqlite3VdbeJumpHere(v, addr);
  95373. break;
  95374. }
  95375. #endif
  95376. #ifndef SQLITE_OMIT_PAGER_PRAGMAS
  95377. /*
  95378. ** PRAGMA [database.]cache_size
  95379. ** PRAGMA [database.]cache_size=N
  95380. **
  95381. ** The first form reports the current local setting for the
  95382. ** page cache size. The second form sets the local
  95383. ** page cache size value. If N is positive then that is the
  95384. ** number of pages in the cache. If N is negative, then the
  95385. ** number of pages is adjusted so that the cache uses -N kibibytes
  95386. ** of memory.
  95387. */
  95388. case PragTyp_CACHE_SIZE: {
  95389. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95390. if( !zRight ){
  95391. returnSingleInt(pParse, "cache_size", pDb->pSchema->cache_size);
  95392. }else{
  95393. int size = sqlite3Atoi(zRight);
  95394. pDb->pSchema->cache_size = size;
  95395. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  95396. }
  95397. break;
  95398. }
  95399. /*
  95400. ** PRAGMA [database.]mmap_size(N)
  95401. **
  95402. ** Used to set mapping size limit. The mapping size limit is
  95403. ** used to limit the aggregate size of all memory mapped regions of the
  95404. ** database file. If this parameter is set to zero, then memory mapping
  95405. ** is not used at all. If N is negative, then the default memory map
  95406. ** limit determined by sqlite3_config(SQLITE_CONFIG_MMAP_SIZE) is set.
  95407. ** The parameter N is measured in bytes.
  95408. **
  95409. ** This value is advisory. The underlying VFS is free to memory map
  95410. ** as little or as much as it wants. Except, if N is set to 0 then the
  95411. ** upper layers will never invoke the xFetch interfaces to the VFS.
  95412. */
  95413. case PragTyp_MMAP_SIZE: {
  95414. sqlite3_int64 sz;
  95415. #if SQLITE_MAX_MMAP_SIZE>0
  95416. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  95417. if( zRight ){
  95418. int ii;
  95419. sqlite3DecOrHexToI64(zRight, &sz);
  95420. if( sz<0 ) sz = sqlite3GlobalConfig.szMmap;
  95421. if( pId2->n==0 ) db->szMmap = sz;
  95422. for(ii=db->nDb-1; ii>=0; ii--){
  95423. if( db->aDb[ii].pBt && (ii==iDb || pId2->n==0) ){
  95424. sqlite3BtreeSetMmapLimit(db->aDb[ii].pBt, sz);
  95425. }
  95426. }
  95427. }
  95428. sz = -1;
  95429. rc = sqlite3_file_control(db, zDb, SQLITE_FCNTL_MMAP_SIZE, &sz);
  95430. #else
  95431. sz = 0;
  95432. rc = SQLITE_OK;
  95433. #endif
  95434. if( rc==SQLITE_OK ){
  95435. returnSingleInt(pParse, "mmap_size", sz);
  95436. }else if( rc!=SQLITE_NOTFOUND ){
  95437. pParse->nErr++;
  95438. pParse->rc = rc;
  95439. }
  95440. break;
  95441. }
  95442. /*
  95443. ** PRAGMA temp_store
  95444. ** PRAGMA temp_store = "default"|"memory"|"file"
  95445. **
  95446. ** Return or set the local value of the temp_store flag. Changing
  95447. ** the local value does not make changes to the disk file and the default
  95448. ** value will be restored the next time the database is opened.
  95449. **
  95450. ** Note that it is possible for the library compile-time options to
  95451. ** override this setting
  95452. */
  95453. case PragTyp_TEMP_STORE: {
  95454. if( !zRight ){
  95455. returnSingleInt(pParse, "temp_store", db->temp_store);
  95456. }else{
  95457. changeTempStorage(pParse, zRight);
  95458. }
  95459. break;
  95460. }
  95461. /*
  95462. ** PRAGMA temp_store_directory
  95463. ** PRAGMA temp_store_directory = ""|"directory_name"
  95464. **
  95465. ** Return or set the local value of the temp_store_directory flag. Changing
  95466. ** the value sets a specific directory to be used for temporary files.
  95467. ** Setting to a null string reverts to the default temporary directory search.
  95468. ** If temporary directory is changed, then invalidateTempStorage.
  95469. **
  95470. */
  95471. case PragTyp_TEMP_STORE_DIRECTORY: {
  95472. if( !zRight ){
  95473. if( sqlite3_temp_directory ){
  95474. sqlite3VdbeSetNumCols(v, 1);
  95475. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  95476. "temp_store_directory", SQLITE_STATIC);
  95477. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_temp_directory, 0);
  95478. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95479. }
  95480. }else{
  95481. #ifndef SQLITE_OMIT_WSD
  95482. if( zRight[0] ){
  95483. int res;
  95484. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  95485. if( rc!=SQLITE_OK || res==0 ){
  95486. sqlite3ErrorMsg(pParse, "not a writable directory");
  95487. goto pragma_out;
  95488. }
  95489. }
  95490. if( SQLITE_TEMP_STORE==0
  95491. || (SQLITE_TEMP_STORE==1 && db->temp_store<=1)
  95492. || (SQLITE_TEMP_STORE==2 && db->temp_store==1)
  95493. ){
  95494. invalidateTempStorage(pParse);
  95495. }
  95496. sqlite3_free(sqlite3_temp_directory);
  95497. if( zRight[0] ){
  95498. sqlite3_temp_directory = sqlite3_mprintf("%s", zRight);
  95499. }else{
  95500. sqlite3_temp_directory = 0;
  95501. }
  95502. #endif /* SQLITE_OMIT_WSD */
  95503. }
  95504. break;
  95505. }
  95506. #if SQLITE_OS_WIN
  95507. /*
  95508. ** PRAGMA data_store_directory
  95509. ** PRAGMA data_store_directory = ""|"directory_name"
  95510. **
  95511. ** Return or set the local value of the data_store_directory flag. Changing
  95512. ** the value sets a specific directory to be used for database files that
  95513. ** were specified with a relative pathname. Setting to a null string reverts
  95514. ** to the default database directory, which for database files specified with
  95515. ** a relative path will probably be based on the current directory for the
  95516. ** process. Database file specified with an absolute path are not impacted
  95517. ** by this setting, regardless of its value.
  95518. **
  95519. */
  95520. case PragTyp_DATA_STORE_DIRECTORY: {
  95521. if( !zRight ){
  95522. if( sqlite3_data_directory ){
  95523. sqlite3VdbeSetNumCols(v, 1);
  95524. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  95525. "data_store_directory", SQLITE_STATIC);
  95526. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, sqlite3_data_directory, 0);
  95527. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95528. }
  95529. }else{
  95530. #ifndef SQLITE_OMIT_WSD
  95531. if( zRight[0] ){
  95532. int res;
  95533. rc = sqlite3OsAccess(db->pVfs, zRight, SQLITE_ACCESS_READWRITE, &res);
  95534. if( rc!=SQLITE_OK || res==0 ){
  95535. sqlite3ErrorMsg(pParse, "not a writable directory");
  95536. goto pragma_out;
  95537. }
  95538. }
  95539. sqlite3_free(sqlite3_data_directory);
  95540. if( zRight[0] ){
  95541. sqlite3_data_directory = sqlite3_mprintf("%s", zRight);
  95542. }else{
  95543. sqlite3_data_directory = 0;
  95544. }
  95545. #endif /* SQLITE_OMIT_WSD */
  95546. }
  95547. break;
  95548. }
  95549. #endif
  95550. #if SQLITE_ENABLE_LOCKING_STYLE
  95551. /*
  95552. ** PRAGMA [database.]lock_proxy_file
  95553. ** PRAGMA [database.]lock_proxy_file = ":auto:"|"lock_file_path"
  95554. **
  95555. ** Return or set the value of the lock_proxy_file flag. Changing
  95556. ** the value sets a specific file to be used for database access locks.
  95557. **
  95558. */
  95559. case PragTyp_LOCK_PROXY_FILE: {
  95560. if( !zRight ){
  95561. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  95562. char *proxy_file_path = NULL;
  95563. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  95564. sqlite3OsFileControlHint(pFile, SQLITE_GET_LOCKPROXYFILE,
  95565. &proxy_file_path);
  95566. if( proxy_file_path ){
  95567. sqlite3VdbeSetNumCols(v, 1);
  95568. sqlite3VdbeSetColName(v, 0, COLNAME_NAME,
  95569. "lock_proxy_file", SQLITE_STATIC);
  95570. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, proxy_file_path, 0);
  95571. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  95572. }
  95573. }else{
  95574. Pager *pPager = sqlite3BtreePager(pDb->pBt);
  95575. sqlite3_file *pFile = sqlite3PagerFile(pPager);
  95576. int res;
  95577. if( zRight[0] ){
  95578. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  95579. zRight);
  95580. } else {
  95581. res=sqlite3OsFileControl(pFile, SQLITE_SET_LOCKPROXYFILE,
  95582. NULL);
  95583. }
  95584. if( res!=SQLITE_OK ){
  95585. sqlite3ErrorMsg(pParse, "failed to set lock proxy file");
  95586. goto pragma_out;
  95587. }
  95588. }
  95589. break;
  95590. }
  95591. #endif /* SQLITE_ENABLE_LOCKING_STYLE */
  95592. /*
  95593. ** PRAGMA [database.]synchronous
  95594. ** PRAGMA [database.]synchronous=OFF|ON|NORMAL|FULL
  95595. **
  95596. ** Return or set the local value of the synchronous flag. Changing
  95597. ** the local value does not make changes to the disk file and the
  95598. ** default value will be restored the next time the database is
  95599. ** opened.
  95600. */
  95601. case PragTyp_SYNCHRONOUS: {
  95602. if( !zRight ){
  95603. returnSingleInt(pParse, "synchronous", pDb->safety_level-1);
  95604. }else{
  95605. if( !db->autoCommit ){
  95606. sqlite3ErrorMsg(pParse,
  95607. "Safety level may not be changed inside a transaction");
  95608. }else{
  95609. pDb->safety_level = getSafetyLevel(zRight,0,1)+1;
  95610. setAllPagerFlags(db);
  95611. }
  95612. }
  95613. break;
  95614. }
  95615. #endif /* SQLITE_OMIT_PAGER_PRAGMAS */
  95616. #ifndef SQLITE_OMIT_FLAG_PRAGMAS
  95617. case PragTyp_FLAG: {
  95618. if( zRight==0 ){
  95619. returnSingleInt(pParse, aPragmaNames[mid].zName,
  95620. (db->flags & aPragmaNames[mid].iArg)!=0 );
  95621. }else{
  95622. int mask = aPragmaNames[mid].iArg; /* Mask of bits to set or clear. */
  95623. if( db->autoCommit==0 ){
  95624. /* Foreign key support may not be enabled or disabled while not
  95625. ** in auto-commit mode. */
  95626. mask &= ~(SQLITE_ForeignKeys);
  95627. }
  95628. #if SQLITE_USER_AUTHENTICATION
  95629. if( db->auth.authLevel==UAUTH_User ){
  95630. /* Do not allow non-admin users to modify the schema arbitrarily */
  95631. mask &= ~(SQLITE_WriteSchema);
  95632. }
  95633. #endif
  95634. if( sqlite3GetBoolean(zRight, 0) ){
  95635. db->flags |= mask;
  95636. }else{
  95637. db->flags &= ~mask;
  95638. if( mask==SQLITE_DeferFKs ) db->nDeferredImmCons = 0;
  95639. }
  95640. /* Many of the flag-pragmas modify the code generated by the SQL
  95641. ** compiler (eg. count_changes). So add an opcode to expire all
  95642. ** compiled SQL statements after modifying a pragma value.
  95643. */
  95644. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  95645. setAllPagerFlags(db);
  95646. }
  95647. break;
  95648. }
  95649. #endif /* SQLITE_OMIT_FLAG_PRAGMAS */
  95650. #ifndef SQLITE_OMIT_SCHEMA_PRAGMAS
  95651. /*
  95652. ** PRAGMA table_info(<table>)
  95653. **
  95654. ** Return a single row for each column of the named table. The columns of
  95655. ** the returned data set are:
  95656. **
  95657. ** cid: Column id (numbered from left to right, starting at 0)
  95658. ** name: Column name
  95659. ** type: Column declaration type.
  95660. ** notnull: True if 'NOT NULL' is part of column declaration
  95661. ** dflt_value: The default value for the column, if any.
  95662. */
  95663. case PragTyp_TABLE_INFO: if( zRight ){
  95664. Table *pTab;
  95665. pTab = sqlite3FindTable(db, zRight, zDb);
  95666. if( pTab ){
  95667. int i, k;
  95668. int nHidden = 0;
  95669. Column *pCol;
  95670. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  95671. sqlite3VdbeSetNumCols(v, 6);
  95672. pParse->nMem = 6;
  95673. sqlite3CodeVerifySchema(pParse, iDb);
  95674. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "cid", SQLITE_STATIC);
  95675. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  95676. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "type", SQLITE_STATIC);
  95677. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "notnull", SQLITE_STATIC);
  95678. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "dflt_value", SQLITE_STATIC);
  95679. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "pk", SQLITE_STATIC);
  95680. sqlite3ViewGetColumnNames(pParse, pTab);
  95681. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  95682. if( IsHiddenColumn(pCol) ){
  95683. nHidden++;
  95684. continue;
  95685. }
  95686. sqlite3VdbeAddOp2(v, OP_Integer, i-nHidden, 1);
  95687. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pCol->zName, 0);
  95688. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  95689. pCol->zType ? pCol->zType : "", 0);
  95690. sqlite3VdbeAddOp2(v, OP_Integer, (pCol->notNull ? 1 : 0), 4);
  95691. if( pCol->zDflt ){
  95692. sqlite3VdbeAddOp4(v, OP_String8, 0, 5, 0, (char*)pCol->zDflt, 0);
  95693. }else{
  95694. sqlite3VdbeAddOp2(v, OP_Null, 0, 5);
  95695. }
  95696. if( (pCol->colFlags & COLFLAG_PRIMKEY)==0 ){
  95697. k = 0;
  95698. }else if( pPk==0 ){
  95699. k = 1;
  95700. }else{
  95701. for(k=1; ALWAYS(k<=pTab->nCol) && pPk->aiColumn[k-1]!=i; k++){}
  95702. }
  95703. sqlite3VdbeAddOp2(v, OP_Integer, k, 6);
  95704. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 6);
  95705. }
  95706. }
  95707. }
  95708. break;
  95709. case PragTyp_STATS: {
  95710. Index *pIdx;
  95711. HashElem *i;
  95712. v = sqlite3GetVdbe(pParse);
  95713. sqlite3VdbeSetNumCols(v, 4);
  95714. pParse->nMem = 4;
  95715. sqlite3CodeVerifySchema(pParse, iDb);
  95716. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  95717. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "index", SQLITE_STATIC);
  95718. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "width", SQLITE_STATIC);
  95719. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "height", SQLITE_STATIC);
  95720. for(i=sqliteHashFirst(&pDb->pSchema->tblHash); i; i=sqliteHashNext(i)){
  95721. Table *pTab = sqliteHashData(i);
  95722. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, pTab->zName, 0);
  95723. sqlite3VdbeAddOp2(v, OP_Null, 0, 2);
  95724. sqlite3VdbeAddOp2(v, OP_Integer,
  95725. (int)sqlite3LogEstToInt(pTab->szTabRow), 3);
  95726. sqlite3VdbeAddOp2(v, OP_Integer,
  95727. (int)sqlite3LogEstToInt(pTab->nRowLogEst), 4);
  95728. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  95729. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  95730. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  95731. sqlite3VdbeAddOp2(v, OP_Integer,
  95732. (int)sqlite3LogEstToInt(pIdx->szIdxRow), 3);
  95733. sqlite3VdbeAddOp2(v, OP_Integer,
  95734. (int)sqlite3LogEstToInt(pIdx->aiRowLogEst[0]), 4);
  95735. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 4);
  95736. }
  95737. }
  95738. }
  95739. break;
  95740. case PragTyp_INDEX_INFO: if( zRight ){
  95741. Index *pIdx;
  95742. Table *pTab;
  95743. pIdx = sqlite3FindIndex(db, zRight, zDb);
  95744. if( pIdx ){
  95745. int i;
  95746. pTab = pIdx->pTable;
  95747. sqlite3VdbeSetNumCols(v, 3);
  95748. pParse->nMem = 3;
  95749. sqlite3CodeVerifySchema(pParse, iDb);
  95750. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seqno", SQLITE_STATIC);
  95751. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "cid", SQLITE_STATIC);
  95752. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "name", SQLITE_STATIC);
  95753. for(i=0; i<pIdx->nKeyCol; i++){
  95754. i16 cnum = pIdx->aiColumn[i];
  95755. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  95756. sqlite3VdbeAddOp2(v, OP_Integer, cnum, 2);
  95757. assert( pTab->nCol>cnum );
  95758. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pTab->aCol[cnum].zName, 0);
  95759. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  95760. }
  95761. }
  95762. }
  95763. break;
  95764. case PragTyp_INDEX_LIST: if( zRight ){
  95765. Index *pIdx;
  95766. Table *pTab;
  95767. int i;
  95768. pTab = sqlite3FindTable(db, zRight, zDb);
  95769. if( pTab ){
  95770. v = sqlite3GetVdbe(pParse);
  95771. sqlite3VdbeSetNumCols(v, 3);
  95772. pParse->nMem = 3;
  95773. sqlite3CodeVerifySchema(pParse, iDb);
  95774. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  95775. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  95776. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "unique", SQLITE_STATIC);
  95777. for(pIdx=pTab->pIndex, i=0; pIdx; pIdx=pIdx->pNext, i++){
  95778. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  95779. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pIdx->zName, 0);
  95780. sqlite3VdbeAddOp2(v, OP_Integer, IsUniqueIndex(pIdx), 3);
  95781. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  95782. }
  95783. }
  95784. }
  95785. break;
  95786. case PragTyp_DATABASE_LIST: {
  95787. int i;
  95788. sqlite3VdbeSetNumCols(v, 3);
  95789. pParse->nMem = 3;
  95790. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  95791. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  95792. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "file", SQLITE_STATIC);
  95793. for(i=0; i<db->nDb; i++){
  95794. if( db->aDb[i].pBt==0 ) continue;
  95795. assert( db->aDb[i].zName!=0 );
  95796. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  95797. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, db->aDb[i].zName, 0);
  95798. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  95799. sqlite3BtreeGetFilename(db->aDb[i].pBt), 0);
  95800. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  95801. }
  95802. }
  95803. break;
  95804. case PragTyp_COLLATION_LIST: {
  95805. int i = 0;
  95806. HashElem *p;
  95807. sqlite3VdbeSetNumCols(v, 2);
  95808. pParse->nMem = 2;
  95809. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "seq", SQLITE_STATIC);
  95810. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "name", SQLITE_STATIC);
  95811. for(p=sqliteHashFirst(&db->aCollSeq); p; p=sqliteHashNext(p)){
  95812. CollSeq *pColl = (CollSeq *)sqliteHashData(p);
  95813. sqlite3VdbeAddOp2(v, OP_Integer, i++, 1);
  95814. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, pColl->zName, 0);
  95815. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  95816. }
  95817. }
  95818. break;
  95819. #endif /* SQLITE_OMIT_SCHEMA_PRAGMAS */
  95820. #ifndef SQLITE_OMIT_FOREIGN_KEY
  95821. case PragTyp_FOREIGN_KEY_LIST: if( zRight ){
  95822. FKey *pFK;
  95823. Table *pTab;
  95824. pTab = sqlite3FindTable(db, zRight, zDb);
  95825. if( pTab ){
  95826. v = sqlite3GetVdbe(pParse);
  95827. pFK = pTab->pFKey;
  95828. if( pFK ){
  95829. int i = 0;
  95830. sqlite3VdbeSetNumCols(v, 8);
  95831. pParse->nMem = 8;
  95832. sqlite3CodeVerifySchema(pParse, iDb);
  95833. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "id", SQLITE_STATIC);
  95834. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "seq", SQLITE_STATIC);
  95835. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "table", SQLITE_STATIC);
  95836. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "from", SQLITE_STATIC);
  95837. sqlite3VdbeSetColName(v, 4, COLNAME_NAME, "to", SQLITE_STATIC);
  95838. sqlite3VdbeSetColName(v, 5, COLNAME_NAME, "on_update", SQLITE_STATIC);
  95839. sqlite3VdbeSetColName(v, 6, COLNAME_NAME, "on_delete", SQLITE_STATIC);
  95840. sqlite3VdbeSetColName(v, 7, COLNAME_NAME, "match", SQLITE_STATIC);
  95841. while(pFK){
  95842. int j;
  95843. for(j=0; j<pFK->nCol; j++){
  95844. char *zCol = pFK->aCol[j].zCol;
  95845. char *zOnDelete = (char *)actionName(pFK->aAction[0]);
  95846. char *zOnUpdate = (char *)actionName(pFK->aAction[1]);
  95847. sqlite3VdbeAddOp2(v, OP_Integer, i, 1);
  95848. sqlite3VdbeAddOp2(v, OP_Integer, j, 2);
  95849. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pFK->zTo, 0);
  95850. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  95851. pTab->aCol[pFK->aCol[j].iFrom].zName, 0);
  95852. sqlite3VdbeAddOp4(v, zCol ? OP_String8 : OP_Null, 0, 5, 0, zCol, 0);
  95853. sqlite3VdbeAddOp4(v, OP_String8, 0, 6, 0, zOnUpdate, 0);
  95854. sqlite3VdbeAddOp4(v, OP_String8, 0, 7, 0, zOnDelete, 0);
  95855. sqlite3VdbeAddOp4(v, OP_String8, 0, 8, 0, "NONE", 0);
  95856. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 8);
  95857. }
  95858. ++i;
  95859. pFK = pFK->pNextFrom;
  95860. }
  95861. }
  95862. }
  95863. }
  95864. break;
  95865. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  95866. #ifndef SQLITE_OMIT_FOREIGN_KEY
  95867. #ifndef SQLITE_OMIT_TRIGGER
  95868. case PragTyp_FOREIGN_KEY_CHECK: {
  95869. FKey *pFK; /* A foreign key constraint */
  95870. Table *pTab; /* Child table contain "REFERENCES" keyword */
  95871. Table *pParent; /* Parent table that child points to */
  95872. Index *pIdx; /* Index in the parent table */
  95873. int i; /* Loop counter: Foreign key number for pTab */
  95874. int j; /* Loop counter: Field of the foreign key */
  95875. HashElem *k; /* Loop counter: Next table in schema */
  95876. int x; /* result variable */
  95877. int regResult; /* 3 registers to hold a result row */
  95878. int regKey; /* Register to hold key for checking the FK */
  95879. int regRow; /* Registers to hold a row from pTab */
  95880. int addrTop; /* Top of a loop checking foreign keys */
  95881. int addrOk; /* Jump here if the key is OK */
  95882. int *aiCols; /* child to parent column mapping */
  95883. regResult = pParse->nMem+1;
  95884. pParse->nMem += 4;
  95885. regKey = ++pParse->nMem;
  95886. regRow = ++pParse->nMem;
  95887. v = sqlite3GetVdbe(pParse);
  95888. sqlite3VdbeSetNumCols(v, 4);
  95889. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "table", SQLITE_STATIC);
  95890. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "rowid", SQLITE_STATIC);
  95891. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "parent", SQLITE_STATIC);
  95892. sqlite3VdbeSetColName(v, 3, COLNAME_NAME, "fkid", SQLITE_STATIC);
  95893. sqlite3CodeVerifySchema(pParse, iDb);
  95894. k = sqliteHashFirst(&db->aDb[iDb].pSchema->tblHash);
  95895. while( k ){
  95896. if( zRight ){
  95897. pTab = sqlite3LocateTable(pParse, 0, zRight, zDb);
  95898. k = 0;
  95899. }else{
  95900. pTab = (Table*)sqliteHashData(k);
  95901. k = sqliteHashNext(k);
  95902. }
  95903. if( pTab==0 || pTab->pFKey==0 ) continue;
  95904. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  95905. if( pTab->nCol+regRow>pParse->nMem ) pParse->nMem = pTab->nCol + regRow;
  95906. sqlite3OpenTable(pParse, 0, iDb, pTab, OP_OpenRead);
  95907. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult, 0, pTab->zName,
  95908. P4_TRANSIENT);
  95909. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  95910. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  95911. if( pParent==0 ) continue;
  95912. pIdx = 0;
  95913. sqlite3TableLock(pParse, iDb, pParent->tnum, 0, pParent->zName);
  95914. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, 0);
  95915. if( x==0 ){
  95916. if( pIdx==0 ){
  95917. sqlite3OpenTable(pParse, i, iDb, pParent, OP_OpenRead);
  95918. }else{
  95919. sqlite3VdbeAddOp3(v, OP_OpenRead, i, pIdx->tnum, iDb);
  95920. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  95921. }
  95922. }else{
  95923. k = 0;
  95924. break;
  95925. }
  95926. }
  95927. assert( pParse->nErr>0 || pFK==0 );
  95928. if( pFK ) break;
  95929. if( pParse->nTab<i ) pParse->nTab = i;
  95930. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, 0); VdbeCoverage(v);
  95931. for(i=1, pFK=pTab->pFKey; pFK; i++, pFK=pFK->pNextFrom){
  95932. pParent = sqlite3FindTable(db, pFK->zTo, zDb);
  95933. pIdx = 0;
  95934. aiCols = 0;
  95935. if( pParent ){
  95936. x = sqlite3FkLocateIndex(pParse, pParent, pFK, &pIdx, &aiCols);
  95937. assert( x==0 );
  95938. }
  95939. addrOk = sqlite3VdbeMakeLabel(v);
  95940. if( pParent && pIdx==0 ){
  95941. int iKey = pFK->aCol[0].iFrom;
  95942. assert( iKey>=0 && iKey<pTab->nCol );
  95943. if( iKey!=pTab->iPKey ){
  95944. sqlite3VdbeAddOp3(v, OP_Column, 0, iKey, regRow);
  95945. sqlite3ColumnDefault(v, pTab, iKey, regRow);
  95946. sqlite3VdbeAddOp2(v, OP_IsNull, regRow, addrOk); VdbeCoverage(v);
  95947. sqlite3VdbeAddOp2(v, OP_MustBeInt, regRow,
  95948. sqlite3VdbeCurrentAddr(v)+3); VdbeCoverage(v);
  95949. }else{
  95950. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regRow);
  95951. }
  95952. sqlite3VdbeAddOp3(v, OP_NotExists, i, 0, regRow); VdbeCoverage(v);
  95953. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrOk);
  95954. sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-2);
  95955. }else{
  95956. for(j=0; j<pFK->nCol; j++){
  95957. sqlite3ExprCodeGetColumnOfTable(v, pTab, 0,
  95958. aiCols ? aiCols[j] : pFK->aCol[j].iFrom, regRow+j);
  95959. sqlite3VdbeAddOp2(v, OP_IsNull, regRow+j, addrOk); VdbeCoverage(v);
  95960. }
  95961. if( pParent ){
  95962. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, pFK->nCol, regKey,
  95963. sqlite3IndexAffinityStr(v,pIdx), pFK->nCol);
  95964. sqlite3VdbeAddOp4Int(v, OP_Found, i, addrOk, regKey, 0);
  95965. VdbeCoverage(v);
  95966. }
  95967. }
  95968. sqlite3VdbeAddOp2(v, OP_Rowid, 0, regResult+1);
  95969. sqlite3VdbeAddOp4(v, OP_String8, 0, regResult+2, 0,
  95970. pFK->zTo, P4_TRANSIENT);
  95971. sqlite3VdbeAddOp2(v, OP_Integer, i-1, regResult+3);
  95972. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, 4);
  95973. sqlite3VdbeResolveLabel(v, addrOk);
  95974. sqlite3DbFree(db, aiCols);
  95975. }
  95976. sqlite3VdbeAddOp2(v, OP_Next, 0, addrTop+1); VdbeCoverage(v);
  95977. sqlite3VdbeJumpHere(v, addrTop);
  95978. }
  95979. }
  95980. break;
  95981. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  95982. #endif /* !defined(SQLITE_OMIT_FOREIGN_KEY) */
  95983. #ifndef NDEBUG
  95984. case PragTyp_PARSER_TRACE: {
  95985. if( zRight ){
  95986. if( sqlite3GetBoolean(zRight, 0) ){
  95987. sqlite3ParserTrace(stderr, "parser: ");
  95988. }else{
  95989. sqlite3ParserTrace(0, 0);
  95990. }
  95991. }
  95992. }
  95993. break;
  95994. #endif
  95995. /* Reinstall the LIKE and GLOB functions. The variant of LIKE
  95996. ** used will be case sensitive or not depending on the RHS.
  95997. */
  95998. case PragTyp_CASE_SENSITIVE_LIKE: {
  95999. if( zRight ){
  96000. sqlite3RegisterLikeFunctions(db, sqlite3GetBoolean(zRight, 0));
  96001. }
  96002. }
  96003. break;
  96004. #ifndef SQLITE_INTEGRITY_CHECK_ERROR_MAX
  96005. # define SQLITE_INTEGRITY_CHECK_ERROR_MAX 100
  96006. #endif
  96007. #ifndef SQLITE_OMIT_INTEGRITY_CHECK
  96008. /* Pragma "quick_check" is reduced version of
  96009. ** integrity_check designed to detect most database corruption
  96010. ** without most of the overhead of a full integrity-check.
  96011. */
  96012. case PragTyp_INTEGRITY_CHECK: {
  96013. int i, j, addr, mxErr;
  96014. /* Code that appears at the end of the integrity check. If no error
  96015. ** messages have been generated, output OK. Otherwise output the
  96016. ** error message
  96017. */
  96018. static const int iLn = VDBE_OFFSET_LINENO(2);
  96019. static const VdbeOpList endCode[] = {
  96020. { OP_IfNeg, 1, 0, 0}, /* 0 */
  96021. { OP_String8, 0, 3, 0}, /* 1 */
  96022. { OP_ResultRow, 3, 1, 0},
  96023. };
  96024. int isQuick = (sqlite3Tolower(zLeft[0])=='q');
  96025. /* If the PRAGMA command was of the form "PRAGMA <db>.integrity_check",
  96026. ** then iDb is set to the index of the database identified by <db>.
  96027. ** In this case, the integrity of database iDb only is verified by
  96028. ** the VDBE created below.
  96029. **
  96030. ** Otherwise, if the command was simply "PRAGMA integrity_check" (or
  96031. ** "PRAGMA quick_check"), then iDb is set to 0. In this case, set iDb
  96032. ** to -1 here, to indicate that the VDBE should verify the integrity
  96033. ** of all attached databases. */
  96034. assert( iDb>=0 );
  96035. assert( iDb==0 || pId2->z );
  96036. if( pId2->z==0 ) iDb = -1;
  96037. /* Initialize the VDBE program */
  96038. pParse->nMem = 6;
  96039. sqlite3VdbeSetNumCols(v, 1);
  96040. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "integrity_check", SQLITE_STATIC);
  96041. /* Set the maximum error count */
  96042. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  96043. if( zRight ){
  96044. sqlite3GetInt32(zRight, &mxErr);
  96045. if( mxErr<=0 ){
  96046. mxErr = SQLITE_INTEGRITY_CHECK_ERROR_MAX;
  96047. }
  96048. }
  96049. sqlite3VdbeAddOp2(v, OP_Integer, mxErr, 1); /* reg[1] holds errors left */
  96050. /* Do an integrity check on each database file */
  96051. for(i=0; i<db->nDb; i++){
  96052. HashElem *x;
  96053. Hash *pTbls;
  96054. int cnt = 0;
  96055. if( OMIT_TEMPDB && i==1 ) continue;
  96056. if( iDb>=0 && i!=iDb ) continue;
  96057. sqlite3CodeVerifySchema(pParse, i);
  96058. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Halt if out of errors */
  96059. VdbeCoverage(v);
  96060. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  96061. sqlite3VdbeJumpHere(v, addr);
  96062. /* Do an integrity check of the B-Tree
  96063. **
  96064. ** Begin by filling registers 2, 3, ... with the root pages numbers
  96065. ** for all tables and indices in the database.
  96066. */
  96067. assert( sqlite3SchemaMutexHeld(db, i, 0) );
  96068. pTbls = &db->aDb[i].pSchema->tblHash;
  96069. for(x=sqliteHashFirst(pTbls); x; x=sqliteHashNext(x)){
  96070. Table *pTab = sqliteHashData(x);
  96071. Index *pIdx;
  96072. if( HasRowid(pTab) ){
  96073. sqlite3VdbeAddOp2(v, OP_Integer, pTab->tnum, 2+cnt);
  96074. VdbeComment((v, "%s", pTab->zName));
  96075. cnt++;
  96076. }
  96077. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  96078. sqlite3VdbeAddOp2(v, OP_Integer, pIdx->tnum, 2+cnt);
  96079. VdbeComment((v, "%s", pIdx->zName));
  96080. cnt++;
  96081. }
  96082. }
  96083. /* Make sure sufficient number of registers have been allocated */
  96084. pParse->nMem = MAX( pParse->nMem, cnt+8 );
  96085. /* Do the b-tree integrity checks */
  96086. sqlite3VdbeAddOp3(v, OP_IntegrityCk, 2, cnt, 1);
  96087. sqlite3VdbeChangeP5(v, (u8)i);
  96088. addr = sqlite3VdbeAddOp1(v, OP_IsNull, 2); VdbeCoverage(v);
  96089. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  96090. sqlite3MPrintf(db, "*** in database %s ***\n", db->aDb[i].zName),
  96091. P4_DYNAMIC);
  96092. sqlite3VdbeAddOp3(v, OP_Move, 2, 4, 1);
  96093. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 2);
  96094. sqlite3VdbeAddOp2(v, OP_ResultRow, 2, 1);
  96095. sqlite3VdbeJumpHere(v, addr);
  96096. /* Make sure all the indices are constructed correctly.
  96097. */
  96098. for(x=sqliteHashFirst(pTbls); x && !isQuick; x=sqliteHashNext(x)){
  96099. Table *pTab = sqliteHashData(x);
  96100. Index *pIdx, *pPk;
  96101. Index *pPrior = 0;
  96102. int loopTop;
  96103. int iDataCur, iIdxCur;
  96104. int r1 = -1;
  96105. if( pTab->pIndex==0 ) continue;
  96106. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  96107. addr = sqlite3VdbeAddOp1(v, OP_IfPos, 1); /* Stop if out of errors */
  96108. VdbeCoverage(v);
  96109. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  96110. sqlite3VdbeJumpHere(v, addr);
  96111. sqlite3ExprCacheClear(pParse);
  96112. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenRead,
  96113. 1, 0, &iDataCur, &iIdxCur);
  96114. sqlite3VdbeAddOp2(v, OP_Integer, 0, 7);
  96115. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  96116. sqlite3VdbeAddOp2(v, OP_Integer, 0, 8+j); /* index entries counter */
  96117. }
  96118. pParse->nMem = MAX(pParse->nMem, 8+j);
  96119. sqlite3VdbeAddOp2(v, OP_Rewind, iDataCur, 0); VdbeCoverage(v);
  96120. loopTop = sqlite3VdbeAddOp2(v, OP_AddImm, 7, 1);
  96121. /* Verify that all NOT NULL columns really are NOT NULL */
  96122. for(j=0; j<pTab->nCol; j++){
  96123. char *zErr;
  96124. int jmp2, jmp3;
  96125. if( j==pTab->iPKey ) continue;
  96126. if( pTab->aCol[j].notNull==0 ) continue;
  96127. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, j, 3);
  96128. sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
  96129. jmp2 = sqlite3VdbeAddOp1(v, OP_NotNull, 3); VdbeCoverage(v);
  96130. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  96131. zErr = sqlite3MPrintf(db, "NULL value in %s.%s", pTab->zName,
  96132. pTab->aCol[j].zName);
  96133. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, zErr, P4_DYNAMIC);
  96134. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  96135. jmp3 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  96136. sqlite3VdbeAddOp0(v, OP_Halt);
  96137. sqlite3VdbeJumpHere(v, jmp2);
  96138. sqlite3VdbeJumpHere(v, jmp3);
  96139. }
  96140. /* Validate index entries for the current row */
  96141. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  96142. int jmp2, jmp3, jmp4, jmp5;
  96143. int ckUniq = sqlite3VdbeMakeLabel(v);
  96144. if( pPk==pIdx ) continue;
  96145. r1 = sqlite3GenerateIndexKey(pParse, pIdx, iDataCur, 0, 0, &jmp3,
  96146. pPrior, r1);
  96147. pPrior = pIdx;
  96148. sqlite3VdbeAddOp2(v, OP_AddImm, 8+j, 1); /* increment entry count */
  96149. /* Verify that an index entry exists for the current table row */
  96150. jmp2 = sqlite3VdbeAddOp4Int(v, OP_Found, iIdxCur+j, ckUniq, r1,
  96151. pIdx->nColumn); VdbeCoverage(v);
  96152. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  96153. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, "row ", P4_STATIC);
  96154. sqlite3VdbeAddOp3(v, OP_Concat, 7, 3, 3);
  96155. sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  96156. " missing from index ", P4_STATIC);
  96157. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  96158. jmp5 = sqlite3VdbeAddOp4(v, OP_String8, 0, 4, 0,
  96159. pIdx->zName, P4_TRANSIENT);
  96160. sqlite3VdbeAddOp3(v, OP_Concat, 4, 3, 3);
  96161. sqlite3VdbeAddOp2(v, OP_ResultRow, 3, 1);
  96162. jmp4 = sqlite3VdbeAddOp1(v, OP_IfPos, 1); VdbeCoverage(v);
  96163. sqlite3VdbeAddOp0(v, OP_Halt);
  96164. sqlite3VdbeJumpHere(v, jmp2);
  96165. /* For UNIQUE indexes, verify that only one entry exists with the
  96166. ** current key. The entry is unique if (1) any column is NULL
  96167. ** or (2) the next entry has a different key */
  96168. if( IsUniqueIndex(pIdx) ){
  96169. int uniqOk = sqlite3VdbeMakeLabel(v);
  96170. int jmp6;
  96171. int kk;
  96172. for(kk=0; kk<pIdx->nKeyCol; kk++){
  96173. int iCol = pIdx->aiColumn[kk];
  96174. assert( iCol>=0 && iCol<pTab->nCol );
  96175. if( pTab->aCol[iCol].notNull ) continue;
  96176. sqlite3VdbeAddOp2(v, OP_IsNull, r1+kk, uniqOk);
  96177. VdbeCoverage(v);
  96178. }
  96179. jmp6 = sqlite3VdbeAddOp1(v, OP_Next, iIdxCur+j); VdbeCoverage(v);
  96180. sqlite3VdbeAddOp2(v, OP_Goto, 0, uniqOk);
  96181. sqlite3VdbeJumpHere(v, jmp6);
  96182. sqlite3VdbeAddOp4Int(v, OP_IdxGT, iIdxCur+j, uniqOk, r1,
  96183. pIdx->nKeyCol); VdbeCoverage(v);
  96184. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1); /* Decrement error limit */
  96185. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0,
  96186. "non-unique entry in index ", P4_STATIC);
  96187. sqlite3VdbeAddOp2(v, OP_Goto, 0, jmp5);
  96188. sqlite3VdbeResolveLabel(v, uniqOk);
  96189. }
  96190. sqlite3VdbeJumpHere(v, jmp4);
  96191. sqlite3ResolvePartIdxLabel(pParse, jmp3);
  96192. }
  96193. sqlite3VdbeAddOp2(v, OP_Next, iDataCur, loopTop); VdbeCoverage(v);
  96194. sqlite3VdbeJumpHere(v, loopTop-1);
  96195. #ifndef SQLITE_OMIT_BTREECOUNT
  96196. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0,
  96197. "wrong # of entries in index ", P4_STATIC);
  96198. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  96199. if( pPk==pIdx ) continue;
  96200. addr = sqlite3VdbeCurrentAddr(v);
  96201. sqlite3VdbeAddOp2(v, OP_IfPos, 1, addr+2); VdbeCoverage(v);
  96202. sqlite3VdbeAddOp2(v, OP_Halt, 0, 0);
  96203. sqlite3VdbeAddOp2(v, OP_Count, iIdxCur+j, 3);
  96204. sqlite3VdbeAddOp3(v, OP_Eq, 8+j, addr+8, 3); VdbeCoverage(v);
  96205. sqlite3VdbeChangeP5(v, SQLITE_NOTNULL);
  96206. sqlite3VdbeAddOp2(v, OP_AddImm, 1, -1);
  96207. sqlite3VdbeAddOp4(v, OP_String8, 0, 3, 0, pIdx->zName, P4_TRANSIENT);
  96208. sqlite3VdbeAddOp3(v, OP_Concat, 3, 2, 7);
  96209. sqlite3VdbeAddOp2(v, OP_ResultRow, 7, 1);
  96210. }
  96211. #endif /* SQLITE_OMIT_BTREECOUNT */
  96212. }
  96213. }
  96214. addr = sqlite3VdbeAddOpList(v, ArraySize(endCode), endCode, iLn);
  96215. sqlite3VdbeChangeP3(v, addr, -mxErr);
  96216. sqlite3VdbeJumpHere(v, addr);
  96217. sqlite3VdbeChangeP4(v, addr+1, "ok", P4_STATIC);
  96218. }
  96219. break;
  96220. #endif /* SQLITE_OMIT_INTEGRITY_CHECK */
  96221. #ifndef SQLITE_OMIT_UTF16
  96222. /*
  96223. ** PRAGMA encoding
  96224. ** PRAGMA encoding = "utf-8"|"utf-16"|"utf-16le"|"utf-16be"
  96225. **
  96226. ** In its first form, this pragma returns the encoding of the main
  96227. ** database. If the database is not initialized, it is initialized now.
  96228. **
  96229. ** The second form of this pragma is a no-op if the main database file
  96230. ** has not already been initialized. In this case it sets the default
  96231. ** encoding that will be used for the main database file if a new file
  96232. ** is created. If an existing main database file is opened, then the
  96233. ** default text encoding for the existing database is used.
  96234. **
  96235. ** In all cases new databases created using the ATTACH command are
  96236. ** created to use the same default text encoding as the main database. If
  96237. ** the main database has not been initialized and/or created when ATTACH
  96238. ** is executed, this is done before the ATTACH operation.
  96239. **
  96240. ** In the second form this pragma sets the text encoding to be used in
  96241. ** new database files created using this database handle. It is only
  96242. ** useful if invoked immediately after the main database i
  96243. */
  96244. case PragTyp_ENCODING: {
  96245. static const struct EncName {
  96246. char *zName;
  96247. u8 enc;
  96248. } encnames[] = {
  96249. { "UTF8", SQLITE_UTF8 },
  96250. { "UTF-8", SQLITE_UTF8 }, /* Must be element [1] */
  96251. { "UTF-16le", SQLITE_UTF16LE }, /* Must be element [2] */
  96252. { "UTF-16be", SQLITE_UTF16BE }, /* Must be element [3] */
  96253. { "UTF16le", SQLITE_UTF16LE },
  96254. { "UTF16be", SQLITE_UTF16BE },
  96255. { "UTF-16", 0 }, /* SQLITE_UTF16NATIVE */
  96256. { "UTF16", 0 }, /* SQLITE_UTF16NATIVE */
  96257. { 0, 0 }
  96258. };
  96259. const struct EncName *pEnc;
  96260. if( !zRight ){ /* "PRAGMA encoding" */
  96261. if( sqlite3ReadSchema(pParse) ) goto pragma_out;
  96262. sqlite3VdbeSetNumCols(v, 1);
  96263. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "encoding", SQLITE_STATIC);
  96264. sqlite3VdbeAddOp2(v, OP_String8, 0, 1);
  96265. assert( encnames[SQLITE_UTF8].enc==SQLITE_UTF8 );
  96266. assert( encnames[SQLITE_UTF16LE].enc==SQLITE_UTF16LE );
  96267. assert( encnames[SQLITE_UTF16BE].enc==SQLITE_UTF16BE );
  96268. sqlite3VdbeChangeP4(v, -1, encnames[ENC(pParse->db)].zName, P4_STATIC);
  96269. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  96270. }else{ /* "PRAGMA encoding = XXX" */
  96271. /* Only change the value of sqlite.enc if the database handle is not
  96272. ** initialized. If the main database exists, the new sqlite.enc value
  96273. ** will be overwritten when the schema is next loaded. If it does not
  96274. ** already exists, it will be created to use the new encoding value.
  96275. */
  96276. if(
  96277. !(DbHasProperty(db, 0, DB_SchemaLoaded)) ||
  96278. DbHasProperty(db, 0, DB_Empty)
  96279. ){
  96280. for(pEnc=&encnames[0]; pEnc->zName; pEnc++){
  96281. if( 0==sqlite3StrICmp(zRight, pEnc->zName) ){
  96282. ENC(pParse->db) = pEnc->enc ? pEnc->enc : SQLITE_UTF16NATIVE;
  96283. break;
  96284. }
  96285. }
  96286. if( !pEnc->zName ){
  96287. sqlite3ErrorMsg(pParse, "unsupported encoding: %s", zRight);
  96288. }
  96289. }
  96290. }
  96291. }
  96292. break;
  96293. #endif /* SQLITE_OMIT_UTF16 */
  96294. #ifndef SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS
  96295. /*
  96296. ** PRAGMA [database.]schema_version
  96297. ** PRAGMA [database.]schema_version = <integer>
  96298. **
  96299. ** PRAGMA [database.]user_version
  96300. ** PRAGMA [database.]user_version = <integer>
  96301. **
  96302. ** PRAGMA [database.]freelist_count = <integer>
  96303. **
  96304. ** PRAGMA [database.]application_id
  96305. ** PRAGMA [database.]application_id = <integer>
  96306. **
  96307. ** The pragma's schema_version and user_version are used to set or get
  96308. ** the value of the schema-version and user-version, respectively. Both
  96309. ** the schema-version and the user-version are 32-bit signed integers
  96310. ** stored in the database header.
  96311. **
  96312. ** The schema-cookie is usually only manipulated internally by SQLite. It
  96313. ** is incremented by SQLite whenever the database schema is modified (by
  96314. ** creating or dropping a table or index). The schema version is used by
  96315. ** SQLite each time a query is executed to ensure that the internal cache
  96316. ** of the schema used when compiling the SQL query matches the schema of
  96317. ** the database against which the compiled query is actually executed.
  96318. ** Subverting this mechanism by using "PRAGMA schema_version" to modify
  96319. ** the schema-version is potentially dangerous and may lead to program
  96320. ** crashes or database corruption. Use with caution!
  96321. **
  96322. ** The user-version is not used internally by SQLite. It may be used by
  96323. ** applications for any purpose.
  96324. */
  96325. case PragTyp_HEADER_VALUE: {
  96326. int iCookie; /* Cookie index. 1 for schema-cookie, 6 for user-cookie. */
  96327. sqlite3VdbeUsesBtree(v, iDb);
  96328. switch( zLeft[0] ){
  96329. case 'a': case 'A':
  96330. iCookie = BTREE_APPLICATION_ID;
  96331. break;
  96332. case 'f': case 'F':
  96333. iCookie = BTREE_FREE_PAGE_COUNT;
  96334. break;
  96335. case 's': case 'S':
  96336. iCookie = BTREE_SCHEMA_VERSION;
  96337. break;
  96338. default:
  96339. iCookie = BTREE_USER_VERSION;
  96340. break;
  96341. }
  96342. if( zRight && iCookie!=BTREE_FREE_PAGE_COUNT ){
  96343. /* Write the specified cookie value */
  96344. static const VdbeOpList setCookie[] = {
  96345. { OP_Transaction, 0, 1, 0}, /* 0 */
  96346. { OP_Integer, 0, 1, 0}, /* 1 */
  96347. { OP_SetCookie, 0, 0, 1}, /* 2 */
  96348. };
  96349. int addr = sqlite3VdbeAddOpList(v, ArraySize(setCookie), setCookie, 0);
  96350. sqlite3VdbeChangeP1(v, addr, iDb);
  96351. sqlite3VdbeChangeP1(v, addr+1, sqlite3Atoi(zRight));
  96352. sqlite3VdbeChangeP1(v, addr+2, iDb);
  96353. sqlite3VdbeChangeP2(v, addr+2, iCookie);
  96354. }else{
  96355. /* Read the specified cookie value */
  96356. static const VdbeOpList readCookie[] = {
  96357. { OP_Transaction, 0, 0, 0}, /* 0 */
  96358. { OP_ReadCookie, 0, 1, 0}, /* 1 */
  96359. { OP_ResultRow, 1, 1, 0}
  96360. };
  96361. int addr = sqlite3VdbeAddOpList(v, ArraySize(readCookie), readCookie, 0);
  96362. sqlite3VdbeChangeP1(v, addr, iDb);
  96363. sqlite3VdbeChangeP1(v, addr+1, iDb);
  96364. sqlite3VdbeChangeP3(v, addr+1, iCookie);
  96365. sqlite3VdbeSetNumCols(v, 1);
  96366. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, zLeft, SQLITE_TRANSIENT);
  96367. }
  96368. }
  96369. break;
  96370. #endif /* SQLITE_OMIT_SCHEMA_VERSION_PRAGMAS */
  96371. #ifndef SQLITE_OMIT_COMPILEOPTION_DIAGS
  96372. /*
  96373. ** PRAGMA compile_options
  96374. **
  96375. ** Return the names of all compile-time options used in this build,
  96376. ** one option per row.
  96377. */
  96378. case PragTyp_COMPILE_OPTIONS: {
  96379. int i = 0;
  96380. const char *zOpt;
  96381. sqlite3VdbeSetNumCols(v, 1);
  96382. pParse->nMem = 1;
  96383. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "compile_option", SQLITE_STATIC);
  96384. while( (zOpt = sqlite3_compileoption_get(i++))!=0 ){
  96385. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, zOpt, 0);
  96386. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 1);
  96387. }
  96388. }
  96389. break;
  96390. #endif /* SQLITE_OMIT_COMPILEOPTION_DIAGS */
  96391. #ifndef SQLITE_OMIT_WAL
  96392. /*
  96393. ** PRAGMA [database.]wal_checkpoint = passive|full|restart
  96394. **
  96395. ** Checkpoint the database.
  96396. */
  96397. case PragTyp_WAL_CHECKPOINT: {
  96398. int iBt = (pId2->z?iDb:SQLITE_MAX_ATTACHED);
  96399. int eMode = SQLITE_CHECKPOINT_PASSIVE;
  96400. if( zRight ){
  96401. if( sqlite3StrICmp(zRight, "full")==0 ){
  96402. eMode = SQLITE_CHECKPOINT_FULL;
  96403. }else if( sqlite3StrICmp(zRight, "restart")==0 ){
  96404. eMode = SQLITE_CHECKPOINT_RESTART;
  96405. }
  96406. }
  96407. sqlite3VdbeSetNumCols(v, 3);
  96408. pParse->nMem = 3;
  96409. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "busy", SQLITE_STATIC);
  96410. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "log", SQLITE_STATIC);
  96411. sqlite3VdbeSetColName(v, 2, COLNAME_NAME, "checkpointed", SQLITE_STATIC);
  96412. sqlite3VdbeAddOp3(v, OP_Checkpoint, iBt, eMode, 1);
  96413. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 3);
  96414. }
  96415. break;
  96416. /*
  96417. ** PRAGMA wal_autocheckpoint
  96418. ** PRAGMA wal_autocheckpoint = N
  96419. **
  96420. ** Configure a database connection to automatically checkpoint a database
  96421. ** after accumulating N frames in the log. Or query for the current value
  96422. ** of N.
  96423. */
  96424. case PragTyp_WAL_AUTOCHECKPOINT: {
  96425. if( zRight ){
  96426. sqlite3_wal_autocheckpoint(db, sqlite3Atoi(zRight));
  96427. }
  96428. returnSingleInt(pParse, "wal_autocheckpoint",
  96429. db->xWalCallback==sqlite3WalDefaultHook ?
  96430. SQLITE_PTR_TO_INT(db->pWalArg) : 0);
  96431. }
  96432. break;
  96433. #endif
  96434. /*
  96435. ** PRAGMA shrink_memory
  96436. **
  96437. ** This pragma attempts to free as much memory as possible from the
  96438. ** current database connection.
  96439. */
  96440. case PragTyp_SHRINK_MEMORY: {
  96441. sqlite3_db_release_memory(db);
  96442. break;
  96443. }
  96444. /*
  96445. ** PRAGMA busy_timeout
  96446. ** PRAGMA busy_timeout = N
  96447. **
  96448. ** Call sqlite3_busy_timeout(db, N). Return the current timeout value
  96449. ** if one is set. If no busy handler or a different busy handler is set
  96450. ** then 0 is returned. Setting the busy_timeout to 0 or negative
  96451. ** disables the timeout.
  96452. */
  96453. /*case PragTyp_BUSY_TIMEOUT*/ default: {
  96454. assert( aPragmaNames[mid].ePragTyp==PragTyp_BUSY_TIMEOUT );
  96455. if( zRight ){
  96456. sqlite3_busy_timeout(db, sqlite3Atoi(zRight));
  96457. }
  96458. returnSingleInt(pParse, "timeout", db->busyTimeout);
  96459. break;
  96460. }
  96461. /*
  96462. ** PRAGMA soft_heap_limit
  96463. ** PRAGMA soft_heap_limit = N
  96464. **
  96465. ** Call sqlite3_soft_heap_limit64(N). Return the result. If N is omitted,
  96466. ** use -1.
  96467. */
  96468. case PragTyp_SOFT_HEAP_LIMIT: {
  96469. sqlite3_int64 N;
  96470. if( zRight && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK ){
  96471. sqlite3_soft_heap_limit64(N);
  96472. }
  96473. returnSingleInt(pParse, "soft_heap_limit", sqlite3_soft_heap_limit64(-1));
  96474. break;
  96475. }
  96476. /*
  96477. ** PRAGMA threads
  96478. ** PRAGMA threads = N
  96479. **
  96480. ** Configure the maximum number of worker threads. Return the new
  96481. ** maximum, which might be less than requested.
  96482. */
  96483. case PragTyp_THREADS: {
  96484. sqlite3_int64 N;
  96485. if( zRight
  96486. && sqlite3DecOrHexToI64(zRight, &N)==SQLITE_OK
  96487. && N>=0
  96488. ){
  96489. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, (int)(N&0x7fffffff));
  96490. }
  96491. returnSingleInt(pParse, "threads",
  96492. sqlite3_limit(db, SQLITE_LIMIT_WORKER_THREADS, -1));
  96493. break;
  96494. }
  96495. #if defined(SQLITE_DEBUG) || defined(SQLITE_TEST)
  96496. /*
  96497. ** Report the current state of file logs for all databases
  96498. */
  96499. case PragTyp_LOCK_STATUS: {
  96500. static const char *const azLockName[] = {
  96501. "unlocked", "shared", "reserved", "pending", "exclusive"
  96502. };
  96503. int i;
  96504. sqlite3VdbeSetNumCols(v, 2);
  96505. pParse->nMem = 2;
  96506. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "database", SQLITE_STATIC);
  96507. sqlite3VdbeSetColName(v, 1, COLNAME_NAME, "status", SQLITE_STATIC);
  96508. for(i=0; i<db->nDb; i++){
  96509. Btree *pBt;
  96510. const char *zState = "unknown";
  96511. int j;
  96512. if( db->aDb[i].zName==0 ) continue;
  96513. sqlite3VdbeAddOp4(v, OP_String8, 0, 1, 0, db->aDb[i].zName, P4_STATIC);
  96514. pBt = db->aDb[i].pBt;
  96515. if( pBt==0 || sqlite3BtreePager(pBt)==0 ){
  96516. zState = "closed";
  96517. }else if( sqlite3_file_control(db, i ? db->aDb[i].zName : 0,
  96518. SQLITE_FCNTL_LOCKSTATE, &j)==SQLITE_OK ){
  96519. zState = azLockName[j];
  96520. }
  96521. sqlite3VdbeAddOp4(v, OP_String8, 0, 2, 0, zState, P4_STATIC);
  96522. sqlite3VdbeAddOp2(v, OP_ResultRow, 1, 2);
  96523. }
  96524. break;
  96525. }
  96526. #endif
  96527. #ifdef SQLITE_HAS_CODEC
  96528. case PragTyp_KEY: {
  96529. if( zRight ) sqlite3_key_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  96530. break;
  96531. }
  96532. case PragTyp_REKEY: {
  96533. if( zRight ) sqlite3_rekey_v2(db, zDb, zRight, sqlite3Strlen30(zRight));
  96534. break;
  96535. }
  96536. case PragTyp_HEXKEY: {
  96537. if( zRight ){
  96538. u8 iByte;
  96539. int i;
  96540. char zKey[40];
  96541. for(i=0, iByte=0; i<sizeof(zKey)*2 && sqlite3Isxdigit(zRight[i]); i++){
  96542. iByte = (iByte<<4) + sqlite3HexToInt(zRight[i]);
  96543. if( (i&1)!=0 ) zKey[i/2] = iByte;
  96544. }
  96545. if( (zLeft[3] & 0xf)==0xb ){
  96546. sqlite3_key_v2(db, zDb, zKey, i/2);
  96547. }else{
  96548. sqlite3_rekey_v2(db, zDb, zKey, i/2);
  96549. }
  96550. }
  96551. break;
  96552. }
  96553. #endif
  96554. #if defined(SQLITE_HAS_CODEC) || defined(SQLITE_ENABLE_CEROD)
  96555. case PragTyp_ACTIVATE_EXTENSIONS: if( zRight ){
  96556. #ifdef SQLITE_HAS_CODEC
  96557. if( sqlite3StrNICmp(zRight, "see-", 4)==0 ){
  96558. sqlite3_activate_see(&zRight[4]);
  96559. }
  96560. #endif
  96561. #ifdef SQLITE_ENABLE_CEROD
  96562. if( sqlite3StrNICmp(zRight, "cerod-", 6)==0 ){
  96563. sqlite3_activate_cerod(&zRight[6]);
  96564. }
  96565. #endif
  96566. }
  96567. break;
  96568. #endif
  96569. } /* End of the PRAGMA switch */
  96570. pragma_out:
  96571. sqlite3DbFree(db, zLeft);
  96572. sqlite3DbFree(db, zRight);
  96573. }
  96574. #endif /* SQLITE_OMIT_PRAGMA */
  96575. /************** End of pragma.c **********************************************/
  96576. /************** Begin file prepare.c *****************************************/
  96577. /*
  96578. ** 2005 May 25
  96579. **
  96580. ** The author disclaims copyright to this source code. In place of
  96581. ** a legal notice, here is a blessing:
  96582. **
  96583. ** May you do good and not evil.
  96584. ** May you find forgiveness for yourself and forgive others.
  96585. ** May you share freely, never taking more than you give.
  96586. **
  96587. *************************************************************************
  96588. ** This file contains the implementation of the sqlite3_prepare()
  96589. ** interface, and routines that contribute to loading the database schema
  96590. ** from disk.
  96591. */
  96592. /*
  96593. ** Fill the InitData structure with an error message that indicates
  96594. ** that the database is corrupt.
  96595. */
  96596. static void corruptSchema(
  96597. InitData *pData, /* Initialization context */
  96598. const char *zObj, /* Object being parsed at the point of error */
  96599. const char *zExtra /* Error information */
  96600. ){
  96601. sqlite3 *db = pData->db;
  96602. if( !db->mallocFailed && (db->flags & SQLITE_RecoveryMode)==0 ){
  96603. if( zObj==0 ) zObj = "?";
  96604. sqlite3SetString(pData->pzErrMsg, db,
  96605. "malformed database schema (%s)", zObj);
  96606. if( zExtra ){
  96607. *pData->pzErrMsg = sqlite3MAppendf(db, *pData->pzErrMsg,
  96608. "%s - %s", *pData->pzErrMsg, zExtra);
  96609. }
  96610. }
  96611. pData->rc = db->mallocFailed ? SQLITE_NOMEM : SQLITE_CORRUPT_BKPT;
  96612. }
  96613. /*
  96614. ** This is the callback routine for the code that initializes the
  96615. ** database. See sqlite3Init() below for additional information.
  96616. ** This routine is also called from the OP_ParseSchema opcode of the VDBE.
  96617. **
  96618. ** Each callback contains the following information:
  96619. **
  96620. ** argv[0] = name of thing being created
  96621. ** argv[1] = root page number for table or index. 0 for trigger or view.
  96622. ** argv[2] = SQL text for the CREATE statement.
  96623. **
  96624. */
  96625. SQLITE_PRIVATE int sqlite3InitCallback(void *pInit, int argc, char **argv, char **NotUsed){
  96626. InitData *pData = (InitData*)pInit;
  96627. sqlite3 *db = pData->db;
  96628. int iDb = pData->iDb;
  96629. assert( argc==3 );
  96630. UNUSED_PARAMETER2(NotUsed, argc);
  96631. assert( sqlite3_mutex_held(db->mutex) );
  96632. DbClearProperty(db, iDb, DB_Empty);
  96633. if( db->mallocFailed ){
  96634. corruptSchema(pData, argv[0], 0);
  96635. return 1;
  96636. }
  96637. assert( iDb>=0 && iDb<db->nDb );
  96638. if( argv==0 ) return 0; /* Might happen if EMPTY_RESULT_CALLBACKS are on */
  96639. if( argv[1]==0 ){
  96640. corruptSchema(pData, argv[0], 0);
  96641. }else if( argv[2] && argv[2][0] ){
  96642. /* Call the parser to process a CREATE TABLE, INDEX or VIEW.
  96643. ** But because db->init.busy is set to 1, no VDBE code is generated
  96644. ** or executed. All the parser does is build the internal data
  96645. ** structures that describe the table, index, or view.
  96646. */
  96647. int rc;
  96648. sqlite3_stmt *pStmt;
  96649. TESTONLY(int rcp); /* Return code from sqlite3_prepare() */
  96650. assert( db->init.busy );
  96651. db->init.iDb = iDb;
  96652. db->init.newTnum = sqlite3Atoi(argv[1]);
  96653. db->init.orphanTrigger = 0;
  96654. TESTONLY(rcp = ) sqlite3_prepare(db, argv[2], -1, &pStmt, 0);
  96655. rc = db->errCode;
  96656. assert( (rc&0xFF)==(rcp&0xFF) );
  96657. db->init.iDb = 0;
  96658. if( SQLITE_OK!=rc ){
  96659. if( db->init.orphanTrigger ){
  96660. assert( iDb==1 );
  96661. }else{
  96662. pData->rc = rc;
  96663. if( rc==SQLITE_NOMEM ){
  96664. db->mallocFailed = 1;
  96665. }else if( rc!=SQLITE_INTERRUPT && (rc&0xFF)!=SQLITE_LOCKED ){
  96666. corruptSchema(pData, argv[0], sqlite3_errmsg(db));
  96667. }
  96668. }
  96669. }
  96670. sqlite3_finalize(pStmt);
  96671. }else if( argv[0]==0 ){
  96672. corruptSchema(pData, 0, 0);
  96673. }else{
  96674. /* If the SQL column is blank it means this is an index that
  96675. ** was created to be the PRIMARY KEY or to fulfill a UNIQUE
  96676. ** constraint for a CREATE TABLE. The index should have already
  96677. ** been created when we processed the CREATE TABLE. All we have
  96678. ** to do here is record the root page number for that index.
  96679. */
  96680. Index *pIndex;
  96681. pIndex = sqlite3FindIndex(db, argv[0], db->aDb[iDb].zName);
  96682. if( pIndex==0 ){
  96683. /* This can occur if there exists an index on a TEMP table which
  96684. ** has the same name as another index on a permanent index. Since
  96685. ** the permanent table is hidden by the TEMP table, we can also
  96686. ** safely ignore the index on the permanent table.
  96687. */
  96688. /* Do Nothing */;
  96689. }else if( sqlite3GetInt32(argv[1], &pIndex->tnum)==0 ){
  96690. corruptSchema(pData, argv[0], "invalid rootpage");
  96691. }
  96692. }
  96693. return 0;
  96694. }
  96695. /*
  96696. ** Attempt to read the database schema and initialize internal
  96697. ** data structures for a single database file. The index of the
  96698. ** database file is given by iDb. iDb==0 is used for the main
  96699. ** database. iDb==1 should never be used. iDb>=2 is used for
  96700. ** auxiliary databases. Return one of the SQLITE_ error codes to
  96701. ** indicate success or failure.
  96702. */
  96703. static int sqlite3InitOne(sqlite3 *db, int iDb, char **pzErrMsg){
  96704. int rc;
  96705. int i;
  96706. #ifndef SQLITE_OMIT_DEPRECATED
  96707. int size;
  96708. #endif
  96709. Table *pTab;
  96710. Db *pDb;
  96711. char const *azArg[4];
  96712. int meta[5];
  96713. InitData initData;
  96714. char const *zMasterSchema;
  96715. char const *zMasterName;
  96716. int openedTransaction = 0;
  96717. /*
  96718. ** The master database table has a structure like this
  96719. */
  96720. static const char master_schema[] =
  96721. "CREATE TABLE sqlite_master(\n"
  96722. " type text,\n"
  96723. " name text,\n"
  96724. " tbl_name text,\n"
  96725. " rootpage integer,\n"
  96726. " sql text\n"
  96727. ")"
  96728. ;
  96729. #ifndef SQLITE_OMIT_TEMPDB
  96730. static const char temp_master_schema[] =
  96731. "CREATE TEMP TABLE sqlite_temp_master(\n"
  96732. " type text,\n"
  96733. " name text,\n"
  96734. " tbl_name text,\n"
  96735. " rootpage integer,\n"
  96736. " sql text\n"
  96737. ")"
  96738. ;
  96739. #else
  96740. #define temp_master_schema 0
  96741. #endif
  96742. assert( iDb>=0 && iDb<db->nDb );
  96743. assert( db->aDb[iDb].pSchema );
  96744. assert( sqlite3_mutex_held(db->mutex) );
  96745. assert( iDb==1 || sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
  96746. /* zMasterSchema and zInitScript are set to point at the master schema
  96747. ** and initialisation script appropriate for the database being
  96748. ** initialized. zMasterName is the name of the master table.
  96749. */
  96750. if( !OMIT_TEMPDB && iDb==1 ){
  96751. zMasterSchema = temp_master_schema;
  96752. }else{
  96753. zMasterSchema = master_schema;
  96754. }
  96755. zMasterName = SCHEMA_TABLE(iDb);
  96756. /* Construct the schema tables. */
  96757. azArg[0] = zMasterName;
  96758. azArg[1] = "1";
  96759. azArg[2] = zMasterSchema;
  96760. azArg[3] = 0;
  96761. initData.db = db;
  96762. initData.iDb = iDb;
  96763. initData.rc = SQLITE_OK;
  96764. initData.pzErrMsg = pzErrMsg;
  96765. sqlite3InitCallback(&initData, 3, (char **)azArg, 0);
  96766. if( initData.rc ){
  96767. rc = initData.rc;
  96768. goto error_out;
  96769. }
  96770. pTab = sqlite3FindTable(db, zMasterName, db->aDb[iDb].zName);
  96771. if( ALWAYS(pTab) ){
  96772. pTab->tabFlags |= TF_Readonly;
  96773. }
  96774. /* Create a cursor to hold the database open
  96775. */
  96776. pDb = &db->aDb[iDb];
  96777. if( pDb->pBt==0 ){
  96778. if( !OMIT_TEMPDB && ALWAYS(iDb==1) ){
  96779. DbSetProperty(db, 1, DB_SchemaLoaded);
  96780. }
  96781. return SQLITE_OK;
  96782. }
  96783. /* If there is not already a read-only (or read-write) transaction opened
  96784. ** on the b-tree database, open one now. If a transaction is opened, it
  96785. ** will be closed before this function returns. */
  96786. sqlite3BtreeEnter(pDb->pBt);
  96787. if( !sqlite3BtreeIsInReadTrans(pDb->pBt) ){
  96788. rc = sqlite3BtreeBeginTrans(pDb->pBt, 0);
  96789. if( rc!=SQLITE_OK ){
  96790. sqlite3SetString(pzErrMsg, db, "%s", sqlite3ErrStr(rc));
  96791. goto initone_error_out;
  96792. }
  96793. openedTransaction = 1;
  96794. }
  96795. /* Get the database meta information.
  96796. **
  96797. ** Meta values are as follows:
  96798. ** meta[0] Schema cookie. Changes with each schema change.
  96799. ** meta[1] File format of schema layer.
  96800. ** meta[2] Size of the page cache.
  96801. ** meta[3] Largest rootpage (auto/incr_vacuum mode)
  96802. ** meta[4] Db text encoding. 1:UTF-8 2:UTF-16LE 3:UTF-16BE
  96803. ** meta[5] User version
  96804. ** meta[6] Incremental vacuum mode
  96805. ** meta[7] unused
  96806. ** meta[8] unused
  96807. ** meta[9] unused
  96808. **
  96809. ** Note: The #defined SQLITE_UTF* symbols in sqliteInt.h correspond to
  96810. ** the possible values of meta[4].
  96811. */
  96812. for(i=0; i<ArraySize(meta); i++){
  96813. sqlite3BtreeGetMeta(pDb->pBt, i+1, (u32 *)&meta[i]);
  96814. }
  96815. pDb->pSchema->schema_cookie = meta[BTREE_SCHEMA_VERSION-1];
  96816. /* If opening a non-empty database, check the text encoding. For the
  96817. ** main database, set sqlite3.enc to the encoding of the main database.
  96818. ** For an attached db, it is an error if the encoding is not the same
  96819. ** as sqlite3.enc.
  96820. */
  96821. if( meta[BTREE_TEXT_ENCODING-1] ){ /* text encoding */
  96822. if( iDb==0 ){
  96823. #ifndef SQLITE_OMIT_UTF16
  96824. u8 encoding;
  96825. /* If opening the main database, set ENC(db). */
  96826. encoding = (u8)meta[BTREE_TEXT_ENCODING-1] & 3;
  96827. if( encoding==0 ) encoding = SQLITE_UTF8;
  96828. ENC(db) = encoding;
  96829. #else
  96830. ENC(db) = SQLITE_UTF8;
  96831. #endif
  96832. }else{
  96833. /* If opening an attached database, the encoding much match ENC(db) */
  96834. if( meta[BTREE_TEXT_ENCODING-1]!=ENC(db) ){
  96835. sqlite3SetString(pzErrMsg, db, "attached databases must use the same"
  96836. " text encoding as main database");
  96837. rc = SQLITE_ERROR;
  96838. goto initone_error_out;
  96839. }
  96840. }
  96841. }else{
  96842. DbSetProperty(db, iDb, DB_Empty);
  96843. }
  96844. pDb->pSchema->enc = ENC(db);
  96845. if( pDb->pSchema->cache_size==0 ){
  96846. #ifndef SQLITE_OMIT_DEPRECATED
  96847. size = sqlite3AbsInt32(meta[BTREE_DEFAULT_CACHE_SIZE-1]);
  96848. if( size==0 ){ size = SQLITE_DEFAULT_CACHE_SIZE; }
  96849. pDb->pSchema->cache_size = size;
  96850. #else
  96851. pDb->pSchema->cache_size = SQLITE_DEFAULT_CACHE_SIZE;
  96852. #endif
  96853. sqlite3BtreeSetCacheSize(pDb->pBt, pDb->pSchema->cache_size);
  96854. }
  96855. /*
  96856. ** file_format==1 Version 3.0.0.
  96857. ** file_format==2 Version 3.1.3. // ALTER TABLE ADD COLUMN
  96858. ** file_format==3 Version 3.1.4. // ditto but with non-NULL defaults
  96859. ** file_format==4 Version 3.3.0. // DESC indices. Boolean constants
  96860. */
  96861. pDb->pSchema->file_format = (u8)meta[BTREE_FILE_FORMAT-1];
  96862. if( pDb->pSchema->file_format==0 ){
  96863. pDb->pSchema->file_format = 1;
  96864. }
  96865. if( pDb->pSchema->file_format>SQLITE_MAX_FILE_FORMAT ){
  96866. sqlite3SetString(pzErrMsg, db, "unsupported file format");
  96867. rc = SQLITE_ERROR;
  96868. goto initone_error_out;
  96869. }
  96870. /* Ticket #2804: When we open a database in the newer file format,
  96871. ** clear the legacy_file_format pragma flag so that a VACUUM will
  96872. ** not downgrade the database and thus invalidate any descending
  96873. ** indices that the user might have created.
  96874. */
  96875. if( iDb==0 && meta[BTREE_FILE_FORMAT-1]>=4 ){
  96876. db->flags &= ~SQLITE_LegacyFileFmt;
  96877. }
  96878. /* Read the schema information out of the schema tables
  96879. */
  96880. assert( db->init.busy );
  96881. {
  96882. char *zSql;
  96883. zSql = sqlite3MPrintf(db,
  96884. "SELECT name, rootpage, sql FROM '%q'.%s ORDER BY rowid",
  96885. db->aDb[iDb].zName, zMasterName);
  96886. #ifndef SQLITE_OMIT_AUTHORIZATION
  96887. {
  96888. sqlite3_xauth xAuth;
  96889. xAuth = db->xAuth;
  96890. db->xAuth = 0;
  96891. #endif
  96892. rc = sqlite3_exec(db, zSql, sqlite3InitCallback, &initData, 0);
  96893. #ifndef SQLITE_OMIT_AUTHORIZATION
  96894. db->xAuth = xAuth;
  96895. }
  96896. #endif
  96897. if( rc==SQLITE_OK ) rc = initData.rc;
  96898. sqlite3DbFree(db, zSql);
  96899. #ifndef SQLITE_OMIT_ANALYZE
  96900. if( rc==SQLITE_OK ){
  96901. sqlite3AnalysisLoad(db, iDb);
  96902. }
  96903. #endif
  96904. }
  96905. if( db->mallocFailed ){
  96906. rc = SQLITE_NOMEM;
  96907. sqlite3ResetAllSchemasOfConnection(db);
  96908. }
  96909. if( rc==SQLITE_OK || (db->flags&SQLITE_RecoveryMode)){
  96910. /* Black magic: If the SQLITE_RecoveryMode flag is set, then consider
  96911. ** the schema loaded, even if errors occurred. In this situation the
  96912. ** current sqlite3_prepare() operation will fail, but the following one
  96913. ** will attempt to compile the supplied statement against whatever subset
  96914. ** of the schema was loaded before the error occurred. The primary
  96915. ** purpose of this is to allow access to the sqlite_master table
  96916. ** even when its contents have been corrupted.
  96917. */
  96918. DbSetProperty(db, iDb, DB_SchemaLoaded);
  96919. rc = SQLITE_OK;
  96920. }
  96921. /* Jump here for an error that occurs after successfully allocating
  96922. ** curMain and calling sqlite3BtreeEnter(). For an error that occurs
  96923. ** before that point, jump to error_out.
  96924. */
  96925. initone_error_out:
  96926. if( openedTransaction ){
  96927. sqlite3BtreeCommit(pDb->pBt);
  96928. }
  96929. sqlite3BtreeLeave(pDb->pBt);
  96930. error_out:
  96931. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  96932. db->mallocFailed = 1;
  96933. }
  96934. return rc;
  96935. }
  96936. /*
  96937. ** Initialize all database files - the main database file, the file
  96938. ** used to store temporary tables, and any additional database files
  96939. ** created using ATTACH statements. Return a success code. If an
  96940. ** error occurs, write an error message into *pzErrMsg.
  96941. **
  96942. ** After a database is initialized, the DB_SchemaLoaded bit is set
  96943. ** bit is set in the flags field of the Db structure. If the database
  96944. ** file was of zero-length, then the DB_Empty flag is also set.
  96945. */
  96946. SQLITE_PRIVATE int sqlite3Init(sqlite3 *db, char **pzErrMsg){
  96947. int i, rc;
  96948. int commit_internal = !(db->flags&SQLITE_InternChanges);
  96949. assert( sqlite3_mutex_held(db->mutex) );
  96950. assert( db->init.busy==0 );
  96951. rc = SQLITE_OK;
  96952. db->init.busy = 1;
  96953. for(i=0; rc==SQLITE_OK && i<db->nDb; i++){
  96954. if( DbHasProperty(db, i, DB_SchemaLoaded) || i==1 ) continue;
  96955. rc = sqlite3InitOne(db, i, pzErrMsg);
  96956. if( rc ){
  96957. sqlite3ResetOneSchema(db, i);
  96958. }
  96959. }
  96960. /* Once all the other databases have been initialized, load the schema
  96961. ** for the TEMP database. This is loaded last, as the TEMP database
  96962. ** schema may contain references to objects in other databases.
  96963. */
  96964. #ifndef SQLITE_OMIT_TEMPDB
  96965. assert( db->nDb>1 );
  96966. if( rc==SQLITE_OK && !DbHasProperty(db, 1, DB_SchemaLoaded) ){
  96967. rc = sqlite3InitOne(db, 1, pzErrMsg);
  96968. if( rc ){
  96969. sqlite3ResetOneSchema(db, 1);
  96970. }
  96971. }
  96972. #endif
  96973. db->init.busy = 0;
  96974. if( rc==SQLITE_OK && commit_internal ){
  96975. sqlite3CommitInternalChanges(db);
  96976. }
  96977. return rc;
  96978. }
  96979. /*
  96980. ** This routine is a no-op if the database schema is already initialized.
  96981. ** Otherwise, the schema is loaded. An error code is returned.
  96982. */
  96983. SQLITE_PRIVATE int sqlite3ReadSchema(Parse *pParse){
  96984. int rc = SQLITE_OK;
  96985. sqlite3 *db = pParse->db;
  96986. assert( sqlite3_mutex_held(db->mutex) );
  96987. if( !db->init.busy ){
  96988. rc = sqlite3Init(db, &pParse->zErrMsg);
  96989. }
  96990. if( rc!=SQLITE_OK ){
  96991. pParse->rc = rc;
  96992. pParse->nErr++;
  96993. }
  96994. return rc;
  96995. }
  96996. /*
  96997. ** Check schema cookies in all databases. If any cookie is out
  96998. ** of date set pParse->rc to SQLITE_SCHEMA. If all schema cookies
  96999. ** make no changes to pParse->rc.
  97000. */
  97001. static void schemaIsValid(Parse *pParse){
  97002. sqlite3 *db = pParse->db;
  97003. int iDb;
  97004. int rc;
  97005. int cookie;
  97006. assert( pParse->checkSchema );
  97007. assert( sqlite3_mutex_held(db->mutex) );
  97008. for(iDb=0; iDb<db->nDb; iDb++){
  97009. int openedTransaction = 0; /* True if a transaction is opened */
  97010. Btree *pBt = db->aDb[iDb].pBt; /* Btree database to read cookie from */
  97011. if( pBt==0 ) continue;
  97012. /* If there is not already a read-only (or read-write) transaction opened
  97013. ** on the b-tree database, open one now. If a transaction is opened, it
  97014. ** will be closed immediately after reading the meta-value. */
  97015. if( !sqlite3BtreeIsInReadTrans(pBt) ){
  97016. rc = sqlite3BtreeBeginTrans(pBt, 0);
  97017. if( rc==SQLITE_NOMEM || rc==SQLITE_IOERR_NOMEM ){
  97018. db->mallocFailed = 1;
  97019. }
  97020. if( rc!=SQLITE_OK ) return;
  97021. openedTransaction = 1;
  97022. }
  97023. /* Read the schema cookie from the database. If it does not match the
  97024. ** value stored as part of the in-memory schema representation,
  97025. ** set Parse.rc to SQLITE_SCHEMA. */
  97026. sqlite3BtreeGetMeta(pBt, BTREE_SCHEMA_VERSION, (u32 *)&cookie);
  97027. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  97028. if( cookie!=db->aDb[iDb].pSchema->schema_cookie ){
  97029. sqlite3ResetOneSchema(db, iDb);
  97030. pParse->rc = SQLITE_SCHEMA;
  97031. }
  97032. /* Close the transaction, if one was opened. */
  97033. if( openedTransaction ){
  97034. sqlite3BtreeCommit(pBt);
  97035. }
  97036. }
  97037. }
  97038. /*
  97039. ** Convert a schema pointer into the iDb index that indicates
  97040. ** which database file in db->aDb[] the schema refers to.
  97041. **
  97042. ** If the same database is attached more than once, the first
  97043. ** attached database is returned.
  97044. */
  97045. SQLITE_PRIVATE int sqlite3SchemaToIndex(sqlite3 *db, Schema *pSchema){
  97046. int i = -1000000;
  97047. /* If pSchema is NULL, then return -1000000. This happens when code in
  97048. ** expr.c is trying to resolve a reference to a transient table (i.e. one
  97049. ** created by a sub-select). In this case the return value of this
  97050. ** function should never be used.
  97051. **
  97052. ** We return -1000000 instead of the more usual -1 simply because using
  97053. ** -1000000 as the incorrect index into db->aDb[] is much
  97054. ** more likely to cause a segfault than -1 (of course there are assert()
  97055. ** statements too, but it never hurts to play the odds).
  97056. */
  97057. assert( sqlite3_mutex_held(db->mutex) );
  97058. if( pSchema ){
  97059. for(i=0; ALWAYS(i<db->nDb); i++){
  97060. if( db->aDb[i].pSchema==pSchema ){
  97061. break;
  97062. }
  97063. }
  97064. assert( i>=0 && i<db->nDb );
  97065. }
  97066. return i;
  97067. }
  97068. /*
  97069. ** Free all memory allocations in the pParse object
  97070. */
  97071. SQLITE_PRIVATE void sqlite3ParserReset(Parse *pParse){
  97072. if( pParse ){
  97073. sqlite3 *db = pParse->db;
  97074. sqlite3DbFree(db, pParse->aLabel);
  97075. sqlite3ExprListDelete(db, pParse->pConstExpr);
  97076. }
  97077. }
  97078. /*
  97079. ** Compile the UTF-8 encoded SQL statement zSql into a statement handle.
  97080. */
  97081. static int sqlite3Prepare(
  97082. sqlite3 *db, /* Database handle. */
  97083. const char *zSql, /* UTF-8 encoded SQL statement. */
  97084. int nBytes, /* Length of zSql in bytes. */
  97085. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  97086. Vdbe *pReprepare, /* VM being reprepared */
  97087. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97088. const char **pzTail /* OUT: End of parsed string */
  97089. ){
  97090. Parse *pParse; /* Parsing context */
  97091. char *zErrMsg = 0; /* Error message */
  97092. int rc = SQLITE_OK; /* Result code */
  97093. int i; /* Loop counter */
  97094. /* Allocate the parsing context */
  97095. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  97096. if( pParse==0 ){
  97097. rc = SQLITE_NOMEM;
  97098. goto end_prepare;
  97099. }
  97100. pParse->pReprepare = pReprepare;
  97101. assert( ppStmt && *ppStmt==0 );
  97102. assert( !db->mallocFailed );
  97103. assert( sqlite3_mutex_held(db->mutex) );
  97104. /* Check to verify that it is possible to get a read lock on all
  97105. ** database schemas. The inability to get a read lock indicates that
  97106. ** some other database connection is holding a write-lock, which in
  97107. ** turn means that the other connection has made uncommitted changes
  97108. ** to the schema.
  97109. **
  97110. ** Were we to proceed and prepare the statement against the uncommitted
  97111. ** schema changes and if those schema changes are subsequently rolled
  97112. ** back and different changes are made in their place, then when this
  97113. ** prepared statement goes to run the schema cookie would fail to detect
  97114. ** the schema change. Disaster would follow.
  97115. **
  97116. ** This thread is currently holding mutexes on all Btrees (because
  97117. ** of the sqlite3BtreeEnterAll() in sqlite3LockAndPrepare()) so it
  97118. ** is not possible for another thread to start a new schema change
  97119. ** while this routine is running. Hence, we do not need to hold
  97120. ** locks on the schema, we just need to make sure nobody else is
  97121. ** holding them.
  97122. **
  97123. ** Note that setting READ_UNCOMMITTED overrides most lock detection,
  97124. ** but it does *not* override schema lock detection, so this all still
  97125. ** works even if READ_UNCOMMITTED is set.
  97126. */
  97127. for(i=0; i<db->nDb; i++) {
  97128. Btree *pBt = db->aDb[i].pBt;
  97129. if( pBt ){
  97130. assert( sqlite3BtreeHoldsMutex(pBt) );
  97131. rc = sqlite3BtreeSchemaLocked(pBt);
  97132. if( rc ){
  97133. const char *zDb = db->aDb[i].zName;
  97134. sqlite3ErrorWithMsg(db, rc, "database schema is locked: %s", zDb);
  97135. testcase( db->flags & SQLITE_ReadUncommitted );
  97136. goto end_prepare;
  97137. }
  97138. }
  97139. }
  97140. sqlite3VtabUnlockList(db);
  97141. pParse->db = db;
  97142. pParse->nQueryLoop = 0; /* Logarithmic, so 0 really means 1 */
  97143. if( nBytes>=0 && (nBytes==0 || zSql[nBytes-1]!=0) ){
  97144. char *zSqlCopy;
  97145. int mxLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  97146. testcase( nBytes==mxLen );
  97147. testcase( nBytes==mxLen+1 );
  97148. if( nBytes>mxLen ){
  97149. sqlite3ErrorWithMsg(db, SQLITE_TOOBIG, "statement too long");
  97150. rc = sqlite3ApiExit(db, SQLITE_TOOBIG);
  97151. goto end_prepare;
  97152. }
  97153. zSqlCopy = sqlite3DbStrNDup(db, zSql, nBytes);
  97154. if( zSqlCopy ){
  97155. sqlite3RunParser(pParse, zSqlCopy, &zErrMsg);
  97156. sqlite3DbFree(db, zSqlCopy);
  97157. pParse->zTail = &zSql[pParse->zTail-zSqlCopy];
  97158. }else{
  97159. pParse->zTail = &zSql[nBytes];
  97160. }
  97161. }else{
  97162. sqlite3RunParser(pParse, zSql, &zErrMsg);
  97163. }
  97164. assert( 0==pParse->nQueryLoop );
  97165. if( db->mallocFailed ){
  97166. pParse->rc = SQLITE_NOMEM;
  97167. }
  97168. if( pParse->rc==SQLITE_DONE ) pParse->rc = SQLITE_OK;
  97169. if( pParse->checkSchema ){
  97170. schemaIsValid(pParse);
  97171. }
  97172. if( db->mallocFailed ){
  97173. pParse->rc = SQLITE_NOMEM;
  97174. }
  97175. if( pzTail ){
  97176. *pzTail = pParse->zTail;
  97177. }
  97178. rc = pParse->rc;
  97179. #ifndef SQLITE_OMIT_EXPLAIN
  97180. if( rc==SQLITE_OK && pParse->pVdbe && pParse->explain ){
  97181. static const char * const azColName[] = {
  97182. "addr", "opcode", "p1", "p2", "p3", "p4", "p5", "comment",
  97183. "selectid", "order", "from", "detail"
  97184. };
  97185. int iFirst, mx;
  97186. if( pParse->explain==2 ){
  97187. sqlite3VdbeSetNumCols(pParse->pVdbe, 4);
  97188. iFirst = 8;
  97189. mx = 12;
  97190. }else{
  97191. sqlite3VdbeSetNumCols(pParse->pVdbe, 8);
  97192. iFirst = 0;
  97193. mx = 8;
  97194. }
  97195. for(i=iFirst; i<mx; i++){
  97196. sqlite3VdbeSetColName(pParse->pVdbe, i-iFirst, COLNAME_NAME,
  97197. azColName[i], SQLITE_STATIC);
  97198. }
  97199. }
  97200. #endif
  97201. if( db->init.busy==0 ){
  97202. Vdbe *pVdbe = pParse->pVdbe;
  97203. sqlite3VdbeSetSql(pVdbe, zSql, (int)(pParse->zTail-zSql), saveSqlFlag);
  97204. }
  97205. if( pParse->pVdbe && (rc!=SQLITE_OK || db->mallocFailed) ){
  97206. sqlite3VdbeFinalize(pParse->pVdbe);
  97207. assert(!(*ppStmt));
  97208. }else{
  97209. *ppStmt = (sqlite3_stmt*)pParse->pVdbe;
  97210. }
  97211. if( zErrMsg ){
  97212. sqlite3ErrorWithMsg(db, rc, "%s", zErrMsg);
  97213. sqlite3DbFree(db, zErrMsg);
  97214. }else{
  97215. sqlite3Error(db, rc);
  97216. }
  97217. /* Delete any TriggerPrg structures allocated while parsing this statement. */
  97218. while( pParse->pTriggerPrg ){
  97219. TriggerPrg *pT = pParse->pTriggerPrg;
  97220. pParse->pTriggerPrg = pT->pNext;
  97221. sqlite3DbFree(db, pT);
  97222. }
  97223. end_prepare:
  97224. sqlite3ParserReset(pParse);
  97225. sqlite3StackFree(db, pParse);
  97226. rc = sqlite3ApiExit(db, rc);
  97227. assert( (rc&db->errMask)==rc );
  97228. return rc;
  97229. }
  97230. static int sqlite3LockAndPrepare(
  97231. sqlite3 *db, /* Database handle. */
  97232. const char *zSql, /* UTF-8 encoded SQL statement. */
  97233. int nBytes, /* Length of zSql in bytes. */
  97234. int saveSqlFlag, /* True to copy SQL text into the sqlite3_stmt */
  97235. Vdbe *pOld, /* VM being reprepared */
  97236. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97237. const char **pzTail /* OUT: End of parsed string */
  97238. ){
  97239. int rc;
  97240. assert( ppStmt!=0 );
  97241. *ppStmt = 0;
  97242. if( !sqlite3SafetyCheckOk(db) ){
  97243. return SQLITE_MISUSE_BKPT;
  97244. }
  97245. sqlite3_mutex_enter(db->mutex);
  97246. sqlite3BtreeEnterAll(db);
  97247. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  97248. if( rc==SQLITE_SCHEMA ){
  97249. sqlite3_finalize(*ppStmt);
  97250. rc = sqlite3Prepare(db, zSql, nBytes, saveSqlFlag, pOld, ppStmt, pzTail);
  97251. }
  97252. sqlite3BtreeLeaveAll(db);
  97253. sqlite3_mutex_leave(db->mutex);
  97254. assert( rc==SQLITE_OK || *ppStmt==0 );
  97255. return rc;
  97256. }
  97257. /*
  97258. ** Rerun the compilation of a statement after a schema change.
  97259. **
  97260. ** If the statement is successfully recompiled, return SQLITE_OK. Otherwise,
  97261. ** if the statement cannot be recompiled because another connection has
  97262. ** locked the sqlite3_master table, return SQLITE_LOCKED. If any other error
  97263. ** occurs, return SQLITE_SCHEMA.
  97264. */
  97265. SQLITE_PRIVATE int sqlite3Reprepare(Vdbe *p){
  97266. int rc;
  97267. sqlite3_stmt *pNew;
  97268. const char *zSql;
  97269. sqlite3 *db;
  97270. assert( sqlite3_mutex_held(sqlite3VdbeDb(p)->mutex) );
  97271. zSql = sqlite3_sql((sqlite3_stmt *)p);
  97272. assert( zSql!=0 ); /* Reprepare only called for prepare_v2() statements */
  97273. db = sqlite3VdbeDb(p);
  97274. assert( sqlite3_mutex_held(db->mutex) );
  97275. rc = sqlite3LockAndPrepare(db, zSql, -1, 0, p, &pNew, 0);
  97276. if( rc ){
  97277. if( rc==SQLITE_NOMEM ){
  97278. db->mallocFailed = 1;
  97279. }
  97280. assert( pNew==0 );
  97281. return rc;
  97282. }else{
  97283. assert( pNew!=0 );
  97284. }
  97285. sqlite3VdbeSwap((Vdbe*)pNew, p);
  97286. sqlite3TransferBindings(pNew, (sqlite3_stmt*)p);
  97287. sqlite3VdbeResetStepResult((Vdbe*)pNew);
  97288. sqlite3VdbeFinalize((Vdbe*)pNew);
  97289. return SQLITE_OK;
  97290. }
  97291. /*
  97292. ** Two versions of the official API. Legacy and new use. In the legacy
  97293. ** version, the original SQL text is not saved in the prepared statement
  97294. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  97295. ** sqlite3_step(). In the new version, the original SQL text is retained
  97296. ** and the statement is automatically recompiled if an schema change
  97297. ** occurs.
  97298. */
  97299. SQLITE_API int sqlite3_prepare(
  97300. sqlite3 *db, /* Database handle. */
  97301. const char *zSql, /* UTF-8 encoded SQL statement. */
  97302. int nBytes, /* Length of zSql in bytes. */
  97303. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97304. const char **pzTail /* OUT: End of parsed string */
  97305. ){
  97306. int rc;
  97307. rc = sqlite3LockAndPrepare(db,zSql,nBytes,0,0,ppStmt,pzTail);
  97308. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  97309. return rc;
  97310. }
  97311. SQLITE_API int sqlite3_prepare_v2(
  97312. sqlite3 *db, /* Database handle. */
  97313. const char *zSql, /* UTF-8 encoded SQL statement. */
  97314. int nBytes, /* Length of zSql in bytes. */
  97315. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97316. const char **pzTail /* OUT: End of parsed string */
  97317. ){
  97318. int rc;
  97319. rc = sqlite3LockAndPrepare(db,zSql,nBytes,1,0,ppStmt,pzTail);
  97320. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  97321. return rc;
  97322. }
  97323. #ifndef SQLITE_OMIT_UTF16
  97324. /*
  97325. ** Compile the UTF-16 encoded SQL statement zSql into a statement handle.
  97326. */
  97327. static int sqlite3Prepare16(
  97328. sqlite3 *db, /* Database handle. */
  97329. const void *zSql, /* UTF-16 encoded SQL statement. */
  97330. int nBytes, /* Length of zSql in bytes. */
  97331. int saveSqlFlag, /* True to save SQL text into the sqlite3_stmt */
  97332. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97333. const void **pzTail /* OUT: End of parsed string */
  97334. ){
  97335. /* This function currently works by first transforming the UTF-16
  97336. ** encoded string to UTF-8, then invoking sqlite3_prepare(). The
  97337. ** tricky bit is figuring out the pointer to return in *pzTail.
  97338. */
  97339. char *zSql8;
  97340. const char *zTail8 = 0;
  97341. int rc = SQLITE_OK;
  97342. assert( ppStmt );
  97343. *ppStmt = 0;
  97344. if( !sqlite3SafetyCheckOk(db) ){
  97345. return SQLITE_MISUSE_BKPT;
  97346. }
  97347. if( nBytes>=0 ){
  97348. int sz;
  97349. const char *z = (const char*)zSql;
  97350. for(sz=0; sz<nBytes && (z[sz]!=0 || z[sz+1]!=0); sz += 2){}
  97351. nBytes = sz;
  97352. }
  97353. sqlite3_mutex_enter(db->mutex);
  97354. zSql8 = sqlite3Utf16to8(db, zSql, nBytes, SQLITE_UTF16NATIVE);
  97355. if( zSql8 ){
  97356. rc = sqlite3LockAndPrepare(db, zSql8, -1, saveSqlFlag, 0, ppStmt, &zTail8);
  97357. }
  97358. if( zTail8 && pzTail ){
  97359. /* If sqlite3_prepare returns a tail pointer, we calculate the
  97360. ** equivalent pointer into the UTF-16 string by counting the unicode
  97361. ** characters between zSql8 and zTail8, and then returning a pointer
  97362. ** the same number of characters into the UTF-16 string.
  97363. */
  97364. int chars_parsed = sqlite3Utf8CharLen(zSql8, (int)(zTail8-zSql8));
  97365. *pzTail = (u8 *)zSql + sqlite3Utf16ByteLen(zSql, chars_parsed);
  97366. }
  97367. sqlite3DbFree(db, zSql8);
  97368. rc = sqlite3ApiExit(db, rc);
  97369. sqlite3_mutex_leave(db->mutex);
  97370. return rc;
  97371. }
  97372. /*
  97373. ** Two versions of the official API. Legacy and new use. In the legacy
  97374. ** version, the original SQL text is not saved in the prepared statement
  97375. ** and so if a schema change occurs, SQLITE_SCHEMA is returned by
  97376. ** sqlite3_step(). In the new version, the original SQL text is retained
  97377. ** and the statement is automatically recompiled if an schema change
  97378. ** occurs.
  97379. */
  97380. SQLITE_API int sqlite3_prepare16(
  97381. sqlite3 *db, /* Database handle. */
  97382. const void *zSql, /* UTF-16 encoded SQL statement. */
  97383. int nBytes, /* Length of zSql in bytes. */
  97384. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97385. const void **pzTail /* OUT: End of parsed string */
  97386. ){
  97387. int rc;
  97388. rc = sqlite3Prepare16(db,zSql,nBytes,0,ppStmt,pzTail);
  97389. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  97390. return rc;
  97391. }
  97392. SQLITE_API int sqlite3_prepare16_v2(
  97393. sqlite3 *db, /* Database handle. */
  97394. const void *zSql, /* UTF-16 encoded SQL statement. */
  97395. int nBytes, /* Length of zSql in bytes. */
  97396. sqlite3_stmt **ppStmt, /* OUT: A pointer to the prepared statement */
  97397. const void **pzTail /* OUT: End of parsed string */
  97398. ){
  97399. int rc;
  97400. rc = sqlite3Prepare16(db,zSql,nBytes,1,ppStmt,pzTail);
  97401. assert( rc==SQLITE_OK || ppStmt==0 || *ppStmt==0 ); /* VERIFY: F13021 */
  97402. return rc;
  97403. }
  97404. #endif /* SQLITE_OMIT_UTF16 */
  97405. /************** End of prepare.c *********************************************/
  97406. /************** Begin file select.c ******************************************/
  97407. /*
  97408. ** 2001 September 15
  97409. **
  97410. ** The author disclaims copyright to this source code. In place of
  97411. ** a legal notice, here is a blessing:
  97412. **
  97413. ** May you do good and not evil.
  97414. ** May you find forgiveness for yourself and forgive others.
  97415. ** May you share freely, never taking more than you give.
  97416. **
  97417. *************************************************************************
  97418. ** This file contains C code routines that are called by the parser
  97419. ** to handle SELECT statements in SQLite.
  97420. */
  97421. /*
  97422. ** Trace output macros
  97423. */
  97424. #if SELECTTRACE_ENABLED
  97425. /***/ int sqlite3SelectTrace = 0;
  97426. # define SELECTTRACE(K,P,S,X) \
  97427. if(sqlite3SelectTrace&(K)) \
  97428. sqlite3DebugPrintf("%*s%s.%p: ",(P)->nSelectIndent*2-2,"",(S)->zSelName,(S)),\
  97429. sqlite3DebugPrintf X
  97430. #else
  97431. # define SELECTTRACE(K,P,S,X)
  97432. #endif
  97433. /*
  97434. ** An instance of the following object is used to record information about
  97435. ** how to process the DISTINCT keyword, to simplify passing that information
  97436. ** into the selectInnerLoop() routine.
  97437. */
  97438. typedef struct DistinctCtx DistinctCtx;
  97439. struct DistinctCtx {
  97440. u8 isTnct; /* True if the DISTINCT keyword is present */
  97441. u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
  97442. int tabTnct; /* Ephemeral table used for DISTINCT processing */
  97443. int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
  97444. };
  97445. /*
  97446. ** An instance of the following object is used to record information about
  97447. ** the ORDER BY (or GROUP BY) clause of query is being coded.
  97448. */
  97449. typedef struct SortCtx SortCtx;
  97450. struct SortCtx {
  97451. ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
  97452. int nOBSat; /* Number of ORDER BY terms satisfied by indices */
  97453. int iECursor; /* Cursor number for the sorter */
  97454. int regReturn; /* Register holding block-output return address */
  97455. int labelBkOut; /* Start label for the block-output subroutine */
  97456. int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
  97457. u8 sortFlags; /* Zero or more SORTFLAG_* bits */
  97458. };
  97459. #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
  97460. /*
  97461. ** Delete all the content of a Select structure but do not deallocate
  97462. ** the select structure itself.
  97463. */
  97464. static void clearSelect(sqlite3 *db, Select *p){
  97465. sqlite3ExprListDelete(db, p->pEList);
  97466. sqlite3SrcListDelete(db, p->pSrc);
  97467. sqlite3ExprDelete(db, p->pWhere);
  97468. sqlite3ExprListDelete(db, p->pGroupBy);
  97469. sqlite3ExprDelete(db, p->pHaving);
  97470. sqlite3ExprListDelete(db, p->pOrderBy);
  97471. sqlite3SelectDelete(db, p->pPrior);
  97472. sqlite3ExprDelete(db, p->pLimit);
  97473. sqlite3ExprDelete(db, p->pOffset);
  97474. sqlite3WithDelete(db, p->pWith);
  97475. }
  97476. /*
  97477. ** Initialize a SelectDest structure.
  97478. */
  97479. SQLITE_PRIVATE void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
  97480. pDest->eDest = (u8)eDest;
  97481. pDest->iSDParm = iParm;
  97482. pDest->affSdst = 0;
  97483. pDest->iSdst = 0;
  97484. pDest->nSdst = 0;
  97485. }
  97486. /*
  97487. ** Allocate a new Select structure and return a pointer to that
  97488. ** structure.
  97489. */
  97490. SQLITE_PRIVATE Select *sqlite3SelectNew(
  97491. Parse *pParse, /* Parsing context */
  97492. ExprList *pEList, /* which columns to include in the result */
  97493. SrcList *pSrc, /* the FROM clause -- which tables to scan */
  97494. Expr *pWhere, /* the WHERE clause */
  97495. ExprList *pGroupBy, /* the GROUP BY clause */
  97496. Expr *pHaving, /* the HAVING clause */
  97497. ExprList *pOrderBy, /* the ORDER BY clause */
  97498. u16 selFlags, /* Flag parameters, such as SF_Distinct */
  97499. Expr *pLimit, /* LIMIT value. NULL means not used */
  97500. Expr *pOffset /* OFFSET value. NULL means no offset */
  97501. ){
  97502. Select *pNew;
  97503. Select standin;
  97504. sqlite3 *db = pParse->db;
  97505. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  97506. assert( db->mallocFailed || !pOffset || pLimit ); /* OFFSET implies LIMIT */
  97507. if( pNew==0 ){
  97508. assert( db->mallocFailed );
  97509. pNew = &standin;
  97510. memset(pNew, 0, sizeof(*pNew));
  97511. }
  97512. if( pEList==0 ){
  97513. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db,TK_ALL,0));
  97514. }
  97515. pNew->pEList = pEList;
  97516. if( pSrc==0 ) pSrc = sqlite3DbMallocZero(db, sizeof(*pSrc));
  97517. pNew->pSrc = pSrc;
  97518. pNew->pWhere = pWhere;
  97519. pNew->pGroupBy = pGroupBy;
  97520. pNew->pHaving = pHaving;
  97521. pNew->pOrderBy = pOrderBy;
  97522. pNew->selFlags = selFlags;
  97523. pNew->op = TK_SELECT;
  97524. pNew->pLimit = pLimit;
  97525. pNew->pOffset = pOffset;
  97526. assert( pOffset==0 || pLimit!=0 );
  97527. pNew->addrOpenEphm[0] = -1;
  97528. pNew->addrOpenEphm[1] = -1;
  97529. if( db->mallocFailed ) {
  97530. clearSelect(db, pNew);
  97531. if( pNew!=&standin ) sqlite3DbFree(db, pNew);
  97532. pNew = 0;
  97533. }else{
  97534. assert( pNew->pSrc!=0 || pParse->nErr>0 );
  97535. }
  97536. assert( pNew!=&standin );
  97537. return pNew;
  97538. }
  97539. #if SELECTTRACE_ENABLED
  97540. /*
  97541. ** Set the name of a Select object
  97542. */
  97543. SQLITE_PRIVATE void sqlite3SelectSetName(Select *p, const char *zName){
  97544. if( p && zName ){
  97545. sqlite3_snprintf(sizeof(p->zSelName), p->zSelName, "%s", zName);
  97546. }
  97547. }
  97548. #endif
  97549. /*
  97550. ** Delete the given Select structure and all of its substructures.
  97551. */
  97552. SQLITE_PRIVATE void sqlite3SelectDelete(sqlite3 *db, Select *p){
  97553. if( p ){
  97554. clearSelect(db, p);
  97555. sqlite3DbFree(db, p);
  97556. }
  97557. }
  97558. /*
  97559. ** Return a pointer to the right-most SELECT statement in a compound.
  97560. */
  97561. static Select *findRightmost(Select *p){
  97562. while( p->pNext ) p = p->pNext;
  97563. return p;
  97564. }
  97565. /*
  97566. ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
  97567. ** type of join. Return an integer constant that expresses that type
  97568. ** in terms of the following bit values:
  97569. **
  97570. ** JT_INNER
  97571. ** JT_CROSS
  97572. ** JT_OUTER
  97573. ** JT_NATURAL
  97574. ** JT_LEFT
  97575. ** JT_RIGHT
  97576. **
  97577. ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
  97578. **
  97579. ** If an illegal or unsupported join type is seen, then still return
  97580. ** a join type, but put an error in the pParse structure.
  97581. */
  97582. SQLITE_PRIVATE int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
  97583. int jointype = 0;
  97584. Token *apAll[3];
  97585. Token *p;
  97586. /* 0123456789 123456789 123456789 123 */
  97587. static const char zKeyText[] = "naturaleftouterightfullinnercross";
  97588. static const struct {
  97589. u8 i; /* Beginning of keyword text in zKeyText[] */
  97590. u8 nChar; /* Length of the keyword in characters */
  97591. u8 code; /* Join type mask */
  97592. } aKeyword[] = {
  97593. /* natural */ { 0, 7, JT_NATURAL },
  97594. /* left */ { 6, 4, JT_LEFT|JT_OUTER },
  97595. /* outer */ { 10, 5, JT_OUTER },
  97596. /* right */ { 14, 5, JT_RIGHT|JT_OUTER },
  97597. /* full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
  97598. /* inner */ { 23, 5, JT_INNER },
  97599. /* cross */ { 28, 5, JT_INNER|JT_CROSS },
  97600. };
  97601. int i, j;
  97602. apAll[0] = pA;
  97603. apAll[1] = pB;
  97604. apAll[2] = pC;
  97605. for(i=0; i<3 && apAll[i]; i++){
  97606. p = apAll[i];
  97607. for(j=0; j<ArraySize(aKeyword); j++){
  97608. if( p->n==aKeyword[j].nChar
  97609. && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
  97610. jointype |= aKeyword[j].code;
  97611. break;
  97612. }
  97613. }
  97614. testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
  97615. if( j>=ArraySize(aKeyword) ){
  97616. jointype |= JT_ERROR;
  97617. break;
  97618. }
  97619. }
  97620. if(
  97621. (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
  97622. (jointype & JT_ERROR)!=0
  97623. ){
  97624. const char *zSp = " ";
  97625. assert( pB!=0 );
  97626. if( pC==0 ){ zSp++; }
  97627. sqlite3ErrorMsg(pParse, "unknown or unsupported join type: "
  97628. "%T %T%s%T", pA, pB, zSp, pC);
  97629. jointype = JT_INNER;
  97630. }else if( (jointype & JT_OUTER)!=0
  97631. && (jointype & (JT_LEFT|JT_RIGHT))!=JT_LEFT ){
  97632. sqlite3ErrorMsg(pParse,
  97633. "RIGHT and FULL OUTER JOINs are not currently supported");
  97634. jointype = JT_INNER;
  97635. }
  97636. return jointype;
  97637. }
  97638. /*
  97639. ** Return the index of a column in a table. Return -1 if the column
  97640. ** is not contained in the table.
  97641. */
  97642. static int columnIndex(Table *pTab, const char *zCol){
  97643. int i;
  97644. for(i=0; i<pTab->nCol; i++){
  97645. if( sqlite3StrICmp(pTab->aCol[i].zName, zCol)==0 ) return i;
  97646. }
  97647. return -1;
  97648. }
  97649. /*
  97650. ** Search the first N tables in pSrc, from left to right, looking for a
  97651. ** table that has a column named zCol.
  97652. **
  97653. ** When found, set *piTab and *piCol to the table index and column index
  97654. ** of the matching column and return TRUE.
  97655. **
  97656. ** If not found, return FALSE.
  97657. */
  97658. static int tableAndColumnIndex(
  97659. SrcList *pSrc, /* Array of tables to search */
  97660. int N, /* Number of tables in pSrc->a[] to search */
  97661. const char *zCol, /* Name of the column we are looking for */
  97662. int *piTab, /* Write index of pSrc->a[] here */
  97663. int *piCol /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
  97664. ){
  97665. int i; /* For looping over tables in pSrc */
  97666. int iCol; /* Index of column matching zCol */
  97667. assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
  97668. for(i=0; i<N; i++){
  97669. iCol = columnIndex(pSrc->a[i].pTab, zCol);
  97670. if( iCol>=0 ){
  97671. if( piTab ){
  97672. *piTab = i;
  97673. *piCol = iCol;
  97674. }
  97675. return 1;
  97676. }
  97677. }
  97678. return 0;
  97679. }
  97680. /*
  97681. ** This function is used to add terms implied by JOIN syntax to the
  97682. ** WHERE clause expression of a SELECT statement. The new term, which
  97683. ** is ANDed with the existing WHERE clause, is of the form:
  97684. **
  97685. ** (tab1.col1 = tab2.col2)
  97686. **
  97687. ** where tab1 is the iSrc'th table in SrcList pSrc and tab2 is the
  97688. ** (iSrc+1)'th. Column col1 is column iColLeft of tab1, and col2 is
  97689. ** column iColRight of tab2.
  97690. */
  97691. static void addWhereTerm(
  97692. Parse *pParse, /* Parsing context */
  97693. SrcList *pSrc, /* List of tables in FROM clause */
  97694. int iLeft, /* Index of first table to join in pSrc */
  97695. int iColLeft, /* Index of column in first table */
  97696. int iRight, /* Index of second table in pSrc */
  97697. int iColRight, /* Index of column in second table */
  97698. int isOuterJoin, /* True if this is an OUTER join */
  97699. Expr **ppWhere /* IN/OUT: The WHERE clause to add to */
  97700. ){
  97701. sqlite3 *db = pParse->db;
  97702. Expr *pE1;
  97703. Expr *pE2;
  97704. Expr *pEq;
  97705. assert( iLeft<iRight );
  97706. assert( pSrc->nSrc>iRight );
  97707. assert( pSrc->a[iLeft].pTab );
  97708. assert( pSrc->a[iRight].pTab );
  97709. pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iColLeft);
  97710. pE2 = sqlite3CreateColumnExpr(db, pSrc, iRight, iColRight);
  97711. pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2, 0);
  97712. if( pEq && isOuterJoin ){
  97713. ExprSetProperty(pEq, EP_FromJoin);
  97714. assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
  97715. ExprSetVVAProperty(pEq, EP_NoReduce);
  97716. pEq->iRightJoinTable = (i16)pE2->iTable;
  97717. }
  97718. *ppWhere = sqlite3ExprAnd(db, *ppWhere, pEq);
  97719. }
  97720. /*
  97721. ** Set the EP_FromJoin property on all terms of the given expression.
  97722. ** And set the Expr.iRightJoinTable to iTable for every term in the
  97723. ** expression.
  97724. **
  97725. ** The EP_FromJoin property is used on terms of an expression to tell
  97726. ** the LEFT OUTER JOIN processing logic that this term is part of the
  97727. ** join restriction specified in the ON or USING clause and not a part
  97728. ** of the more general WHERE clause. These terms are moved over to the
  97729. ** WHERE clause during join processing but we need to remember that they
  97730. ** originated in the ON or USING clause.
  97731. **
  97732. ** The Expr.iRightJoinTable tells the WHERE clause processing that the
  97733. ** expression depends on table iRightJoinTable even if that table is not
  97734. ** explicitly mentioned in the expression. That information is needed
  97735. ** for cases like this:
  97736. **
  97737. ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
  97738. **
  97739. ** The where clause needs to defer the handling of the t1.x=5
  97740. ** term until after the t2 loop of the join. In that way, a
  97741. ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
  97742. ** defer the handling of t1.x=5, it will be processed immediately
  97743. ** after the t1 loop and rows with t1.x!=5 will never appear in
  97744. ** the output, which is incorrect.
  97745. */
  97746. static void setJoinExpr(Expr *p, int iTable){
  97747. while( p ){
  97748. ExprSetProperty(p, EP_FromJoin);
  97749. assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
  97750. ExprSetVVAProperty(p, EP_NoReduce);
  97751. p->iRightJoinTable = (i16)iTable;
  97752. setJoinExpr(p->pLeft, iTable);
  97753. p = p->pRight;
  97754. }
  97755. }
  97756. /*
  97757. ** This routine processes the join information for a SELECT statement.
  97758. ** ON and USING clauses are converted into extra terms of the WHERE clause.
  97759. ** NATURAL joins also create extra WHERE clause terms.
  97760. **
  97761. ** The terms of a FROM clause are contained in the Select.pSrc structure.
  97762. ** The left most table is the first entry in Select.pSrc. The right-most
  97763. ** table is the last entry. The join operator is held in the entry to
  97764. ** the left. Thus entry 0 contains the join operator for the join between
  97765. ** entries 0 and 1. Any ON or USING clauses associated with the join are
  97766. ** also attached to the left entry.
  97767. **
  97768. ** This routine returns the number of errors encountered.
  97769. */
  97770. static int sqliteProcessJoin(Parse *pParse, Select *p){
  97771. SrcList *pSrc; /* All tables in the FROM clause */
  97772. int i, j; /* Loop counters */
  97773. struct SrcList_item *pLeft; /* Left table being joined */
  97774. struct SrcList_item *pRight; /* Right table being joined */
  97775. pSrc = p->pSrc;
  97776. pLeft = &pSrc->a[0];
  97777. pRight = &pLeft[1];
  97778. for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
  97779. Table *pLeftTab = pLeft->pTab;
  97780. Table *pRightTab = pRight->pTab;
  97781. int isOuter;
  97782. if( NEVER(pLeftTab==0 || pRightTab==0) ) continue;
  97783. isOuter = (pRight->jointype & JT_OUTER)!=0;
  97784. /* When the NATURAL keyword is present, add WHERE clause terms for
  97785. ** every column that the two tables have in common.
  97786. */
  97787. if( pRight->jointype & JT_NATURAL ){
  97788. if( pRight->pOn || pRight->pUsing ){
  97789. sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
  97790. "an ON or USING clause", 0);
  97791. return 1;
  97792. }
  97793. for(j=0; j<pRightTab->nCol; j++){
  97794. char *zName; /* Name of column in the right table */
  97795. int iLeft; /* Matching left table */
  97796. int iLeftCol; /* Matching column in the left table */
  97797. zName = pRightTab->aCol[j].zName;
  97798. if( tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol) ){
  97799. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, j,
  97800. isOuter, &p->pWhere);
  97801. }
  97802. }
  97803. }
  97804. /* Disallow both ON and USING clauses in the same join
  97805. */
  97806. if( pRight->pOn && pRight->pUsing ){
  97807. sqlite3ErrorMsg(pParse, "cannot have both ON and USING "
  97808. "clauses in the same join");
  97809. return 1;
  97810. }
  97811. /* Add the ON clause to the end of the WHERE clause, connected by
  97812. ** an AND operator.
  97813. */
  97814. if( pRight->pOn ){
  97815. if( isOuter ) setJoinExpr(pRight->pOn, pRight->iCursor);
  97816. p->pWhere = sqlite3ExprAnd(pParse->db, p->pWhere, pRight->pOn);
  97817. pRight->pOn = 0;
  97818. }
  97819. /* Create extra terms on the WHERE clause for each column named
  97820. ** in the USING clause. Example: If the two tables to be joined are
  97821. ** A and B and the USING clause names X, Y, and Z, then add this
  97822. ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
  97823. ** Report an error if any column mentioned in the USING clause is
  97824. ** not contained in both tables to be joined.
  97825. */
  97826. if( pRight->pUsing ){
  97827. IdList *pList = pRight->pUsing;
  97828. for(j=0; j<pList->nId; j++){
  97829. char *zName; /* Name of the term in the USING clause */
  97830. int iLeft; /* Table on the left with matching column name */
  97831. int iLeftCol; /* Column number of matching column on the left */
  97832. int iRightCol; /* Column number of matching column on the right */
  97833. zName = pList->a[j].zName;
  97834. iRightCol = columnIndex(pRightTab, zName);
  97835. if( iRightCol<0
  97836. || !tableAndColumnIndex(pSrc, i+1, zName, &iLeft, &iLeftCol)
  97837. ){
  97838. sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
  97839. "not present in both tables", zName);
  97840. return 1;
  97841. }
  97842. addWhereTerm(pParse, pSrc, iLeft, iLeftCol, i+1, iRightCol,
  97843. isOuter, &p->pWhere);
  97844. }
  97845. }
  97846. }
  97847. return 0;
  97848. }
  97849. /* Forward reference */
  97850. static KeyInfo *keyInfoFromExprList(
  97851. Parse *pParse, /* Parsing context */
  97852. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  97853. int iStart, /* Begin with this column of pList */
  97854. int nExtra /* Add this many extra columns to the end */
  97855. );
  97856. /*
  97857. ** Generate code that will push the record in registers regData
  97858. ** through regData+nData-1 onto the sorter.
  97859. */
  97860. static void pushOntoSorter(
  97861. Parse *pParse, /* Parser context */
  97862. SortCtx *pSort, /* Information about the ORDER BY clause */
  97863. Select *pSelect, /* The whole SELECT statement */
  97864. int regData, /* First register holding data to be sorted */
  97865. int nData, /* Number of elements in the data array */
  97866. int nPrefixReg /* No. of reg prior to regData available for use */
  97867. ){
  97868. Vdbe *v = pParse->pVdbe; /* Stmt under construction */
  97869. int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
  97870. int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
  97871. int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
  97872. int regBase; /* Regs for sorter record */
  97873. int regRecord = ++pParse->nMem; /* Assembled sorter record */
  97874. int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
  97875. int op; /* Opcode to add sorter record to sorter */
  97876. assert( bSeq==0 || bSeq==1 );
  97877. if( nPrefixReg ){
  97878. assert( nPrefixReg==nExpr+bSeq );
  97879. regBase = regData - nExpr - bSeq;
  97880. }else{
  97881. regBase = pParse->nMem + 1;
  97882. pParse->nMem += nBase;
  97883. }
  97884. sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, SQLITE_ECEL_DUP);
  97885. if( bSeq ){
  97886. sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
  97887. }
  97888. if( nPrefixReg==0 ){
  97889. sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
  97890. }
  97891. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regRecord);
  97892. if( nOBSat>0 ){
  97893. int regPrevKey; /* The first nOBSat columns of the previous row */
  97894. int addrFirst; /* Address of the OP_IfNot opcode */
  97895. int addrJmp; /* Address of the OP_Jump opcode */
  97896. VdbeOp *pOp; /* Opcode that opens the sorter */
  97897. int nKey; /* Number of sorting key columns, including OP_Sequence */
  97898. KeyInfo *pKI; /* Original KeyInfo on the sorter table */
  97899. regPrevKey = pParse->nMem+1;
  97900. pParse->nMem += pSort->nOBSat;
  97901. nKey = nExpr - pSort->nOBSat + bSeq;
  97902. if( bSeq ){
  97903. addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
  97904. }else{
  97905. addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
  97906. }
  97907. VdbeCoverage(v);
  97908. sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
  97909. pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
  97910. if( pParse->db->mallocFailed ) return;
  97911. pOp->p2 = nKey + nData;
  97912. pKI = pOp->p4.pKeyInfo;
  97913. memset(pKI->aSortOrder, 0, pKI->nField); /* Makes OP_Jump below testable */
  97914. sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
  97915. pOp->p4.pKeyInfo = keyInfoFromExprList(pParse, pSort->pOrderBy, nOBSat, 1);
  97916. addrJmp = sqlite3VdbeCurrentAddr(v);
  97917. sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
  97918. pSort->labelBkOut = sqlite3VdbeMakeLabel(v);
  97919. pSort->regReturn = ++pParse->nMem;
  97920. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  97921. sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
  97922. sqlite3VdbeJumpHere(v, addrFirst);
  97923. sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
  97924. sqlite3VdbeJumpHere(v, addrJmp);
  97925. }
  97926. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  97927. op = OP_SorterInsert;
  97928. }else{
  97929. op = OP_IdxInsert;
  97930. }
  97931. sqlite3VdbeAddOp2(v, op, pSort->iECursor, regRecord);
  97932. if( pSelect->iLimit ){
  97933. int addr1, addr2;
  97934. int iLimit;
  97935. if( pSelect->iOffset ){
  97936. iLimit = pSelect->iOffset+1;
  97937. }else{
  97938. iLimit = pSelect->iLimit;
  97939. }
  97940. addr1 = sqlite3VdbeAddOp1(v, OP_IfZero, iLimit); VdbeCoverage(v);
  97941. sqlite3VdbeAddOp2(v, OP_AddImm, iLimit, -1);
  97942. addr2 = sqlite3VdbeAddOp0(v, OP_Goto);
  97943. sqlite3VdbeJumpHere(v, addr1);
  97944. sqlite3VdbeAddOp1(v, OP_Last, pSort->iECursor);
  97945. sqlite3VdbeAddOp1(v, OP_Delete, pSort->iECursor);
  97946. sqlite3VdbeJumpHere(v, addr2);
  97947. }
  97948. }
  97949. /*
  97950. ** Add code to implement the OFFSET
  97951. */
  97952. static void codeOffset(
  97953. Vdbe *v, /* Generate code into this VM */
  97954. int iOffset, /* Register holding the offset counter */
  97955. int iContinue /* Jump here to skip the current record */
  97956. ){
  97957. if( iOffset>0 ){
  97958. int addr;
  97959. addr = sqlite3VdbeAddOp3(v, OP_IfNeg, iOffset, 0, -1); VdbeCoverage(v);
  97960. sqlite3VdbeAddOp2(v, OP_Goto, 0, iContinue);
  97961. VdbeComment((v, "skip OFFSET records"));
  97962. sqlite3VdbeJumpHere(v, addr);
  97963. }
  97964. }
  97965. /*
  97966. ** Add code that will check to make sure the N registers starting at iMem
  97967. ** form a distinct entry. iTab is a sorting index that holds previously
  97968. ** seen combinations of the N values. A new entry is made in iTab
  97969. ** if the current N values are new.
  97970. **
  97971. ** A jump to addrRepeat is made and the N+1 values are popped from the
  97972. ** stack if the top N elements are not distinct.
  97973. */
  97974. static void codeDistinct(
  97975. Parse *pParse, /* Parsing and code generating context */
  97976. int iTab, /* A sorting index used to test for distinctness */
  97977. int addrRepeat, /* Jump to here if not distinct */
  97978. int N, /* Number of elements */
  97979. int iMem /* First element */
  97980. ){
  97981. Vdbe *v;
  97982. int r1;
  97983. v = pParse->pVdbe;
  97984. r1 = sqlite3GetTempReg(pParse);
  97985. sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, iMem, N); VdbeCoverage(v);
  97986. sqlite3VdbeAddOp3(v, OP_MakeRecord, iMem, N, r1);
  97987. sqlite3VdbeAddOp2(v, OP_IdxInsert, iTab, r1);
  97988. sqlite3ReleaseTempReg(pParse, r1);
  97989. }
  97990. #ifndef SQLITE_OMIT_SUBQUERY
  97991. /*
  97992. ** Generate an error message when a SELECT is used within a subexpression
  97993. ** (example: "a IN (SELECT * FROM table)") but it has more than 1 result
  97994. ** column. We do this in a subroutine because the error used to occur
  97995. ** in multiple places. (The error only occurs in one place now, but we
  97996. ** retain the subroutine to minimize code disruption.)
  97997. */
  97998. static int checkForMultiColumnSelectError(
  97999. Parse *pParse, /* Parse context. */
  98000. SelectDest *pDest, /* Destination of SELECT results */
  98001. int nExpr /* Number of result columns returned by SELECT */
  98002. ){
  98003. int eDest = pDest->eDest;
  98004. if( nExpr>1 && (eDest==SRT_Mem || eDest==SRT_Set) ){
  98005. sqlite3ErrorMsg(pParse, "only a single result allowed for "
  98006. "a SELECT that is part of an expression");
  98007. return 1;
  98008. }else{
  98009. return 0;
  98010. }
  98011. }
  98012. #endif
  98013. /*
  98014. ** This routine generates the code for the inside of the inner loop
  98015. ** of a SELECT.
  98016. **
  98017. ** If srcTab is negative, then the pEList expressions
  98018. ** are evaluated in order to get the data for this row. If srcTab is
  98019. ** zero or more, then data is pulled from srcTab and pEList is used only
  98020. ** to get number columns and the datatype for each column.
  98021. */
  98022. static void selectInnerLoop(
  98023. Parse *pParse, /* The parser context */
  98024. Select *p, /* The complete select statement being coded */
  98025. ExprList *pEList, /* List of values being extracted */
  98026. int srcTab, /* Pull data from this table */
  98027. SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
  98028. DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
  98029. SelectDest *pDest, /* How to dispose of the results */
  98030. int iContinue, /* Jump here to continue with next row */
  98031. int iBreak /* Jump here to break out of the inner loop */
  98032. ){
  98033. Vdbe *v = pParse->pVdbe;
  98034. int i;
  98035. int hasDistinct; /* True if the DISTINCT keyword is present */
  98036. int regResult; /* Start of memory holding result set */
  98037. int eDest = pDest->eDest; /* How to dispose of results */
  98038. int iParm = pDest->iSDParm; /* First argument to disposal method */
  98039. int nResultCol; /* Number of result columns */
  98040. int nPrefixReg = 0; /* Number of extra registers before regResult */
  98041. assert( v );
  98042. assert( pEList!=0 );
  98043. hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
  98044. if( pSort && pSort->pOrderBy==0 ) pSort = 0;
  98045. if( pSort==0 && !hasDistinct ){
  98046. assert( iContinue!=0 );
  98047. codeOffset(v, p->iOffset, iContinue);
  98048. }
  98049. /* Pull the requested columns.
  98050. */
  98051. nResultCol = pEList->nExpr;
  98052. if( pDest->iSdst==0 ){
  98053. if( pSort ){
  98054. nPrefixReg = pSort->pOrderBy->nExpr;
  98055. if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
  98056. pParse->nMem += nPrefixReg;
  98057. }
  98058. pDest->iSdst = pParse->nMem+1;
  98059. pParse->nMem += nResultCol;
  98060. }else if( pDest->iSdst+nResultCol > pParse->nMem ){
  98061. /* This is an error condition that can result, for example, when a SELECT
  98062. ** on the right-hand side of an INSERT contains more result columns than
  98063. ** there are columns in the table on the left. The error will be caught
  98064. ** and reported later. But we need to make sure enough memory is allocated
  98065. ** to avoid other spurious errors in the meantime. */
  98066. pParse->nMem += nResultCol;
  98067. }
  98068. pDest->nSdst = nResultCol;
  98069. regResult = pDest->iSdst;
  98070. if( srcTab>=0 ){
  98071. for(i=0; i<nResultCol; i++){
  98072. sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
  98073. VdbeComment((v, "%s", pEList->a[i].zName));
  98074. }
  98075. }else if( eDest!=SRT_Exists ){
  98076. /* If the destination is an EXISTS(...) expression, the actual
  98077. ** values returned by the SELECT are not required.
  98078. */
  98079. sqlite3ExprCodeExprList(pParse, pEList, regResult,
  98080. (eDest==SRT_Output||eDest==SRT_Coroutine)?SQLITE_ECEL_DUP:0);
  98081. }
  98082. /* If the DISTINCT keyword was present on the SELECT statement
  98083. ** and this row has been seen before, then do not make this row
  98084. ** part of the result.
  98085. */
  98086. if( hasDistinct ){
  98087. switch( pDistinct->eTnctType ){
  98088. case WHERE_DISTINCT_ORDERED: {
  98089. VdbeOp *pOp; /* No longer required OpenEphemeral instr. */
  98090. int iJump; /* Jump destination */
  98091. int regPrev; /* Previous row content */
  98092. /* Allocate space for the previous row */
  98093. regPrev = pParse->nMem+1;
  98094. pParse->nMem += nResultCol;
  98095. /* Change the OP_OpenEphemeral coded earlier to an OP_Null
  98096. ** sets the MEM_Cleared bit on the first register of the
  98097. ** previous value. This will cause the OP_Ne below to always
  98098. ** fail on the first iteration of the loop even if the first
  98099. ** row is all NULLs.
  98100. */
  98101. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  98102. pOp = sqlite3VdbeGetOp(v, pDistinct->addrTnct);
  98103. pOp->opcode = OP_Null;
  98104. pOp->p1 = 1;
  98105. pOp->p2 = regPrev;
  98106. iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
  98107. for(i=0; i<nResultCol; i++){
  98108. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
  98109. if( i<nResultCol-1 ){
  98110. sqlite3VdbeAddOp3(v, OP_Ne, regResult+i, iJump, regPrev+i);
  98111. VdbeCoverage(v);
  98112. }else{
  98113. sqlite3VdbeAddOp3(v, OP_Eq, regResult+i, iContinue, regPrev+i);
  98114. VdbeCoverage(v);
  98115. }
  98116. sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
  98117. sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
  98118. }
  98119. assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
  98120. sqlite3VdbeAddOp3(v, OP_Copy, regResult, regPrev, nResultCol-1);
  98121. break;
  98122. }
  98123. case WHERE_DISTINCT_UNIQUE: {
  98124. sqlite3VdbeChangeToNoop(v, pDistinct->addrTnct);
  98125. break;
  98126. }
  98127. default: {
  98128. assert( pDistinct->eTnctType==WHERE_DISTINCT_UNORDERED );
  98129. codeDistinct(pParse, pDistinct->tabTnct, iContinue, nResultCol, regResult);
  98130. break;
  98131. }
  98132. }
  98133. if( pSort==0 ){
  98134. codeOffset(v, p->iOffset, iContinue);
  98135. }
  98136. }
  98137. switch( eDest ){
  98138. /* In this mode, write each query result to the key of the temporary
  98139. ** table iParm.
  98140. */
  98141. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  98142. case SRT_Union: {
  98143. int r1;
  98144. r1 = sqlite3GetTempReg(pParse);
  98145. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
  98146. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  98147. sqlite3ReleaseTempReg(pParse, r1);
  98148. break;
  98149. }
  98150. /* Construct a record from the query result, but instead of
  98151. ** saving that record, use it as a key to delete elements from
  98152. ** the temporary table iParm.
  98153. */
  98154. case SRT_Except: {
  98155. sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
  98156. break;
  98157. }
  98158. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  98159. /* Store the result as data using a unique key.
  98160. */
  98161. case SRT_Fifo:
  98162. case SRT_DistFifo:
  98163. case SRT_Table:
  98164. case SRT_EphemTab: {
  98165. int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
  98166. testcase( eDest==SRT_Table );
  98167. testcase( eDest==SRT_EphemTab );
  98168. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
  98169. #ifndef SQLITE_OMIT_CTE
  98170. if( eDest==SRT_DistFifo ){
  98171. /* If the destination is DistFifo, then cursor (iParm+1) is open
  98172. ** on an ephemeral index. If the current row is already present
  98173. ** in the index, do not write it to the output. If not, add the
  98174. ** current row to the index and proceed with writing it to the
  98175. ** output table as well. */
  98176. int addr = sqlite3VdbeCurrentAddr(v) + 4;
  98177. sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0); VdbeCoverage(v);
  98178. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r1);
  98179. assert( pSort==0 );
  98180. }
  98181. #endif
  98182. if( pSort ){
  98183. pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, 1, nPrefixReg);
  98184. }else{
  98185. int r2 = sqlite3GetTempReg(pParse);
  98186. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
  98187. sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
  98188. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  98189. sqlite3ReleaseTempReg(pParse, r2);
  98190. }
  98191. sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
  98192. break;
  98193. }
  98194. #ifndef SQLITE_OMIT_SUBQUERY
  98195. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  98196. ** then there should be a single item on the stack. Write this
  98197. ** item into the set table with bogus data.
  98198. */
  98199. case SRT_Set: {
  98200. assert( nResultCol==1 );
  98201. pDest->affSdst =
  98202. sqlite3CompareAffinity(pEList->a[0].pExpr, pDest->affSdst);
  98203. if( pSort ){
  98204. /* At first glance you would think we could optimize out the
  98205. ** ORDER BY in this case since the order of entries in the set
  98206. ** does not matter. But there might be a LIMIT clause, in which
  98207. ** case the order does matter */
  98208. pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
  98209. }else{
  98210. int r1 = sqlite3GetTempReg(pParse);
  98211. sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult,1,r1, &pDest->affSdst, 1);
  98212. sqlite3ExprCacheAffinityChange(pParse, regResult, 1);
  98213. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  98214. sqlite3ReleaseTempReg(pParse, r1);
  98215. }
  98216. break;
  98217. }
  98218. /* If any row exist in the result set, record that fact and abort.
  98219. */
  98220. case SRT_Exists: {
  98221. sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
  98222. /* The LIMIT clause will terminate the loop for us */
  98223. break;
  98224. }
  98225. /* If this is a scalar select that is part of an expression, then
  98226. ** store the results in the appropriate memory cell and break out
  98227. ** of the scan loop.
  98228. */
  98229. case SRT_Mem: {
  98230. assert( nResultCol==1 );
  98231. if( pSort ){
  98232. pushOntoSorter(pParse, pSort, p, regResult, 1, nPrefixReg);
  98233. }else{
  98234. assert( regResult==iParm );
  98235. /* The LIMIT clause will jump out of the loop for us */
  98236. }
  98237. break;
  98238. }
  98239. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  98240. case SRT_Coroutine: /* Send data to a co-routine */
  98241. case SRT_Output: { /* Return the results */
  98242. testcase( eDest==SRT_Coroutine );
  98243. testcase( eDest==SRT_Output );
  98244. if( pSort ){
  98245. pushOntoSorter(pParse, pSort, p, regResult, nResultCol, nPrefixReg);
  98246. }else if( eDest==SRT_Coroutine ){
  98247. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  98248. }else{
  98249. sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
  98250. sqlite3ExprCacheAffinityChange(pParse, regResult, nResultCol);
  98251. }
  98252. break;
  98253. }
  98254. #ifndef SQLITE_OMIT_CTE
  98255. /* Write the results into a priority queue that is order according to
  98256. ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
  98257. ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
  98258. ** pSO->nExpr columns, then make sure all keys are unique by adding a
  98259. ** final OP_Sequence column. The last column is the record as a blob.
  98260. */
  98261. case SRT_DistQueue:
  98262. case SRT_Queue: {
  98263. int nKey;
  98264. int r1, r2, r3;
  98265. int addrTest = 0;
  98266. ExprList *pSO;
  98267. pSO = pDest->pOrderBy;
  98268. assert( pSO );
  98269. nKey = pSO->nExpr;
  98270. r1 = sqlite3GetTempReg(pParse);
  98271. r2 = sqlite3GetTempRange(pParse, nKey+2);
  98272. r3 = r2+nKey+1;
  98273. if( eDest==SRT_DistQueue ){
  98274. /* If the destination is DistQueue, then cursor (iParm+1) is open
  98275. ** on a second ephemeral index that holds all values every previously
  98276. ** added to the queue. */
  98277. addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
  98278. regResult, nResultCol);
  98279. VdbeCoverage(v);
  98280. }
  98281. sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
  98282. if( eDest==SRT_DistQueue ){
  98283. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
  98284. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  98285. }
  98286. for(i=0; i<nKey; i++){
  98287. sqlite3VdbeAddOp2(v, OP_SCopy,
  98288. regResult + pSO->a[i].u.x.iOrderByCol - 1,
  98289. r2+i);
  98290. }
  98291. sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
  98292. sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
  98293. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, r1);
  98294. if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
  98295. sqlite3ReleaseTempReg(pParse, r1);
  98296. sqlite3ReleaseTempRange(pParse, r2, nKey+2);
  98297. break;
  98298. }
  98299. #endif /* SQLITE_OMIT_CTE */
  98300. #if !defined(SQLITE_OMIT_TRIGGER)
  98301. /* Discard the results. This is used for SELECT statements inside
  98302. ** the body of a TRIGGER. The purpose of such selects is to call
  98303. ** user-defined functions that have side effects. We do not care
  98304. ** about the actual results of the select.
  98305. */
  98306. default: {
  98307. assert( eDest==SRT_Discard );
  98308. break;
  98309. }
  98310. #endif
  98311. }
  98312. /* Jump to the end of the loop if the LIMIT is reached. Except, if
  98313. ** there is a sorter, in which case the sorter has already limited
  98314. ** the output for us.
  98315. */
  98316. if( pSort==0 && p->iLimit ){
  98317. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
  98318. }
  98319. }
  98320. /*
  98321. ** Allocate a KeyInfo object sufficient for an index of N key columns and
  98322. ** X extra columns.
  98323. */
  98324. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
  98325. KeyInfo *p = sqlite3DbMallocZero(0,
  98326. sizeof(KeyInfo) + (N+X)*(sizeof(CollSeq*)+1));
  98327. if( p ){
  98328. p->aSortOrder = (u8*)&p->aColl[N+X];
  98329. p->nField = (u16)N;
  98330. p->nXField = (u16)X;
  98331. p->enc = ENC(db);
  98332. p->db = db;
  98333. p->nRef = 1;
  98334. }else{
  98335. db->mallocFailed = 1;
  98336. }
  98337. return p;
  98338. }
  98339. /*
  98340. ** Deallocate a KeyInfo object
  98341. */
  98342. SQLITE_PRIVATE void sqlite3KeyInfoUnref(KeyInfo *p){
  98343. if( p ){
  98344. assert( p->nRef>0 );
  98345. p->nRef--;
  98346. if( p->nRef==0 ) sqlite3DbFree(0, p);
  98347. }
  98348. }
  98349. /*
  98350. ** Make a new pointer to a KeyInfo object
  98351. */
  98352. SQLITE_PRIVATE KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
  98353. if( p ){
  98354. assert( p->nRef>0 );
  98355. p->nRef++;
  98356. }
  98357. return p;
  98358. }
  98359. #ifdef SQLITE_DEBUG
  98360. /*
  98361. ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
  98362. ** can only be changed if this is just a single reference to the object.
  98363. **
  98364. ** This routine is used only inside of assert() statements.
  98365. */
  98366. SQLITE_PRIVATE int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
  98367. #endif /* SQLITE_DEBUG */
  98368. /*
  98369. ** Given an expression list, generate a KeyInfo structure that records
  98370. ** the collating sequence for each expression in that expression list.
  98371. **
  98372. ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
  98373. ** KeyInfo structure is appropriate for initializing a virtual index to
  98374. ** implement that clause. If the ExprList is the result set of a SELECT
  98375. ** then the KeyInfo structure is appropriate for initializing a virtual
  98376. ** index to implement a DISTINCT test.
  98377. **
  98378. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  98379. ** function is responsible for seeing that this structure is eventually
  98380. ** freed.
  98381. */
  98382. static KeyInfo *keyInfoFromExprList(
  98383. Parse *pParse, /* Parsing context */
  98384. ExprList *pList, /* Form the KeyInfo object from this ExprList */
  98385. int iStart, /* Begin with this column of pList */
  98386. int nExtra /* Add this many extra columns to the end */
  98387. ){
  98388. int nExpr;
  98389. KeyInfo *pInfo;
  98390. struct ExprList_item *pItem;
  98391. sqlite3 *db = pParse->db;
  98392. int i;
  98393. nExpr = pList->nExpr;
  98394. pInfo = sqlite3KeyInfoAlloc(db, nExpr+nExtra-iStart, 1);
  98395. if( pInfo ){
  98396. assert( sqlite3KeyInfoIsWriteable(pInfo) );
  98397. for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
  98398. CollSeq *pColl;
  98399. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  98400. if( !pColl ) pColl = db->pDfltColl;
  98401. pInfo->aColl[i-iStart] = pColl;
  98402. pInfo->aSortOrder[i-iStart] = pItem->sortOrder;
  98403. }
  98404. }
  98405. return pInfo;
  98406. }
  98407. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  98408. /*
  98409. ** Name of the connection operator, used for error messages.
  98410. */
  98411. static const char *selectOpName(int id){
  98412. char *z;
  98413. switch( id ){
  98414. case TK_ALL: z = "UNION ALL"; break;
  98415. case TK_INTERSECT: z = "INTERSECT"; break;
  98416. case TK_EXCEPT: z = "EXCEPT"; break;
  98417. default: z = "UNION"; break;
  98418. }
  98419. return z;
  98420. }
  98421. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  98422. #ifndef SQLITE_OMIT_EXPLAIN
  98423. /*
  98424. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  98425. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  98426. ** where the caption is of the form:
  98427. **
  98428. ** "USE TEMP B-TREE FOR xxx"
  98429. **
  98430. ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
  98431. ** is determined by the zUsage argument.
  98432. */
  98433. static void explainTempTable(Parse *pParse, const char *zUsage){
  98434. if( pParse->explain==2 ){
  98435. Vdbe *v = pParse->pVdbe;
  98436. char *zMsg = sqlite3MPrintf(pParse->db, "USE TEMP B-TREE FOR %s", zUsage);
  98437. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  98438. }
  98439. }
  98440. /*
  98441. ** Assign expression b to lvalue a. A second, no-op, version of this macro
  98442. ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
  98443. ** in sqlite3Select() to assign values to structure member variables that
  98444. ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
  98445. ** code with #ifndef directives.
  98446. */
  98447. # define explainSetInteger(a, b) a = b
  98448. #else
  98449. /* No-op versions of the explainXXX() functions and macros. */
  98450. # define explainTempTable(y,z)
  98451. # define explainSetInteger(y,z)
  98452. #endif
  98453. #if !defined(SQLITE_OMIT_EXPLAIN) && !defined(SQLITE_OMIT_COMPOUND_SELECT)
  98454. /*
  98455. ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
  98456. ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
  98457. ** where the caption is of one of the two forms:
  98458. **
  98459. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 (op)"
  98460. ** "COMPOSITE SUBQUERIES iSub1 and iSub2 USING TEMP B-TREE (op)"
  98461. **
  98462. ** where iSub1 and iSub2 are the integers passed as the corresponding
  98463. ** function parameters, and op is the text representation of the parameter
  98464. ** of the same name. The parameter "op" must be one of TK_UNION, TK_EXCEPT,
  98465. ** TK_INTERSECT or TK_ALL. The first form is used if argument bUseTmp is
  98466. ** false, or the second form if it is true.
  98467. */
  98468. static void explainComposite(
  98469. Parse *pParse, /* Parse context */
  98470. int op, /* One of TK_UNION, TK_EXCEPT etc. */
  98471. int iSub1, /* Subquery id 1 */
  98472. int iSub2, /* Subquery id 2 */
  98473. int bUseTmp /* True if a temp table was used */
  98474. ){
  98475. assert( op==TK_UNION || op==TK_EXCEPT || op==TK_INTERSECT || op==TK_ALL );
  98476. if( pParse->explain==2 ){
  98477. Vdbe *v = pParse->pVdbe;
  98478. char *zMsg = sqlite3MPrintf(
  98479. pParse->db, "COMPOUND SUBQUERIES %d AND %d %s(%s)", iSub1, iSub2,
  98480. bUseTmp?"USING TEMP B-TREE ":"", selectOpName(op)
  98481. );
  98482. sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
  98483. }
  98484. }
  98485. #else
  98486. /* No-op versions of the explainXXX() functions and macros. */
  98487. # define explainComposite(v,w,x,y,z)
  98488. #endif
  98489. /*
  98490. ** If the inner loop was generated using a non-null pOrderBy argument,
  98491. ** then the results were placed in a sorter. After the loop is terminated
  98492. ** we need to run the sorter and output the results. The following
  98493. ** routine generates the code needed to do that.
  98494. */
  98495. static void generateSortTail(
  98496. Parse *pParse, /* Parsing context */
  98497. Select *p, /* The SELECT statement */
  98498. SortCtx *pSort, /* Information on the ORDER BY clause */
  98499. int nColumn, /* Number of columns of data */
  98500. SelectDest *pDest /* Write the sorted results here */
  98501. ){
  98502. Vdbe *v = pParse->pVdbe; /* The prepared statement */
  98503. int addrBreak = sqlite3VdbeMakeLabel(v); /* Jump here to exit loop */
  98504. int addrContinue = sqlite3VdbeMakeLabel(v); /* Jump here for next cycle */
  98505. int addr;
  98506. int addrOnce = 0;
  98507. int iTab;
  98508. ExprList *pOrderBy = pSort->pOrderBy;
  98509. int eDest = pDest->eDest;
  98510. int iParm = pDest->iSDParm;
  98511. int regRow;
  98512. int regRowid;
  98513. int nKey;
  98514. int iSortTab; /* Sorter cursor to read from */
  98515. int nSortData; /* Trailing values to read from sorter */
  98516. int i;
  98517. int bSeq; /* True if sorter record includes seq. no. */
  98518. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  98519. struct ExprList_item *aOutEx = p->pEList->a;
  98520. #endif
  98521. if( pSort->labelBkOut ){
  98522. sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
  98523. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrBreak);
  98524. sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
  98525. }
  98526. iTab = pSort->iECursor;
  98527. if( eDest==SRT_Output || eDest==SRT_Coroutine ){
  98528. regRowid = 0;
  98529. regRow = pDest->iSdst;
  98530. nSortData = nColumn;
  98531. }else{
  98532. regRowid = sqlite3GetTempReg(pParse);
  98533. regRow = sqlite3GetTempReg(pParse);
  98534. nSortData = 1;
  98535. }
  98536. nKey = pOrderBy->nExpr - pSort->nOBSat;
  98537. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  98538. int regSortOut = ++pParse->nMem;
  98539. iSortTab = pParse->nTab++;
  98540. if( pSort->labelBkOut ){
  98541. addrOnce = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  98542. }
  98543. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut, nKey+1+nSortData);
  98544. if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
  98545. addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
  98546. VdbeCoverage(v);
  98547. codeOffset(v, p->iOffset, addrContinue);
  98548. sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
  98549. bSeq = 0;
  98550. }else{
  98551. addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
  98552. codeOffset(v, p->iOffset, addrContinue);
  98553. iSortTab = iTab;
  98554. bSeq = 1;
  98555. }
  98556. for(i=0; i<nSortData; i++){
  98557. sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq+i, regRow+i);
  98558. VdbeComment((v, "%s", aOutEx[i].zName ? aOutEx[i].zName : aOutEx[i].zSpan));
  98559. }
  98560. switch( eDest ){
  98561. case SRT_Table:
  98562. case SRT_EphemTab: {
  98563. testcase( eDest==SRT_Table );
  98564. testcase( eDest==SRT_EphemTab );
  98565. sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
  98566. sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
  98567. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  98568. break;
  98569. }
  98570. #ifndef SQLITE_OMIT_SUBQUERY
  98571. case SRT_Set: {
  98572. assert( nColumn==1 );
  98573. sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, 1, regRowid,
  98574. &pDest->affSdst, 1);
  98575. sqlite3ExprCacheAffinityChange(pParse, regRow, 1);
  98576. sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm, regRowid);
  98577. break;
  98578. }
  98579. case SRT_Mem: {
  98580. assert( nColumn==1 );
  98581. sqlite3ExprCodeMove(pParse, regRow, iParm, 1);
  98582. /* The LIMIT clause will terminate the loop for us */
  98583. break;
  98584. }
  98585. #endif
  98586. default: {
  98587. assert( eDest==SRT_Output || eDest==SRT_Coroutine );
  98588. testcase( eDest==SRT_Output );
  98589. testcase( eDest==SRT_Coroutine );
  98590. if( eDest==SRT_Output ){
  98591. sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
  98592. sqlite3ExprCacheAffinityChange(pParse, pDest->iSdst, nColumn);
  98593. }else{
  98594. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  98595. }
  98596. break;
  98597. }
  98598. }
  98599. if( regRowid ){
  98600. sqlite3ReleaseTempReg(pParse, regRow);
  98601. sqlite3ReleaseTempReg(pParse, regRowid);
  98602. }
  98603. /* The bottom of the loop
  98604. */
  98605. sqlite3VdbeResolveLabel(v, addrContinue);
  98606. if( pSort->sortFlags & SORTFLAG_UseSorter ){
  98607. sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
  98608. }else{
  98609. sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
  98610. }
  98611. if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
  98612. sqlite3VdbeResolveLabel(v, addrBreak);
  98613. }
  98614. /*
  98615. ** Return a pointer to a string containing the 'declaration type' of the
  98616. ** expression pExpr. The string may be treated as static by the caller.
  98617. **
  98618. ** Also try to estimate the size of the returned value and return that
  98619. ** result in *pEstWidth.
  98620. **
  98621. ** The declaration type is the exact datatype definition extracted from the
  98622. ** original CREATE TABLE statement if the expression is a column. The
  98623. ** declaration type for a ROWID field is INTEGER. Exactly when an expression
  98624. ** is considered a column can be complex in the presence of subqueries. The
  98625. ** result-set expression in all of the following SELECT statements is
  98626. ** considered a column by this function.
  98627. **
  98628. ** SELECT col FROM tbl;
  98629. ** SELECT (SELECT col FROM tbl;
  98630. ** SELECT (SELECT col FROM tbl);
  98631. ** SELECT abc FROM (SELECT col AS abc FROM tbl);
  98632. **
  98633. ** The declaration type for any expression other than a column is NULL.
  98634. **
  98635. ** This routine has either 3 or 6 parameters depending on whether or not
  98636. ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
  98637. */
  98638. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  98639. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,C,D,E,F)
  98640. static const char *columnTypeImpl(
  98641. NameContext *pNC,
  98642. Expr *pExpr,
  98643. const char **pzOrigDb,
  98644. const char **pzOrigTab,
  98645. const char **pzOrigCol,
  98646. u8 *pEstWidth
  98647. ){
  98648. char const *zOrigDb = 0;
  98649. char const *zOrigTab = 0;
  98650. char const *zOrigCol = 0;
  98651. #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  98652. # define columnType(A,B,C,D,E,F) columnTypeImpl(A,B,F)
  98653. static const char *columnTypeImpl(
  98654. NameContext *pNC,
  98655. Expr *pExpr,
  98656. u8 *pEstWidth
  98657. ){
  98658. #endif /* !defined(SQLITE_ENABLE_COLUMN_METADATA) */
  98659. char const *zType = 0;
  98660. int j;
  98661. u8 estWidth = 1;
  98662. if( NEVER(pExpr==0) || pNC->pSrcList==0 ) return 0;
  98663. switch( pExpr->op ){
  98664. case TK_AGG_COLUMN:
  98665. case TK_COLUMN: {
  98666. /* The expression is a column. Locate the table the column is being
  98667. ** extracted from in NameContext.pSrcList. This table may be real
  98668. ** database table or a subquery.
  98669. */
  98670. Table *pTab = 0; /* Table structure column is extracted from */
  98671. Select *pS = 0; /* Select the column is extracted from */
  98672. int iCol = pExpr->iColumn; /* Index of column in pTab */
  98673. testcase( pExpr->op==TK_AGG_COLUMN );
  98674. testcase( pExpr->op==TK_COLUMN );
  98675. while( pNC && !pTab ){
  98676. SrcList *pTabList = pNC->pSrcList;
  98677. for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
  98678. if( j<pTabList->nSrc ){
  98679. pTab = pTabList->a[j].pTab;
  98680. pS = pTabList->a[j].pSelect;
  98681. }else{
  98682. pNC = pNC->pNext;
  98683. }
  98684. }
  98685. if( pTab==0 ){
  98686. /* At one time, code such as "SELECT new.x" within a trigger would
  98687. ** cause this condition to run. Since then, we have restructured how
  98688. ** trigger code is generated and so this condition is no longer
  98689. ** possible. However, it can still be true for statements like
  98690. ** the following:
  98691. **
  98692. ** CREATE TABLE t1(col INTEGER);
  98693. ** SELECT (SELECT t1.col) FROM FROM t1;
  98694. **
  98695. ** when columnType() is called on the expression "t1.col" in the
  98696. ** sub-select. In this case, set the column type to NULL, even
  98697. ** though it should really be "INTEGER".
  98698. **
  98699. ** This is not a problem, as the column type of "t1.col" is never
  98700. ** used. When columnType() is called on the expression
  98701. ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
  98702. ** branch below. */
  98703. break;
  98704. }
  98705. assert( pTab && pExpr->pTab==pTab );
  98706. if( pS ){
  98707. /* The "table" is actually a sub-select or a view in the FROM clause
  98708. ** of the SELECT statement. Return the declaration type and origin
  98709. ** data for the result-set column of the sub-select.
  98710. */
  98711. if( iCol>=0 && ALWAYS(iCol<pS->pEList->nExpr) ){
  98712. /* If iCol is less than zero, then the expression requests the
  98713. ** rowid of the sub-select or view. This expression is legal (see
  98714. ** test case misc2.2.2) - it always evaluates to NULL.
  98715. */
  98716. NameContext sNC;
  98717. Expr *p = pS->pEList->a[iCol].pExpr;
  98718. sNC.pSrcList = pS->pSrc;
  98719. sNC.pNext = pNC;
  98720. sNC.pParse = pNC->pParse;
  98721. zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol, &estWidth);
  98722. }
  98723. }else if( pTab->pSchema ){
  98724. /* A real table */
  98725. assert( !pS );
  98726. if( iCol<0 ) iCol = pTab->iPKey;
  98727. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  98728. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  98729. if( iCol<0 ){
  98730. zType = "INTEGER";
  98731. zOrigCol = "rowid";
  98732. }else{
  98733. zType = pTab->aCol[iCol].zType;
  98734. zOrigCol = pTab->aCol[iCol].zName;
  98735. estWidth = pTab->aCol[iCol].szEst;
  98736. }
  98737. zOrigTab = pTab->zName;
  98738. if( pNC->pParse ){
  98739. int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
  98740. zOrigDb = pNC->pParse->db->aDb[iDb].zName;
  98741. }
  98742. #else
  98743. if( iCol<0 ){
  98744. zType = "INTEGER";
  98745. }else{
  98746. zType = pTab->aCol[iCol].zType;
  98747. estWidth = pTab->aCol[iCol].szEst;
  98748. }
  98749. #endif
  98750. }
  98751. break;
  98752. }
  98753. #ifndef SQLITE_OMIT_SUBQUERY
  98754. case TK_SELECT: {
  98755. /* The expression is a sub-select. Return the declaration type and
  98756. ** origin info for the single column in the result set of the SELECT
  98757. ** statement.
  98758. */
  98759. NameContext sNC;
  98760. Select *pS = pExpr->x.pSelect;
  98761. Expr *p = pS->pEList->a[0].pExpr;
  98762. assert( ExprHasProperty(pExpr, EP_xIsSelect) );
  98763. sNC.pSrcList = pS->pSrc;
  98764. sNC.pNext = pNC;
  98765. sNC.pParse = pNC->pParse;
  98766. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, &estWidth);
  98767. break;
  98768. }
  98769. #endif
  98770. }
  98771. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  98772. if( pzOrigDb ){
  98773. assert( pzOrigTab && pzOrigCol );
  98774. *pzOrigDb = zOrigDb;
  98775. *pzOrigTab = zOrigTab;
  98776. *pzOrigCol = zOrigCol;
  98777. }
  98778. #endif
  98779. if( pEstWidth ) *pEstWidth = estWidth;
  98780. return zType;
  98781. }
  98782. /*
  98783. ** Generate code that will tell the VDBE the declaration types of columns
  98784. ** in the result set.
  98785. */
  98786. static void generateColumnTypes(
  98787. Parse *pParse, /* Parser context */
  98788. SrcList *pTabList, /* List of tables */
  98789. ExprList *pEList /* Expressions defining the result set */
  98790. ){
  98791. #ifndef SQLITE_OMIT_DECLTYPE
  98792. Vdbe *v = pParse->pVdbe;
  98793. int i;
  98794. NameContext sNC;
  98795. sNC.pSrcList = pTabList;
  98796. sNC.pParse = pParse;
  98797. for(i=0; i<pEList->nExpr; i++){
  98798. Expr *p = pEList->a[i].pExpr;
  98799. const char *zType;
  98800. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  98801. const char *zOrigDb = 0;
  98802. const char *zOrigTab = 0;
  98803. const char *zOrigCol = 0;
  98804. zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol, 0);
  98805. /* The vdbe must make its own copy of the column-type and other
  98806. ** column specific strings, in case the schema is reset before this
  98807. ** virtual machine is deleted.
  98808. */
  98809. sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
  98810. sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
  98811. sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
  98812. #else
  98813. zType = columnType(&sNC, p, 0, 0, 0, 0);
  98814. #endif
  98815. sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
  98816. }
  98817. #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
  98818. }
  98819. /*
  98820. ** Generate code that will tell the VDBE the names of columns
  98821. ** in the result set. This information is used to provide the
  98822. ** azCol[] values in the callback.
  98823. */
  98824. static void generateColumnNames(
  98825. Parse *pParse, /* Parser context */
  98826. SrcList *pTabList, /* List of tables */
  98827. ExprList *pEList /* Expressions defining the result set */
  98828. ){
  98829. Vdbe *v = pParse->pVdbe;
  98830. int i, j;
  98831. sqlite3 *db = pParse->db;
  98832. int fullNames, shortNames;
  98833. #ifndef SQLITE_OMIT_EXPLAIN
  98834. /* If this is an EXPLAIN, skip this step */
  98835. if( pParse->explain ){
  98836. return;
  98837. }
  98838. #endif
  98839. if( pParse->colNamesSet || NEVER(v==0) || db->mallocFailed ) return;
  98840. pParse->colNamesSet = 1;
  98841. fullNames = (db->flags & SQLITE_FullColNames)!=0;
  98842. shortNames = (db->flags & SQLITE_ShortColNames)!=0;
  98843. sqlite3VdbeSetNumCols(v, pEList->nExpr);
  98844. for(i=0; i<pEList->nExpr; i++){
  98845. Expr *p;
  98846. p = pEList->a[i].pExpr;
  98847. if( NEVER(p==0) ) continue;
  98848. if( pEList->a[i].zName ){
  98849. char *zName = pEList->a[i].zName;
  98850. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
  98851. }else if( (p->op==TK_COLUMN || p->op==TK_AGG_COLUMN) && pTabList ){
  98852. Table *pTab;
  98853. char *zCol;
  98854. int iCol = p->iColumn;
  98855. for(j=0; ALWAYS(j<pTabList->nSrc); j++){
  98856. if( pTabList->a[j].iCursor==p->iTable ) break;
  98857. }
  98858. assert( j<pTabList->nSrc );
  98859. pTab = pTabList->a[j].pTab;
  98860. if( iCol<0 ) iCol = pTab->iPKey;
  98861. assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
  98862. if( iCol<0 ){
  98863. zCol = "rowid";
  98864. }else{
  98865. zCol = pTab->aCol[iCol].zName;
  98866. }
  98867. if( !shortNames && !fullNames ){
  98868. sqlite3VdbeSetColName(v, i, COLNAME_NAME,
  98869. sqlite3DbStrDup(db, pEList->a[i].zSpan), SQLITE_DYNAMIC);
  98870. }else if( fullNames ){
  98871. char *zName = 0;
  98872. zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
  98873. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
  98874. }else{
  98875. sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
  98876. }
  98877. }else{
  98878. const char *z = pEList->a[i].zSpan;
  98879. z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
  98880. sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
  98881. }
  98882. }
  98883. generateColumnTypes(pParse, pTabList, pEList);
  98884. }
  98885. /*
  98886. ** Given an expression list (which is really the list of expressions
  98887. ** that form the result set of a SELECT statement) compute appropriate
  98888. ** column names for a table that would hold the expression list.
  98889. **
  98890. ** All column names will be unique.
  98891. **
  98892. ** Only the column names are computed. Column.zType, Column.zColl,
  98893. ** and other fields of Column are zeroed.
  98894. **
  98895. ** Return SQLITE_OK on success. If a memory allocation error occurs,
  98896. ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
  98897. */
  98898. static int selectColumnsFromExprList(
  98899. Parse *pParse, /* Parsing context */
  98900. ExprList *pEList, /* Expr list from which to derive column names */
  98901. i16 *pnCol, /* Write the number of columns here */
  98902. Column **paCol /* Write the new column list here */
  98903. ){
  98904. sqlite3 *db = pParse->db; /* Database connection */
  98905. int i, j; /* Loop counters */
  98906. int cnt; /* Index added to make the name unique */
  98907. Column *aCol, *pCol; /* For looping over result columns */
  98908. int nCol; /* Number of columns in the result set */
  98909. Expr *p; /* Expression for a single result column */
  98910. char *zName; /* Column name */
  98911. int nName; /* Size of name in zName[] */
  98912. if( pEList ){
  98913. nCol = pEList->nExpr;
  98914. aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
  98915. testcase( aCol==0 );
  98916. }else{
  98917. nCol = 0;
  98918. aCol = 0;
  98919. }
  98920. *pnCol = nCol;
  98921. *paCol = aCol;
  98922. for(i=0, pCol=aCol; i<nCol; i++, pCol++){
  98923. /* Get an appropriate name for the column
  98924. */
  98925. p = sqlite3ExprSkipCollate(pEList->a[i].pExpr);
  98926. if( (zName = pEList->a[i].zName)!=0 ){
  98927. /* If the column contains an "AS <name>" phrase, use <name> as the name */
  98928. zName = sqlite3DbStrDup(db, zName);
  98929. }else{
  98930. Expr *pColExpr = p; /* The expression that is the result column name */
  98931. Table *pTab; /* Table associated with this expression */
  98932. while( pColExpr->op==TK_DOT ){
  98933. pColExpr = pColExpr->pRight;
  98934. assert( pColExpr!=0 );
  98935. }
  98936. if( pColExpr->op==TK_COLUMN && ALWAYS(pColExpr->pTab!=0) ){
  98937. /* For columns use the column name name */
  98938. int iCol = pColExpr->iColumn;
  98939. pTab = pColExpr->pTab;
  98940. if( iCol<0 ) iCol = pTab->iPKey;
  98941. zName = sqlite3MPrintf(db, "%s",
  98942. iCol>=0 ? pTab->aCol[iCol].zName : "rowid");
  98943. }else if( pColExpr->op==TK_ID ){
  98944. assert( !ExprHasProperty(pColExpr, EP_IntValue) );
  98945. zName = sqlite3MPrintf(db, "%s", pColExpr->u.zToken);
  98946. }else{
  98947. /* Use the original text of the column expression as its name */
  98948. zName = sqlite3MPrintf(db, "%s", pEList->a[i].zSpan);
  98949. }
  98950. }
  98951. if( db->mallocFailed ){
  98952. sqlite3DbFree(db, zName);
  98953. break;
  98954. }
  98955. /* Make sure the column name is unique. If the name is not unique,
  98956. ** append an integer to the name so that it becomes unique.
  98957. */
  98958. nName = sqlite3Strlen30(zName);
  98959. for(j=cnt=0; j<i; j++){
  98960. if( sqlite3StrICmp(aCol[j].zName, zName)==0 ){
  98961. char *zNewName;
  98962. int k;
  98963. for(k=nName-1; k>1 && sqlite3Isdigit(zName[k]); k--){}
  98964. if( k>=0 && zName[k]==':' ) nName = k;
  98965. zName[nName] = 0;
  98966. zNewName = sqlite3MPrintf(db, "%s:%d", zName, ++cnt);
  98967. sqlite3DbFree(db, zName);
  98968. zName = zNewName;
  98969. j = -1;
  98970. if( zName==0 ) break;
  98971. }
  98972. }
  98973. pCol->zName = zName;
  98974. }
  98975. if( db->mallocFailed ){
  98976. for(j=0; j<i; j++){
  98977. sqlite3DbFree(db, aCol[j].zName);
  98978. }
  98979. sqlite3DbFree(db, aCol);
  98980. *paCol = 0;
  98981. *pnCol = 0;
  98982. return SQLITE_NOMEM;
  98983. }
  98984. return SQLITE_OK;
  98985. }
  98986. /*
  98987. ** Add type and collation information to a column list based on
  98988. ** a SELECT statement.
  98989. **
  98990. ** The column list presumably came from selectColumnNamesFromExprList().
  98991. ** The column list has only names, not types or collations. This
  98992. ** routine goes through and adds the types and collations.
  98993. **
  98994. ** This routine requires that all identifiers in the SELECT
  98995. ** statement be resolved.
  98996. */
  98997. static void selectAddColumnTypeAndCollation(
  98998. Parse *pParse, /* Parsing contexts */
  98999. Table *pTab, /* Add column type information to this table */
  99000. Select *pSelect /* SELECT used to determine types and collations */
  99001. ){
  99002. sqlite3 *db = pParse->db;
  99003. NameContext sNC;
  99004. Column *pCol;
  99005. CollSeq *pColl;
  99006. int i;
  99007. Expr *p;
  99008. struct ExprList_item *a;
  99009. u64 szAll = 0;
  99010. assert( pSelect!=0 );
  99011. assert( (pSelect->selFlags & SF_Resolved)!=0 );
  99012. assert( pTab->nCol==pSelect->pEList->nExpr || db->mallocFailed );
  99013. if( db->mallocFailed ) return;
  99014. memset(&sNC, 0, sizeof(sNC));
  99015. sNC.pSrcList = pSelect->pSrc;
  99016. a = pSelect->pEList->a;
  99017. for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
  99018. p = a[i].pExpr;
  99019. pCol->zType = sqlite3DbStrDup(db, columnType(&sNC, p,0,0,0, &pCol->szEst));
  99020. szAll += pCol->szEst;
  99021. pCol->affinity = sqlite3ExprAffinity(p);
  99022. if( pCol->affinity==0 ) pCol->affinity = SQLITE_AFF_NONE;
  99023. pColl = sqlite3ExprCollSeq(pParse, p);
  99024. if( pColl ){
  99025. pCol->zColl = sqlite3DbStrDup(db, pColl->zName);
  99026. }
  99027. }
  99028. pTab->szTabRow = sqlite3LogEst(szAll*4);
  99029. }
  99030. /*
  99031. ** Given a SELECT statement, generate a Table structure that describes
  99032. ** the result set of that SELECT.
  99033. */
  99034. SQLITE_PRIVATE Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect){
  99035. Table *pTab;
  99036. sqlite3 *db = pParse->db;
  99037. int savedFlags;
  99038. savedFlags = db->flags;
  99039. db->flags &= ~SQLITE_FullColNames;
  99040. db->flags |= SQLITE_ShortColNames;
  99041. sqlite3SelectPrep(pParse, pSelect, 0);
  99042. if( pParse->nErr ) return 0;
  99043. while( pSelect->pPrior ) pSelect = pSelect->pPrior;
  99044. db->flags = savedFlags;
  99045. pTab = sqlite3DbMallocZero(db, sizeof(Table) );
  99046. if( pTab==0 ){
  99047. return 0;
  99048. }
  99049. /* The sqlite3ResultSetOfSelect() is only used n contexts where lookaside
  99050. ** is disabled */
  99051. assert( db->lookaside.bEnabled==0 );
  99052. pTab->nRef = 1;
  99053. pTab->zName = 0;
  99054. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  99055. selectColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
  99056. selectAddColumnTypeAndCollation(pParse, pTab, pSelect);
  99057. pTab->iPKey = -1;
  99058. if( db->mallocFailed ){
  99059. sqlite3DeleteTable(db, pTab);
  99060. return 0;
  99061. }
  99062. return pTab;
  99063. }
  99064. /*
  99065. ** Get a VDBE for the given parser context. Create a new one if necessary.
  99066. ** If an error occurs, return NULL and leave a message in pParse.
  99067. */
  99068. SQLITE_PRIVATE Vdbe *sqlite3GetVdbe(Parse *pParse){
  99069. Vdbe *v = pParse->pVdbe;
  99070. if( v==0 ){
  99071. v = pParse->pVdbe = sqlite3VdbeCreate(pParse);
  99072. if( v ) sqlite3VdbeAddOp0(v, OP_Init);
  99073. if( pParse->pToplevel==0
  99074. && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
  99075. ){
  99076. pParse->okConstFactor = 1;
  99077. }
  99078. }
  99079. return v;
  99080. }
  99081. /*
  99082. ** Compute the iLimit and iOffset fields of the SELECT based on the
  99083. ** pLimit and pOffset expressions. pLimit and pOffset hold the expressions
  99084. ** that appear in the original SQL statement after the LIMIT and OFFSET
  99085. ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
  99086. ** are the integer memory register numbers for counters used to compute
  99087. ** the limit and offset. If there is no limit and/or offset, then
  99088. ** iLimit and iOffset are negative.
  99089. **
  99090. ** This routine changes the values of iLimit and iOffset only if
  99091. ** a limit or offset is defined by pLimit and pOffset. iLimit and
  99092. ** iOffset should have been preset to appropriate default values (zero)
  99093. ** prior to calling this routine.
  99094. **
  99095. ** The iOffset register (if it exists) is initialized to the value
  99096. ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
  99097. ** iOffset+1 is initialized to LIMIT+OFFSET.
  99098. **
  99099. ** Only if pLimit!=0 or pOffset!=0 do the limit registers get
  99100. ** redefined. The UNION ALL operator uses this property to force
  99101. ** the reuse of the same limit and offset registers across multiple
  99102. ** SELECT statements.
  99103. */
  99104. static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
  99105. Vdbe *v = 0;
  99106. int iLimit = 0;
  99107. int iOffset;
  99108. int addr1, n;
  99109. if( p->iLimit ) return;
  99110. /*
  99111. ** "LIMIT -1" always shows all rows. There is some
  99112. ** controversy about what the correct behavior should be.
  99113. ** The current implementation interprets "LIMIT 0" to mean
  99114. ** no rows.
  99115. */
  99116. sqlite3ExprCacheClear(pParse);
  99117. assert( p->pOffset==0 || p->pLimit!=0 );
  99118. if( p->pLimit ){
  99119. p->iLimit = iLimit = ++pParse->nMem;
  99120. v = sqlite3GetVdbe(pParse);
  99121. assert( v!=0 );
  99122. if( sqlite3ExprIsInteger(p->pLimit, &n) ){
  99123. sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
  99124. VdbeComment((v, "LIMIT counter"));
  99125. if( n==0 ){
  99126. sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
  99127. }else if( n>=0 && p->nSelectRow>(u64)n ){
  99128. p->nSelectRow = n;
  99129. }
  99130. }else{
  99131. sqlite3ExprCode(pParse, p->pLimit, iLimit);
  99132. sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
  99133. VdbeComment((v, "LIMIT counter"));
  99134. sqlite3VdbeAddOp2(v, OP_IfZero, iLimit, iBreak); VdbeCoverage(v);
  99135. }
  99136. if( p->pOffset ){
  99137. p->iOffset = iOffset = ++pParse->nMem;
  99138. pParse->nMem++; /* Allocate an extra register for limit+offset */
  99139. sqlite3ExprCode(pParse, p->pOffset, iOffset);
  99140. sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
  99141. VdbeComment((v, "OFFSET counter"));
  99142. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iOffset); VdbeCoverage(v);
  99143. sqlite3VdbeAddOp2(v, OP_Integer, 0, iOffset);
  99144. sqlite3VdbeJumpHere(v, addr1);
  99145. sqlite3VdbeAddOp3(v, OP_Add, iLimit, iOffset, iOffset+1);
  99146. VdbeComment((v, "LIMIT+OFFSET"));
  99147. addr1 = sqlite3VdbeAddOp1(v, OP_IfPos, iLimit); VdbeCoverage(v);
  99148. sqlite3VdbeAddOp2(v, OP_Integer, -1, iOffset+1);
  99149. sqlite3VdbeJumpHere(v, addr1);
  99150. }
  99151. }
  99152. }
  99153. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  99154. /*
  99155. ** Return the appropriate collating sequence for the iCol-th column of
  99156. ** the result set for the compound-select statement "p". Return NULL if
  99157. ** the column has no default collating sequence.
  99158. **
  99159. ** The collating sequence for the compound select is taken from the
  99160. ** left-most term of the select that has a collating sequence.
  99161. */
  99162. static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
  99163. CollSeq *pRet;
  99164. if( p->pPrior ){
  99165. pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
  99166. }else{
  99167. pRet = 0;
  99168. }
  99169. assert( iCol>=0 );
  99170. if( pRet==0 && iCol<p->pEList->nExpr ){
  99171. pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
  99172. }
  99173. return pRet;
  99174. }
  99175. /*
  99176. ** The select statement passed as the second parameter is a compound SELECT
  99177. ** with an ORDER BY clause. This function allocates and returns a KeyInfo
  99178. ** structure suitable for implementing the ORDER BY.
  99179. **
  99180. ** Space to hold the KeyInfo structure is obtained from malloc. The calling
  99181. ** function is responsible for ensuring that this structure is eventually
  99182. ** freed.
  99183. */
  99184. static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
  99185. ExprList *pOrderBy = p->pOrderBy;
  99186. int nOrderBy = p->pOrderBy->nExpr;
  99187. sqlite3 *db = pParse->db;
  99188. KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
  99189. if( pRet ){
  99190. int i;
  99191. for(i=0; i<nOrderBy; i++){
  99192. struct ExprList_item *pItem = &pOrderBy->a[i];
  99193. Expr *pTerm = pItem->pExpr;
  99194. CollSeq *pColl;
  99195. if( pTerm->flags & EP_Collate ){
  99196. pColl = sqlite3ExprCollSeq(pParse, pTerm);
  99197. }else{
  99198. pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
  99199. if( pColl==0 ) pColl = db->pDfltColl;
  99200. pOrderBy->a[i].pExpr =
  99201. sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
  99202. }
  99203. assert( sqlite3KeyInfoIsWriteable(pRet) );
  99204. pRet->aColl[i] = pColl;
  99205. pRet->aSortOrder[i] = pOrderBy->a[i].sortOrder;
  99206. }
  99207. }
  99208. return pRet;
  99209. }
  99210. #ifndef SQLITE_OMIT_CTE
  99211. /*
  99212. ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
  99213. ** query of the form:
  99214. **
  99215. ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
  99216. ** \___________/ \_______________/
  99217. ** p->pPrior p
  99218. **
  99219. **
  99220. ** There is exactly one reference to the recursive-table in the FROM clause
  99221. ** of recursive-query, marked with the SrcList->a[].isRecursive flag.
  99222. **
  99223. ** The setup-query runs once to generate an initial set of rows that go
  99224. ** into a Queue table. Rows are extracted from the Queue table one by
  99225. ** one. Each row extracted from Queue is output to pDest. Then the single
  99226. ** extracted row (now in the iCurrent table) becomes the content of the
  99227. ** recursive-table for a recursive-query run. The output of the recursive-query
  99228. ** is added back into the Queue table. Then another row is extracted from Queue
  99229. ** and the iteration continues until the Queue table is empty.
  99230. **
  99231. ** If the compound query operator is UNION then no duplicate rows are ever
  99232. ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
  99233. ** that have ever been inserted into Queue and causes duplicates to be
  99234. ** discarded. If the operator is UNION ALL, then duplicates are allowed.
  99235. **
  99236. ** If the query has an ORDER BY, then entries in the Queue table are kept in
  99237. ** ORDER BY order and the first entry is extracted for each cycle. Without
  99238. ** an ORDER BY, the Queue table is just a FIFO.
  99239. **
  99240. ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
  99241. ** have been output to pDest. A LIMIT of zero means to output no rows and a
  99242. ** negative LIMIT means to output all rows. If there is also an OFFSET clause
  99243. ** with a positive value, then the first OFFSET outputs are discarded rather
  99244. ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
  99245. ** rows have been skipped.
  99246. */
  99247. static void generateWithRecursiveQuery(
  99248. Parse *pParse, /* Parsing context */
  99249. Select *p, /* The recursive SELECT to be coded */
  99250. SelectDest *pDest /* What to do with query results */
  99251. ){
  99252. SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
  99253. int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
  99254. Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
  99255. Select *pSetup = p->pPrior; /* The setup query */
  99256. int addrTop; /* Top of the loop */
  99257. int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
  99258. int iCurrent = 0; /* The Current table */
  99259. int regCurrent; /* Register holding Current table */
  99260. int iQueue; /* The Queue table */
  99261. int iDistinct = 0; /* To ensure unique results if UNION */
  99262. int eDest = SRT_Fifo; /* How to write to Queue */
  99263. SelectDest destQueue; /* SelectDest targetting the Queue table */
  99264. int i; /* Loop counter */
  99265. int rc; /* Result code */
  99266. ExprList *pOrderBy; /* The ORDER BY clause */
  99267. Expr *pLimit, *pOffset; /* Saved LIMIT and OFFSET */
  99268. int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
  99269. /* Obtain authorization to do a recursive query */
  99270. if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
  99271. /* Process the LIMIT and OFFSET clauses, if they exist */
  99272. addrBreak = sqlite3VdbeMakeLabel(v);
  99273. computeLimitRegisters(pParse, p, addrBreak);
  99274. pLimit = p->pLimit;
  99275. pOffset = p->pOffset;
  99276. regLimit = p->iLimit;
  99277. regOffset = p->iOffset;
  99278. p->pLimit = p->pOffset = 0;
  99279. p->iLimit = p->iOffset = 0;
  99280. pOrderBy = p->pOrderBy;
  99281. /* Locate the cursor number of the Current table */
  99282. for(i=0; ALWAYS(i<pSrc->nSrc); i++){
  99283. if( pSrc->a[i].isRecursive ){
  99284. iCurrent = pSrc->a[i].iCursor;
  99285. break;
  99286. }
  99287. }
  99288. /* Allocate cursors numbers for Queue and Distinct. The cursor number for
  99289. ** the Distinct table must be exactly one greater than Queue in order
  99290. ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
  99291. iQueue = pParse->nTab++;
  99292. if( p->op==TK_UNION ){
  99293. eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
  99294. iDistinct = pParse->nTab++;
  99295. }else{
  99296. eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
  99297. }
  99298. sqlite3SelectDestInit(&destQueue, eDest, iQueue);
  99299. /* Allocate cursors for Current, Queue, and Distinct. */
  99300. regCurrent = ++pParse->nMem;
  99301. sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
  99302. if( pOrderBy ){
  99303. KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
  99304. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
  99305. (char*)pKeyInfo, P4_KEYINFO);
  99306. destQueue.pOrderBy = pOrderBy;
  99307. }else{
  99308. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
  99309. }
  99310. VdbeComment((v, "Queue table"));
  99311. if( iDistinct ){
  99312. p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
  99313. p->selFlags |= SF_UsesEphemeral;
  99314. }
  99315. /* Detach the ORDER BY clause from the compound SELECT */
  99316. p->pOrderBy = 0;
  99317. /* Store the results of the setup-query in Queue. */
  99318. pSetup->pNext = 0;
  99319. rc = sqlite3Select(pParse, pSetup, &destQueue);
  99320. pSetup->pNext = p;
  99321. if( rc ) goto end_of_recursive_query;
  99322. /* Find the next row in the Queue and output that row */
  99323. addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
  99324. /* Transfer the next row in Queue over to Current */
  99325. sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
  99326. if( pOrderBy ){
  99327. sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
  99328. }else{
  99329. sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
  99330. }
  99331. sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
  99332. /* Output the single row in Current */
  99333. addrCont = sqlite3VdbeMakeLabel(v);
  99334. codeOffset(v, regOffset, addrCont);
  99335. selectInnerLoop(pParse, p, p->pEList, iCurrent,
  99336. 0, 0, pDest, addrCont, addrBreak);
  99337. if( regLimit ){
  99338. sqlite3VdbeAddOp3(v, OP_IfZero, regLimit, addrBreak, -1);
  99339. VdbeCoverage(v);
  99340. }
  99341. sqlite3VdbeResolveLabel(v, addrCont);
  99342. /* Execute the recursive SELECT taking the single row in Current as
  99343. ** the value for the recursive-table. Store the results in the Queue.
  99344. */
  99345. p->pPrior = 0;
  99346. sqlite3Select(pParse, p, &destQueue);
  99347. assert( p->pPrior==0 );
  99348. p->pPrior = pSetup;
  99349. /* Keep running the loop until the Queue is empty */
  99350. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrTop);
  99351. sqlite3VdbeResolveLabel(v, addrBreak);
  99352. end_of_recursive_query:
  99353. sqlite3ExprListDelete(pParse->db, p->pOrderBy);
  99354. p->pOrderBy = pOrderBy;
  99355. p->pLimit = pLimit;
  99356. p->pOffset = pOffset;
  99357. return;
  99358. }
  99359. #endif /* SQLITE_OMIT_CTE */
  99360. /* Forward references */
  99361. static int multiSelectOrderBy(
  99362. Parse *pParse, /* Parsing context */
  99363. Select *p, /* The right-most of SELECTs to be coded */
  99364. SelectDest *pDest /* What to do with query results */
  99365. );
  99366. /*
  99367. ** This routine is called to process a compound query form from
  99368. ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
  99369. ** INTERSECT
  99370. **
  99371. ** "p" points to the right-most of the two queries. the query on the
  99372. ** left is p->pPrior. The left query could also be a compound query
  99373. ** in which case this routine will be called recursively.
  99374. **
  99375. ** The results of the total query are to be written into a destination
  99376. ** of type eDest with parameter iParm.
  99377. **
  99378. ** Example 1: Consider a three-way compound SQL statement.
  99379. **
  99380. ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
  99381. **
  99382. ** This statement is parsed up as follows:
  99383. **
  99384. ** SELECT c FROM t3
  99385. ** |
  99386. ** `-----> SELECT b FROM t2
  99387. ** |
  99388. ** `------> SELECT a FROM t1
  99389. **
  99390. ** The arrows in the diagram above represent the Select.pPrior pointer.
  99391. ** So if this routine is called with p equal to the t3 query, then
  99392. ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
  99393. **
  99394. ** Notice that because of the way SQLite parses compound SELECTs, the
  99395. ** individual selects always group from left to right.
  99396. */
  99397. static int multiSelect(
  99398. Parse *pParse, /* Parsing context */
  99399. Select *p, /* The right-most of SELECTs to be coded */
  99400. SelectDest *pDest /* What to do with query results */
  99401. ){
  99402. int rc = SQLITE_OK; /* Success code from a subroutine */
  99403. Select *pPrior; /* Another SELECT immediately to our left */
  99404. Vdbe *v; /* Generate code to this VDBE */
  99405. SelectDest dest; /* Alternative data destination */
  99406. Select *pDelete = 0; /* Chain of simple selects to delete */
  99407. sqlite3 *db; /* Database connection */
  99408. #ifndef SQLITE_OMIT_EXPLAIN
  99409. int iSub1 = 0; /* EQP id of left-hand query */
  99410. int iSub2 = 0; /* EQP id of right-hand query */
  99411. #endif
  99412. /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
  99413. ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
  99414. */
  99415. assert( p && p->pPrior ); /* Calling function guarantees this much */
  99416. assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
  99417. db = pParse->db;
  99418. pPrior = p->pPrior;
  99419. dest = *pDest;
  99420. if( pPrior->pOrderBy ){
  99421. sqlite3ErrorMsg(pParse,"ORDER BY clause should come after %s not before",
  99422. selectOpName(p->op));
  99423. rc = 1;
  99424. goto multi_select_end;
  99425. }
  99426. if( pPrior->pLimit ){
  99427. sqlite3ErrorMsg(pParse,"LIMIT clause should come after %s not before",
  99428. selectOpName(p->op));
  99429. rc = 1;
  99430. goto multi_select_end;
  99431. }
  99432. v = sqlite3GetVdbe(pParse);
  99433. assert( v!=0 ); /* The VDBE already created by calling function */
  99434. /* Create the destination temporary table if necessary
  99435. */
  99436. if( dest.eDest==SRT_EphemTab ){
  99437. assert( p->pEList );
  99438. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
  99439. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  99440. dest.eDest = SRT_Table;
  99441. }
  99442. /* Make sure all SELECTs in the statement have the same number of elements
  99443. ** in their result sets.
  99444. */
  99445. assert( p->pEList && pPrior->pEList );
  99446. if( p->pEList->nExpr!=pPrior->pEList->nExpr ){
  99447. if( p->selFlags & SF_Values ){
  99448. sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
  99449. }else{
  99450. sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
  99451. " do not have the same number of result columns", selectOpName(p->op));
  99452. }
  99453. rc = 1;
  99454. goto multi_select_end;
  99455. }
  99456. #ifndef SQLITE_OMIT_CTE
  99457. if( p->selFlags & SF_Recursive ){
  99458. generateWithRecursiveQuery(pParse, p, &dest);
  99459. }else
  99460. #endif
  99461. /* Compound SELECTs that have an ORDER BY clause are handled separately.
  99462. */
  99463. if( p->pOrderBy ){
  99464. return multiSelectOrderBy(pParse, p, pDest);
  99465. }else
  99466. /* Generate code for the left and right SELECT statements.
  99467. */
  99468. switch( p->op ){
  99469. case TK_ALL: {
  99470. int addr = 0;
  99471. int nLimit;
  99472. assert( !pPrior->pLimit );
  99473. pPrior->iLimit = p->iLimit;
  99474. pPrior->iOffset = p->iOffset;
  99475. pPrior->pLimit = p->pLimit;
  99476. pPrior->pOffset = p->pOffset;
  99477. explainSetInteger(iSub1, pParse->iNextSelectId);
  99478. rc = sqlite3Select(pParse, pPrior, &dest);
  99479. p->pLimit = 0;
  99480. p->pOffset = 0;
  99481. if( rc ){
  99482. goto multi_select_end;
  99483. }
  99484. p->pPrior = 0;
  99485. p->iLimit = pPrior->iLimit;
  99486. p->iOffset = pPrior->iOffset;
  99487. if( p->iLimit ){
  99488. addr = sqlite3VdbeAddOp1(v, OP_IfZero, p->iLimit); VdbeCoverage(v);
  99489. VdbeComment((v, "Jump ahead if LIMIT reached"));
  99490. }
  99491. explainSetInteger(iSub2, pParse->iNextSelectId);
  99492. rc = sqlite3Select(pParse, p, &dest);
  99493. testcase( rc!=SQLITE_OK );
  99494. pDelete = p->pPrior;
  99495. p->pPrior = pPrior;
  99496. p->nSelectRow += pPrior->nSelectRow;
  99497. if( pPrior->pLimit
  99498. && sqlite3ExprIsInteger(pPrior->pLimit, &nLimit)
  99499. && nLimit>0 && p->nSelectRow > (u64)nLimit
  99500. ){
  99501. p->nSelectRow = nLimit;
  99502. }
  99503. if( addr ){
  99504. sqlite3VdbeJumpHere(v, addr);
  99505. }
  99506. break;
  99507. }
  99508. case TK_EXCEPT:
  99509. case TK_UNION: {
  99510. int unionTab; /* Cursor number of the temporary table holding result */
  99511. u8 op = 0; /* One of the SRT_ operations to apply to self */
  99512. int priorOp; /* The SRT_ operation to apply to prior selects */
  99513. Expr *pLimit, *pOffset; /* Saved values of p->nLimit and p->nOffset */
  99514. int addr;
  99515. SelectDest uniondest;
  99516. testcase( p->op==TK_EXCEPT );
  99517. testcase( p->op==TK_UNION );
  99518. priorOp = SRT_Union;
  99519. if( dest.eDest==priorOp ){
  99520. /* We can reuse a temporary table generated by a SELECT to our
  99521. ** right.
  99522. */
  99523. assert( p->pLimit==0 ); /* Not allowed on leftward elements */
  99524. assert( p->pOffset==0 ); /* Not allowed on leftward elements */
  99525. unionTab = dest.iSDParm;
  99526. }else{
  99527. /* We will need to create our own temporary table to hold the
  99528. ** intermediate results.
  99529. */
  99530. unionTab = pParse->nTab++;
  99531. assert( p->pOrderBy==0 );
  99532. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
  99533. assert( p->addrOpenEphm[0] == -1 );
  99534. p->addrOpenEphm[0] = addr;
  99535. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  99536. assert( p->pEList );
  99537. }
  99538. /* Code the SELECT statements to our left
  99539. */
  99540. assert( !pPrior->pOrderBy );
  99541. sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
  99542. explainSetInteger(iSub1, pParse->iNextSelectId);
  99543. rc = sqlite3Select(pParse, pPrior, &uniondest);
  99544. if( rc ){
  99545. goto multi_select_end;
  99546. }
  99547. /* Code the current SELECT statement
  99548. */
  99549. if( p->op==TK_EXCEPT ){
  99550. op = SRT_Except;
  99551. }else{
  99552. assert( p->op==TK_UNION );
  99553. op = SRT_Union;
  99554. }
  99555. p->pPrior = 0;
  99556. pLimit = p->pLimit;
  99557. p->pLimit = 0;
  99558. pOffset = p->pOffset;
  99559. p->pOffset = 0;
  99560. uniondest.eDest = op;
  99561. explainSetInteger(iSub2, pParse->iNextSelectId);
  99562. rc = sqlite3Select(pParse, p, &uniondest);
  99563. testcase( rc!=SQLITE_OK );
  99564. /* Query flattening in sqlite3Select() might refill p->pOrderBy.
  99565. ** Be sure to delete p->pOrderBy, therefore, to avoid a memory leak. */
  99566. sqlite3ExprListDelete(db, p->pOrderBy);
  99567. pDelete = p->pPrior;
  99568. p->pPrior = pPrior;
  99569. p->pOrderBy = 0;
  99570. if( p->op==TK_UNION ) p->nSelectRow += pPrior->nSelectRow;
  99571. sqlite3ExprDelete(db, p->pLimit);
  99572. p->pLimit = pLimit;
  99573. p->pOffset = pOffset;
  99574. p->iLimit = 0;
  99575. p->iOffset = 0;
  99576. /* Convert the data in the temporary table into whatever form
  99577. ** it is that we currently need.
  99578. */
  99579. assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
  99580. if( dest.eDest!=priorOp ){
  99581. int iCont, iBreak, iStart;
  99582. assert( p->pEList );
  99583. if( dest.eDest==SRT_Output ){
  99584. Select *pFirst = p;
  99585. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  99586. generateColumnNames(pParse, 0, pFirst->pEList);
  99587. }
  99588. iBreak = sqlite3VdbeMakeLabel(v);
  99589. iCont = sqlite3VdbeMakeLabel(v);
  99590. computeLimitRegisters(pParse, p, iBreak);
  99591. sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
  99592. iStart = sqlite3VdbeCurrentAddr(v);
  99593. selectInnerLoop(pParse, p, p->pEList, unionTab,
  99594. 0, 0, &dest, iCont, iBreak);
  99595. sqlite3VdbeResolveLabel(v, iCont);
  99596. sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
  99597. sqlite3VdbeResolveLabel(v, iBreak);
  99598. sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
  99599. }
  99600. break;
  99601. }
  99602. default: assert( p->op==TK_INTERSECT ); {
  99603. int tab1, tab2;
  99604. int iCont, iBreak, iStart;
  99605. Expr *pLimit, *pOffset;
  99606. int addr;
  99607. SelectDest intersectdest;
  99608. int r1;
  99609. /* INTERSECT is different from the others since it requires
  99610. ** two temporary tables. Hence it has its own case. Begin
  99611. ** by allocating the tables we will need.
  99612. */
  99613. tab1 = pParse->nTab++;
  99614. tab2 = pParse->nTab++;
  99615. assert( p->pOrderBy==0 );
  99616. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
  99617. assert( p->addrOpenEphm[0] == -1 );
  99618. p->addrOpenEphm[0] = addr;
  99619. findRightmost(p)->selFlags |= SF_UsesEphemeral;
  99620. assert( p->pEList );
  99621. /* Code the SELECTs to our left into temporary table "tab1".
  99622. */
  99623. sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
  99624. explainSetInteger(iSub1, pParse->iNextSelectId);
  99625. rc = sqlite3Select(pParse, pPrior, &intersectdest);
  99626. if( rc ){
  99627. goto multi_select_end;
  99628. }
  99629. /* Code the current SELECT into temporary table "tab2"
  99630. */
  99631. addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
  99632. assert( p->addrOpenEphm[1] == -1 );
  99633. p->addrOpenEphm[1] = addr;
  99634. p->pPrior = 0;
  99635. pLimit = p->pLimit;
  99636. p->pLimit = 0;
  99637. pOffset = p->pOffset;
  99638. p->pOffset = 0;
  99639. intersectdest.iSDParm = tab2;
  99640. explainSetInteger(iSub2, pParse->iNextSelectId);
  99641. rc = sqlite3Select(pParse, p, &intersectdest);
  99642. testcase( rc!=SQLITE_OK );
  99643. pDelete = p->pPrior;
  99644. p->pPrior = pPrior;
  99645. if( p->nSelectRow>pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  99646. sqlite3ExprDelete(db, p->pLimit);
  99647. p->pLimit = pLimit;
  99648. p->pOffset = pOffset;
  99649. /* Generate code to take the intersection of the two temporary
  99650. ** tables.
  99651. */
  99652. assert( p->pEList );
  99653. if( dest.eDest==SRT_Output ){
  99654. Select *pFirst = p;
  99655. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  99656. generateColumnNames(pParse, 0, pFirst->pEList);
  99657. }
  99658. iBreak = sqlite3VdbeMakeLabel(v);
  99659. iCont = sqlite3VdbeMakeLabel(v);
  99660. computeLimitRegisters(pParse, p, iBreak);
  99661. sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
  99662. r1 = sqlite3GetTempReg(pParse);
  99663. iStart = sqlite3VdbeAddOp2(v, OP_RowKey, tab1, r1);
  99664. sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0); VdbeCoverage(v);
  99665. sqlite3ReleaseTempReg(pParse, r1);
  99666. selectInnerLoop(pParse, p, p->pEList, tab1,
  99667. 0, 0, &dest, iCont, iBreak);
  99668. sqlite3VdbeResolveLabel(v, iCont);
  99669. sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
  99670. sqlite3VdbeResolveLabel(v, iBreak);
  99671. sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
  99672. sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
  99673. break;
  99674. }
  99675. }
  99676. explainComposite(pParse, p->op, iSub1, iSub2, p->op!=TK_ALL);
  99677. /* Compute collating sequences used by
  99678. ** temporary tables needed to implement the compound select.
  99679. ** Attach the KeyInfo structure to all temporary tables.
  99680. **
  99681. ** This section is run by the right-most SELECT statement only.
  99682. ** SELECT statements to the left always skip this part. The right-most
  99683. ** SELECT might also skip this part if it has no ORDER BY clause and
  99684. ** no temp tables are required.
  99685. */
  99686. if( p->selFlags & SF_UsesEphemeral ){
  99687. int i; /* Loop counter */
  99688. KeyInfo *pKeyInfo; /* Collating sequence for the result set */
  99689. Select *pLoop; /* For looping through SELECT statements */
  99690. CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
  99691. int nCol; /* Number of columns in result set */
  99692. assert( p->pNext==0 );
  99693. nCol = p->pEList->nExpr;
  99694. pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
  99695. if( !pKeyInfo ){
  99696. rc = SQLITE_NOMEM;
  99697. goto multi_select_end;
  99698. }
  99699. for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
  99700. *apColl = multiSelectCollSeq(pParse, p, i);
  99701. if( 0==*apColl ){
  99702. *apColl = db->pDfltColl;
  99703. }
  99704. }
  99705. for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
  99706. for(i=0; i<2; i++){
  99707. int addr = pLoop->addrOpenEphm[i];
  99708. if( addr<0 ){
  99709. /* If [0] is unused then [1] is also unused. So we can
  99710. ** always safely abort as soon as the first unused slot is found */
  99711. assert( pLoop->addrOpenEphm[1]<0 );
  99712. break;
  99713. }
  99714. sqlite3VdbeChangeP2(v, addr, nCol);
  99715. sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
  99716. P4_KEYINFO);
  99717. pLoop->addrOpenEphm[i] = -1;
  99718. }
  99719. }
  99720. sqlite3KeyInfoUnref(pKeyInfo);
  99721. }
  99722. multi_select_end:
  99723. pDest->iSdst = dest.iSdst;
  99724. pDest->nSdst = dest.nSdst;
  99725. sqlite3SelectDelete(db, pDelete);
  99726. return rc;
  99727. }
  99728. #endif /* SQLITE_OMIT_COMPOUND_SELECT */
  99729. /*
  99730. ** Code an output subroutine for a coroutine implementation of a
  99731. ** SELECT statment.
  99732. **
  99733. ** The data to be output is contained in pIn->iSdst. There are
  99734. ** pIn->nSdst columns to be output. pDest is where the output should
  99735. ** be sent.
  99736. **
  99737. ** regReturn is the number of the register holding the subroutine
  99738. ** return address.
  99739. **
  99740. ** If regPrev>0 then it is the first register in a vector that
  99741. ** records the previous output. mem[regPrev] is a flag that is false
  99742. ** if there has been no previous output. If regPrev>0 then code is
  99743. ** generated to suppress duplicates. pKeyInfo is used for comparing
  99744. ** keys.
  99745. **
  99746. ** If the LIMIT found in p->iLimit is reached, jump immediately to
  99747. ** iBreak.
  99748. */
  99749. static int generateOutputSubroutine(
  99750. Parse *pParse, /* Parsing context */
  99751. Select *p, /* The SELECT statement */
  99752. SelectDest *pIn, /* Coroutine supplying data */
  99753. SelectDest *pDest, /* Where to send the data */
  99754. int regReturn, /* The return address register */
  99755. int regPrev, /* Previous result register. No uniqueness if 0 */
  99756. KeyInfo *pKeyInfo, /* For comparing with previous entry */
  99757. int iBreak /* Jump here if we hit the LIMIT */
  99758. ){
  99759. Vdbe *v = pParse->pVdbe;
  99760. int iContinue;
  99761. int addr;
  99762. addr = sqlite3VdbeCurrentAddr(v);
  99763. iContinue = sqlite3VdbeMakeLabel(v);
  99764. /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
  99765. */
  99766. if( regPrev ){
  99767. int j1, j2;
  99768. j1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
  99769. j2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
  99770. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  99771. sqlite3VdbeAddOp3(v, OP_Jump, j2+2, iContinue, j2+2); VdbeCoverage(v);
  99772. sqlite3VdbeJumpHere(v, j1);
  99773. sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
  99774. sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
  99775. }
  99776. if( pParse->db->mallocFailed ) return 0;
  99777. /* Suppress the first OFFSET entries if there is an OFFSET clause
  99778. */
  99779. codeOffset(v, p->iOffset, iContinue);
  99780. switch( pDest->eDest ){
  99781. /* Store the result as data using a unique key.
  99782. */
  99783. case SRT_Table:
  99784. case SRT_EphemTab: {
  99785. int r1 = sqlite3GetTempReg(pParse);
  99786. int r2 = sqlite3GetTempReg(pParse);
  99787. testcase( pDest->eDest==SRT_Table );
  99788. testcase( pDest->eDest==SRT_EphemTab );
  99789. sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
  99790. sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
  99791. sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
  99792. sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
  99793. sqlite3ReleaseTempReg(pParse, r2);
  99794. sqlite3ReleaseTempReg(pParse, r1);
  99795. break;
  99796. }
  99797. #ifndef SQLITE_OMIT_SUBQUERY
  99798. /* If we are creating a set for an "expr IN (SELECT ...)" construct,
  99799. ** then there should be a single item on the stack. Write this
  99800. ** item into the set table with bogus data.
  99801. */
  99802. case SRT_Set: {
  99803. int r1;
  99804. assert( pIn->nSdst==1 );
  99805. pDest->affSdst =
  99806. sqlite3CompareAffinity(p->pEList->a[0].pExpr, pDest->affSdst);
  99807. r1 = sqlite3GetTempReg(pParse);
  99808. sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, 1, r1, &pDest->affSdst,1);
  99809. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, 1);
  99810. sqlite3VdbeAddOp2(v, OP_IdxInsert, pDest->iSDParm, r1);
  99811. sqlite3ReleaseTempReg(pParse, r1);
  99812. break;
  99813. }
  99814. #if 0 /* Never occurs on an ORDER BY query */
  99815. /* If any row exist in the result set, record that fact and abort.
  99816. */
  99817. case SRT_Exists: {
  99818. sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
  99819. /* The LIMIT clause will terminate the loop for us */
  99820. break;
  99821. }
  99822. #endif
  99823. /* If this is a scalar select that is part of an expression, then
  99824. ** store the results in the appropriate memory cell and break out
  99825. ** of the scan loop.
  99826. */
  99827. case SRT_Mem: {
  99828. assert( pIn->nSdst==1 );
  99829. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, 1);
  99830. /* The LIMIT clause will jump out of the loop for us */
  99831. break;
  99832. }
  99833. #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
  99834. /* The results are stored in a sequence of registers
  99835. ** starting at pDest->iSdst. Then the co-routine yields.
  99836. */
  99837. case SRT_Coroutine: {
  99838. if( pDest->iSdst==0 ){
  99839. pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
  99840. pDest->nSdst = pIn->nSdst;
  99841. }
  99842. sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pDest->nSdst);
  99843. sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
  99844. break;
  99845. }
  99846. /* If none of the above, then the result destination must be
  99847. ** SRT_Output. This routine is never called with any other
  99848. ** destination other than the ones handled above or SRT_Output.
  99849. **
  99850. ** For SRT_Output, results are stored in a sequence of registers.
  99851. ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
  99852. ** return the next row of result.
  99853. */
  99854. default: {
  99855. assert( pDest->eDest==SRT_Output );
  99856. sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
  99857. sqlite3ExprCacheAffinityChange(pParse, pIn->iSdst, pIn->nSdst);
  99858. break;
  99859. }
  99860. }
  99861. /* Jump to the end of the loop if the LIMIT is reached.
  99862. */
  99863. if( p->iLimit ){
  99864. sqlite3VdbeAddOp3(v, OP_IfZero, p->iLimit, iBreak, -1); VdbeCoverage(v);
  99865. }
  99866. /* Generate the subroutine return
  99867. */
  99868. sqlite3VdbeResolveLabel(v, iContinue);
  99869. sqlite3VdbeAddOp1(v, OP_Return, regReturn);
  99870. return addr;
  99871. }
  99872. /*
  99873. ** Alternative compound select code generator for cases when there
  99874. ** is an ORDER BY clause.
  99875. **
  99876. ** We assume a query of the following form:
  99877. **
  99878. ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
  99879. **
  99880. ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
  99881. ** is to code both <selectA> and <selectB> with the ORDER BY clause as
  99882. ** co-routines. Then run the co-routines in parallel and merge the results
  99883. ** into the output. In addition to the two coroutines (called selectA and
  99884. ** selectB) there are 7 subroutines:
  99885. **
  99886. ** outA: Move the output of the selectA coroutine into the output
  99887. ** of the compound query.
  99888. **
  99889. ** outB: Move the output of the selectB coroutine into the output
  99890. ** of the compound query. (Only generated for UNION and
  99891. ** UNION ALL. EXCEPT and INSERTSECT never output a row that
  99892. ** appears only in B.)
  99893. **
  99894. ** AltB: Called when there is data from both coroutines and A<B.
  99895. **
  99896. ** AeqB: Called when there is data from both coroutines and A==B.
  99897. **
  99898. ** AgtB: Called when there is data from both coroutines and A>B.
  99899. **
  99900. ** EofA: Called when data is exhausted from selectA.
  99901. **
  99902. ** EofB: Called when data is exhausted from selectB.
  99903. **
  99904. ** The implementation of the latter five subroutines depend on which
  99905. ** <operator> is used:
  99906. **
  99907. **
  99908. ** UNION ALL UNION EXCEPT INTERSECT
  99909. ** ------------- ----------------- -------------- -----------------
  99910. ** AltB: outA, nextA outA, nextA outA, nextA nextA
  99911. **
  99912. ** AeqB: outA, nextA nextA nextA outA, nextA
  99913. **
  99914. ** AgtB: outB, nextB outB, nextB nextB nextB
  99915. **
  99916. ** EofA: outB, nextB outB, nextB halt halt
  99917. **
  99918. ** EofB: outA, nextA outA, nextA outA, nextA halt
  99919. **
  99920. ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
  99921. ** causes an immediate jump to EofA and an EOF on B following nextB causes
  99922. ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
  99923. ** following nextX causes a jump to the end of the select processing.
  99924. **
  99925. ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
  99926. ** within the output subroutine. The regPrev register set holds the previously
  99927. ** output value. A comparison is made against this value and the output
  99928. ** is skipped if the next results would be the same as the previous.
  99929. **
  99930. ** The implementation plan is to implement the two coroutines and seven
  99931. ** subroutines first, then put the control logic at the bottom. Like this:
  99932. **
  99933. ** goto Init
  99934. ** coA: coroutine for left query (A)
  99935. ** coB: coroutine for right query (B)
  99936. ** outA: output one row of A
  99937. ** outB: output one row of B (UNION and UNION ALL only)
  99938. ** EofA: ...
  99939. ** EofB: ...
  99940. ** AltB: ...
  99941. ** AeqB: ...
  99942. ** AgtB: ...
  99943. ** Init: initialize coroutine registers
  99944. ** yield coA
  99945. ** if eof(A) goto EofA
  99946. ** yield coB
  99947. ** if eof(B) goto EofB
  99948. ** Cmpr: Compare A, B
  99949. ** Jump AltB, AeqB, AgtB
  99950. ** End: ...
  99951. **
  99952. ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
  99953. ** actually called using Gosub and they do not Return. EofA and EofB loop
  99954. ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
  99955. ** and AgtB jump to either L2 or to one of EofA or EofB.
  99956. */
  99957. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  99958. static int multiSelectOrderBy(
  99959. Parse *pParse, /* Parsing context */
  99960. Select *p, /* The right-most of SELECTs to be coded */
  99961. SelectDest *pDest /* What to do with query results */
  99962. ){
  99963. int i, j; /* Loop counters */
  99964. Select *pPrior; /* Another SELECT immediately to our left */
  99965. Vdbe *v; /* Generate code to this VDBE */
  99966. SelectDest destA; /* Destination for coroutine A */
  99967. SelectDest destB; /* Destination for coroutine B */
  99968. int regAddrA; /* Address register for select-A coroutine */
  99969. int regAddrB; /* Address register for select-B coroutine */
  99970. int addrSelectA; /* Address of the select-A coroutine */
  99971. int addrSelectB; /* Address of the select-B coroutine */
  99972. int regOutA; /* Address register for the output-A subroutine */
  99973. int regOutB; /* Address register for the output-B subroutine */
  99974. int addrOutA; /* Address of the output-A subroutine */
  99975. int addrOutB = 0; /* Address of the output-B subroutine */
  99976. int addrEofA; /* Address of the select-A-exhausted subroutine */
  99977. int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
  99978. int addrEofB; /* Address of the select-B-exhausted subroutine */
  99979. int addrAltB; /* Address of the A<B subroutine */
  99980. int addrAeqB; /* Address of the A==B subroutine */
  99981. int addrAgtB; /* Address of the A>B subroutine */
  99982. int regLimitA; /* Limit register for select-A */
  99983. int regLimitB; /* Limit register for select-A */
  99984. int regPrev; /* A range of registers to hold previous output */
  99985. int savedLimit; /* Saved value of p->iLimit */
  99986. int savedOffset; /* Saved value of p->iOffset */
  99987. int labelCmpr; /* Label for the start of the merge algorithm */
  99988. int labelEnd; /* Label for the end of the overall SELECT stmt */
  99989. int j1; /* Jump instructions that get retargetted */
  99990. int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
  99991. KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
  99992. KeyInfo *pKeyMerge; /* Comparison information for merging rows */
  99993. sqlite3 *db; /* Database connection */
  99994. ExprList *pOrderBy; /* The ORDER BY clause */
  99995. int nOrderBy; /* Number of terms in the ORDER BY clause */
  99996. int *aPermute; /* Mapping from ORDER BY terms to result set columns */
  99997. #ifndef SQLITE_OMIT_EXPLAIN
  99998. int iSub1; /* EQP id of left-hand query */
  99999. int iSub2; /* EQP id of right-hand query */
  100000. #endif
  100001. assert( p->pOrderBy!=0 );
  100002. assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
  100003. db = pParse->db;
  100004. v = pParse->pVdbe;
  100005. assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
  100006. labelEnd = sqlite3VdbeMakeLabel(v);
  100007. labelCmpr = sqlite3VdbeMakeLabel(v);
  100008. /* Patch up the ORDER BY clause
  100009. */
  100010. op = p->op;
  100011. pPrior = p->pPrior;
  100012. assert( pPrior->pOrderBy==0 );
  100013. pOrderBy = p->pOrderBy;
  100014. assert( pOrderBy );
  100015. nOrderBy = pOrderBy->nExpr;
  100016. /* For operators other than UNION ALL we have to make sure that
  100017. ** the ORDER BY clause covers every term of the result set. Add
  100018. ** terms to the ORDER BY clause as necessary.
  100019. */
  100020. if( op!=TK_ALL ){
  100021. for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
  100022. struct ExprList_item *pItem;
  100023. for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
  100024. assert( pItem->u.x.iOrderByCol>0 );
  100025. if( pItem->u.x.iOrderByCol==i ) break;
  100026. }
  100027. if( j==nOrderBy ){
  100028. Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
  100029. if( pNew==0 ) return SQLITE_NOMEM;
  100030. pNew->flags |= EP_IntValue;
  100031. pNew->u.iValue = i;
  100032. pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
  100033. if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
  100034. }
  100035. }
  100036. }
  100037. /* Compute the comparison permutation and keyinfo that is used with
  100038. ** the permutation used to determine if the next
  100039. ** row of results comes from selectA or selectB. Also add explicit
  100040. ** collations to the ORDER BY clause terms so that when the subqueries
  100041. ** to the right and the left are evaluated, they use the correct
  100042. ** collation.
  100043. */
  100044. aPermute = sqlite3DbMallocRaw(db, sizeof(int)*nOrderBy);
  100045. if( aPermute ){
  100046. struct ExprList_item *pItem;
  100047. for(i=0, pItem=pOrderBy->a; i<nOrderBy; i++, pItem++){
  100048. assert( pItem->u.x.iOrderByCol>0
  100049. && pItem->u.x.iOrderByCol<=p->pEList->nExpr );
  100050. aPermute[i] = pItem->u.x.iOrderByCol - 1;
  100051. }
  100052. pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
  100053. }else{
  100054. pKeyMerge = 0;
  100055. }
  100056. /* Reattach the ORDER BY clause to the query.
  100057. */
  100058. p->pOrderBy = pOrderBy;
  100059. pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
  100060. /* Allocate a range of temporary registers and the KeyInfo needed
  100061. ** for the logic that removes duplicate result rows when the
  100062. ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
  100063. */
  100064. if( op==TK_ALL ){
  100065. regPrev = 0;
  100066. }else{
  100067. int nExpr = p->pEList->nExpr;
  100068. assert( nOrderBy>=nExpr || db->mallocFailed );
  100069. regPrev = pParse->nMem+1;
  100070. pParse->nMem += nExpr+1;
  100071. sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
  100072. pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
  100073. if( pKeyDup ){
  100074. assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
  100075. for(i=0; i<nExpr; i++){
  100076. pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
  100077. pKeyDup->aSortOrder[i] = 0;
  100078. }
  100079. }
  100080. }
  100081. /* Separate the left and the right query from one another
  100082. */
  100083. p->pPrior = 0;
  100084. pPrior->pNext = 0;
  100085. sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
  100086. if( pPrior->pPrior==0 ){
  100087. sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
  100088. }
  100089. /* Compute the limit registers */
  100090. computeLimitRegisters(pParse, p, labelEnd);
  100091. if( p->iLimit && op==TK_ALL ){
  100092. regLimitA = ++pParse->nMem;
  100093. regLimitB = ++pParse->nMem;
  100094. sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
  100095. regLimitA);
  100096. sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
  100097. }else{
  100098. regLimitA = regLimitB = 0;
  100099. }
  100100. sqlite3ExprDelete(db, p->pLimit);
  100101. p->pLimit = 0;
  100102. sqlite3ExprDelete(db, p->pOffset);
  100103. p->pOffset = 0;
  100104. regAddrA = ++pParse->nMem;
  100105. regAddrB = ++pParse->nMem;
  100106. regOutA = ++pParse->nMem;
  100107. regOutB = ++pParse->nMem;
  100108. sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
  100109. sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
  100110. /* Generate a coroutine to evaluate the SELECT statement to the
  100111. ** left of the compound operator - the "A" select.
  100112. */
  100113. addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
  100114. j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
  100115. VdbeComment((v, "left SELECT"));
  100116. pPrior->iLimit = regLimitA;
  100117. explainSetInteger(iSub1, pParse->iNextSelectId);
  100118. sqlite3Select(pParse, pPrior, &destA);
  100119. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrA);
  100120. sqlite3VdbeJumpHere(v, j1);
  100121. /* Generate a coroutine to evaluate the SELECT statement on
  100122. ** the right - the "B" select
  100123. */
  100124. addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
  100125. j1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
  100126. VdbeComment((v, "right SELECT"));
  100127. savedLimit = p->iLimit;
  100128. savedOffset = p->iOffset;
  100129. p->iLimit = regLimitB;
  100130. p->iOffset = 0;
  100131. explainSetInteger(iSub2, pParse->iNextSelectId);
  100132. sqlite3Select(pParse, p, &destB);
  100133. p->iLimit = savedLimit;
  100134. p->iOffset = savedOffset;
  100135. sqlite3VdbeAddOp1(v, OP_EndCoroutine, regAddrB);
  100136. /* Generate a subroutine that outputs the current row of the A
  100137. ** select as the next output row of the compound select.
  100138. */
  100139. VdbeNoopComment((v, "Output routine for A"));
  100140. addrOutA = generateOutputSubroutine(pParse,
  100141. p, &destA, pDest, regOutA,
  100142. regPrev, pKeyDup, labelEnd);
  100143. /* Generate a subroutine that outputs the current row of the B
  100144. ** select as the next output row of the compound select.
  100145. */
  100146. if( op==TK_ALL || op==TK_UNION ){
  100147. VdbeNoopComment((v, "Output routine for B"));
  100148. addrOutB = generateOutputSubroutine(pParse,
  100149. p, &destB, pDest, regOutB,
  100150. regPrev, pKeyDup, labelEnd);
  100151. }
  100152. sqlite3KeyInfoUnref(pKeyDup);
  100153. /* Generate a subroutine to run when the results from select A
  100154. ** are exhausted and only data in select B remains.
  100155. */
  100156. if( op==TK_EXCEPT || op==TK_INTERSECT ){
  100157. addrEofA_noB = addrEofA = labelEnd;
  100158. }else{
  100159. VdbeNoopComment((v, "eof-A subroutine"));
  100160. addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  100161. addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
  100162. VdbeCoverage(v);
  100163. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofA);
  100164. p->nSelectRow += pPrior->nSelectRow;
  100165. }
  100166. /* Generate a subroutine to run when the results from select B
  100167. ** are exhausted and only data in select A remains.
  100168. */
  100169. if( op==TK_INTERSECT ){
  100170. addrEofB = addrEofA;
  100171. if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
  100172. }else{
  100173. VdbeNoopComment((v, "eof-B subroutine"));
  100174. addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  100175. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
  100176. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEofB);
  100177. }
  100178. /* Generate code to handle the case of A<B
  100179. */
  100180. VdbeNoopComment((v, "A-lt-B subroutine"));
  100181. addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
  100182. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  100183. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  100184. /* Generate code to handle the case of A==B
  100185. */
  100186. if( op==TK_ALL ){
  100187. addrAeqB = addrAltB;
  100188. }else if( op==TK_INTERSECT ){
  100189. addrAeqB = addrAltB;
  100190. addrAltB++;
  100191. }else{
  100192. VdbeNoopComment((v, "A-eq-B subroutine"));
  100193. addrAeqB =
  100194. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
  100195. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  100196. }
  100197. /* Generate code to handle the case of A>B
  100198. */
  100199. VdbeNoopComment((v, "A-gt-B subroutine"));
  100200. addrAgtB = sqlite3VdbeCurrentAddr(v);
  100201. if( op==TK_ALL || op==TK_UNION ){
  100202. sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
  100203. }
  100204. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  100205. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelCmpr);
  100206. /* This code runs once to initialize everything.
  100207. */
  100208. sqlite3VdbeJumpHere(v, j1);
  100209. sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
  100210. sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
  100211. /* Implement the main merge loop
  100212. */
  100213. sqlite3VdbeResolveLabel(v, labelCmpr);
  100214. sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
  100215. sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
  100216. (char*)pKeyMerge, P4_KEYINFO);
  100217. sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
  100218. sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
  100219. /* Jump to the this point in order to terminate the query.
  100220. */
  100221. sqlite3VdbeResolveLabel(v, labelEnd);
  100222. /* Set the number of output columns
  100223. */
  100224. if( pDest->eDest==SRT_Output ){
  100225. Select *pFirst = pPrior;
  100226. while( pFirst->pPrior ) pFirst = pFirst->pPrior;
  100227. generateColumnNames(pParse, 0, pFirst->pEList);
  100228. }
  100229. /* Reassembly the compound query so that it will be freed correctly
  100230. ** by the calling function */
  100231. if( p->pPrior ){
  100232. sqlite3SelectDelete(db, p->pPrior);
  100233. }
  100234. p->pPrior = pPrior;
  100235. pPrior->pNext = p;
  100236. /*** TBD: Insert subroutine calls to close cursors on incomplete
  100237. **** subqueries ****/
  100238. explainComposite(pParse, p->op, iSub1, iSub2, 0);
  100239. return SQLITE_OK;
  100240. }
  100241. #endif
  100242. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  100243. /* Forward Declarations */
  100244. static void substExprList(sqlite3*, ExprList*, int, ExprList*);
  100245. static void substSelect(sqlite3*, Select *, int, ExprList *);
  100246. /*
  100247. ** Scan through the expression pExpr. Replace every reference to
  100248. ** a column in table number iTable with a copy of the iColumn-th
  100249. ** entry in pEList. (But leave references to the ROWID column
  100250. ** unchanged.)
  100251. **
  100252. ** This routine is part of the flattening procedure. A subquery
  100253. ** whose result set is defined by pEList appears as entry in the
  100254. ** FROM clause of a SELECT such that the VDBE cursor assigned to that
  100255. ** FORM clause entry is iTable. This routine make the necessary
  100256. ** changes to pExpr so that it refers directly to the source table
  100257. ** of the subquery rather the result set of the subquery.
  100258. */
  100259. static Expr *substExpr(
  100260. sqlite3 *db, /* Report malloc errors to this connection */
  100261. Expr *pExpr, /* Expr in which substitution occurs */
  100262. int iTable, /* Table to be substituted */
  100263. ExprList *pEList /* Substitute expressions */
  100264. ){
  100265. if( pExpr==0 ) return 0;
  100266. if( pExpr->op==TK_COLUMN && pExpr->iTable==iTable ){
  100267. if( pExpr->iColumn<0 ){
  100268. pExpr->op = TK_NULL;
  100269. }else{
  100270. Expr *pNew;
  100271. assert( pEList!=0 && pExpr->iColumn<pEList->nExpr );
  100272. assert( pExpr->pLeft==0 && pExpr->pRight==0 );
  100273. pNew = sqlite3ExprDup(db, pEList->a[pExpr->iColumn].pExpr, 0);
  100274. sqlite3ExprDelete(db, pExpr);
  100275. pExpr = pNew;
  100276. }
  100277. }else{
  100278. pExpr->pLeft = substExpr(db, pExpr->pLeft, iTable, pEList);
  100279. pExpr->pRight = substExpr(db, pExpr->pRight, iTable, pEList);
  100280. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  100281. substSelect(db, pExpr->x.pSelect, iTable, pEList);
  100282. }else{
  100283. substExprList(db, pExpr->x.pList, iTable, pEList);
  100284. }
  100285. }
  100286. return pExpr;
  100287. }
  100288. static void substExprList(
  100289. sqlite3 *db, /* Report malloc errors here */
  100290. ExprList *pList, /* List to scan and in which to make substitutes */
  100291. int iTable, /* Table to be substituted */
  100292. ExprList *pEList /* Substitute values */
  100293. ){
  100294. int i;
  100295. if( pList==0 ) return;
  100296. for(i=0; i<pList->nExpr; i++){
  100297. pList->a[i].pExpr = substExpr(db, pList->a[i].pExpr, iTable, pEList);
  100298. }
  100299. }
  100300. static void substSelect(
  100301. sqlite3 *db, /* Report malloc errors here */
  100302. Select *p, /* SELECT statement in which to make substitutions */
  100303. int iTable, /* Table to be replaced */
  100304. ExprList *pEList /* Substitute values */
  100305. ){
  100306. SrcList *pSrc;
  100307. struct SrcList_item *pItem;
  100308. int i;
  100309. if( !p ) return;
  100310. substExprList(db, p->pEList, iTable, pEList);
  100311. substExprList(db, p->pGroupBy, iTable, pEList);
  100312. substExprList(db, p->pOrderBy, iTable, pEList);
  100313. p->pHaving = substExpr(db, p->pHaving, iTable, pEList);
  100314. p->pWhere = substExpr(db, p->pWhere, iTable, pEList);
  100315. substSelect(db, p->pPrior, iTable, pEList);
  100316. pSrc = p->pSrc;
  100317. assert( pSrc ); /* Even for (SELECT 1) we have: pSrc!=0 but pSrc->nSrc==0 */
  100318. if( ALWAYS(pSrc) ){
  100319. for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
  100320. substSelect(db, pItem->pSelect, iTable, pEList);
  100321. }
  100322. }
  100323. }
  100324. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  100325. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  100326. /*
  100327. ** This routine attempts to flatten subqueries as a performance optimization.
  100328. ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
  100329. **
  100330. ** To understand the concept of flattening, consider the following
  100331. ** query:
  100332. **
  100333. ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
  100334. **
  100335. ** The default way of implementing this query is to execute the
  100336. ** subquery first and store the results in a temporary table, then
  100337. ** run the outer query on that temporary table. This requires two
  100338. ** passes over the data. Furthermore, because the temporary table
  100339. ** has no indices, the WHERE clause on the outer query cannot be
  100340. ** optimized.
  100341. **
  100342. ** This routine attempts to rewrite queries such as the above into
  100343. ** a single flat select, like this:
  100344. **
  100345. ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
  100346. **
  100347. ** The code generated for this simplification gives the same result
  100348. ** but only has to scan the data once. And because indices might
  100349. ** exist on the table t1, a complete scan of the data might be
  100350. ** avoided.
  100351. **
  100352. ** Flattening is only attempted if all of the following are true:
  100353. **
  100354. ** (1) The subquery and the outer query do not both use aggregates.
  100355. **
  100356. ** (2) The subquery is not an aggregate or the outer query is not a join.
  100357. **
  100358. ** (3) The subquery is not the right operand of a left outer join
  100359. ** (Originally ticket #306. Strengthened by ticket #3300)
  100360. **
  100361. ** (4) The subquery is not DISTINCT.
  100362. **
  100363. ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
  100364. ** sub-queries that were excluded from this optimization. Restriction
  100365. ** (4) has since been expanded to exclude all DISTINCT subqueries.
  100366. **
  100367. ** (6) The subquery does not use aggregates or the outer query is not
  100368. ** DISTINCT.
  100369. **
  100370. ** (7) The subquery has a FROM clause. TODO: For subqueries without
  100371. ** A FROM clause, consider adding a FROM close with the special
  100372. ** table sqlite_once that consists of a single row containing a
  100373. ** single NULL.
  100374. **
  100375. ** (8) The subquery does not use LIMIT or the outer query is not a join.
  100376. **
  100377. ** (9) The subquery does not use LIMIT or the outer query does not use
  100378. ** aggregates.
  100379. **
  100380. ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
  100381. ** accidently carried the comment forward until 2014-09-15. Original
  100382. ** text: "The subquery does not use aggregates or the outer query does not
  100383. ** use LIMIT."
  100384. **
  100385. ** (11) The subquery and the outer query do not both have ORDER BY clauses.
  100386. **
  100387. ** (**) Not implemented. Subsumed into restriction (3). Was previously
  100388. ** a separate restriction deriving from ticket #350.
  100389. **
  100390. ** (13) The subquery and outer query do not both use LIMIT.
  100391. **
  100392. ** (14) The subquery does not use OFFSET.
  100393. **
  100394. ** (15) The outer query is not part of a compound select or the
  100395. ** subquery does not have a LIMIT clause.
  100396. ** (See ticket #2339 and ticket [02a8e81d44]).
  100397. **
  100398. ** (16) The outer query is not an aggregate or the subquery does
  100399. ** not contain ORDER BY. (Ticket #2942) This used to not matter
  100400. ** until we introduced the group_concat() function.
  100401. **
  100402. ** (17) The sub-query is not a compound select, or it is a UNION ALL
  100403. ** compound clause made up entirely of non-aggregate queries, and
  100404. ** the parent query:
  100405. **
  100406. ** * is not itself part of a compound select,
  100407. ** * is not an aggregate or DISTINCT query, and
  100408. ** * is not a join
  100409. **
  100410. ** The parent and sub-query may contain WHERE clauses. Subject to
  100411. ** rules (11), (13) and (14), they may also contain ORDER BY,
  100412. ** LIMIT and OFFSET clauses. The subquery cannot use any compound
  100413. ** operator other than UNION ALL because all the other compound
  100414. ** operators have an implied DISTINCT which is disallowed by
  100415. ** restriction (4).
  100416. **
  100417. ** Also, each component of the sub-query must return the same number
  100418. ** of result columns. This is actually a requirement for any compound
  100419. ** SELECT statement, but all the code here does is make sure that no
  100420. ** such (illegal) sub-query is flattened. The caller will detect the
  100421. ** syntax error and return a detailed message.
  100422. **
  100423. ** (18) If the sub-query is a compound select, then all terms of the
  100424. ** ORDER by clause of the parent must be simple references to
  100425. ** columns of the sub-query.
  100426. **
  100427. ** (19) The subquery does not use LIMIT or the outer query does not
  100428. ** have a WHERE clause.
  100429. **
  100430. ** (20) If the sub-query is a compound select, then it must not use
  100431. ** an ORDER BY clause. Ticket #3773. We could relax this constraint
  100432. ** somewhat by saying that the terms of the ORDER BY clause must
  100433. ** appear as unmodified result columns in the outer query. But we
  100434. ** have other optimizations in mind to deal with that case.
  100435. **
  100436. ** (21) The subquery does not use LIMIT or the outer query is not
  100437. ** DISTINCT. (See ticket [752e1646fc]).
  100438. **
  100439. ** (22) The subquery is not a recursive CTE.
  100440. **
  100441. ** (23) The parent is not a recursive CTE, or the sub-query is not a
  100442. ** compound query. This restriction is because transforming the
  100443. ** parent to a compound query confuses the code that handles
  100444. ** recursive queries in multiSelect().
  100445. **
  100446. ** (24) The subquery is not an aggregate that uses the built-in min() or
  100447. ** or max() functions. (Without this restriction, a query like:
  100448. ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
  100449. ** return the value X for which Y was maximal.)
  100450. **
  100451. **
  100452. ** In this routine, the "p" parameter is a pointer to the outer query.
  100453. ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
  100454. ** uses aggregates and subqueryIsAgg is true if the subquery uses aggregates.
  100455. **
  100456. ** If flattening is not attempted, this routine is a no-op and returns 0.
  100457. ** If flattening is attempted this routine returns 1.
  100458. **
  100459. ** All of the expression analysis must occur on both the outer query and
  100460. ** the subquery before this routine runs.
  100461. */
  100462. static int flattenSubquery(
  100463. Parse *pParse, /* Parsing context */
  100464. Select *p, /* The parent or outer SELECT statement */
  100465. int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
  100466. int isAgg, /* True if outer SELECT uses aggregate functions */
  100467. int subqueryIsAgg /* True if the subquery uses aggregate functions */
  100468. ){
  100469. const char *zSavedAuthContext = pParse->zAuthContext;
  100470. Select *pParent;
  100471. Select *pSub; /* The inner query or "subquery" */
  100472. Select *pSub1; /* Pointer to the rightmost select in sub-query */
  100473. SrcList *pSrc; /* The FROM clause of the outer query */
  100474. SrcList *pSubSrc; /* The FROM clause of the subquery */
  100475. ExprList *pList; /* The result set of the outer query */
  100476. int iParent; /* VDBE cursor number of the pSub result set temp table */
  100477. int i; /* Loop counter */
  100478. Expr *pWhere; /* The WHERE clause */
  100479. struct SrcList_item *pSubitem; /* The subquery */
  100480. sqlite3 *db = pParse->db;
  100481. /* Check to see if flattening is permitted. Return 0 if not.
  100482. */
  100483. assert( p!=0 );
  100484. assert( p->pPrior==0 ); /* Unable to flatten compound queries */
  100485. if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
  100486. pSrc = p->pSrc;
  100487. assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
  100488. pSubitem = &pSrc->a[iFrom];
  100489. iParent = pSubitem->iCursor;
  100490. pSub = pSubitem->pSelect;
  100491. assert( pSub!=0 );
  100492. if( isAgg && subqueryIsAgg ) return 0; /* Restriction (1) */
  100493. if( subqueryIsAgg && pSrc->nSrc>1 ) return 0; /* Restriction (2) */
  100494. pSubSrc = pSub->pSrc;
  100495. assert( pSubSrc );
  100496. /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
  100497. ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
  100498. ** because they could be computed at compile-time. But when LIMIT and OFFSET
  100499. ** became arbitrary expressions, we were forced to add restrictions (13)
  100500. ** and (14). */
  100501. if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
  100502. if( pSub->pOffset ) return 0; /* Restriction (14) */
  100503. if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
  100504. return 0; /* Restriction (15) */
  100505. }
  100506. if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
  100507. if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (5) */
  100508. if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
  100509. return 0; /* Restrictions (8)(9) */
  100510. }
  100511. if( (p->selFlags & SF_Distinct)!=0 && subqueryIsAgg ){
  100512. return 0; /* Restriction (6) */
  100513. }
  100514. if( p->pOrderBy && pSub->pOrderBy ){
  100515. return 0; /* Restriction (11) */
  100516. }
  100517. if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
  100518. if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
  100519. if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
  100520. return 0; /* Restriction (21) */
  100521. }
  100522. testcase( pSub->selFlags & SF_Recursive );
  100523. testcase( pSub->selFlags & SF_MinMaxAgg );
  100524. if( pSub->selFlags & (SF_Recursive|SF_MinMaxAgg) ){
  100525. return 0; /* Restrictions (22) and (24) */
  100526. }
  100527. if( (p->selFlags & SF_Recursive) && pSub->pPrior ){
  100528. return 0; /* Restriction (23) */
  100529. }
  100530. /* OBSOLETE COMMENT 1:
  100531. ** Restriction 3: If the subquery is a join, make sure the subquery is
  100532. ** not used as the right operand of an outer join. Examples of why this
  100533. ** is not allowed:
  100534. **
  100535. ** t1 LEFT OUTER JOIN (t2 JOIN t3)
  100536. **
  100537. ** If we flatten the above, we would get
  100538. **
  100539. ** (t1 LEFT OUTER JOIN t2) JOIN t3
  100540. **
  100541. ** which is not at all the same thing.
  100542. **
  100543. ** OBSOLETE COMMENT 2:
  100544. ** Restriction 12: If the subquery is the right operand of a left outer
  100545. ** join, make sure the subquery has no WHERE clause.
  100546. ** An examples of why this is not allowed:
  100547. **
  100548. ** t1 LEFT OUTER JOIN (SELECT * FROM t2 WHERE t2.x>0)
  100549. **
  100550. ** If we flatten the above, we would get
  100551. **
  100552. ** (t1 LEFT OUTER JOIN t2) WHERE t2.x>0
  100553. **
  100554. ** But the t2.x>0 test will always fail on a NULL row of t2, which
  100555. ** effectively converts the OUTER JOIN into an INNER JOIN.
  100556. **
  100557. ** THIS OVERRIDES OBSOLETE COMMENTS 1 AND 2 ABOVE:
  100558. ** Ticket #3300 shows that flattening the right term of a LEFT JOIN
  100559. ** is fraught with danger. Best to avoid the whole thing. If the
  100560. ** subquery is the right term of a LEFT JOIN, then do not flatten.
  100561. */
  100562. if( (pSubitem->jointype & JT_OUTER)!=0 ){
  100563. return 0;
  100564. }
  100565. /* Restriction 17: If the sub-query is a compound SELECT, then it must
  100566. ** use only the UNION ALL operator. And none of the simple select queries
  100567. ** that make up the compound SELECT are allowed to be aggregate or distinct
  100568. ** queries.
  100569. */
  100570. if( pSub->pPrior ){
  100571. if( pSub->pOrderBy ){
  100572. return 0; /* Restriction 20 */
  100573. }
  100574. if( isAgg || (p->selFlags & SF_Distinct)!=0 || pSrc->nSrc!=1 ){
  100575. return 0;
  100576. }
  100577. for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
  100578. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
  100579. testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
  100580. assert( pSub->pSrc!=0 );
  100581. if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0
  100582. || (pSub1->pPrior && pSub1->op!=TK_ALL)
  100583. || pSub1->pSrc->nSrc<1
  100584. || pSub->pEList->nExpr!=pSub1->pEList->nExpr
  100585. ){
  100586. return 0;
  100587. }
  100588. testcase( pSub1->pSrc->nSrc>1 );
  100589. }
  100590. /* Restriction 18. */
  100591. if( p->pOrderBy ){
  100592. int ii;
  100593. for(ii=0; ii<p->pOrderBy->nExpr; ii++){
  100594. if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
  100595. }
  100596. }
  100597. }
  100598. /***** If we reach this point, flattening is permitted. *****/
  100599. SELECTTRACE(1,pParse,p,("flatten %s.%p from term %d\n",
  100600. pSub->zSelName, pSub, iFrom));
  100601. /* Authorize the subquery */
  100602. pParse->zAuthContext = pSubitem->zName;
  100603. TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
  100604. testcase( i==SQLITE_DENY );
  100605. pParse->zAuthContext = zSavedAuthContext;
  100606. /* If the sub-query is a compound SELECT statement, then (by restrictions
  100607. ** 17 and 18 above) it must be a UNION ALL and the parent query must
  100608. ** be of the form:
  100609. **
  100610. ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
  100611. **
  100612. ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
  100613. ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
  100614. ** OFFSET clauses and joins them to the left-hand-side of the original
  100615. ** using UNION ALL operators. In this case N is the number of simple
  100616. ** select statements in the compound sub-query.
  100617. **
  100618. ** Example:
  100619. **
  100620. ** SELECT a+1 FROM (
  100621. ** SELECT x FROM tab
  100622. ** UNION ALL
  100623. ** SELECT y FROM tab
  100624. ** UNION ALL
  100625. ** SELECT abs(z*2) FROM tab2
  100626. ** ) WHERE a!=5 ORDER BY 1
  100627. **
  100628. ** Transformed into:
  100629. **
  100630. ** SELECT x+1 FROM tab WHERE x+1!=5
  100631. ** UNION ALL
  100632. ** SELECT y+1 FROM tab WHERE y+1!=5
  100633. ** UNION ALL
  100634. ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
  100635. ** ORDER BY 1
  100636. **
  100637. ** We call this the "compound-subquery flattening".
  100638. */
  100639. for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
  100640. Select *pNew;
  100641. ExprList *pOrderBy = p->pOrderBy;
  100642. Expr *pLimit = p->pLimit;
  100643. Expr *pOffset = p->pOffset;
  100644. Select *pPrior = p->pPrior;
  100645. p->pOrderBy = 0;
  100646. p->pSrc = 0;
  100647. p->pPrior = 0;
  100648. p->pLimit = 0;
  100649. p->pOffset = 0;
  100650. pNew = sqlite3SelectDup(db, p, 0);
  100651. sqlite3SelectSetName(pNew, pSub->zSelName);
  100652. p->pOffset = pOffset;
  100653. p->pLimit = pLimit;
  100654. p->pOrderBy = pOrderBy;
  100655. p->pSrc = pSrc;
  100656. p->op = TK_ALL;
  100657. if( pNew==0 ){
  100658. p->pPrior = pPrior;
  100659. }else{
  100660. pNew->pPrior = pPrior;
  100661. if( pPrior ) pPrior->pNext = pNew;
  100662. pNew->pNext = p;
  100663. p->pPrior = pNew;
  100664. SELECTTRACE(2,pParse,p,
  100665. ("compound-subquery flattener creates %s.%p as peer\n",
  100666. pNew->zSelName, pNew));
  100667. }
  100668. if( db->mallocFailed ) return 1;
  100669. }
  100670. /* Begin flattening the iFrom-th entry of the FROM clause
  100671. ** in the outer query.
  100672. */
  100673. pSub = pSub1 = pSubitem->pSelect;
  100674. /* Delete the transient table structure associated with the
  100675. ** subquery
  100676. */
  100677. sqlite3DbFree(db, pSubitem->zDatabase);
  100678. sqlite3DbFree(db, pSubitem->zName);
  100679. sqlite3DbFree(db, pSubitem->zAlias);
  100680. pSubitem->zDatabase = 0;
  100681. pSubitem->zName = 0;
  100682. pSubitem->zAlias = 0;
  100683. pSubitem->pSelect = 0;
  100684. /* Defer deleting the Table object associated with the
  100685. ** subquery until code generation is
  100686. ** complete, since there may still exist Expr.pTab entries that
  100687. ** refer to the subquery even after flattening. Ticket #3346.
  100688. **
  100689. ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
  100690. */
  100691. if( ALWAYS(pSubitem->pTab!=0) ){
  100692. Table *pTabToDel = pSubitem->pTab;
  100693. if( pTabToDel->nRef==1 ){
  100694. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  100695. pTabToDel->pNextZombie = pToplevel->pZombieTab;
  100696. pToplevel->pZombieTab = pTabToDel;
  100697. }else{
  100698. pTabToDel->nRef--;
  100699. }
  100700. pSubitem->pTab = 0;
  100701. }
  100702. /* The following loop runs once for each term in a compound-subquery
  100703. ** flattening (as described above). If we are doing a different kind
  100704. ** of flattening - a flattening other than a compound-subquery flattening -
  100705. ** then this loop only runs once.
  100706. **
  100707. ** This loop moves all of the FROM elements of the subquery into the
  100708. ** the FROM clause of the outer query. Before doing this, remember
  100709. ** the cursor number for the original outer query FROM element in
  100710. ** iParent. The iParent cursor will never be used. Subsequent code
  100711. ** will scan expressions looking for iParent references and replace
  100712. ** those references with expressions that resolve to the subquery FROM
  100713. ** elements we are now copying in.
  100714. */
  100715. for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
  100716. int nSubSrc;
  100717. u8 jointype = 0;
  100718. pSubSrc = pSub->pSrc; /* FROM clause of subquery */
  100719. nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
  100720. pSrc = pParent->pSrc; /* FROM clause of the outer query */
  100721. if( pSrc ){
  100722. assert( pParent==p ); /* First time through the loop */
  100723. jointype = pSubitem->jointype;
  100724. }else{
  100725. assert( pParent!=p ); /* 2nd and subsequent times through the loop */
  100726. pSrc = pParent->pSrc = sqlite3SrcListAppend(db, 0, 0, 0);
  100727. if( pSrc==0 ){
  100728. assert( db->mallocFailed );
  100729. break;
  100730. }
  100731. }
  100732. /* The subquery uses a single slot of the FROM clause of the outer
  100733. ** query. If the subquery has more than one element in its FROM clause,
  100734. ** then expand the outer query to make space for it to hold all elements
  100735. ** of the subquery.
  100736. **
  100737. ** Example:
  100738. **
  100739. ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
  100740. **
  100741. ** The outer query has 3 slots in its FROM clause. One slot of the
  100742. ** outer query (the middle slot) is used by the subquery. The next
  100743. ** block of code will expand the out query to 4 slots. The middle
  100744. ** slot is expanded to two slots in order to make space for the
  100745. ** two elements in the FROM clause of the subquery.
  100746. */
  100747. if( nSubSrc>1 ){
  100748. pParent->pSrc = pSrc = sqlite3SrcListEnlarge(db, pSrc, nSubSrc-1,iFrom+1);
  100749. if( db->mallocFailed ){
  100750. break;
  100751. }
  100752. }
  100753. /* Transfer the FROM clause terms from the subquery into the
  100754. ** outer query.
  100755. */
  100756. for(i=0; i<nSubSrc; i++){
  100757. sqlite3IdListDelete(db, pSrc->a[i+iFrom].pUsing);
  100758. pSrc->a[i+iFrom] = pSubSrc->a[i];
  100759. memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
  100760. }
  100761. pSrc->a[iFrom].jointype = jointype;
  100762. /* Now begin substituting subquery result set expressions for
  100763. ** references to the iParent in the outer query.
  100764. **
  100765. ** Example:
  100766. **
  100767. ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
  100768. ** \ \_____________ subquery __________/ /
  100769. ** \_____________________ outer query ______________________________/
  100770. **
  100771. ** We look at every expression in the outer query and every place we see
  100772. ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
  100773. */
  100774. pList = pParent->pEList;
  100775. for(i=0; i<pList->nExpr; i++){
  100776. if( pList->a[i].zName==0 ){
  100777. char *zName = sqlite3DbStrDup(db, pList->a[i].zSpan);
  100778. sqlite3Dequote(zName);
  100779. pList->a[i].zName = zName;
  100780. }
  100781. }
  100782. substExprList(db, pParent->pEList, iParent, pSub->pEList);
  100783. if( isAgg ){
  100784. substExprList(db, pParent->pGroupBy, iParent, pSub->pEList);
  100785. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  100786. }
  100787. if( pSub->pOrderBy ){
  100788. /* At this point, any non-zero iOrderByCol values indicate that the
  100789. ** ORDER BY column expression is identical to the iOrderByCol'th
  100790. ** expression returned by SELECT statement pSub. Since these values
  100791. ** do not necessarily correspond to columns in SELECT statement pParent,
  100792. ** zero them before transfering the ORDER BY clause.
  100793. **
  100794. ** Not doing this may cause an error if a subsequent call to this
  100795. ** function attempts to flatten a compound sub-query into pParent
  100796. ** (the only way this can happen is if the compound sub-query is
  100797. ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
  100798. ExprList *pOrderBy = pSub->pOrderBy;
  100799. for(i=0; i<pOrderBy->nExpr; i++){
  100800. pOrderBy->a[i].u.x.iOrderByCol = 0;
  100801. }
  100802. assert( pParent->pOrderBy==0 );
  100803. assert( pSub->pPrior==0 );
  100804. pParent->pOrderBy = pOrderBy;
  100805. pSub->pOrderBy = 0;
  100806. }else if( pParent->pOrderBy ){
  100807. substExprList(db, pParent->pOrderBy, iParent, pSub->pEList);
  100808. }
  100809. if( pSub->pWhere ){
  100810. pWhere = sqlite3ExprDup(db, pSub->pWhere, 0);
  100811. }else{
  100812. pWhere = 0;
  100813. }
  100814. if( subqueryIsAgg ){
  100815. assert( pParent->pHaving==0 );
  100816. pParent->pHaving = pParent->pWhere;
  100817. pParent->pWhere = pWhere;
  100818. pParent->pHaving = substExpr(db, pParent->pHaving, iParent, pSub->pEList);
  100819. pParent->pHaving = sqlite3ExprAnd(db, pParent->pHaving,
  100820. sqlite3ExprDup(db, pSub->pHaving, 0));
  100821. assert( pParent->pGroupBy==0 );
  100822. pParent->pGroupBy = sqlite3ExprListDup(db, pSub->pGroupBy, 0);
  100823. }else{
  100824. pParent->pWhere = substExpr(db, pParent->pWhere, iParent, pSub->pEList);
  100825. pParent->pWhere = sqlite3ExprAnd(db, pParent->pWhere, pWhere);
  100826. }
  100827. /* The flattened query is distinct if either the inner or the
  100828. ** outer query is distinct.
  100829. */
  100830. pParent->selFlags |= pSub->selFlags & SF_Distinct;
  100831. /*
  100832. ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
  100833. **
  100834. ** One is tempted to try to add a and b to combine the limits. But this
  100835. ** does not work if either limit is negative.
  100836. */
  100837. if( pSub->pLimit ){
  100838. pParent->pLimit = pSub->pLimit;
  100839. pSub->pLimit = 0;
  100840. }
  100841. }
  100842. /* Finially, delete what is left of the subquery and return
  100843. ** success.
  100844. */
  100845. sqlite3SelectDelete(db, pSub1);
  100846. #if SELECTTRACE_ENABLED
  100847. if( sqlite3SelectTrace & 0x100 ){
  100848. sqlite3DebugPrintf("After flattening:\n");
  100849. sqlite3TreeViewSelect(0, p, 0);
  100850. }
  100851. #endif
  100852. return 1;
  100853. }
  100854. #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
  100855. /*
  100856. ** Based on the contents of the AggInfo structure indicated by the first
  100857. ** argument, this function checks if the following are true:
  100858. **
  100859. ** * the query contains just a single aggregate function,
  100860. ** * the aggregate function is either min() or max(), and
  100861. ** * the argument to the aggregate function is a column value.
  100862. **
  100863. ** If all of the above are true, then WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX
  100864. ** is returned as appropriate. Also, *ppMinMax is set to point to the
  100865. ** list of arguments passed to the aggregate before returning.
  100866. **
  100867. ** Or, if the conditions above are not met, *ppMinMax is set to 0 and
  100868. ** WHERE_ORDERBY_NORMAL is returned.
  100869. */
  100870. static u8 minMaxQuery(AggInfo *pAggInfo, ExprList **ppMinMax){
  100871. int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
  100872. *ppMinMax = 0;
  100873. if( pAggInfo->nFunc==1 ){
  100874. Expr *pExpr = pAggInfo->aFunc[0].pExpr; /* Aggregate function */
  100875. ExprList *pEList = pExpr->x.pList; /* Arguments to agg function */
  100876. assert( pExpr->op==TK_AGG_FUNCTION );
  100877. if( pEList && pEList->nExpr==1 && pEList->a[0].pExpr->op==TK_AGG_COLUMN ){
  100878. const char *zFunc = pExpr->u.zToken;
  100879. if( sqlite3StrICmp(zFunc, "min")==0 ){
  100880. eRet = WHERE_ORDERBY_MIN;
  100881. *ppMinMax = pEList;
  100882. }else if( sqlite3StrICmp(zFunc, "max")==0 ){
  100883. eRet = WHERE_ORDERBY_MAX;
  100884. *ppMinMax = pEList;
  100885. }
  100886. }
  100887. }
  100888. assert( *ppMinMax==0 || (*ppMinMax)->nExpr==1 );
  100889. return eRet;
  100890. }
  100891. /*
  100892. ** The select statement passed as the first argument is an aggregate query.
  100893. ** The second argument is the associated aggregate-info object. This
  100894. ** function tests if the SELECT is of the form:
  100895. **
  100896. ** SELECT count(*) FROM <tbl>
  100897. **
  100898. ** where table is a database table, not a sub-select or view. If the query
  100899. ** does match this pattern, then a pointer to the Table object representing
  100900. ** <tbl> is returned. Otherwise, 0 is returned.
  100901. */
  100902. static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
  100903. Table *pTab;
  100904. Expr *pExpr;
  100905. assert( !p->pGroupBy );
  100906. if( p->pWhere || p->pEList->nExpr!=1
  100907. || p->pSrc->nSrc!=1 || p->pSrc->a[0].pSelect
  100908. ){
  100909. return 0;
  100910. }
  100911. pTab = p->pSrc->a[0].pTab;
  100912. pExpr = p->pEList->a[0].pExpr;
  100913. assert( pTab && !pTab->pSelect && pExpr );
  100914. if( IsVirtual(pTab) ) return 0;
  100915. if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
  100916. if( NEVER(pAggInfo->nFunc==0) ) return 0;
  100917. if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
  100918. if( pExpr->flags&EP_Distinct ) return 0;
  100919. return pTab;
  100920. }
  100921. /*
  100922. ** If the source-list item passed as an argument was augmented with an
  100923. ** INDEXED BY clause, then try to locate the specified index. If there
  100924. ** was such a clause and the named index cannot be found, return
  100925. ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
  100926. ** pFrom->pIndex and return SQLITE_OK.
  100927. */
  100928. SQLITE_PRIVATE int sqlite3IndexedByLookup(Parse *pParse, struct SrcList_item *pFrom){
  100929. if( pFrom->pTab && pFrom->zIndex ){
  100930. Table *pTab = pFrom->pTab;
  100931. char *zIndex = pFrom->zIndex;
  100932. Index *pIdx;
  100933. for(pIdx=pTab->pIndex;
  100934. pIdx && sqlite3StrICmp(pIdx->zName, zIndex);
  100935. pIdx=pIdx->pNext
  100936. );
  100937. if( !pIdx ){
  100938. sqlite3ErrorMsg(pParse, "no such index: %s", zIndex, 0);
  100939. pParse->checkSchema = 1;
  100940. return SQLITE_ERROR;
  100941. }
  100942. pFrom->pIndex = pIdx;
  100943. }
  100944. return SQLITE_OK;
  100945. }
  100946. /*
  100947. ** Detect compound SELECT statements that use an ORDER BY clause with
  100948. ** an alternative collating sequence.
  100949. **
  100950. ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
  100951. **
  100952. ** These are rewritten as a subquery:
  100953. **
  100954. ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
  100955. ** ORDER BY ... COLLATE ...
  100956. **
  100957. ** This transformation is necessary because the multiSelectOrderBy() routine
  100958. ** above that generates the code for a compound SELECT with an ORDER BY clause
  100959. ** uses a merge algorithm that requires the same collating sequence on the
  100960. ** result columns as on the ORDER BY clause. See ticket
  100961. ** http://www.sqlite.org/src/info/6709574d2a
  100962. **
  100963. ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
  100964. ** The UNION ALL operator works fine with multiSelectOrderBy() even when
  100965. ** there are COLLATE terms in the ORDER BY.
  100966. */
  100967. static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
  100968. int i;
  100969. Select *pNew;
  100970. Select *pX;
  100971. sqlite3 *db;
  100972. struct ExprList_item *a;
  100973. SrcList *pNewSrc;
  100974. Parse *pParse;
  100975. Token dummy;
  100976. if( p->pPrior==0 ) return WRC_Continue;
  100977. if( p->pOrderBy==0 ) return WRC_Continue;
  100978. for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
  100979. if( pX==0 ) return WRC_Continue;
  100980. a = p->pOrderBy->a;
  100981. for(i=p->pOrderBy->nExpr-1; i>=0; i--){
  100982. if( a[i].pExpr->flags & EP_Collate ) break;
  100983. }
  100984. if( i<0 ) return WRC_Continue;
  100985. /* If we reach this point, that means the transformation is required. */
  100986. pParse = pWalker->pParse;
  100987. db = pParse->db;
  100988. pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
  100989. if( pNew==0 ) return WRC_Abort;
  100990. memset(&dummy, 0, sizeof(dummy));
  100991. pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0,0);
  100992. if( pNewSrc==0 ) return WRC_Abort;
  100993. *pNew = *p;
  100994. p->pSrc = pNewSrc;
  100995. p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ALL, 0));
  100996. p->op = TK_SELECT;
  100997. p->pWhere = 0;
  100998. pNew->pGroupBy = 0;
  100999. pNew->pHaving = 0;
  101000. pNew->pOrderBy = 0;
  101001. p->pPrior = 0;
  101002. p->pNext = 0;
  101003. p->selFlags &= ~SF_Compound;
  101004. assert( pNew->pPrior!=0 );
  101005. pNew->pPrior->pNext = pNew;
  101006. pNew->pLimit = 0;
  101007. pNew->pOffset = 0;
  101008. return WRC_Continue;
  101009. }
  101010. #ifndef SQLITE_OMIT_CTE
  101011. /*
  101012. ** Argument pWith (which may be NULL) points to a linked list of nested
  101013. ** WITH contexts, from inner to outermost. If the table identified by
  101014. ** FROM clause element pItem is really a common-table-expression (CTE)
  101015. ** then return a pointer to the CTE definition for that table. Otherwise
  101016. ** return NULL.
  101017. **
  101018. ** If a non-NULL value is returned, set *ppContext to point to the With
  101019. ** object that the returned CTE belongs to.
  101020. */
  101021. static struct Cte *searchWith(
  101022. With *pWith, /* Current outermost WITH clause */
  101023. struct SrcList_item *pItem, /* FROM clause element to resolve */
  101024. With **ppContext /* OUT: WITH clause return value belongs to */
  101025. ){
  101026. const char *zName;
  101027. if( pItem->zDatabase==0 && (zName = pItem->zName)!=0 ){
  101028. With *p;
  101029. for(p=pWith; p; p=p->pOuter){
  101030. int i;
  101031. for(i=0; i<p->nCte; i++){
  101032. if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
  101033. *ppContext = p;
  101034. return &p->a[i];
  101035. }
  101036. }
  101037. }
  101038. }
  101039. return 0;
  101040. }
  101041. /* The code generator maintains a stack of active WITH clauses
  101042. ** with the inner-most WITH clause being at the top of the stack.
  101043. **
  101044. ** This routine pushes the WITH clause passed as the second argument
  101045. ** onto the top of the stack. If argument bFree is true, then this
  101046. ** WITH clause will never be popped from the stack. In this case it
  101047. ** should be freed along with the Parse object. In other cases, when
  101048. ** bFree==0, the With object will be freed along with the SELECT
  101049. ** statement with which it is associated.
  101050. */
  101051. SQLITE_PRIVATE void sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
  101052. assert( bFree==0 || pParse->pWith==0 );
  101053. if( pWith ){
  101054. pWith->pOuter = pParse->pWith;
  101055. pParse->pWith = pWith;
  101056. pParse->bFreeWith = bFree;
  101057. }
  101058. }
  101059. /*
  101060. ** This function checks if argument pFrom refers to a CTE declared by
  101061. ** a WITH clause on the stack currently maintained by the parser. And,
  101062. ** if currently processing a CTE expression, if it is a recursive
  101063. ** reference to the current CTE.
  101064. **
  101065. ** If pFrom falls into either of the two categories above, pFrom->pTab
  101066. ** and other fields are populated accordingly. The caller should check
  101067. ** (pFrom->pTab!=0) to determine whether or not a successful match
  101068. ** was found.
  101069. **
  101070. ** Whether or not a match is found, SQLITE_OK is returned if no error
  101071. ** occurs. If an error does occur, an error message is stored in the
  101072. ** parser and some error code other than SQLITE_OK returned.
  101073. */
  101074. static int withExpand(
  101075. Walker *pWalker,
  101076. struct SrcList_item *pFrom
  101077. ){
  101078. Parse *pParse = pWalker->pParse;
  101079. sqlite3 *db = pParse->db;
  101080. struct Cte *pCte; /* Matched CTE (or NULL if no match) */
  101081. With *pWith; /* WITH clause that pCte belongs to */
  101082. assert( pFrom->pTab==0 );
  101083. pCte = searchWith(pParse->pWith, pFrom, &pWith);
  101084. if( pCte ){
  101085. Table *pTab;
  101086. ExprList *pEList;
  101087. Select *pSel;
  101088. Select *pLeft; /* Left-most SELECT statement */
  101089. int bMayRecursive; /* True if compound joined by UNION [ALL] */
  101090. With *pSavedWith; /* Initial value of pParse->pWith */
  101091. /* If pCte->zErr is non-NULL at this point, then this is an illegal
  101092. ** recursive reference to CTE pCte. Leave an error in pParse and return
  101093. ** early. If pCte->zErr is NULL, then this is not a recursive reference.
  101094. ** In this case, proceed. */
  101095. if( pCte->zErr ){
  101096. sqlite3ErrorMsg(pParse, pCte->zErr, pCte->zName);
  101097. return SQLITE_ERROR;
  101098. }
  101099. assert( pFrom->pTab==0 );
  101100. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  101101. if( pTab==0 ) return WRC_Abort;
  101102. pTab->nRef = 1;
  101103. pTab->zName = sqlite3DbStrDup(db, pCte->zName);
  101104. pTab->iPKey = -1;
  101105. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  101106. pTab->tabFlags |= TF_Ephemeral;
  101107. pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
  101108. if( db->mallocFailed ) return SQLITE_NOMEM;
  101109. assert( pFrom->pSelect );
  101110. /* Check if this is a recursive CTE. */
  101111. pSel = pFrom->pSelect;
  101112. bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
  101113. if( bMayRecursive ){
  101114. int i;
  101115. SrcList *pSrc = pFrom->pSelect->pSrc;
  101116. for(i=0; i<pSrc->nSrc; i++){
  101117. struct SrcList_item *pItem = &pSrc->a[i];
  101118. if( pItem->zDatabase==0
  101119. && pItem->zName!=0
  101120. && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
  101121. ){
  101122. pItem->pTab = pTab;
  101123. pItem->isRecursive = 1;
  101124. pTab->nRef++;
  101125. pSel->selFlags |= SF_Recursive;
  101126. }
  101127. }
  101128. }
  101129. /* Only one recursive reference is permitted. */
  101130. if( pTab->nRef>2 ){
  101131. sqlite3ErrorMsg(
  101132. pParse, "multiple references to recursive table: %s", pCte->zName
  101133. );
  101134. return SQLITE_ERROR;
  101135. }
  101136. assert( pTab->nRef==1 || ((pSel->selFlags&SF_Recursive) && pTab->nRef==2 ));
  101137. pCte->zErr = "circular reference: %s";
  101138. pSavedWith = pParse->pWith;
  101139. pParse->pWith = pWith;
  101140. sqlite3WalkSelect(pWalker, bMayRecursive ? pSel->pPrior : pSel);
  101141. for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
  101142. pEList = pLeft->pEList;
  101143. if( pCte->pCols ){
  101144. if( pEList->nExpr!=pCte->pCols->nExpr ){
  101145. sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
  101146. pCte->zName, pEList->nExpr, pCte->pCols->nExpr
  101147. );
  101148. pParse->pWith = pSavedWith;
  101149. return SQLITE_ERROR;
  101150. }
  101151. pEList = pCte->pCols;
  101152. }
  101153. selectColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
  101154. if( bMayRecursive ){
  101155. if( pSel->selFlags & SF_Recursive ){
  101156. pCte->zErr = "multiple recursive references: %s";
  101157. }else{
  101158. pCte->zErr = "recursive reference in a subquery: %s";
  101159. }
  101160. sqlite3WalkSelect(pWalker, pSel);
  101161. }
  101162. pCte->zErr = 0;
  101163. pParse->pWith = pSavedWith;
  101164. }
  101165. return SQLITE_OK;
  101166. }
  101167. #endif
  101168. #ifndef SQLITE_OMIT_CTE
  101169. /*
  101170. ** If the SELECT passed as the second argument has an associated WITH
  101171. ** clause, pop it from the stack stored as part of the Parse object.
  101172. **
  101173. ** This function is used as the xSelectCallback2() callback by
  101174. ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
  101175. ** names and other FROM clause elements.
  101176. */
  101177. static void selectPopWith(Walker *pWalker, Select *p){
  101178. Parse *pParse = pWalker->pParse;
  101179. With *pWith = findRightmost(p)->pWith;
  101180. if( pWith!=0 ){
  101181. assert( pParse->pWith==pWith );
  101182. pParse->pWith = pWith->pOuter;
  101183. }
  101184. }
  101185. #else
  101186. #define selectPopWith 0
  101187. #endif
  101188. /*
  101189. ** This routine is a Walker callback for "expanding" a SELECT statement.
  101190. ** "Expanding" means to do the following:
  101191. **
  101192. ** (1) Make sure VDBE cursor numbers have been assigned to every
  101193. ** element of the FROM clause.
  101194. **
  101195. ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
  101196. ** defines FROM clause. When views appear in the FROM clause,
  101197. ** fill pTabList->a[].pSelect with a copy of the SELECT statement
  101198. ** that implements the view. A copy is made of the view's SELECT
  101199. ** statement so that we can freely modify or delete that statement
  101200. ** without worrying about messing up the persistent representation
  101201. ** of the view.
  101202. **
  101203. ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
  101204. ** on joins and the ON and USING clause of joins.
  101205. **
  101206. ** (4) Scan the list of columns in the result set (pEList) looking
  101207. ** for instances of the "*" operator or the TABLE.* operator.
  101208. ** If found, expand each "*" to be every column in every table
  101209. ** and TABLE.* to be every column in TABLE.
  101210. **
  101211. */
  101212. static int selectExpander(Walker *pWalker, Select *p){
  101213. Parse *pParse = pWalker->pParse;
  101214. int i, j, k;
  101215. SrcList *pTabList;
  101216. ExprList *pEList;
  101217. struct SrcList_item *pFrom;
  101218. sqlite3 *db = pParse->db;
  101219. Expr *pE, *pRight, *pExpr;
  101220. u16 selFlags = p->selFlags;
  101221. p->selFlags |= SF_Expanded;
  101222. if( db->mallocFailed ){
  101223. return WRC_Abort;
  101224. }
  101225. if( NEVER(p->pSrc==0) || (selFlags & SF_Expanded)!=0 ){
  101226. return WRC_Prune;
  101227. }
  101228. pTabList = p->pSrc;
  101229. pEList = p->pEList;
  101230. sqlite3WithPush(pParse, findRightmost(p)->pWith, 0);
  101231. /* Make sure cursor numbers have been assigned to all entries in
  101232. ** the FROM clause of the SELECT statement.
  101233. */
  101234. sqlite3SrcListAssignCursors(pParse, pTabList);
  101235. /* Look up every table named in the FROM clause of the select. If
  101236. ** an entry of the FROM clause is a subquery instead of a table or view,
  101237. ** then create a transient table structure to describe the subquery.
  101238. */
  101239. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  101240. Table *pTab;
  101241. assert( pFrom->isRecursive==0 || pFrom->pTab );
  101242. if( pFrom->isRecursive ) continue;
  101243. if( pFrom->pTab!=0 ){
  101244. /* This statement has already been prepared. There is no need
  101245. ** to go further. */
  101246. assert( i==0 );
  101247. #ifndef SQLITE_OMIT_CTE
  101248. selectPopWith(pWalker, p);
  101249. #endif
  101250. return WRC_Prune;
  101251. }
  101252. #ifndef SQLITE_OMIT_CTE
  101253. if( withExpand(pWalker, pFrom) ) return WRC_Abort;
  101254. if( pFrom->pTab ) {} else
  101255. #endif
  101256. if( pFrom->zName==0 ){
  101257. #ifndef SQLITE_OMIT_SUBQUERY
  101258. Select *pSel = pFrom->pSelect;
  101259. /* A sub-query in the FROM clause of a SELECT */
  101260. assert( pSel!=0 );
  101261. assert( pFrom->pTab==0 );
  101262. sqlite3WalkSelect(pWalker, pSel);
  101263. pFrom->pTab = pTab = sqlite3DbMallocZero(db, sizeof(Table));
  101264. if( pTab==0 ) return WRC_Abort;
  101265. pTab->nRef = 1;
  101266. pTab->zName = sqlite3MPrintf(db, "sqlite_sq_%p", (void*)pTab);
  101267. while( pSel->pPrior ){ pSel = pSel->pPrior; }
  101268. selectColumnsFromExprList(pParse, pSel->pEList, &pTab->nCol, &pTab->aCol);
  101269. pTab->iPKey = -1;
  101270. pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
  101271. pTab->tabFlags |= TF_Ephemeral;
  101272. #endif
  101273. }else{
  101274. /* An ordinary table or view name in the FROM clause */
  101275. assert( pFrom->pTab==0 );
  101276. pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
  101277. if( pTab==0 ) return WRC_Abort;
  101278. if( pTab->nRef==0xffff ){
  101279. sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
  101280. pTab->zName);
  101281. pFrom->pTab = 0;
  101282. return WRC_Abort;
  101283. }
  101284. pTab->nRef++;
  101285. #if !defined(SQLITE_OMIT_VIEW) || !defined (SQLITE_OMIT_VIRTUALTABLE)
  101286. if( pTab->pSelect || IsVirtual(pTab) ){
  101287. /* We reach here if the named table is a really a view */
  101288. if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
  101289. assert( pFrom->pSelect==0 );
  101290. pFrom->pSelect = sqlite3SelectDup(db, pTab->pSelect, 0);
  101291. sqlite3SelectSetName(pFrom->pSelect, pTab->zName);
  101292. sqlite3WalkSelect(pWalker, pFrom->pSelect);
  101293. }
  101294. #endif
  101295. }
  101296. /* Locate the index named by the INDEXED BY clause, if any. */
  101297. if( sqlite3IndexedByLookup(pParse, pFrom) ){
  101298. return WRC_Abort;
  101299. }
  101300. }
  101301. /* Process NATURAL keywords, and ON and USING clauses of joins.
  101302. */
  101303. if( db->mallocFailed || sqliteProcessJoin(pParse, p) ){
  101304. return WRC_Abort;
  101305. }
  101306. /* For every "*" that occurs in the column list, insert the names of
  101307. ** all columns in all tables. And for every TABLE.* insert the names
  101308. ** of all columns in TABLE. The parser inserted a special expression
  101309. ** with the TK_ALL operator for each "*" that it found in the column list.
  101310. ** The following code just has to locate the TK_ALL expressions and expand
  101311. ** each one to the list of all columns in all tables.
  101312. **
  101313. ** The first loop just checks to see if there are any "*" operators
  101314. ** that need expanding.
  101315. */
  101316. for(k=0; k<pEList->nExpr; k++){
  101317. pE = pEList->a[k].pExpr;
  101318. if( pE->op==TK_ALL ) break;
  101319. assert( pE->op!=TK_DOT || pE->pRight!=0 );
  101320. assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
  101321. if( pE->op==TK_DOT && pE->pRight->op==TK_ALL ) break;
  101322. }
  101323. if( k<pEList->nExpr ){
  101324. /*
  101325. ** If we get here it means the result set contains one or more "*"
  101326. ** operators that need to be expanded. Loop through each expression
  101327. ** in the result set and expand them one by one.
  101328. */
  101329. struct ExprList_item *a = pEList->a;
  101330. ExprList *pNew = 0;
  101331. int flags = pParse->db->flags;
  101332. int longNames = (flags & SQLITE_FullColNames)!=0
  101333. && (flags & SQLITE_ShortColNames)==0;
  101334. /* When processing FROM-clause subqueries, it is always the case
  101335. ** that full_column_names=OFF and short_column_names=ON. The
  101336. ** sqlite3ResultSetOfSelect() routine makes it so. */
  101337. assert( (p->selFlags & SF_NestedFrom)==0
  101338. || ((flags & SQLITE_FullColNames)==0 &&
  101339. (flags & SQLITE_ShortColNames)!=0) );
  101340. for(k=0; k<pEList->nExpr; k++){
  101341. pE = a[k].pExpr;
  101342. pRight = pE->pRight;
  101343. assert( pE->op!=TK_DOT || pRight!=0 );
  101344. if( pE->op!=TK_ALL && (pE->op!=TK_DOT || pRight->op!=TK_ALL) ){
  101345. /* This particular expression does not need to be expanded.
  101346. */
  101347. pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
  101348. if( pNew ){
  101349. pNew->a[pNew->nExpr-1].zName = a[k].zName;
  101350. pNew->a[pNew->nExpr-1].zSpan = a[k].zSpan;
  101351. a[k].zName = 0;
  101352. a[k].zSpan = 0;
  101353. }
  101354. a[k].pExpr = 0;
  101355. }else{
  101356. /* This expression is a "*" or a "TABLE.*" and needs to be
  101357. ** expanded. */
  101358. int tableSeen = 0; /* Set to 1 when TABLE matches */
  101359. char *zTName = 0; /* text of name of TABLE */
  101360. if( pE->op==TK_DOT ){
  101361. assert( pE->pLeft!=0 );
  101362. assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
  101363. zTName = pE->pLeft->u.zToken;
  101364. }
  101365. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  101366. Table *pTab = pFrom->pTab;
  101367. Select *pSub = pFrom->pSelect;
  101368. char *zTabName = pFrom->zAlias;
  101369. const char *zSchemaName = 0;
  101370. int iDb;
  101371. if( zTabName==0 ){
  101372. zTabName = pTab->zName;
  101373. }
  101374. if( db->mallocFailed ) break;
  101375. if( pSub==0 || (pSub->selFlags & SF_NestedFrom)==0 ){
  101376. pSub = 0;
  101377. if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
  101378. continue;
  101379. }
  101380. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  101381. zSchemaName = iDb>=0 ? db->aDb[iDb].zName : "*";
  101382. }
  101383. for(j=0; j<pTab->nCol; j++){
  101384. char *zName = pTab->aCol[j].zName;
  101385. char *zColname; /* The computed column name */
  101386. char *zToFree; /* Malloced string that needs to be freed */
  101387. Token sColname; /* Computed column name as a token */
  101388. assert( zName );
  101389. if( zTName && pSub
  101390. && sqlite3MatchSpanName(pSub->pEList->a[j].zSpan, 0, zTName, 0)==0
  101391. ){
  101392. continue;
  101393. }
  101394. /* If a column is marked as 'hidden' (currently only possible
  101395. ** for virtual tables), do not include it in the expanded
  101396. ** result-set list.
  101397. */
  101398. if( IsHiddenColumn(&pTab->aCol[j]) ){
  101399. assert(IsVirtual(pTab));
  101400. continue;
  101401. }
  101402. tableSeen = 1;
  101403. if( i>0 && zTName==0 ){
  101404. if( (pFrom->jointype & JT_NATURAL)!=0
  101405. && tableAndColumnIndex(pTabList, i, zName, 0, 0)
  101406. ){
  101407. /* In a NATURAL join, omit the join columns from the
  101408. ** table to the right of the join */
  101409. continue;
  101410. }
  101411. if( sqlite3IdListIndex(pFrom->pUsing, zName)>=0 ){
  101412. /* In a join with a USING clause, omit columns in the
  101413. ** using clause from the table on the right. */
  101414. continue;
  101415. }
  101416. }
  101417. pRight = sqlite3Expr(db, TK_ID, zName);
  101418. zColname = zName;
  101419. zToFree = 0;
  101420. if( longNames || pTabList->nSrc>1 ){
  101421. Expr *pLeft;
  101422. pLeft = sqlite3Expr(db, TK_ID, zTabName);
  101423. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  101424. if( zSchemaName ){
  101425. pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
  101426. pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr, 0);
  101427. }
  101428. if( longNames ){
  101429. zColname = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
  101430. zToFree = zColname;
  101431. }
  101432. }else{
  101433. pExpr = pRight;
  101434. }
  101435. pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
  101436. sColname.z = zColname;
  101437. sColname.n = sqlite3Strlen30(zColname);
  101438. sqlite3ExprListSetName(pParse, pNew, &sColname, 0);
  101439. if( pNew && (p->selFlags & SF_NestedFrom)!=0 ){
  101440. struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
  101441. if( pSub ){
  101442. pX->zSpan = sqlite3DbStrDup(db, pSub->pEList->a[j].zSpan);
  101443. testcase( pX->zSpan==0 );
  101444. }else{
  101445. pX->zSpan = sqlite3MPrintf(db, "%s.%s.%s",
  101446. zSchemaName, zTabName, zColname);
  101447. testcase( pX->zSpan==0 );
  101448. }
  101449. pX->bSpanIsTab = 1;
  101450. }
  101451. sqlite3DbFree(db, zToFree);
  101452. }
  101453. }
  101454. if( !tableSeen ){
  101455. if( zTName ){
  101456. sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
  101457. }else{
  101458. sqlite3ErrorMsg(pParse, "no tables specified");
  101459. }
  101460. }
  101461. }
  101462. }
  101463. sqlite3ExprListDelete(db, pEList);
  101464. p->pEList = pNew;
  101465. }
  101466. #if SQLITE_MAX_COLUMN
  101467. if( p->pEList && p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
  101468. sqlite3ErrorMsg(pParse, "too many columns in result set");
  101469. }
  101470. #endif
  101471. return WRC_Continue;
  101472. }
  101473. /*
  101474. ** No-op routine for the parse-tree walker.
  101475. **
  101476. ** When this routine is the Walker.xExprCallback then expression trees
  101477. ** are walked without any actions being taken at each node. Presumably,
  101478. ** when this routine is used for Walker.xExprCallback then
  101479. ** Walker.xSelectCallback is set to do something useful for every
  101480. ** subquery in the parser tree.
  101481. */
  101482. static int exprWalkNoop(Walker *NotUsed, Expr *NotUsed2){
  101483. UNUSED_PARAMETER2(NotUsed, NotUsed2);
  101484. return WRC_Continue;
  101485. }
  101486. /*
  101487. ** This routine "expands" a SELECT statement and all of its subqueries.
  101488. ** For additional information on what it means to "expand" a SELECT
  101489. ** statement, see the comment on the selectExpand worker callback above.
  101490. **
  101491. ** Expanding a SELECT statement is the first step in processing a
  101492. ** SELECT statement. The SELECT statement must be expanded before
  101493. ** name resolution is performed.
  101494. **
  101495. ** If anything goes wrong, an error message is written into pParse.
  101496. ** The calling function can detect the problem by looking at pParse->nErr
  101497. ** and/or pParse->db->mallocFailed.
  101498. */
  101499. static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
  101500. Walker w;
  101501. memset(&w, 0, sizeof(w));
  101502. w.xExprCallback = exprWalkNoop;
  101503. w.pParse = pParse;
  101504. if( pParse->hasCompound ){
  101505. w.xSelectCallback = convertCompoundSelectToSubquery;
  101506. sqlite3WalkSelect(&w, pSelect);
  101507. }
  101508. w.xSelectCallback = selectExpander;
  101509. w.xSelectCallback2 = selectPopWith;
  101510. sqlite3WalkSelect(&w, pSelect);
  101511. }
  101512. #ifndef SQLITE_OMIT_SUBQUERY
  101513. /*
  101514. ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
  101515. ** interface.
  101516. **
  101517. ** For each FROM-clause subquery, add Column.zType and Column.zColl
  101518. ** information to the Table structure that represents the result set
  101519. ** of that subquery.
  101520. **
  101521. ** The Table structure that represents the result set was constructed
  101522. ** by selectExpander() but the type and collation information was omitted
  101523. ** at that point because identifiers had not yet been resolved. This
  101524. ** routine is called after identifier resolution.
  101525. */
  101526. static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
  101527. Parse *pParse;
  101528. int i;
  101529. SrcList *pTabList;
  101530. struct SrcList_item *pFrom;
  101531. assert( p->selFlags & SF_Resolved );
  101532. if( (p->selFlags & SF_HasTypeInfo)==0 ){
  101533. p->selFlags |= SF_HasTypeInfo;
  101534. pParse = pWalker->pParse;
  101535. pTabList = p->pSrc;
  101536. for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
  101537. Table *pTab = pFrom->pTab;
  101538. if( ALWAYS(pTab!=0) && (pTab->tabFlags & TF_Ephemeral)!=0 ){
  101539. /* A sub-query in the FROM clause of a SELECT */
  101540. Select *pSel = pFrom->pSelect;
  101541. if( pSel ){
  101542. while( pSel->pPrior ) pSel = pSel->pPrior;
  101543. selectAddColumnTypeAndCollation(pParse, pTab, pSel);
  101544. }
  101545. }
  101546. }
  101547. }
  101548. }
  101549. #endif
  101550. /*
  101551. ** This routine adds datatype and collating sequence information to
  101552. ** the Table structures of all FROM-clause subqueries in a
  101553. ** SELECT statement.
  101554. **
  101555. ** Use this routine after name resolution.
  101556. */
  101557. static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
  101558. #ifndef SQLITE_OMIT_SUBQUERY
  101559. Walker w;
  101560. memset(&w, 0, sizeof(w));
  101561. w.xSelectCallback2 = selectAddSubqueryTypeInfo;
  101562. w.xExprCallback = exprWalkNoop;
  101563. w.pParse = pParse;
  101564. sqlite3WalkSelect(&w, pSelect);
  101565. #endif
  101566. }
  101567. /*
  101568. ** This routine sets up a SELECT statement for processing. The
  101569. ** following is accomplished:
  101570. **
  101571. ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
  101572. ** * Ephemeral Table objects are created for all FROM-clause subqueries.
  101573. ** * ON and USING clauses are shifted into WHERE statements
  101574. ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
  101575. ** * Identifiers in expression are matched to tables.
  101576. **
  101577. ** This routine acts recursively on all subqueries within the SELECT.
  101578. */
  101579. SQLITE_PRIVATE void sqlite3SelectPrep(
  101580. Parse *pParse, /* The parser context */
  101581. Select *p, /* The SELECT statement being coded. */
  101582. NameContext *pOuterNC /* Name context for container */
  101583. ){
  101584. sqlite3 *db;
  101585. if( NEVER(p==0) ) return;
  101586. db = pParse->db;
  101587. if( db->mallocFailed ) return;
  101588. if( p->selFlags & SF_HasTypeInfo ) return;
  101589. sqlite3SelectExpand(pParse, p);
  101590. if( pParse->nErr || db->mallocFailed ) return;
  101591. sqlite3ResolveSelectNames(pParse, p, pOuterNC);
  101592. if( pParse->nErr || db->mallocFailed ) return;
  101593. sqlite3SelectAddTypeInfo(pParse, p);
  101594. }
  101595. /*
  101596. ** Reset the aggregate accumulator.
  101597. **
  101598. ** The aggregate accumulator is a set of memory cells that hold
  101599. ** intermediate results while calculating an aggregate. This
  101600. ** routine generates code that stores NULLs in all of those memory
  101601. ** cells.
  101602. */
  101603. static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
  101604. Vdbe *v = pParse->pVdbe;
  101605. int i;
  101606. struct AggInfo_func *pFunc;
  101607. int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
  101608. if( nReg==0 ) return;
  101609. #ifdef SQLITE_DEBUG
  101610. /* Verify that all AggInfo registers are within the range specified by
  101611. ** AggInfo.mnReg..AggInfo.mxReg */
  101612. assert( nReg==pAggInfo->mxReg-pAggInfo->mnReg+1 );
  101613. for(i=0; i<pAggInfo->nColumn; i++){
  101614. assert( pAggInfo->aCol[i].iMem>=pAggInfo->mnReg
  101615. && pAggInfo->aCol[i].iMem<=pAggInfo->mxReg );
  101616. }
  101617. for(i=0; i<pAggInfo->nFunc; i++){
  101618. assert( pAggInfo->aFunc[i].iMem>=pAggInfo->mnReg
  101619. && pAggInfo->aFunc[i].iMem<=pAggInfo->mxReg );
  101620. }
  101621. #endif
  101622. sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->mnReg, pAggInfo->mxReg);
  101623. for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
  101624. if( pFunc->iDistinct>=0 ){
  101625. Expr *pE = pFunc->pExpr;
  101626. assert( !ExprHasProperty(pE, EP_xIsSelect) );
  101627. if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
  101628. sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
  101629. "argument");
  101630. pFunc->iDistinct = -1;
  101631. }else{
  101632. KeyInfo *pKeyInfo = keyInfoFromExprList(pParse, pE->x.pList, 0, 0);
  101633. sqlite3VdbeAddOp4(v, OP_OpenEphemeral, pFunc->iDistinct, 0, 0,
  101634. (char*)pKeyInfo, P4_KEYINFO);
  101635. }
  101636. }
  101637. }
  101638. }
  101639. /*
  101640. ** Invoke the OP_AggFinalize opcode for every aggregate function
  101641. ** in the AggInfo structure.
  101642. */
  101643. static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
  101644. Vdbe *v = pParse->pVdbe;
  101645. int i;
  101646. struct AggInfo_func *pF;
  101647. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  101648. ExprList *pList = pF->pExpr->x.pList;
  101649. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  101650. sqlite3VdbeAddOp4(v, OP_AggFinal, pF->iMem, pList ? pList->nExpr : 0, 0,
  101651. (void*)pF->pFunc, P4_FUNCDEF);
  101652. }
  101653. }
  101654. /*
  101655. ** Update the accumulator memory cells for an aggregate based on
  101656. ** the current cursor position.
  101657. */
  101658. static void updateAccumulator(Parse *pParse, AggInfo *pAggInfo){
  101659. Vdbe *v = pParse->pVdbe;
  101660. int i;
  101661. int regHit = 0;
  101662. int addrHitTest = 0;
  101663. struct AggInfo_func *pF;
  101664. struct AggInfo_col *pC;
  101665. pAggInfo->directMode = 1;
  101666. for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
  101667. int nArg;
  101668. int addrNext = 0;
  101669. int regAgg;
  101670. ExprList *pList = pF->pExpr->x.pList;
  101671. assert( !ExprHasProperty(pF->pExpr, EP_xIsSelect) );
  101672. if( pList ){
  101673. nArg = pList->nExpr;
  101674. regAgg = sqlite3GetTempRange(pParse, nArg);
  101675. sqlite3ExprCodeExprList(pParse, pList, regAgg, SQLITE_ECEL_DUP);
  101676. }else{
  101677. nArg = 0;
  101678. regAgg = 0;
  101679. }
  101680. if( pF->iDistinct>=0 ){
  101681. addrNext = sqlite3VdbeMakeLabel(v);
  101682. assert( nArg==1 );
  101683. codeDistinct(pParse, pF->iDistinct, addrNext, 1, regAgg);
  101684. }
  101685. if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
  101686. CollSeq *pColl = 0;
  101687. struct ExprList_item *pItem;
  101688. int j;
  101689. assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
  101690. for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
  101691. pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
  101692. }
  101693. if( !pColl ){
  101694. pColl = pParse->db->pDfltColl;
  101695. }
  101696. if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
  101697. sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
  101698. }
  101699. sqlite3VdbeAddOp4(v, OP_AggStep, 0, regAgg, pF->iMem,
  101700. (void*)pF->pFunc, P4_FUNCDEF);
  101701. sqlite3VdbeChangeP5(v, (u8)nArg);
  101702. sqlite3ExprCacheAffinityChange(pParse, regAgg, nArg);
  101703. sqlite3ReleaseTempRange(pParse, regAgg, nArg);
  101704. if( addrNext ){
  101705. sqlite3VdbeResolveLabel(v, addrNext);
  101706. sqlite3ExprCacheClear(pParse);
  101707. }
  101708. }
  101709. /* Before populating the accumulator registers, clear the column cache.
  101710. ** Otherwise, if any of the required column values are already present
  101711. ** in registers, sqlite3ExprCode() may use OP_SCopy to copy the value
  101712. ** to pC->iMem. But by the time the value is used, the original register
  101713. ** may have been used, invalidating the underlying buffer holding the
  101714. ** text or blob value. See ticket [883034dcb5].
  101715. **
  101716. ** Another solution would be to change the OP_SCopy used to copy cached
  101717. ** values to an OP_Copy.
  101718. */
  101719. if( regHit ){
  101720. addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
  101721. }
  101722. sqlite3ExprCacheClear(pParse);
  101723. for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
  101724. sqlite3ExprCode(pParse, pC->pExpr, pC->iMem);
  101725. }
  101726. pAggInfo->directMode = 0;
  101727. sqlite3ExprCacheClear(pParse);
  101728. if( addrHitTest ){
  101729. sqlite3VdbeJumpHere(v, addrHitTest);
  101730. }
  101731. }
  101732. /*
  101733. ** Add a single OP_Explain instruction to the VDBE to explain a simple
  101734. ** count(*) query ("SELECT count(*) FROM pTab").
  101735. */
  101736. #ifndef SQLITE_OMIT_EXPLAIN
  101737. static void explainSimpleCount(
  101738. Parse *pParse, /* Parse context */
  101739. Table *pTab, /* Table being queried */
  101740. Index *pIdx /* Index used to optimize scan, or NULL */
  101741. ){
  101742. if( pParse->explain==2 ){
  101743. int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
  101744. char *zEqp = sqlite3MPrintf(pParse->db, "SCAN TABLE %s%s%s",
  101745. pTab->zName,
  101746. bCover ? " USING COVERING INDEX " : "",
  101747. bCover ? pIdx->zName : ""
  101748. );
  101749. sqlite3VdbeAddOp4(
  101750. pParse->pVdbe, OP_Explain, pParse->iSelectId, 0, 0, zEqp, P4_DYNAMIC
  101751. );
  101752. }
  101753. }
  101754. #else
  101755. # define explainSimpleCount(a,b,c)
  101756. #endif
  101757. /*
  101758. ** Generate code for the SELECT statement given in the p argument.
  101759. **
  101760. ** The results are returned according to the SelectDest structure.
  101761. ** See comments in sqliteInt.h for further information.
  101762. **
  101763. ** This routine returns the number of errors. If any errors are
  101764. ** encountered, then an appropriate error message is left in
  101765. ** pParse->zErrMsg.
  101766. **
  101767. ** This routine does NOT free the Select structure passed in. The
  101768. ** calling function needs to do that.
  101769. */
  101770. SQLITE_PRIVATE int sqlite3Select(
  101771. Parse *pParse, /* The parser context */
  101772. Select *p, /* The SELECT statement being coded. */
  101773. SelectDest *pDest /* What to do with the query results */
  101774. ){
  101775. int i, j; /* Loop counters */
  101776. WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
  101777. Vdbe *v; /* The virtual machine under construction */
  101778. int isAgg; /* True for select lists like "count(*)" */
  101779. ExprList *pEList; /* List of columns to extract. */
  101780. SrcList *pTabList; /* List of tables to select from */
  101781. Expr *pWhere; /* The WHERE clause. May be NULL */
  101782. ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
  101783. Expr *pHaving; /* The HAVING clause. May be NULL */
  101784. int rc = 1; /* Value to return from this function */
  101785. DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
  101786. SortCtx sSort; /* Info on how to code the ORDER BY clause */
  101787. AggInfo sAggInfo; /* Information used by aggregate queries */
  101788. int iEnd; /* Address of the end of the query */
  101789. sqlite3 *db; /* The database connection */
  101790. #ifndef SQLITE_OMIT_EXPLAIN
  101791. int iRestoreSelectId = pParse->iSelectId;
  101792. pParse->iSelectId = pParse->iNextSelectId++;
  101793. #endif
  101794. db = pParse->db;
  101795. if( p==0 || db->mallocFailed || pParse->nErr ){
  101796. return 1;
  101797. }
  101798. if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
  101799. memset(&sAggInfo, 0, sizeof(sAggInfo));
  101800. #if SELECTTRACE_ENABLED
  101801. pParse->nSelectIndent++;
  101802. SELECTTRACE(1,pParse,p, ("begin processing:\n"));
  101803. if( sqlite3SelectTrace & 0x100 ){
  101804. sqlite3TreeViewSelect(0, p, 0);
  101805. }
  101806. #endif
  101807. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
  101808. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
  101809. assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
  101810. assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
  101811. if( IgnorableOrderby(pDest) ){
  101812. assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
  101813. pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
  101814. pDest->eDest==SRT_Queue || pDest->eDest==SRT_DistFifo ||
  101815. pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_Fifo);
  101816. /* If ORDER BY makes no difference in the output then neither does
  101817. ** DISTINCT so it can be removed too. */
  101818. sqlite3ExprListDelete(db, p->pOrderBy);
  101819. p->pOrderBy = 0;
  101820. p->selFlags &= ~SF_Distinct;
  101821. }
  101822. sqlite3SelectPrep(pParse, p, 0);
  101823. memset(&sSort, 0, sizeof(sSort));
  101824. sSort.pOrderBy = p->pOrderBy;
  101825. pTabList = p->pSrc;
  101826. pEList = p->pEList;
  101827. if( pParse->nErr || db->mallocFailed ){
  101828. goto select_end;
  101829. }
  101830. isAgg = (p->selFlags & SF_Aggregate)!=0;
  101831. assert( pEList!=0 );
  101832. /* Begin generating code.
  101833. */
  101834. v = sqlite3GetVdbe(pParse);
  101835. if( v==0 ) goto select_end;
  101836. /* If writing to memory or generating a set
  101837. ** only a single column may be output.
  101838. */
  101839. #ifndef SQLITE_OMIT_SUBQUERY
  101840. if( checkForMultiColumnSelectError(pParse, pDest, pEList->nExpr) ){
  101841. goto select_end;
  101842. }
  101843. #endif
  101844. /* Generate code for all sub-queries in the FROM clause
  101845. */
  101846. #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
  101847. for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
  101848. struct SrcList_item *pItem = &pTabList->a[i];
  101849. SelectDest dest;
  101850. Select *pSub = pItem->pSelect;
  101851. int isAggSub;
  101852. if( pSub==0 ) continue;
  101853. /* Sometimes the code for a subquery will be generated more than
  101854. ** once, if the subquery is part of the WHERE clause in a LEFT JOIN,
  101855. ** for example. In that case, do not regenerate the code to manifest
  101856. ** a view or the co-routine to implement a view. The first instance
  101857. ** is sufficient, though the subroutine to manifest the view does need
  101858. ** to be invoked again. */
  101859. if( pItem->addrFillSub ){
  101860. if( pItem->viaCoroutine==0 ){
  101861. sqlite3VdbeAddOp2(v, OP_Gosub, pItem->regReturn, pItem->addrFillSub);
  101862. }
  101863. continue;
  101864. }
  101865. /* Increment Parse.nHeight by the height of the largest expression
  101866. ** tree referred to by this, the parent select. The child select
  101867. ** may contain expression trees of at most
  101868. ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
  101869. ** more conservative than necessary, but much easier than enforcing
  101870. ** an exact limit.
  101871. */
  101872. pParse->nHeight += sqlite3SelectExprHeight(p);
  101873. isAggSub = (pSub->selFlags & SF_Aggregate)!=0;
  101874. if( flattenSubquery(pParse, p, i, isAgg, isAggSub) ){
  101875. /* This subquery can be absorbed into its parent. */
  101876. if( isAggSub ){
  101877. isAgg = 1;
  101878. p->selFlags |= SF_Aggregate;
  101879. }
  101880. i = -1;
  101881. }else if( pTabList->nSrc==1
  101882. && OptimizationEnabled(db, SQLITE_SubqCoroutine)
  101883. ){
  101884. /* Implement a co-routine that will return a single row of the result
  101885. ** set on each invocation.
  101886. */
  101887. int addrTop = sqlite3VdbeCurrentAddr(v)+1;
  101888. pItem->regReturn = ++pParse->nMem;
  101889. sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
  101890. VdbeComment((v, "%s", pItem->pTab->zName));
  101891. pItem->addrFillSub = addrTop;
  101892. sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
  101893. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  101894. sqlite3Select(pParse, pSub, &dest);
  101895. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  101896. pItem->viaCoroutine = 1;
  101897. pItem->regResult = dest.iSdst;
  101898. sqlite3VdbeAddOp1(v, OP_EndCoroutine, pItem->regReturn);
  101899. sqlite3VdbeJumpHere(v, addrTop-1);
  101900. sqlite3ClearTempRegCache(pParse);
  101901. }else{
  101902. /* Generate a subroutine that will fill an ephemeral table with
  101903. ** the content of this subquery. pItem->addrFillSub will point
  101904. ** to the address of the generated subroutine. pItem->regReturn
  101905. ** is a register allocated to hold the subroutine return address
  101906. */
  101907. int topAddr;
  101908. int onceAddr = 0;
  101909. int retAddr;
  101910. assert( pItem->addrFillSub==0 );
  101911. pItem->regReturn = ++pParse->nMem;
  101912. topAddr = sqlite3VdbeAddOp2(v, OP_Integer, 0, pItem->regReturn);
  101913. pItem->addrFillSub = topAddr+1;
  101914. if( pItem->isCorrelated==0 ){
  101915. /* If the subquery is not correlated and if we are not inside of
  101916. ** a trigger, then we only need to compute the value of the subquery
  101917. ** once. */
  101918. onceAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  101919. VdbeComment((v, "materialize \"%s\"", pItem->pTab->zName));
  101920. }else{
  101921. VdbeNoopComment((v, "materialize \"%s\"", pItem->pTab->zName));
  101922. }
  101923. sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
  101924. explainSetInteger(pItem->iSelectId, (u8)pParse->iNextSelectId);
  101925. sqlite3Select(pParse, pSub, &dest);
  101926. pItem->pTab->nRowLogEst = sqlite3LogEst(pSub->nSelectRow);
  101927. if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
  101928. retAddr = sqlite3VdbeAddOp1(v, OP_Return, pItem->regReturn);
  101929. VdbeComment((v, "end %s", pItem->pTab->zName));
  101930. sqlite3VdbeChangeP1(v, topAddr, retAddr);
  101931. sqlite3ClearTempRegCache(pParse);
  101932. }
  101933. if( /*pParse->nErr ||*/ db->mallocFailed ){
  101934. goto select_end;
  101935. }
  101936. pParse->nHeight -= sqlite3SelectExprHeight(p);
  101937. pTabList = p->pSrc;
  101938. if( !IgnorableOrderby(pDest) ){
  101939. sSort.pOrderBy = p->pOrderBy;
  101940. }
  101941. }
  101942. pEList = p->pEList;
  101943. #endif
  101944. pWhere = p->pWhere;
  101945. pGroupBy = p->pGroupBy;
  101946. pHaving = p->pHaving;
  101947. sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
  101948. #ifndef SQLITE_OMIT_COMPOUND_SELECT
  101949. /* If there is are a sequence of queries, do the earlier ones first.
  101950. */
  101951. if( p->pPrior ){
  101952. rc = multiSelect(pParse, p, pDest);
  101953. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  101954. #if SELECTTRACE_ENABLED
  101955. SELECTTRACE(1,pParse,p,("end compound-select processing\n"));
  101956. pParse->nSelectIndent--;
  101957. #endif
  101958. return rc;
  101959. }
  101960. #endif
  101961. /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
  101962. ** if the select-list is the same as the ORDER BY list, then this query
  101963. ** can be rewritten as a GROUP BY. In other words, this:
  101964. **
  101965. ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
  101966. **
  101967. ** is transformed to:
  101968. **
  101969. ** SELECT xyz FROM ... GROUP BY xyz
  101970. **
  101971. ** The second form is preferred as a single index (or temp-table) may be
  101972. ** used for both the ORDER BY and DISTINCT processing. As originally
  101973. ** written the query must use a temp-table for at least one of the ORDER
  101974. ** BY and DISTINCT, and an index or separate temp-table for the other.
  101975. */
  101976. if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
  101977. && sqlite3ExprListCompare(sSort.pOrderBy, p->pEList, -1)==0
  101978. ){
  101979. p->selFlags &= ~SF_Distinct;
  101980. p->pGroupBy = sqlite3ExprListDup(db, p->pEList, 0);
  101981. pGroupBy = p->pGroupBy;
  101982. sSort.pOrderBy = 0;
  101983. /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
  101984. ** the sDistinct.isTnct is still set. Hence, isTnct represents the
  101985. ** original setting of the SF_Distinct flag, not the current setting */
  101986. assert( sDistinct.isTnct );
  101987. }
  101988. /* If there is an ORDER BY clause, then this sorting
  101989. ** index might end up being unused if the data can be
  101990. ** extracted in pre-sorted order. If that is the case, then the
  101991. ** OP_OpenEphemeral instruction will be changed to an OP_Noop once
  101992. ** we figure out that the sorting index is not needed. The addrSortIndex
  101993. ** variable is used to facilitate that change.
  101994. */
  101995. if( sSort.pOrderBy ){
  101996. KeyInfo *pKeyInfo;
  101997. pKeyInfo = keyInfoFromExprList(pParse, sSort.pOrderBy, 0, 0);
  101998. sSort.iECursor = pParse->nTab++;
  101999. sSort.addrSortIndex =
  102000. sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  102001. sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
  102002. (char*)pKeyInfo, P4_KEYINFO
  102003. );
  102004. }else{
  102005. sSort.addrSortIndex = -1;
  102006. }
  102007. /* If the output is destined for a temporary table, open that table.
  102008. */
  102009. if( pDest->eDest==SRT_EphemTab ){
  102010. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
  102011. }
  102012. /* Set the limiter.
  102013. */
  102014. iEnd = sqlite3VdbeMakeLabel(v);
  102015. p->nSelectRow = LARGEST_INT64;
  102016. computeLimitRegisters(pParse, p, iEnd);
  102017. if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
  102018. sqlite3VdbeGetOp(v, sSort.addrSortIndex)->opcode = OP_SorterOpen;
  102019. sSort.sortFlags |= SORTFLAG_UseSorter;
  102020. }
  102021. /* Open a virtual index to use for the distinct set.
  102022. */
  102023. if( p->selFlags & SF_Distinct ){
  102024. sDistinct.tabTnct = pParse->nTab++;
  102025. sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
  102026. sDistinct.tabTnct, 0, 0,
  102027. (char*)keyInfoFromExprList(pParse, p->pEList,0,0),
  102028. P4_KEYINFO);
  102029. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  102030. sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
  102031. }else{
  102032. sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
  102033. }
  102034. if( !isAgg && pGroupBy==0 ){
  102035. /* No aggregate functions and no GROUP BY clause */
  102036. u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0);
  102037. /* Begin the database scan. */
  102038. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
  102039. p->pEList, wctrlFlags, 0);
  102040. if( pWInfo==0 ) goto select_end;
  102041. if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
  102042. p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
  102043. }
  102044. if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
  102045. sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
  102046. }
  102047. if( sSort.pOrderBy ){
  102048. sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
  102049. if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
  102050. sSort.pOrderBy = 0;
  102051. }
  102052. }
  102053. /* If sorting index that was created by a prior OP_OpenEphemeral
  102054. ** instruction ended up not being needed, then change the OP_OpenEphemeral
  102055. ** into an OP_Noop.
  102056. */
  102057. if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
  102058. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  102059. }
  102060. /* Use the standard inner loop. */
  102061. selectInnerLoop(pParse, p, pEList, -1, &sSort, &sDistinct, pDest,
  102062. sqlite3WhereContinueLabel(pWInfo),
  102063. sqlite3WhereBreakLabel(pWInfo));
  102064. /* End the database scan loop.
  102065. */
  102066. sqlite3WhereEnd(pWInfo);
  102067. }else{
  102068. /* This case when there exist aggregate functions or a GROUP BY clause
  102069. ** or both */
  102070. NameContext sNC; /* Name context for processing aggregate information */
  102071. int iAMem; /* First Mem address for storing current GROUP BY */
  102072. int iBMem; /* First Mem address for previous GROUP BY */
  102073. int iUseFlag; /* Mem address holding flag indicating that at least
  102074. ** one row of the input to the aggregator has been
  102075. ** processed */
  102076. int iAbortFlag; /* Mem address which causes query abort if positive */
  102077. int groupBySort; /* Rows come from source in GROUP BY order */
  102078. int addrEnd; /* End of processing for this SELECT */
  102079. int sortPTab = 0; /* Pseudotable used to decode sorting results */
  102080. int sortOut = 0; /* Output register from the sorter */
  102081. int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
  102082. /* Remove any and all aliases between the result set and the
  102083. ** GROUP BY clause.
  102084. */
  102085. if( pGroupBy ){
  102086. int k; /* Loop counter */
  102087. struct ExprList_item *pItem; /* For looping over expression in a list */
  102088. for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
  102089. pItem->u.x.iAlias = 0;
  102090. }
  102091. for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
  102092. pItem->u.x.iAlias = 0;
  102093. }
  102094. if( p->nSelectRow>100 ) p->nSelectRow = 100;
  102095. }else{
  102096. p->nSelectRow = 1;
  102097. }
  102098. /* If there is both a GROUP BY and an ORDER BY clause and they are
  102099. ** identical, then it may be possible to disable the ORDER BY clause
  102100. ** on the grounds that the GROUP BY will cause elements to come out
  102101. ** in the correct order. It also may not - the GROUP BY may use a
  102102. ** database index that causes rows to be grouped together as required
  102103. ** but not actually sorted. Either way, record the fact that the
  102104. ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
  102105. ** variable. */
  102106. if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
  102107. orderByGrp = 1;
  102108. }
  102109. /* Create a label to jump to when we want to abort the query */
  102110. addrEnd = sqlite3VdbeMakeLabel(v);
  102111. /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
  102112. ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
  102113. ** SELECT statement.
  102114. */
  102115. memset(&sNC, 0, sizeof(sNC));
  102116. sNC.pParse = pParse;
  102117. sNC.pSrcList = pTabList;
  102118. sNC.pAggInfo = &sAggInfo;
  102119. sAggInfo.mnReg = pParse->nMem+1;
  102120. sAggInfo.nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
  102121. sAggInfo.pGroupBy = pGroupBy;
  102122. sqlite3ExprAnalyzeAggList(&sNC, pEList);
  102123. sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
  102124. if( pHaving ){
  102125. sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
  102126. }
  102127. sAggInfo.nAccumulator = sAggInfo.nColumn;
  102128. for(i=0; i<sAggInfo.nFunc; i++){
  102129. assert( !ExprHasProperty(sAggInfo.aFunc[i].pExpr, EP_xIsSelect) );
  102130. sNC.ncFlags |= NC_InAggFunc;
  102131. sqlite3ExprAnalyzeAggList(&sNC, sAggInfo.aFunc[i].pExpr->x.pList);
  102132. sNC.ncFlags &= ~NC_InAggFunc;
  102133. }
  102134. sAggInfo.mxReg = pParse->nMem;
  102135. if( db->mallocFailed ) goto select_end;
  102136. /* Processing for aggregates with GROUP BY is very different and
  102137. ** much more complex than aggregates without a GROUP BY.
  102138. */
  102139. if( pGroupBy ){
  102140. KeyInfo *pKeyInfo; /* Keying information for the group by clause */
  102141. int j1; /* A-vs-B comparision jump */
  102142. int addrOutputRow; /* Start of subroutine that outputs a result row */
  102143. int regOutputRow; /* Return address register for output subroutine */
  102144. int addrSetAbort; /* Set the abort flag and return */
  102145. int addrTopOfLoop; /* Top of the input loop */
  102146. int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
  102147. int addrReset; /* Subroutine for resetting the accumulator */
  102148. int regReset; /* Return address register for reset subroutine */
  102149. /* If there is a GROUP BY clause we might need a sorting index to
  102150. ** implement it. Allocate that sorting index now. If it turns out
  102151. ** that we do not need it after all, the OP_SorterOpen instruction
  102152. ** will be converted into a Noop.
  102153. */
  102154. sAggInfo.sortingIdx = pParse->nTab++;
  102155. pKeyInfo = keyInfoFromExprList(pParse, pGroupBy, 0, 0);
  102156. addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
  102157. sAggInfo.sortingIdx, sAggInfo.nSortingColumn,
  102158. 0, (char*)pKeyInfo, P4_KEYINFO);
  102159. /* Initialize memory locations used by GROUP BY aggregate processing
  102160. */
  102161. iUseFlag = ++pParse->nMem;
  102162. iAbortFlag = ++pParse->nMem;
  102163. regOutputRow = ++pParse->nMem;
  102164. addrOutputRow = sqlite3VdbeMakeLabel(v);
  102165. regReset = ++pParse->nMem;
  102166. addrReset = sqlite3VdbeMakeLabel(v);
  102167. iAMem = pParse->nMem + 1;
  102168. pParse->nMem += pGroupBy->nExpr;
  102169. iBMem = pParse->nMem + 1;
  102170. pParse->nMem += pGroupBy->nExpr;
  102171. sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
  102172. VdbeComment((v, "clear abort flag"));
  102173. sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
  102174. VdbeComment((v, "indicate accumulator empty"));
  102175. sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
  102176. /* Begin a loop that will extract all source rows in GROUP BY order.
  102177. ** This might involve two separate loops with an OP_Sort in between, or
  102178. ** it might be a single loop that uses an index to extract information
  102179. ** in the right order to begin with.
  102180. */
  102181. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  102182. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, 0,
  102183. WHERE_GROUPBY | (orderByGrp ? WHERE_SORTBYGROUP : 0), 0
  102184. );
  102185. if( pWInfo==0 ) goto select_end;
  102186. if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
  102187. /* The optimizer is able to deliver rows in group by order so
  102188. ** we do not have to sort. The OP_OpenEphemeral table will be
  102189. ** cancelled later because we still need to use the pKeyInfo
  102190. */
  102191. groupBySort = 0;
  102192. }else{
  102193. /* Rows are coming out in undetermined order. We have to push
  102194. ** each row into a sorting index, terminate the first loop,
  102195. ** then loop over the sorting index in order to get the output
  102196. ** in sorted order
  102197. */
  102198. int regBase;
  102199. int regRecord;
  102200. int nCol;
  102201. int nGroupBy;
  102202. explainTempTable(pParse,
  102203. (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
  102204. "DISTINCT" : "GROUP BY");
  102205. groupBySort = 1;
  102206. nGroupBy = pGroupBy->nExpr;
  102207. nCol = nGroupBy;
  102208. j = nGroupBy;
  102209. for(i=0; i<sAggInfo.nColumn; i++){
  102210. if( sAggInfo.aCol[i].iSorterColumn>=j ){
  102211. nCol++;
  102212. j++;
  102213. }
  102214. }
  102215. regBase = sqlite3GetTempRange(pParse, nCol);
  102216. sqlite3ExprCacheClear(pParse);
  102217. sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0);
  102218. j = nGroupBy;
  102219. for(i=0; i<sAggInfo.nColumn; i++){
  102220. struct AggInfo_col *pCol = &sAggInfo.aCol[i];
  102221. if( pCol->iSorterColumn>=j ){
  102222. int r1 = j + regBase;
  102223. int r2;
  102224. r2 = sqlite3ExprCodeGetColumn(pParse,
  102225. pCol->pTab, pCol->iColumn, pCol->iTable, r1, 0);
  102226. if( r1!=r2 ){
  102227. sqlite3VdbeAddOp2(v, OP_SCopy, r2, r1);
  102228. }
  102229. j++;
  102230. }
  102231. }
  102232. regRecord = sqlite3GetTempReg(pParse);
  102233. sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
  102234. sqlite3VdbeAddOp2(v, OP_SorterInsert, sAggInfo.sortingIdx, regRecord);
  102235. sqlite3ReleaseTempReg(pParse, regRecord);
  102236. sqlite3ReleaseTempRange(pParse, regBase, nCol);
  102237. sqlite3WhereEnd(pWInfo);
  102238. sAggInfo.sortingIdxPTab = sortPTab = pParse->nTab++;
  102239. sortOut = sqlite3GetTempReg(pParse);
  102240. sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
  102241. sqlite3VdbeAddOp2(v, OP_SorterSort, sAggInfo.sortingIdx, addrEnd);
  102242. VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
  102243. sAggInfo.useSortingIdx = 1;
  102244. sqlite3ExprCacheClear(pParse);
  102245. }
  102246. /* If the index or temporary table used by the GROUP BY sort
  102247. ** will naturally deliver rows in the order required by the ORDER BY
  102248. ** clause, cancel the ephemeral table open coded earlier.
  102249. **
  102250. ** This is an optimization - the correct answer should result regardless.
  102251. ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
  102252. ** disable this optimization for testing purposes. */
  102253. if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
  102254. && (groupBySort || sqlite3WhereIsSorted(pWInfo))
  102255. ){
  102256. sSort.pOrderBy = 0;
  102257. sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
  102258. }
  102259. /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
  102260. ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
  102261. ** Then compare the current GROUP BY terms against the GROUP BY terms
  102262. ** from the previous row currently stored in a0, a1, a2...
  102263. */
  102264. addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
  102265. sqlite3ExprCacheClear(pParse);
  102266. if( groupBySort ){
  102267. sqlite3VdbeAddOp3(v, OP_SorterData, sAggInfo.sortingIdx, sortOut,sortPTab);
  102268. }
  102269. for(j=0; j<pGroupBy->nExpr; j++){
  102270. if( groupBySort ){
  102271. sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
  102272. }else{
  102273. sAggInfo.directMode = 1;
  102274. sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
  102275. }
  102276. }
  102277. sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
  102278. (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
  102279. j1 = sqlite3VdbeCurrentAddr(v);
  102280. sqlite3VdbeAddOp3(v, OP_Jump, j1+1, 0, j1+1); VdbeCoverage(v);
  102281. /* Generate code that runs whenever the GROUP BY changes.
  102282. ** Changes in the GROUP BY are detected by the previous code
  102283. ** block. If there were no changes, this block is skipped.
  102284. **
  102285. ** This code copies current group by terms in b0,b1,b2,...
  102286. ** over to a0,a1,a2. It then calls the output subroutine
  102287. ** and resets the aggregate accumulator registers in preparation
  102288. ** for the next GROUP BY batch.
  102289. */
  102290. sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
  102291. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  102292. VdbeComment((v, "output one row"));
  102293. sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
  102294. VdbeComment((v, "check abort flag"));
  102295. sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
  102296. VdbeComment((v, "reset accumulator"));
  102297. /* Update the aggregate accumulators based on the content of
  102298. ** the current row
  102299. */
  102300. sqlite3VdbeJumpHere(v, j1);
  102301. updateAccumulator(pParse, &sAggInfo);
  102302. sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
  102303. VdbeComment((v, "indicate data in accumulator"));
  102304. /* End of the loop
  102305. */
  102306. if( groupBySort ){
  102307. sqlite3VdbeAddOp2(v, OP_SorterNext, sAggInfo.sortingIdx, addrTopOfLoop);
  102308. VdbeCoverage(v);
  102309. }else{
  102310. sqlite3WhereEnd(pWInfo);
  102311. sqlite3VdbeChangeToNoop(v, addrSortingIdx);
  102312. }
  102313. /* Output the final row of result
  102314. */
  102315. sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
  102316. VdbeComment((v, "output final row"));
  102317. /* Jump over the subroutines
  102318. */
  102319. sqlite3VdbeAddOp2(v, OP_Goto, 0, addrEnd);
  102320. /* Generate a subroutine that outputs a single row of the result
  102321. ** set. This subroutine first looks at the iUseFlag. If iUseFlag
  102322. ** is less than or equal to zero, the subroutine is a no-op. If
  102323. ** the processing calls for the query to abort, this subroutine
  102324. ** increments the iAbortFlag memory location before returning in
  102325. ** order to signal the caller to abort.
  102326. */
  102327. addrSetAbort = sqlite3VdbeCurrentAddr(v);
  102328. sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
  102329. VdbeComment((v, "set abort flag"));
  102330. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  102331. sqlite3VdbeResolveLabel(v, addrOutputRow);
  102332. addrOutputRow = sqlite3VdbeCurrentAddr(v);
  102333. sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2); VdbeCoverage(v);
  102334. VdbeComment((v, "Groupby result generator entry point"));
  102335. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  102336. finalizeAggFunctions(pParse, &sAggInfo);
  102337. sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
  102338. selectInnerLoop(pParse, p, p->pEList, -1, &sSort,
  102339. &sDistinct, pDest,
  102340. addrOutputRow+1, addrSetAbort);
  102341. sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
  102342. VdbeComment((v, "end groupby result generator"));
  102343. /* Generate a subroutine that will reset the group-by accumulator
  102344. */
  102345. sqlite3VdbeResolveLabel(v, addrReset);
  102346. resetAccumulator(pParse, &sAggInfo);
  102347. sqlite3VdbeAddOp1(v, OP_Return, regReset);
  102348. } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
  102349. else {
  102350. ExprList *pDel = 0;
  102351. #ifndef SQLITE_OMIT_BTREECOUNT
  102352. Table *pTab;
  102353. if( (pTab = isSimpleCount(p, &sAggInfo))!=0 ){
  102354. /* If isSimpleCount() returns a pointer to a Table structure, then
  102355. ** the SQL statement is of the form:
  102356. **
  102357. ** SELECT count(*) FROM <tbl>
  102358. **
  102359. ** where the Table structure returned represents table <tbl>.
  102360. **
  102361. ** This statement is so common that it is optimized specially. The
  102362. ** OP_Count instruction is executed either on the intkey table that
  102363. ** contains the data for table <tbl> or on one of its indexes. It
  102364. ** is better to execute the op on an index, as indexes are almost
  102365. ** always spread across less pages than their corresponding tables.
  102366. */
  102367. const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  102368. const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
  102369. Index *pIdx; /* Iterator variable */
  102370. KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
  102371. Index *pBest = 0; /* Best index found so far */
  102372. int iRoot = pTab->tnum; /* Root page of scanned b-tree */
  102373. sqlite3CodeVerifySchema(pParse, iDb);
  102374. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  102375. /* Search for the index that has the lowest scan cost.
  102376. **
  102377. ** (2011-04-15) Do not do a full scan of an unordered index.
  102378. **
  102379. ** (2013-10-03) Do not count the entries in a partial index.
  102380. **
  102381. ** In practice the KeyInfo structure will not be used. It is only
  102382. ** passed to keep OP_OpenRead happy.
  102383. */
  102384. if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
  102385. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  102386. if( pIdx->bUnordered==0
  102387. && pIdx->szIdxRow<pTab->szTabRow
  102388. && pIdx->pPartIdxWhere==0
  102389. && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
  102390. ){
  102391. pBest = pIdx;
  102392. }
  102393. }
  102394. if( pBest ){
  102395. iRoot = pBest->tnum;
  102396. pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
  102397. }
  102398. /* Open a read-only cursor, execute the OP_Count, close the cursor. */
  102399. sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, iRoot, iDb, 1);
  102400. if( pKeyInfo ){
  102401. sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
  102402. }
  102403. sqlite3VdbeAddOp2(v, OP_Count, iCsr, sAggInfo.aFunc[0].iMem);
  102404. sqlite3VdbeAddOp1(v, OP_Close, iCsr);
  102405. explainSimpleCount(pParse, pTab, pBest);
  102406. }else
  102407. #endif /* SQLITE_OMIT_BTREECOUNT */
  102408. {
  102409. /* Check if the query is of one of the following forms:
  102410. **
  102411. ** SELECT min(x) FROM ...
  102412. ** SELECT max(x) FROM ...
  102413. **
  102414. ** If it is, then ask the code in where.c to attempt to sort results
  102415. ** as if there was an "ORDER ON x" or "ORDER ON x DESC" clause.
  102416. ** If where.c is able to produce results sorted in this order, then
  102417. ** add vdbe code to break out of the processing loop after the
  102418. ** first iteration (since the first iteration of the loop is
  102419. ** guaranteed to operate on the row with the minimum or maximum
  102420. ** value of x, the only row required).
  102421. **
  102422. ** A special flag must be passed to sqlite3WhereBegin() to slightly
  102423. ** modify behavior as follows:
  102424. **
  102425. ** + If the query is a "SELECT min(x)", then the loop coded by
  102426. ** where.c should not iterate over any values with a NULL value
  102427. ** for x.
  102428. **
  102429. ** + The optimizer code in where.c (the thing that decides which
  102430. ** index or indices to use) should place a different priority on
  102431. ** satisfying the 'ORDER BY' clause than it does in other cases.
  102432. ** Refer to code and comments in where.c for details.
  102433. */
  102434. ExprList *pMinMax = 0;
  102435. u8 flag = WHERE_ORDERBY_NORMAL;
  102436. assert( p->pGroupBy==0 );
  102437. assert( flag==0 );
  102438. if( p->pHaving==0 ){
  102439. flag = minMaxQuery(&sAggInfo, &pMinMax);
  102440. }
  102441. assert( flag==0 || (pMinMax!=0 && pMinMax->nExpr==1) );
  102442. if( flag ){
  102443. pMinMax = sqlite3ExprListDup(db, pMinMax, 0);
  102444. pDel = pMinMax;
  102445. if( pMinMax && !db->mallocFailed ){
  102446. pMinMax->a[0].sortOrder = flag!=WHERE_ORDERBY_MIN ?1:0;
  102447. pMinMax->a[0].pExpr->op = TK_COLUMN;
  102448. }
  102449. }
  102450. /* This case runs if the aggregate has no GROUP BY clause. The
  102451. ** processing is much simpler since there is only a single row
  102452. ** of output.
  102453. */
  102454. resetAccumulator(pParse, &sAggInfo);
  102455. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMax,0,flag,0);
  102456. if( pWInfo==0 ){
  102457. sqlite3ExprListDelete(db, pDel);
  102458. goto select_end;
  102459. }
  102460. updateAccumulator(pParse, &sAggInfo);
  102461. assert( pMinMax==0 || pMinMax->nExpr==1 );
  102462. if( sqlite3WhereIsOrdered(pWInfo)>0 ){
  102463. sqlite3VdbeAddOp2(v, OP_Goto, 0, sqlite3WhereBreakLabel(pWInfo));
  102464. VdbeComment((v, "%s() by index",
  102465. (flag==WHERE_ORDERBY_MIN?"min":"max")));
  102466. }
  102467. sqlite3WhereEnd(pWInfo);
  102468. finalizeAggFunctions(pParse, &sAggInfo);
  102469. }
  102470. sSort.pOrderBy = 0;
  102471. sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
  102472. selectInnerLoop(pParse, p, p->pEList, -1, 0, 0,
  102473. pDest, addrEnd, addrEnd);
  102474. sqlite3ExprListDelete(db, pDel);
  102475. }
  102476. sqlite3VdbeResolveLabel(v, addrEnd);
  102477. } /* endif aggregate query */
  102478. if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
  102479. explainTempTable(pParse, "DISTINCT");
  102480. }
  102481. /* If there is an ORDER BY clause, then we need to sort the results
  102482. ** and send them to the callback one by one.
  102483. */
  102484. if( sSort.pOrderBy ){
  102485. explainTempTable(pParse, sSort.nOBSat>0 ? "RIGHT PART OF ORDER BY":"ORDER BY");
  102486. generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
  102487. }
  102488. /* Jump here to skip this query
  102489. */
  102490. sqlite3VdbeResolveLabel(v, iEnd);
  102491. /* The SELECT was successfully coded. Set the return code to 0
  102492. ** to indicate no errors.
  102493. */
  102494. rc = 0;
  102495. /* Control jumps to here if an error is encountered above, or upon
  102496. ** successful coding of the SELECT.
  102497. */
  102498. select_end:
  102499. explainSetInteger(pParse->iSelectId, iRestoreSelectId);
  102500. /* Identify column names if results of the SELECT are to be output.
  102501. */
  102502. if( rc==SQLITE_OK && pDest->eDest==SRT_Output ){
  102503. generateColumnNames(pParse, pTabList, pEList);
  102504. }
  102505. sqlite3DbFree(db, sAggInfo.aCol);
  102506. sqlite3DbFree(db, sAggInfo.aFunc);
  102507. #if SELECTTRACE_ENABLED
  102508. SELECTTRACE(1,pParse,p,("end processing\n"));
  102509. pParse->nSelectIndent--;
  102510. #endif
  102511. return rc;
  102512. }
  102513. #ifdef SQLITE_DEBUG
  102514. /*
  102515. ** Generate a human-readable description of a the Select object.
  102516. */
  102517. SQLITE_PRIVATE void sqlite3TreeViewSelect(TreeView *pView, const Select *p, u8 moreToFollow){
  102518. int n = 0;
  102519. pView = sqlite3TreeViewPush(pView, moreToFollow);
  102520. sqlite3TreeViewLine(pView, "SELECT%s%s",
  102521. ((p->selFlags & SF_Distinct) ? " DISTINCT" : ""),
  102522. ((p->selFlags & SF_Aggregate) ? " agg_flag" : "")
  102523. );
  102524. if( p->pSrc && p->pSrc->nSrc ) n++;
  102525. if( p->pWhere ) n++;
  102526. if( p->pGroupBy ) n++;
  102527. if( p->pHaving ) n++;
  102528. if( p->pOrderBy ) n++;
  102529. if( p->pLimit ) n++;
  102530. if( p->pOffset ) n++;
  102531. if( p->pPrior ) n++;
  102532. sqlite3TreeViewExprList(pView, p->pEList, (n--)>0, "result-set");
  102533. if( p->pSrc && p->pSrc->nSrc ){
  102534. int i;
  102535. pView = sqlite3TreeViewPush(pView, (n--)>0);
  102536. sqlite3TreeViewLine(pView, "FROM");
  102537. for(i=0; i<p->pSrc->nSrc; i++){
  102538. struct SrcList_item *pItem = &p->pSrc->a[i];
  102539. StrAccum x;
  102540. char zLine[100];
  102541. sqlite3StrAccumInit(&x, zLine, sizeof(zLine), 0);
  102542. sqlite3XPrintf(&x, 0, "{%d,*}", pItem->iCursor);
  102543. if( pItem->zDatabase ){
  102544. sqlite3XPrintf(&x, 0, " %s.%s", pItem->zDatabase, pItem->zName);
  102545. }else if( pItem->zName ){
  102546. sqlite3XPrintf(&x, 0, " %s", pItem->zName);
  102547. }
  102548. if( pItem->pTab ){
  102549. sqlite3XPrintf(&x, 0, " tabname=%Q", pItem->pTab->zName);
  102550. }
  102551. if( pItem->zAlias ){
  102552. sqlite3XPrintf(&x, 0, " (AS %s)", pItem->zAlias);
  102553. }
  102554. if( pItem->jointype & JT_LEFT ){
  102555. sqlite3XPrintf(&x, 0, " LEFT-JOIN");
  102556. }
  102557. sqlite3StrAccumFinish(&x);
  102558. sqlite3TreeViewItem(pView, zLine, i<p->pSrc->nSrc-1);
  102559. if( pItem->pSelect ){
  102560. sqlite3TreeViewSelect(pView, pItem->pSelect, 0);
  102561. }
  102562. sqlite3TreeViewPop(pView);
  102563. }
  102564. sqlite3TreeViewPop(pView);
  102565. }
  102566. if( p->pWhere ){
  102567. sqlite3TreeViewItem(pView, "WHERE", (n--)>0);
  102568. sqlite3TreeViewExpr(pView, p->pWhere, 0);
  102569. sqlite3TreeViewPop(pView);
  102570. }
  102571. if( p->pGroupBy ){
  102572. sqlite3TreeViewExprList(pView, p->pGroupBy, (n--)>0, "GROUPBY");
  102573. }
  102574. if( p->pHaving ){
  102575. sqlite3TreeViewItem(pView, "HAVING", (n--)>0);
  102576. sqlite3TreeViewExpr(pView, p->pHaving, 0);
  102577. sqlite3TreeViewPop(pView);
  102578. }
  102579. if( p->pOrderBy ){
  102580. sqlite3TreeViewExprList(pView, p->pOrderBy, (n--)>0, "ORDERBY");
  102581. }
  102582. if( p->pLimit ){
  102583. sqlite3TreeViewItem(pView, "LIMIT", (n--)>0);
  102584. sqlite3TreeViewExpr(pView, p->pLimit, 0);
  102585. sqlite3TreeViewPop(pView);
  102586. }
  102587. if( p->pOffset ){
  102588. sqlite3TreeViewItem(pView, "OFFSET", (n--)>0);
  102589. sqlite3TreeViewExpr(pView, p->pOffset, 0);
  102590. sqlite3TreeViewPop(pView);
  102591. }
  102592. if( p->pPrior ){
  102593. const char *zOp = "UNION";
  102594. switch( p->op ){
  102595. case TK_ALL: zOp = "UNION ALL"; break;
  102596. case TK_INTERSECT: zOp = "INTERSECT"; break;
  102597. case TK_EXCEPT: zOp = "EXCEPT"; break;
  102598. }
  102599. sqlite3TreeViewItem(pView, zOp, (n--)>0);
  102600. sqlite3TreeViewSelect(pView, p->pPrior, 0);
  102601. sqlite3TreeViewPop(pView);
  102602. }
  102603. sqlite3TreeViewPop(pView);
  102604. }
  102605. #endif /* SQLITE_DEBUG */
  102606. /************** End of select.c **********************************************/
  102607. /************** Begin file table.c *******************************************/
  102608. /*
  102609. ** 2001 September 15
  102610. **
  102611. ** The author disclaims copyright to this source code. In place of
  102612. ** a legal notice, here is a blessing:
  102613. **
  102614. ** May you do good and not evil.
  102615. ** May you find forgiveness for yourself and forgive others.
  102616. ** May you share freely, never taking more than you give.
  102617. **
  102618. *************************************************************************
  102619. ** This file contains the sqlite3_get_table() and sqlite3_free_table()
  102620. ** interface routines. These are just wrappers around the main
  102621. ** interface routine of sqlite3_exec().
  102622. **
  102623. ** These routines are in a separate files so that they will not be linked
  102624. ** if they are not used.
  102625. */
  102626. /* #include <stdlib.h> */
  102627. /* #include <string.h> */
  102628. #ifndef SQLITE_OMIT_GET_TABLE
  102629. /*
  102630. ** This structure is used to pass data from sqlite3_get_table() through
  102631. ** to the callback function is uses to build the result.
  102632. */
  102633. typedef struct TabResult {
  102634. char **azResult; /* Accumulated output */
  102635. char *zErrMsg; /* Error message text, if an error occurs */
  102636. u32 nAlloc; /* Slots allocated for azResult[] */
  102637. u32 nRow; /* Number of rows in the result */
  102638. u32 nColumn; /* Number of columns in the result */
  102639. u32 nData; /* Slots used in azResult[]. (nRow+1)*nColumn */
  102640. int rc; /* Return code from sqlite3_exec() */
  102641. } TabResult;
  102642. /*
  102643. ** This routine is called once for each row in the result table. Its job
  102644. ** is to fill in the TabResult structure appropriately, allocating new
  102645. ** memory as necessary.
  102646. */
  102647. static int sqlite3_get_table_cb(void *pArg, int nCol, char **argv, char **colv){
  102648. TabResult *p = (TabResult*)pArg; /* Result accumulator */
  102649. int need; /* Slots needed in p->azResult[] */
  102650. int i; /* Loop counter */
  102651. char *z; /* A single column of result */
  102652. /* Make sure there is enough space in p->azResult to hold everything
  102653. ** we need to remember from this invocation of the callback.
  102654. */
  102655. if( p->nRow==0 && argv!=0 ){
  102656. need = nCol*2;
  102657. }else{
  102658. need = nCol;
  102659. }
  102660. if( p->nData + need > p->nAlloc ){
  102661. char **azNew;
  102662. p->nAlloc = p->nAlloc*2 + need;
  102663. azNew = sqlite3_realloc64( p->azResult, sizeof(char*)*p->nAlloc );
  102664. if( azNew==0 ) goto malloc_failed;
  102665. p->azResult = azNew;
  102666. }
  102667. /* If this is the first row, then generate an extra row containing
  102668. ** the names of all columns.
  102669. */
  102670. if( p->nRow==0 ){
  102671. p->nColumn = nCol;
  102672. for(i=0; i<nCol; i++){
  102673. z = sqlite3_mprintf("%s", colv[i]);
  102674. if( z==0 ) goto malloc_failed;
  102675. p->azResult[p->nData++] = z;
  102676. }
  102677. }else if( (int)p->nColumn!=nCol ){
  102678. sqlite3_free(p->zErrMsg);
  102679. p->zErrMsg = sqlite3_mprintf(
  102680. "sqlite3_get_table() called with two or more incompatible queries"
  102681. );
  102682. p->rc = SQLITE_ERROR;
  102683. return 1;
  102684. }
  102685. /* Copy over the row data
  102686. */
  102687. if( argv!=0 ){
  102688. for(i=0; i<nCol; i++){
  102689. if( argv[i]==0 ){
  102690. z = 0;
  102691. }else{
  102692. int n = sqlite3Strlen30(argv[i])+1;
  102693. z = sqlite3_malloc( n );
  102694. if( z==0 ) goto malloc_failed;
  102695. memcpy(z, argv[i], n);
  102696. }
  102697. p->azResult[p->nData++] = z;
  102698. }
  102699. p->nRow++;
  102700. }
  102701. return 0;
  102702. malloc_failed:
  102703. p->rc = SQLITE_NOMEM;
  102704. return 1;
  102705. }
  102706. /*
  102707. ** Query the database. But instead of invoking a callback for each row,
  102708. ** malloc() for space to hold the result and return the entire results
  102709. ** at the conclusion of the call.
  102710. **
  102711. ** The result that is written to ***pazResult is held in memory obtained
  102712. ** from malloc(). But the caller cannot free this memory directly.
  102713. ** Instead, the entire table should be passed to sqlite3_free_table() when
  102714. ** the calling procedure is finished using it.
  102715. */
  102716. SQLITE_API int sqlite3_get_table(
  102717. sqlite3 *db, /* The database on which the SQL executes */
  102718. const char *zSql, /* The SQL to be executed */
  102719. char ***pazResult, /* Write the result table here */
  102720. int *pnRow, /* Write the number of rows in the result here */
  102721. int *pnColumn, /* Write the number of columns of result here */
  102722. char **pzErrMsg /* Write error messages here */
  102723. ){
  102724. int rc;
  102725. TabResult res;
  102726. *pazResult = 0;
  102727. if( pnColumn ) *pnColumn = 0;
  102728. if( pnRow ) *pnRow = 0;
  102729. if( pzErrMsg ) *pzErrMsg = 0;
  102730. res.zErrMsg = 0;
  102731. res.nRow = 0;
  102732. res.nColumn = 0;
  102733. res.nData = 1;
  102734. res.nAlloc = 20;
  102735. res.rc = SQLITE_OK;
  102736. res.azResult = sqlite3_malloc(sizeof(char*)*res.nAlloc );
  102737. if( res.azResult==0 ){
  102738. db->errCode = SQLITE_NOMEM;
  102739. return SQLITE_NOMEM;
  102740. }
  102741. res.azResult[0] = 0;
  102742. rc = sqlite3_exec(db, zSql, sqlite3_get_table_cb, &res, pzErrMsg);
  102743. assert( sizeof(res.azResult[0])>= sizeof(res.nData) );
  102744. res.azResult[0] = SQLITE_INT_TO_PTR(res.nData);
  102745. if( (rc&0xff)==SQLITE_ABORT ){
  102746. sqlite3_free_table(&res.azResult[1]);
  102747. if( res.zErrMsg ){
  102748. if( pzErrMsg ){
  102749. sqlite3_free(*pzErrMsg);
  102750. *pzErrMsg = sqlite3_mprintf("%s",res.zErrMsg);
  102751. }
  102752. sqlite3_free(res.zErrMsg);
  102753. }
  102754. db->errCode = res.rc; /* Assume 32-bit assignment is atomic */
  102755. return res.rc;
  102756. }
  102757. sqlite3_free(res.zErrMsg);
  102758. if( rc!=SQLITE_OK ){
  102759. sqlite3_free_table(&res.azResult[1]);
  102760. return rc;
  102761. }
  102762. if( res.nAlloc>res.nData ){
  102763. char **azNew;
  102764. azNew = sqlite3_realloc( res.azResult, sizeof(char*)*res.nData );
  102765. if( azNew==0 ){
  102766. sqlite3_free_table(&res.azResult[1]);
  102767. db->errCode = SQLITE_NOMEM;
  102768. return SQLITE_NOMEM;
  102769. }
  102770. res.azResult = azNew;
  102771. }
  102772. *pazResult = &res.azResult[1];
  102773. if( pnColumn ) *pnColumn = res.nColumn;
  102774. if( pnRow ) *pnRow = res.nRow;
  102775. return rc;
  102776. }
  102777. /*
  102778. ** This routine frees the space the sqlite3_get_table() malloced.
  102779. */
  102780. SQLITE_API void sqlite3_free_table(
  102781. char **azResult /* Result returned from sqlite3_get_table() */
  102782. ){
  102783. if( azResult ){
  102784. int i, n;
  102785. azResult--;
  102786. assert( azResult!=0 );
  102787. n = SQLITE_PTR_TO_INT(azResult[0]);
  102788. for(i=1; i<n; i++){ if( azResult[i] ) sqlite3_free(azResult[i]); }
  102789. sqlite3_free(azResult);
  102790. }
  102791. }
  102792. #endif /* SQLITE_OMIT_GET_TABLE */
  102793. /************** End of table.c ***********************************************/
  102794. /************** Begin file trigger.c *****************************************/
  102795. /*
  102796. **
  102797. ** The author disclaims copyright to this source code. In place of
  102798. ** a legal notice, here is a blessing:
  102799. **
  102800. ** May you do good and not evil.
  102801. ** May you find forgiveness for yourself and forgive others.
  102802. ** May you share freely, never taking more than you give.
  102803. **
  102804. *************************************************************************
  102805. ** This file contains the implementation for TRIGGERs
  102806. */
  102807. #ifndef SQLITE_OMIT_TRIGGER
  102808. /*
  102809. ** Delete a linked list of TriggerStep structures.
  102810. */
  102811. SQLITE_PRIVATE void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
  102812. while( pTriggerStep ){
  102813. TriggerStep * pTmp = pTriggerStep;
  102814. pTriggerStep = pTriggerStep->pNext;
  102815. sqlite3ExprDelete(db, pTmp->pWhere);
  102816. sqlite3ExprListDelete(db, pTmp->pExprList);
  102817. sqlite3SelectDelete(db, pTmp->pSelect);
  102818. sqlite3IdListDelete(db, pTmp->pIdList);
  102819. sqlite3DbFree(db, pTmp);
  102820. }
  102821. }
  102822. /*
  102823. ** Given table pTab, return a list of all the triggers attached to
  102824. ** the table. The list is connected by Trigger.pNext pointers.
  102825. **
  102826. ** All of the triggers on pTab that are in the same database as pTab
  102827. ** are already attached to pTab->pTrigger. But there might be additional
  102828. ** triggers on pTab in the TEMP schema. This routine prepends all
  102829. ** TEMP triggers on pTab to the beginning of the pTab->pTrigger list
  102830. ** and returns the combined list.
  102831. **
  102832. ** To state it another way: This routine returns a list of all triggers
  102833. ** that fire off of pTab. The list will include any TEMP triggers on
  102834. ** pTab as well as the triggers lised in pTab->pTrigger.
  102835. */
  102836. SQLITE_PRIVATE Trigger *sqlite3TriggerList(Parse *pParse, Table *pTab){
  102837. Schema * const pTmpSchema = pParse->db->aDb[1].pSchema;
  102838. Trigger *pList = 0; /* List of triggers to return */
  102839. if( pParse->disableTriggers ){
  102840. return 0;
  102841. }
  102842. if( pTmpSchema!=pTab->pSchema ){
  102843. HashElem *p;
  102844. assert( sqlite3SchemaMutexHeld(pParse->db, 0, pTmpSchema) );
  102845. for(p=sqliteHashFirst(&pTmpSchema->trigHash); p; p=sqliteHashNext(p)){
  102846. Trigger *pTrig = (Trigger *)sqliteHashData(p);
  102847. if( pTrig->pTabSchema==pTab->pSchema
  102848. && 0==sqlite3StrICmp(pTrig->table, pTab->zName)
  102849. ){
  102850. pTrig->pNext = (pList ? pList : pTab->pTrigger);
  102851. pList = pTrig;
  102852. }
  102853. }
  102854. }
  102855. return (pList ? pList : pTab->pTrigger);
  102856. }
  102857. /*
  102858. ** This is called by the parser when it sees a CREATE TRIGGER statement
  102859. ** up to the point of the BEGIN before the trigger actions. A Trigger
  102860. ** structure is generated based on the information available and stored
  102861. ** in pParse->pNewTrigger. After the trigger actions have been parsed, the
  102862. ** sqlite3FinishTrigger() function is called to complete the trigger
  102863. ** construction process.
  102864. */
  102865. SQLITE_PRIVATE void sqlite3BeginTrigger(
  102866. Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
  102867. Token *pName1, /* The name of the trigger */
  102868. Token *pName2, /* The name of the trigger */
  102869. int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
  102870. int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
  102871. IdList *pColumns, /* column list if this is an UPDATE OF trigger */
  102872. SrcList *pTableName,/* The name of the table/view the trigger applies to */
  102873. Expr *pWhen, /* WHEN clause */
  102874. int isTemp, /* True if the TEMPORARY keyword is present */
  102875. int noErr /* Suppress errors if the trigger already exists */
  102876. ){
  102877. Trigger *pTrigger = 0; /* The new trigger */
  102878. Table *pTab; /* Table that the trigger fires off of */
  102879. char *zName = 0; /* Name of the trigger */
  102880. sqlite3 *db = pParse->db; /* The database connection */
  102881. int iDb; /* The database to store the trigger in */
  102882. Token *pName; /* The unqualified db name */
  102883. DbFixer sFix; /* State vector for the DB fixer */
  102884. int iTabDb; /* Index of the database holding pTab */
  102885. assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
  102886. assert( pName2!=0 );
  102887. assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
  102888. assert( op>0 && op<0xff );
  102889. if( isTemp ){
  102890. /* If TEMP was specified, then the trigger name may not be qualified. */
  102891. if( pName2->n>0 ){
  102892. sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
  102893. goto trigger_cleanup;
  102894. }
  102895. iDb = 1;
  102896. pName = pName1;
  102897. }else{
  102898. /* Figure out the db that the trigger will be created in */
  102899. iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
  102900. if( iDb<0 ){
  102901. goto trigger_cleanup;
  102902. }
  102903. }
  102904. if( !pTableName || db->mallocFailed ){
  102905. goto trigger_cleanup;
  102906. }
  102907. /* A long-standing parser bug is that this syntax was allowed:
  102908. **
  102909. ** CREATE TRIGGER attached.demo AFTER INSERT ON attached.tab ....
  102910. ** ^^^^^^^^
  102911. **
  102912. ** To maintain backwards compatibility, ignore the database
  102913. ** name on pTableName if we are reparsing out of SQLITE_MASTER.
  102914. */
  102915. if( db->init.busy && iDb!=1 ){
  102916. sqlite3DbFree(db, pTableName->a[0].zDatabase);
  102917. pTableName->a[0].zDatabase = 0;
  102918. }
  102919. /* If the trigger name was unqualified, and the table is a temp table,
  102920. ** then set iDb to 1 to create the trigger in the temporary database.
  102921. ** If sqlite3SrcListLookup() returns 0, indicating the table does not
  102922. ** exist, the error is caught by the block below.
  102923. */
  102924. pTab = sqlite3SrcListLookup(pParse, pTableName);
  102925. if( db->init.busy==0 && pName2->n==0 && pTab
  102926. && pTab->pSchema==db->aDb[1].pSchema ){
  102927. iDb = 1;
  102928. }
  102929. /* Ensure the table name matches database name and that the table exists */
  102930. if( db->mallocFailed ) goto trigger_cleanup;
  102931. assert( pTableName->nSrc==1 );
  102932. sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName);
  102933. if( sqlite3FixSrcList(&sFix, pTableName) ){
  102934. goto trigger_cleanup;
  102935. }
  102936. pTab = sqlite3SrcListLookup(pParse, pTableName);
  102937. if( !pTab ){
  102938. /* The table does not exist. */
  102939. if( db->init.iDb==1 ){
  102940. /* Ticket #3810.
  102941. ** Normally, whenever a table is dropped, all associated triggers are
  102942. ** dropped too. But if a TEMP trigger is created on a non-TEMP table
  102943. ** and the table is dropped by a different database connection, the
  102944. ** trigger is not visible to the database connection that does the
  102945. ** drop so the trigger cannot be dropped. This results in an
  102946. ** "orphaned trigger" - a trigger whose associated table is missing.
  102947. */
  102948. db->init.orphanTrigger = 1;
  102949. }
  102950. goto trigger_cleanup;
  102951. }
  102952. if( IsVirtual(pTab) ){
  102953. sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
  102954. goto trigger_cleanup;
  102955. }
  102956. /* Check that the trigger name is not reserved and that no trigger of the
  102957. ** specified name exists */
  102958. zName = sqlite3NameFromToken(db, pName);
  102959. if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
  102960. goto trigger_cleanup;
  102961. }
  102962. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  102963. if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),zName) ){
  102964. if( !noErr ){
  102965. sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
  102966. }else{
  102967. assert( !db->init.busy );
  102968. sqlite3CodeVerifySchema(pParse, iDb);
  102969. }
  102970. goto trigger_cleanup;
  102971. }
  102972. /* Do not create a trigger on a system table */
  102973. if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
  102974. sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
  102975. pParse->nErr++;
  102976. goto trigger_cleanup;
  102977. }
  102978. /* INSTEAD of triggers are only for views and views only support INSTEAD
  102979. ** of triggers.
  102980. */
  102981. if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
  102982. sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
  102983. (tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
  102984. goto trigger_cleanup;
  102985. }
  102986. if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
  102987. sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
  102988. " trigger on table: %S", pTableName, 0);
  102989. goto trigger_cleanup;
  102990. }
  102991. iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  102992. #ifndef SQLITE_OMIT_AUTHORIZATION
  102993. {
  102994. int code = SQLITE_CREATE_TRIGGER;
  102995. const char *zDb = db->aDb[iTabDb].zName;
  102996. const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
  102997. if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
  102998. if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
  102999. goto trigger_cleanup;
  103000. }
  103001. if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
  103002. goto trigger_cleanup;
  103003. }
  103004. }
  103005. #endif
  103006. /* INSTEAD OF triggers can only appear on views and BEFORE triggers
  103007. ** cannot appear on views. So we might as well translate every
  103008. ** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
  103009. ** elsewhere.
  103010. */
  103011. if (tr_tm == TK_INSTEAD){
  103012. tr_tm = TK_BEFORE;
  103013. }
  103014. /* Build the Trigger object */
  103015. pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
  103016. if( pTrigger==0 ) goto trigger_cleanup;
  103017. pTrigger->zName = zName;
  103018. zName = 0;
  103019. pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
  103020. pTrigger->pSchema = db->aDb[iDb].pSchema;
  103021. pTrigger->pTabSchema = pTab->pSchema;
  103022. pTrigger->op = (u8)op;
  103023. pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
  103024. pTrigger->pWhen = sqlite3ExprDup(db, pWhen, EXPRDUP_REDUCE);
  103025. pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
  103026. assert( pParse->pNewTrigger==0 );
  103027. pParse->pNewTrigger = pTrigger;
  103028. trigger_cleanup:
  103029. sqlite3DbFree(db, zName);
  103030. sqlite3SrcListDelete(db, pTableName);
  103031. sqlite3IdListDelete(db, pColumns);
  103032. sqlite3ExprDelete(db, pWhen);
  103033. if( !pParse->pNewTrigger ){
  103034. sqlite3DeleteTrigger(db, pTrigger);
  103035. }else{
  103036. assert( pParse->pNewTrigger==pTrigger );
  103037. }
  103038. }
  103039. /*
  103040. ** This routine is called after all of the trigger actions have been parsed
  103041. ** in order to complete the process of building the trigger.
  103042. */
  103043. SQLITE_PRIVATE void sqlite3FinishTrigger(
  103044. Parse *pParse, /* Parser context */
  103045. TriggerStep *pStepList, /* The triggered program */
  103046. Token *pAll /* Token that describes the complete CREATE TRIGGER */
  103047. ){
  103048. Trigger *pTrig = pParse->pNewTrigger; /* Trigger being finished */
  103049. char *zName; /* Name of trigger */
  103050. sqlite3 *db = pParse->db; /* The database */
  103051. DbFixer sFix; /* Fixer object */
  103052. int iDb; /* Database containing the trigger */
  103053. Token nameToken; /* Trigger name for error reporting */
  103054. pParse->pNewTrigger = 0;
  103055. if( NEVER(pParse->nErr) || !pTrig ) goto triggerfinish_cleanup;
  103056. zName = pTrig->zName;
  103057. iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
  103058. pTrig->step_list = pStepList;
  103059. while( pStepList ){
  103060. pStepList->pTrig = pTrig;
  103061. pStepList = pStepList->pNext;
  103062. }
  103063. nameToken.z = pTrig->zName;
  103064. nameToken.n = sqlite3Strlen30(nameToken.z);
  103065. sqlite3FixInit(&sFix, pParse, iDb, "trigger", &nameToken);
  103066. if( sqlite3FixTriggerStep(&sFix, pTrig->step_list)
  103067. || sqlite3FixExpr(&sFix, pTrig->pWhen)
  103068. ){
  103069. goto triggerfinish_cleanup;
  103070. }
  103071. /* if we are not initializing,
  103072. ** build the sqlite_master entry
  103073. */
  103074. if( !db->init.busy ){
  103075. Vdbe *v;
  103076. char *z;
  103077. /* Make an entry in the sqlite_master table */
  103078. v = sqlite3GetVdbe(pParse);
  103079. if( v==0 ) goto triggerfinish_cleanup;
  103080. sqlite3BeginWriteOperation(pParse, 0, iDb);
  103081. z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
  103082. sqlite3NestedParse(pParse,
  103083. "INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
  103084. db->aDb[iDb].zName, SCHEMA_TABLE(iDb), zName,
  103085. pTrig->table, z);
  103086. sqlite3DbFree(db, z);
  103087. sqlite3ChangeCookie(pParse, iDb);
  103088. sqlite3VdbeAddParseSchemaOp(v, iDb,
  103089. sqlite3MPrintf(db, "type='trigger' AND name='%q'", zName));
  103090. }
  103091. if( db->init.busy ){
  103092. Trigger *pLink = pTrig;
  103093. Hash *pHash = &db->aDb[iDb].pSchema->trigHash;
  103094. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103095. pTrig = sqlite3HashInsert(pHash, zName, pTrig);
  103096. if( pTrig ){
  103097. db->mallocFailed = 1;
  103098. }else if( pLink->pSchema==pLink->pTabSchema ){
  103099. Table *pTab;
  103100. pTab = sqlite3HashFind(&pLink->pTabSchema->tblHash, pLink->table);
  103101. assert( pTab!=0 );
  103102. pLink->pNext = pTab->pTrigger;
  103103. pTab->pTrigger = pLink;
  103104. }
  103105. }
  103106. triggerfinish_cleanup:
  103107. sqlite3DeleteTrigger(db, pTrig);
  103108. assert( !pParse->pNewTrigger );
  103109. sqlite3DeleteTriggerStep(db, pStepList);
  103110. }
  103111. /*
  103112. ** Turn a SELECT statement (that the pSelect parameter points to) into
  103113. ** a trigger step. Return a pointer to a TriggerStep structure.
  103114. **
  103115. ** The parser calls this routine when it finds a SELECT statement in
  103116. ** body of a TRIGGER.
  103117. */
  103118. SQLITE_PRIVATE TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
  103119. TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
  103120. if( pTriggerStep==0 ) {
  103121. sqlite3SelectDelete(db, pSelect);
  103122. return 0;
  103123. }
  103124. pTriggerStep->op = TK_SELECT;
  103125. pTriggerStep->pSelect = pSelect;
  103126. pTriggerStep->orconf = OE_Default;
  103127. return pTriggerStep;
  103128. }
  103129. /*
  103130. ** Allocate space to hold a new trigger step. The allocated space
  103131. ** holds both the TriggerStep object and the TriggerStep.target.z string.
  103132. **
  103133. ** If an OOM error occurs, NULL is returned and db->mallocFailed is set.
  103134. */
  103135. static TriggerStep *triggerStepAllocate(
  103136. sqlite3 *db, /* Database connection */
  103137. u8 op, /* Trigger opcode */
  103138. Token *pName /* The target name */
  103139. ){
  103140. TriggerStep *pTriggerStep;
  103141. pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep) + pName->n);
  103142. if( pTriggerStep ){
  103143. char *z = (char*)&pTriggerStep[1];
  103144. memcpy(z, pName->z, pName->n);
  103145. pTriggerStep->target.z = z;
  103146. pTriggerStep->target.n = pName->n;
  103147. pTriggerStep->op = op;
  103148. }
  103149. return pTriggerStep;
  103150. }
  103151. /*
  103152. ** Build a trigger step out of an INSERT statement. Return a pointer
  103153. ** to the new trigger step.
  103154. **
  103155. ** The parser calls this routine when it sees an INSERT inside the
  103156. ** body of a trigger.
  103157. */
  103158. SQLITE_PRIVATE TriggerStep *sqlite3TriggerInsertStep(
  103159. sqlite3 *db, /* The database connection */
  103160. Token *pTableName, /* Name of the table into which we insert */
  103161. IdList *pColumn, /* List of columns in pTableName to insert into */
  103162. Select *pSelect, /* A SELECT statement that supplies values */
  103163. u8 orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
  103164. ){
  103165. TriggerStep *pTriggerStep;
  103166. assert(pSelect != 0 || db->mallocFailed);
  103167. pTriggerStep = triggerStepAllocate(db, TK_INSERT, pTableName);
  103168. if( pTriggerStep ){
  103169. pTriggerStep->pSelect = sqlite3SelectDup(db, pSelect, EXPRDUP_REDUCE);
  103170. pTriggerStep->pIdList = pColumn;
  103171. pTriggerStep->orconf = orconf;
  103172. }else{
  103173. sqlite3IdListDelete(db, pColumn);
  103174. }
  103175. sqlite3SelectDelete(db, pSelect);
  103176. return pTriggerStep;
  103177. }
  103178. /*
  103179. ** Construct a trigger step that implements an UPDATE statement and return
  103180. ** a pointer to that trigger step. The parser calls this routine when it
  103181. ** sees an UPDATE statement inside the body of a CREATE TRIGGER.
  103182. */
  103183. SQLITE_PRIVATE TriggerStep *sqlite3TriggerUpdateStep(
  103184. sqlite3 *db, /* The database connection */
  103185. Token *pTableName, /* Name of the table to be updated */
  103186. ExprList *pEList, /* The SET clause: list of column and new values */
  103187. Expr *pWhere, /* The WHERE clause */
  103188. u8 orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
  103189. ){
  103190. TriggerStep *pTriggerStep;
  103191. pTriggerStep = triggerStepAllocate(db, TK_UPDATE, pTableName);
  103192. if( pTriggerStep ){
  103193. pTriggerStep->pExprList = sqlite3ExprListDup(db, pEList, EXPRDUP_REDUCE);
  103194. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  103195. pTriggerStep->orconf = orconf;
  103196. }
  103197. sqlite3ExprListDelete(db, pEList);
  103198. sqlite3ExprDelete(db, pWhere);
  103199. return pTriggerStep;
  103200. }
  103201. /*
  103202. ** Construct a trigger step that implements a DELETE statement and return
  103203. ** a pointer to that trigger step. The parser calls this routine when it
  103204. ** sees a DELETE statement inside the body of a CREATE TRIGGER.
  103205. */
  103206. SQLITE_PRIVATE TriggerStep *sqlite3TriggerDeleteStep(
  103207. sqlite3 *db, /* Database connection */
  103208. Token *pTableName, /* The table from which rows are deleted */
  103209. Expr *pWhere /* The WHERE clause */
  103210. ){
  103211. TriggerStep *pTriggerStep;
  103212. pTriggerStep = triggerStepAllocate(db, TK_DELETE, pTableName);
  103213. if( pTriggerStep ){
  103214. pTriggerStep->pWhere = sqlite3ExprDup(db, pWhere, EXPRDUP_REDUCE);
  103215. pTriggerStep->orconf = OE_Default;
  103216. }
  103217. sqlite3ExprDelete(db, pWhere);
  103218. return pTriggerStep;
  103219. }
  103220. /*
  103221. ** Recursively delete a Trigger structure
  103222. */
  103223. SQLITE_PRIVATE void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
  103224. if( pTrigger==0 ) return;
  103225. sqlite3DeleteTriggerStep(db, pTrigger->step_list);
  103226. sqlite3DbFree(db, pTrigger->zName);
  103227. sqlite3DbFree(db, pTrigger->table);
  103228. sqlite3ExprDelete(db, pTrigger->pWhen);
  103229. sqlite3IdListDelete(db, pTrigger->pColumns);
  103230. sqlite3DbFree(db, pTrigger);
  103231. }
  103232. /*
  103233. ** This function is called to drop a trigger from the database schema.
  103234. **
  103235. ** This may be called directly from the parser and therefore identifies
  103236. ** the trigger by name. The sqlite3DropTriggerPtr() routine does the
  103237. ** same job as this routine except it takes a pointer to the trigger
  103238. ** instead of the trigger name.
  103239. **/
  103240. SQLITE_PRIVATE void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
  103241. Trigger *pTrigger = 0;
  103242. int i;
  103243. const char *zDb;
  103244. const char *zName;
  103245. sqlite3 *db = pParse->db;
  103246. if( db->mallocFailed ) goto drop_trigger_cleanup;
  103247. if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
  103248. goto drop_trigger_cleanup;
  103249. }
  103250. assert( pName->nSrc==1 );
  103251. zDb = pName->a[0].zDatabase;
  103252. zName = pName->a[0].zName;
  103253. assert( zDb!=0 || sqlite3BtreeHoldsAllMutexes(db) );
  103254. for(i=OMIT_TEMPDB; i<db->nDb; i++){
  103255. int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
  103256. if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
  103257. assert( sqlite3SchemaMutexHeld(db, j, 0) );
  103258. pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName);
  103259. if( pTrigger ) break;
  103260. }
  103261. if( !pTrigger ){
  103262. if( !noErr ){
  103263. sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
  103264. }else{
  103265. sqlite3CodeVerifyNamedSchema(pParse, zDb);
  103266. }
  103267. pParse->checkSchema = 1;
  103268. goto drop_trigger_cleanup;
  103269. }
  103270. sqlite3DropTriggerPtr(pParse, pTrigger);
  103271. drop_trigger_cleanup:
  103272. sqlite3SrcListDelete(db, pName);
  103273. }
  103274. /*
  103275. ** Return a pointer to the Table structure for the table that a trigger
  103276. ** is set on.
  103277. */
  103278. static Table *tableOfTrigger(Trigger *pTrigger){
  103279. return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table);
  103280. }
  103281. /*
  103282. ** Drop a trigger given a pointer to that trigger.
  103283. */
  103284. SQLITE_PRIVATE void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
  103285. Table *pTable;
  103286. Vdbe *v;
  103287. sqlite3 *db = pParse->db;
  103288. int iDb;
  103289. iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
  103290. assert( iDb>=0 && iDb<db->nDb );
  103291. pTable = tableOfTrigger(pTrigger);
  103292. assert( pTable );
  103293. assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
  103294. #ifndef SQLITE_OMIT_AUTHORIZATION
  103295. {
  103296. int code = SQLITE_DROP_TRIGGER;
  103297. const char *zDb = db->aDb[iDb].zName;
  103298. const char *zTab = SCHEMA_TABLE(iDb);
  103299. if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
  103300. if( sqlite3AuthCheck(pParse, code, pTrigger->zName, pTable->zName, zDb) ||
  103301. sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
  103302. return;
  103303. }
  103304. }
  103305. #endif
  103306. /* Generate code to destroy the database record of the trigger.
  103307. */
  103308. assert( pTable!=0 );
  103309. if( (v = sqlite3GetVdbe(pParse))!=0 ){
  103310. int base;
  103311. static const int iLn = VDBE_OFFSET_LINENO(2);
  103312. static const VdbeOpList dropTrigger[] = {
  103313. { OP_Rewind, 0, ADDR(9), 0},
  103314. { OP_String8, 0, 1, 0}, /* 1 */
  103315. { OP_Column, 0, 1, 2},
  103316. { OP_Ne, 2, ADDR(8), 1},
  103317. { OP_String8, 0, 1, 0}, /* 4: "trigger" */
  103318. { OP_Column, 0, 0, 2},
  103319. { OP_Ne, 2, ADDR(8), 1},
  103320. { OP_Delete, 0, 0, 0},
  103321. { OP_Next, 0, ADDR(1), 0}, /* 8 */
  103322. };
  103323. sqlite3BeginWriteOperation(pParse, 0, iDb);
  103324. sqlite3OpenMasterTable(pParse, iDb);
  103325. base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger, iLn);
  103326. sqlite3VdbeChangeP4(v, base+1, pTrigger->zName, P4_TRANSIENT);
  103327. sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
  103328. sqlite3ChangeCookie(pParse, iDb);
  103329. sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
  103330. sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->zName, 0);
  103331. if( pParse->nMem<3 ){
  103332. pParse->nMem = 3;
  103333. }
  103334. }
  103335. }
  103336. /*
  103337. ** Remove a trigger from the hash tables of the sqlite* pointer.
  103338. */
  103339. SQLITE_PRIVATE void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
  103340. Trigger *pTrigger;
  103341. Hash *pHash;
  103342. assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
  103343. pHash = &(db->aDb[iDb].pSchema->trigHash);
  103344. pTrigger = sqlite3HashInsert(pHash, zName, 0);
  103345. if( ALWAYS(pTrigger) ){
  103346. if( pTrigger->pSchema==pTrigger->pTabSchema ){
  103347. Table *pTab = tableOfTrigger(pTrigger);
  103348. Trigger **pp;
  103349. for(pp=&pTab->pTrigger; *pp!=pTrigger; pp=&((*pp)->pNext));
  103350. *pp = (*pp)->pNext;
  103351. }
  103352. sqlite3DeleteTrigger(db, pTrigger);
  103353. db->flags |= SQLITE_InternChanges;
  103354. }
  103355. }
  103356. /*
  103357. ** pEList is the SET clause of an UPDATE statement. Each entry
  103358. ** in pEList is of the format <id>=<expr>. If any of the entries
  103359. ** in pEList have an <id> which matches an identifier in pIdList,
  103360. ** then return TRUE. If pIdList==NULL, then it is considered a
  103361. ** wildcard that matches anything. Likewise if pEList==NULL then
  103362. ** it matches anything so always return true. Return false only
  103363. ** if there is no match.
  103364. */
  103365. static int checkColumnOverlap(IdList *pIdList, ExprList *pEList){
  103366. int e;
  103367. if( pIdList==0 || NEVER(pEList==0) ) return 1;
  103368. for(e=0; e<pEList->nExpr; e++){
  103369. if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
  103370. }
  103371. return 0;
  103372. }
  103373. /*
  103374. ** Return a list of all triggers on table pTab if there exists at least
  103375. ** one trigger that must be fired when an operation of type 'op' is
  103376. ** performed on the table, and, if that operation is an UPDATE, if at
  103377. ** least one of the columns in pChanges is being modified.
  103378. */
  103379. SQLITE_PRIVATE Trigger *sqlite3TriggersExist(
  103380. Parse *pParse, /* Parse context */
  103381. Table *pTab, /* The table the contains the triggers */
  103382. int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
  103383. ExprList *pChanges, /* Columns that change in an UPDATE statement */
  103384. int *pMask /* OUT: Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  103385. ){
  103386. int mask = 0;
  103387. Trigger *pList = 0;
  103388. Trigger *p;
  103389. if( (pParse->db->flags & SQLITE_EnableTrigger)!=0 ){
  103390. pList = sqlite3TriggerList(pParse, pTab);
  103391. }
  103392. assert( pList==0 || IsVirtual(pTab)==0 );
  103393. for(p=pList; p; p=p->pNext){
  103394. if( p->op==op && checkColumnOverlap(p->pColumns, pChanges) ){
  103395. mask |= p->tr_tm;
  103396. }
  103397. }
  103398. if( pMask ){
  103399. *pMask = mask;
  103400. }
  103401. return (mask ? pList : 0);
  103402. }
  103403. /*
  103404. ** Convert the pStep->target token into a SrcList and return a pointer
  103405. ** to that SrcList.
  103406. **
  103407. ** This routine adds a specific database name, if needed, to the target when
  103408. ** forming the SrcList. This prevents a trigger in one database from
  103409. ** referring to a target in another database. An exception is when the
  103410. ** trigger is in TEMP in which case it can refer to any other database it
  103411. ** wants.
  103412. */
  103413. static SrcList *targetSrcList(
  103414. Parse *pParse, /* The parsing context */
  103415. TriggerStep *pStep /* The trigger containing the target token */
  103416. ){
  103417. int iDb; /* Index of the database to use */
  103418. SrcList *pSrc; /* SrcList to be returned */
  103419. pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
  103420. if( pSrc ){
  103421. assert( pSrc->nSrc>0 );
  103422. assert( pSrc->a!=0 );
  103423. iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
  103424. if( iDb==0 || iDb>=2 ){
  103425. sqlite3 *db = pParse->db;
  103426. assert( iDb<pParse->db->nDb );
  103427. pSrc->a[pSrc->nSrc-1].zDatabase = sqlite3DbStrDup(db, db->aDb[iDb].zName);
  103428. }
  103429. }
  103430. return pSrc;
  103431. }
  103432. /*
  103433. ** Generate VDBE code for the statements inside the body of a single
  103434. ** trigger.
  103435. */
  103436. static int codeTriggerProgram(
  103437. Parse *pParse, /* The parser context */
  103438. TriggerStep *pStepList, /* List of statements inside the trigger body */
  103439. int orconf /* Conflict algorithm. (OE_Abort, etc) */
  103440. ){
  103441. TriggerStep *pStep;
  103442. Vdbe *v = pParse->pVdbe;
  103443. sqlite3 *db = pParse->db;
  103444. assert( pParse->pTriggerTab && pParse->pToplevel );
  103445. assert( pStepList );
  103446. assert( v!=0 );
  103447. for(pStep=pStepList; pStep; pStep=pStep->pNext){
  103448. /* Figure out the ON CONFLICT policy that will be used for this step
  103449. ** of the trigger program. If the statement that caused this trigger
  103450. ** to fire had an explicit ON CONFLICT, then use it. Otherwise, use
  103451. ** the ON CONFLICT policy that was specified as part of the trigger
  103452. ** step statement. Example:
  103453. **
  103454. ** CREATE TRIGGER AFTER INSERT ON t1 BEGIN;
  103455. ** INSERT OR REPLACE INTO t2 VALUES(new.a, new.b);
  103456. ** END;
  103457. **
  103458. ** INSERT INTO t1 ... ; -- insert into t2 uses REPLACE policy
  103459. ** INSERT OR IGNORE INTO t1 ... ; -- insert into t2 uses IGNORE policy
  103460. */
  103461. pParse->eOrconf = (orconf==OE_Default)?pStep->orconf:(u8)orconf;
  103462. assert( pParse->okConstFactor==0 );
  103463. switch( pStep->op ){
  103464. case TK_UPDATE: {
  103465. sqlite3Update(pParse,
  103466. targetSrcList(pParse, pStep),
  103467. sqlite3ExprListDup(db, pStep->pExprList, 0),
  103468. sqlite3ExprDup(db, pStep->pWhere, 0),
  103469. pParse->eOrconf
  103470. );
  103471. break;
  103472. }
  103473. case TK_INSERT: {
  103474. sqlite3Insert(pParse,
  103475. targetSrcList(pParse, pStep),
  103476. sqlite3SelectDup(db, pStep->pSelect, 0),
  103477. sqlite3IdListDup(db, pStep->pIdList),
  103478. pParse->eOrconf
  103479. );
  103480. break;
  103481. }
  103482. case TK_DELETE: {
  103483. sqlite3DeleteFrom(pParse,
  103484. targetSrcList(pParse, pStep),
  103485. sqlite3ExprDup(db, pStep->pWhere, 0)
  103486. );
  103487. break;
  103488. }
  103489. default: assert( pStep->op==TK_SELECT ); {
  103490. SelectDest sDest;
  103491. Select *pSelect = sqlite3SelectDup(db, pStep->pSelect, 0);
  103492. sqlite3SelectDestInit(&sDest, SRT_Discard, 0);
  103493. sqlite3Select(pParse, pSelect, &sDest);
  103494. sqlite3SelectDelete(db, pSelect);
  103495. break;
  103496. }
  103497. }
  103498. if( pStep->op!=TK_SELECT ){
  103499. sqlite3VdbeAddOp0(v, OP_ResetCount);
  103500. }
  103501. }
  103502. return 0;
  103503. }
  103504. #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
  103505. /*
  103506. ** This function is used to add VdbeComment() annotations to a VDBE
  103507. ** program. It is not used in production code, only for debugging.
  103508. */
  103509. static const char *onErrorText(int onError){
  103510. switch( onError ){
  103511. case OE_Abort: return "abort";
  103512. case OE_Rollback: return "rollback";
  103513. case OE_Fail: return "fail";
  103514. case OE_Replace: return "replace";
  103515. case OE_Ignore: return "ignore";
  103516. case OE_Default: return "default";
  103517. }
  103518. return "n/a";
  103519. }
  103520. #endif
  103521. /*
  103522. ** Parse context structure pFrom has just been used to create a sub-vdbe
  103523. ** (trigger program). If an error has occurred, transfer error information
  103524. ** from pFrom to pTo.
  103525. */
  103526. static void transferParseError(Parse *pTo, Parse *pFrom){
  103527. assert( pFrom->zErrMsg==0 || pFrom->nErr );
  103528. assert( pTo->zErrMsg==0 || pTo->nErr );
  103529. if( pTo->nErr==0 ){
  103530. pTo->zErrMsg = pFrom->zErrMsg;
  103531. pTo->nErr = pFrom->nErr;
  103532. }else{
  103533. sqlite3DbFree(pFrom->db, pFrom->zErrMsg);
  103534. }
  103535. }
  103536. /*
  103537. ** Create and populate a new TriggerPrg object with a sub-program
  103538. ** implementing trigger pTrigger with ON CONFLICT policy orconf.
  103539. */
  103540. static TriggerPrg *codeRowTrigger(
  103541. Parse *pParse, /* Current parse context */
  103542. Trigger *pTrigger, /* Trigger to code */
  103543. Table *pTab, /* The table pTrigger is attached to */
  103544. int orconf /* ON CONFLICT policy to code trigger program with */
  103545. ){
  103546. Parse *pTop = sqlite3ParseToplevel(pParse);
  103547. sqlite3 *db = pParse->db; /* Database handle */
  103548. TriggerPrg *pPrg; /* Value to return */
  103549. Expr *pWhen = 0; /* Duplicate of trigger WHEN expression */
  103550. Vdbe *v; /* Temporary VM */
  103551. NameContext sNC; /* Name context for sub-vdbe */
  103552. SubProgram *pProgram = 0; /* Sub-vdbe for trigger program */
  103553. Parse *pSubParse; /* Parse context for sub-vdbe */
  103554. int iEndTrigger = 0; /* Label to jump to if WHEN is false */
  103555. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  103556. assert( pTop->pVdbe );
  103557. /* Allocate the TriggerPrg and SubProgram objects. To ensure that they
  103558. ** are freed if an error occurs, link them into the Parse.pTriggerPrg
  103559. ** list of the top-level Parse object sooner rather than later. */
  103560. pPrg = sqlite3DbMallocZero(db, sizeof(TriggerPrg));
  103561. if( !pPrg ) return 0;
  103562. pPrg->pNext = pTop->pTriggerPrg;
  103563. pTop->pTriggerPrg = pPrg;
  103564. pPrg->pProgram = pProgram = sqlite3DbMallocZero(db, sizeof(SubProgram));
  103565. if( !pProgram ) return 0;
  103566. sqlite3VdbeLinkSubProgram(pTop->pVdbe, pProgram);
  103567. pPrg->pTrigger = pTrigger;
  103568. pPrg->orconf = orconf;
  103569. pPrg->aColmask[0] = 0xffffffff;
  103570. pPrg->aColmask[1] = 0xffffffff;
  103571. /* Allocate and populate a new Parse context to use for coding the
  103572. ** trigger sub-program. */
  103573. pSubParse = sqlite3StackAllocZero(db, sizeof(Parse));
  103574. if( !pSubParse ) return 0;
  103575. memset(&sNC, 0, sizeof(sNC));
  103576. sNC.pParse = pSubParse;
  103577. pSubParse->db = db;
  103578. pSubParse->pTriggerTab = pTab;
  103579. pSubParse->pToplevel = pTop;
  103580. pSubParse->zAuthContext = pTrigger->zName;
  103581. pSubParse->eTriggerOp = pTrigger->op;
  103582. pSubParse->nQueryLoop = pParse->nQueryLoop;
  103583. v = sqlite3GetVdbe(pSubParse);
  103584. if( v ){
  103585. VdbeComment((v, "Start: %s.%s (%s %s%s%s ON %s)",
  103586. pTrigger->zName, onErrorText(orconf),
  103587. (pTrigger->tr_tm==TRIGGER_BEFORE ? "BEFORE" : "AFTER"),
  103588. (pTrigger->op==TK_UPDATE ? "UPDATE" : ""),
  103589. (pTrigger->op==TK_INSERT ? "INSERT" : ""),
  103590. (pTrigger->op==TK_DELETE ? "DELETE" : ""),
  103591. pTab->zName
  103592. ));
  103593. #ifndef SQLITE_OMIT_TRACE
  103594. sqlite3VdbeChangeP4(v, -1,
  103595. sqlite3MPrintf(db, "-- TRIGGER %s", pTrigger->zName), P4_DYNAMIC
  103596. );
  103597. #endif
  103598. /* If one was specified, code the WHEN clause. If it evaluates to false
  103599. ** (or NULL) the sub-vdbe is immediately halted by jumping to the
  103600. ** OP_Halt inserted at the end of the program. */
  103601. if( pTrigger->pWhen ){
  103602. pWhen = sqlite3ExprDup(db, pTrigger->pWhen, 0);
  103603. if( SQLITE_OK==sqlite3ResolveExprNames(&sNC, pWhen)
  103604. && db->mallocFailed==0
  103605. ){
  103606. iEndTrigger = sqlite3VdbeMakeLabel(v);
  103607. sqlite3ExprIfFalse(pSubParse, pWhen, iEndTrigger, SQLITE_JUMPIFNULL);
  103608. }
  103609. sqlite3ExprDelete(db, pWhen);
  103610. }
  103611. /* Code the trigger program into the sub-vdbe. */
  103612. codeTriggerProgram(pSubParse, pTrigger->step_list, orconf);
  103613. /* Insert an OP_Halt at the end of the sub-program. */
  103614. if( iEndTrigger ){
  103615. sqlite3VdbeResolveLabel(v, iEndTrigger);
  103616. }
  103617. sqlite3VdbeAddOp0(v, OP_Halt);
  103618. VdbeComment((v, "End: %s.%s", pTrigger->zName, onErrorText(orconf)));
  103619. transferParseError(pParse, pSubParse);
  103620. if( db->mallocFailed==0 ){
  103621. pProgram->aOp = sqlite3VdbeTakeOpArray(v, &pProgram->nOp, &pTop->nMaxArg);
  103622. }
  103623. pProgram->nMem = pSubParse->nMem;
  103624. pProgram->nCsr = pSubParse->nTab;
  103625. pProgram->nOnce = pSubParse->nOnce;
  103626. pProgram->token = (void *)pTrigger;
  103627. pPrg->aColmask[0] = pSubParse->oldmask;
  103628. pPrg->aColmask[1] = pSubParse->newmask;
  103629. sqlite3VdbeDelete(v);
  103630. }
  103631. assert( !pSubParse->pAinc && !pSubParse->pZombieTab );
  103632. assert( !pSubParse->pTriggerPrg && !pSubParse->nMaxArg );
  103633. sqlite3ParserReset(pSubParse);
  103634. sqlite3StackFree(db, pSubParse);
  103635. return pPrg;
  103636. }
  103637. /*
  103638. ** Return a pointer to a TriggerPrg object containing the sub-program for
  103639. ** trigger pTrigger with default ON CONFLICT algorithm orconf. If no such
  103640. ** TriggerPrg object exists, a new object is allocated and populated before
  103641. ** being returned.
  103642. */
  103643. static TriggerPrg *getRowTrigger(
  103644. Parse *pParse, /* Current parse context */
  103645. Trigger *pTrigger, /* Trigger to code */
  103646. Table *pTab, /* The table trigger pTrigger is attached to */
  103647. int orconf /* ON CONFLICT algorithm. */
  103648. ){
  103649. Parse *pRoot = sqlite3ParseToplevel(pParse);
  103650. TriggerPrg *pPrg;
  103651. assert( pTrigger->zName==0 || pTab==tableOfTrigger(pTrigger) );
  103652. /* It may be that this trigger has already been coded (or is in the
  103653. ** process of being coded). If this is the case, then an entry with
  103654. ** a matching TriggerPrg.pTrigger field will be present somewhere
  103655. ** in the Parse.pTriggerPrg list. Search for such an entry. */
  103656. for(pPrg=pRoot->pTriggerPrg;
  103657. pPrg && (pPrg->pTrigger!=pTrigger || pPrg->orconf!=orconf);
  103658. pPrg=pPrg->pNext
  103659. );
  103660. /* If an existing TriggerPrg could not be located, create a new one. */
  103661. if( !pPrg ){
  103662. pPrg = codeRowTrigger(pParse, pTrigger, pTab, orconf);
  103663. }
  103664. return pPrg;
  103665. }
  103666. /*
  103667. ** Generate code for the trigger program associated with trigger p on
  103668. ** table pTab. The reg, orconf and ignoreJump parameters passed to this
  103669. ** function are the same as those described in the header function for
  103670. ** sqlite3CodeRowTrigger()
  103671. */
  103672. SQLITE_PRIVATE void sqlite3CodeRowTriggerDirect(
  103673. Parse *pParse, /* Parse context */
  103674. Trigger *p, /* Trigger to code */
  103675. Table *pTab, /* The table to code triggers from */
  103676. int reg, /* Reg array containing OLD.* and NEW.* values */
  103677. int orconf, /* ON CONFLICT policy */
  103678. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  103679. ){
  103680. Vdbe *v = sqlite3GetVdbe(pParse); /* Main VM */
  103681. TriggerPrg *pPrg;
  103682. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  103683. assert( pPrg || pParse->nErr || pParse->db->mallocFailed );
  103684. /* Code the OP_Program opcode in the parent VDBE. P4 of the OP_Program
  103685. ** is a pointer to the sub-vdbe containing the trigger program. */
  103686. if( pPrg ){
  103687. int bRecursive = (p->zName && 0==(pParse->db->flags&SQLITE_RecTriggers));
  103688. sqlite3VdbeAddOp3(v, OP_Program, reg, ignoreJump, ++pParse->nMem);
  103689. sqlite3VdbeChangeP4(v, -1, (const char *)pPrg->pProgram, P4_SUBPROGRAM);
  103690. VdbeComment(
  103691. (v, "Call: %s.%s", (p->zName?p->zName:"fkey"), onErrorText(orconf)));
  103692. /* Set the P5 operand of the OP_Program instruction to non-zero if
  103693. ** recursive invocation of this trigger program is disallowed. Recursive
  103694. ** invocation is disallowed if (a) the sub-program is really a trigger,
  103695. ** not a foreign key action, and (b) the flag to enable recursive triggers
  103696. ** is clear. */
  103697. sqlite3VdbeChangeP5(v, (u8)bRecursive);
  103698. }
  103699. }
  103700. /*
  103701. ** This is called to code the required FOR EACH ROW triggers for an operation
  103702. ** on table pTab. The operation to code triggers for (INSERT, UPDATE or DELETE)
  103703. ** is given by the op parameter. The tr_tm parameter determines whether the
  103704. ** BEFORE or AFTER triggers are coded. If the operation is an UPDATE, then
  103705. ** parameter pChanges is passed the list of columns being modified.
  103706. **
  103707. ** If there are no triggers that fire at the specified time for the specified
  103708. ** operation on pTab, this function is a no-op.
  103709. **
  103710. ** The reg argument is the address of the first in an array of registers
  103711. ** that contain the values substituted for the new.* and old.* references
  103712. ** in the trigger program. If N is the number of columns in table pTab
  103713. ** (a copy of pTab->nCol), then registers are populated as follows:
  103714. **
  103715. ** Register Contains
  103716. ** ------------------------------------------------------
  103717. ** reg+0 OLD.rowid
  103718. ** reg+1 OLD.* value of left-most column of pTab
  103719. ** ... ...
  103720. ** reg+N OLD.* value of right-most column of pTab
  103721. ** reg+N+1 NEW.rowid
  103722. ** reg+N+2 OLD.* value of left-most column of pTab
  103723. ** ... ...
  103724. ** reg+N+N+1 NEW.* value of right-most column of pTab
  103725. **
  103726. ** For ON DELETE triggers, the registers containing the NEW.* values will
  103727. ** never be accessed by the trigger program, so they are not allocated or
  103728. ** populated by the caller (there is no data to populate them with anyway).
  103729. ** Similarly, for ON INSERT triggers the values stored in the OLD.* registers
  103730. ** are never accessed, and so are not allocated by the caller. So, for an
  103731. ** ON INSERT trigger, the value passed to this function as parameter reg
  103732. ** is not a readable register, although registers (reg+N) through
  103733. ** (reg+N+N+1) are.
  103734. **
  103735. ** Parameter orconf is the default conflict resolution algorithm for the
  103736. ** trigger program to use (REPLACE, IGNORE etc.). Parameter ignoreJump
  103737. ** is the instruction that control should jump to if a trigger program
  103738. ** raises an IGNORE exception.
  103739. */
  103740. SQLITE_PRIVATE void sqlite3CodeRowTrigger(
  103741. Parse *pParse, /* Parse context */
  103742. Trigger *pTrigger, /* List of triggers on table pTab */
  103743. int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
  103744. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  103745. int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
  103746. Table *pTab, /* The table to code triggers from */
  103747. int reg, /* The first in an array of registers (see above) */
  103748. int orconf, /* ON CONFLICT policy */
  103749. int ignoreJump /* Instruction to jump to for RAISE(IGNORE) */
  103750. ){
  103751. Trigger *p; /* Used to iterate through pTrigger list */
  103752. assert( op==TK_UPDATE || op==TK_INSERT || op==TK_DELETE );
  103753. assert( tr_tm==TRIGGER_BEFORE || tr_tm==TRIGGER_AFTER );
  103754. assert( (op==TK_UPDATE)==(pChanges!=0) );
  103755. for(p=pTrigger; p; p=p->pNext){
  103756. /* Sanity checking: The schema for the trigger and for the table are
  103757. ** always defined. The trigger must be in the same schema as the table
  103758. ** or else it must be a TEMP trigger. */
  103759. assert( p->pSchema!=0 );
  103760. assert( p->pTabSchema!=0 );
  103761. assert( p->pSchema==p->pTabSchema
  103762. || p->pSchema==pParse->db->aDb[1].pSchema );
  103763. /* Determine whether we should code this trigger */
  103764. if( p->op==op
  103765. && p->tr_tm==tr_tm
  103766. && checkColumnOverlap(p->pColumns, pChanges)
  103767. ){
  103768. sqlite3CodeRowTriggerDirect(pParse, p, pTab, reg, orconf, ignoreJump);
  103769. }
  103770. }
  103771. }
  103772. /*
  103773. ** Triggers may access values stored in the old.* or new.* pseudo-table.
  103774. ** This function returns a 32-bit bitmask indicating which columns of the
  103775. ** old.* or new.* tables actually are used by triggers. This information
  103776. ** may be used by the caller, for example, to avoid having to load the entire
  103777. ** old.* record into memory when executing an UPDATE or DELETE command.
  103778. **
  103779. ** Bit 0 of the returned mask is set if the left-most column of the
  103780. ** table may be accessed using an [old|new].<col> reference. Bit 1 is set if
  103781. ** the second leftmost column value is required, and so on. If there
  103782. ** are more than 32 columns in the table, and at least one of the columns
  103783. ** with an index greater than 32 may be accessed, 0xffffffff is returned.
  103784. **
  103785. ** It is not possible to determine if the old.rowid or new.rowid column is
  103786. ** accessed by triggers. The caller must always assume that it is.
  103787. **
  103788. ** Parameter isNew must be either 1 or 0. If it is 0, then the mask returned
  103789. ** applies to the old.* table. If 1, the new.* table.
  103790. **
  103791. ** Parameter tr_tm must be a mask with one or both of the TRIGGER_BEFORE
  103792. ** and TRIGGER_AFTER bits set. Values accessed by BEFORE triggers are only
  103793. ** included in the returned mask if the TRIGGER_BEFORE bit is set in the
  103794. ** tr_tm parameter. Similarly, values accessed by AFTER triggers are only
  103795. ** included in the returned mask if the TRIGGER_AFTER bit is set in tr_tm.
  103796. */
  103797. SQLITE_PRIVATE u32 sqlite3TriggerColmask(
  103798. Parse *pParse, /* Parse context */
  103799. Trigger *pTrigger, /* List of triggers on table pTab */
  103800. ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
  103801. int isNew, /* 1 for new.* ref mask, 0 for old.* ref mask */
  103802. int tr_tm, /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  103803. Table *pTab, /* The table to code triggers from */
  103804. int orconf /* Default ON CONFLICT policy for trigger steps */
  103805. ){
  103806. const int op = pChanges ? TK_UPDATE : TK_DELETE;
  103807. u32 mask = 0;
  103808. Trigger *p;
  103809. assert( isNew==1 || isNew==0 );
  103810. for(p=pTrigger; p; p=p->pNext){
  103811. if( p->op==op && (tr_tm&p->tr_tm)
  103812. && checkColumnOverlap(p->pColumns,pChanges)
  103813. ){
  103814. TriggerPrg *pPrg;
  103815. pPrg = getRowTrigger(pParse, p, pTab, orconf);
  103816. if( pPrg ){
  103817. mask |= pPrg->aColmask[isNew];
  103818. }
  103819. }
  103820. }
  103821. return mask;
  103822. }
  103823. #endif /* !defined(SQLITE_OMIT_TRIGGER) */
  103824. /************** End of trigger.c *********************************************/
  103825. /************** Begin file update.c ******************************************/
  103826. /*
  103827. ** 2001 September 15
  103828. **
  103829. ** The author disclaims copyright to this source code. In place of
  103830. ** a legal notice, here is a blessing:
  103831. **
  103832. ** May you do good and not evil.
  103833. ** May you find forgiveness for yourself and forgive others.
  103834. ** May you share freely, never taking more than you give.
  103835. **
  103836. *************************************************************************
  103837. ** This file contains C code routines that are called by the parser
  103838. ** to handle UPDATE statements.
  103839. */
  103840. #ifndef SQLITE_OMIT_VIRTUALTABLE
  103841. /* Forward declaration */
  103842. static void updateVirtualTable(
  103843. Parse *pParse, /* The parsing context */
  103844. SrcList *pSrc, /* The virtual table to be modified */
  103845. Table *pTab, /* The virtual table */
  103846. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  103847. Expr *pRowidExpr, /* Expression used to recompute the rowid */
  103848. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  103849. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  103850. int onError /* ON CONFLICT strategy */
  103851. );
  103852. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  103853. /*
  103854. ** The most recently coded instruction was an OP_Column to retrieve the
  103855. ** i-th column of table pTab. This routine sets the P4 parameter of the
  103856. ** OP_Column to the default value, if any.
  103857. **
  103858. ** The default value of a column is specified by a DEFAULT clause in the
  103859. ** column definition. This was either supplied by the user when the table
  103860. ** was created, or added later to the table definition by an ALTER TABLE
  103861. ** command. If the latter, then the row-records in the table btree on disk
  103862. ** may not contain a value for the column and the default value, taken
  103863. ** from the P4 parameter of the OP_Column instruction, is returned instead.
  103864. ** If the former, then all row-records are guaranteed to include a value
  103865. ** for the column and the P4 value is not required.
  103866. **
  103867. ** Column definitions created by an ALTER TABLE command may only have
  103868. ** literal default values specified: a number, null or a string. (If a more
  103869. ** complicated default expression value was provided, it is evaluated
  103870. ** when the ALTER TABLE is executed and one of the literal values written
  103871. ** into the sqlite_master table.)
  103872. **
  103873. ** Therefore, the P4 parameter is only required if the default value for
  103874. ** the column is a literal number, string or null. The sqlite3ValueFromExpr()
  103875. ** function is capable of transforming these types of expressions into
  103876. ** sqlite3_value objects.
  103877. **
  103878. ** If parameter iReg is not negative, code an OP_RealAffinity instruction
  103879. ** on register iReg. This is used when an equivalent integer value is
  103880. ** stored in place of an 8-byte floating point value in order to save
  103881. ** space.
  103882. */
  103883. SQLITE_PRIVATE void sqlite3ColumnDefault(Vdbe *v, Table *pTab, int i, int iReg){
  103884. assert( pTab!=0 );
  103885. if( !pTab->pSelect ){
  103886. sqlite3_value *pValue = 0;
  103887. u8 enc = ENC(sqlite3VdbeDb(v));
  103888. Column *pCol = &pTab->aCol[i];
  103889. VdbeComment((v, "%s.%s", pTab->zName, pCol->zName));
  103890. assert( i<pTab->nCol );
  103891. sqlite3ValueFromExpr(sqlite3VdbeDb(v), pCol->pDflt, enc,
  103892. pCol->affinity, &pValue);
  103893. if( pValue ){
  103894. sqlite3VdbeChangeP4(v, -1, (const char *)pValue, P4_MEM);
  103895. }
  103896. #ifndef SQLITE_OMIT_FLOATING_POINT
  103897. if( pTab->aCol[i].affinity==SQLITE_AFF_REAL ){
  103898. sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
  103899. }
  103900. #endif
  103901. }
  103902. }
  103903. /*
  103904. ** Process an UPDATE statement.
  103905. **
  103906. ** UPDATE OR IGNORE table_wxyz SET a=b, c=d WHERE e<5 AND f NOT NULL;
  103907. ** \_______/ \________/ \______/ \________________/
  103908. * onError pTabList pChanges pWhere
  103909. */
  103910. SQLITE_PRIVATE void sqlite3Update(
  103911. Parse *pParse, /* The parser context */
  103912. SrcList *pTabList, /* The table in which we should change things */
  103913. ExprList *pChanges, /* Things to be changed */
  103914. Expr *pWhere, /* The WHERE clause. May be null */
  103915. int onError /* How to handle constraint errors */
  103916. ){
  103917. int i, j; /* Loop counters */
  103918. Table *pTab; /* The table to be updated */
  103919. int addrTop = 0; /* VDBE instruction address of the start of the loop */
  103920. WhereInfo *pWInfo; /* Information about the WHERE clause */
  103921. Vdbe *v; /* The virtual database engine */
  103922. Index *pIdx; /* For looping over indices */
  103923. Index *pPk; /* The PRIMARY KEY index for WITHOUT ROWID tables */
  103924. int nIdx; /* Number of indices that need updating */
  103925. int iBaseCur; /* Base cursor number */
  103926. int iDataCur; /* Cursor for the canonical data btree */
  103927. int iIdxCur; /* Cursor for the first index */
  103928. sqlite3 *db; /* The database structure */
  103929. int *aRegIdx = 0; /* One register assigned to each index to be updated */
  103930. int *aXRef = 0; /* aXRef[i] is the index in pChanges->a[] of the
  103931. ** an expression for the i-th column of the table.
  103932. ** aXRef[i]==-1 if the i-th column is not changed. */
  103933. u8 *aToOpen; /* 1 for tables and indices to be opened */
  103934. u8 chngPk; /* PRIMARY KEY changed in a WITHOUT ROWID table */
  103935. u8 chngRowid; /* Rowid changed in a normal table */
  103936. u8 chngKey; /* Either chngPk or chngRowid */
  103937. Expr *pRowidExpr = 0; /* Expression defining the new record number */
  103938. AuthContext sContext; /* The authorization context */
  103939. NameContext sNC; /* The name-context to resolve expressions in */
  103940. int iDb; /* Database containing the table being updated */
  103941. int okOnePass; /* True for one-pass algorithm without the FIFO */
  103942. int hasFK; /* True if foreign key processing is required */
  103943. int labelBreak; /* Jump here to break out of UPDATE loop */
  103944. int labelContinue; /* Jump here to continue next step of UPDATE loop */
  103945. #ifndef SQLITE_OMIT_TRIGGER
  103946. int isView; /* True when updating a view (INSTEAD OF trigger) */
  103947. Trigger *pTrigger; /* List of triggers on pTab, if required */
  103948. int tmask; /* Mask of TRIGGER_BEFORE|TRIGGER_AFTER */
  103949. #endif
  103950. int newmask; /* Mask of NEW.* columns accessed by BEFORE triggers */
  103951. int iEph = 0; /* Ephemeral table holding all primary key values */
  103952. int nKey = 0; /* Number of elements in regKey for WITHOUT ROWID */
  103953. int aiCurOnePass[2]; /* The write cursors opened by WHERE_ONEPASS */
  103954. /* Register Allocations */
  103955. int regRowCount = 0; /* A count of rows changed */
  103956. int regOldRowid; /* The old rowid */
  103957. int regNewRowid; /* The new rowid */
  103958. int regNew; /* Content of the NEW.* table in triggers */
  103959. int regOld = 0; /* Content of OLD.* table in triggers */
  103960. int regRowSet = 0; /* Rowset of rows to be updated */
  103961. int regKey = 0; /* composite PRIMARY KEY value */
  103962. memset(&sContext, 0, sizeof(sContext));
  103963. db = pParse->db;
  103964. if( pParse->nErr || db->mallocFailed ){
  103965. goto update_cleanup;
  103966. }
  103967. assert( pTabList->nSrc==1 );
  103968. /* Locate the table which we want to update.
  103969. */
  103970. pTab = sqlite3SrcListLookup(pParse, pTabList);
  103971. if( pTab==0 ) goto update_cleanup;
  103972. iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
  103973. /* Figure out if we have any triggers and if the table being
  103974. ** updated is a view.
  103975. */
  103976. #ifndef SQLITE_OMIT_TRIGGER
  103977. pTrigger = sqlite3TriggersExist(pParse, pTab, TK_UPDATE, pChanges, &tmask);
  103978. isView = pTab->pSelect!=0;
  103979. assert( pTrigger || tmask==0 );
  103980. #else
  103981. # define pTrigger 0
  103982. # define isView 0
  103983. # define tmask 0
  103984. #endif
  103985. #ifdef SQLITE_OMIT_VIEW
  103986. # undef isView
  103987. # define isView 0
  103988. #endif
  103989. if( sqlite3ViewGetColumnNames(pParse, pTab) ){
  103990. goto update_cleanup;
  103991. }
  103992. if( sqlite3IsReadOnly(pParse, pTab, tmask) ){
  103993. goto update_cleanup;
  103994. }
  103995. /* Allocate a cursors for the main database table and for all indices.
  103996. ** The index cursors might not be used, but if they are used they
  103997. ** need to occur right after the database cursor. So go ahead and
  103998. ** allocate enough space, just in case.
  103999. */
  104000. pTabList->a[0].iCursor = iBaseCur = iDataCur = pParse->nTab++;
  104001. iIdxCur = iDataCur+1;
  104002. pPk = HasRowid(pTab) ? 0 : sqlite3PrimaryKeyIndex(pTab);
  104003. for(nIdx=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, nIdx++){
  104004. if( IsPrimaryKeyIndex(pIdx) && pPk!=0 ){
  104005. iDataCur = pParse->nTab;
  104006. pTabList->a[0].iCursor = iDataCur;
  104007. }
  104008. pParse->nTab++;
  104009. }
  104010. /* Allocate space for aXRef[], aRegIdx[], and aToOpen[].
  104011. ** Initialize aXRef[] and aToOpen[] to their default values.
  104012. */
  104013. aXRef = sqlite3DbMallocRaw(db, sizeof(int) * (pTab->nCol+nIdx) + nIdx+2 );
  104014. if( aXRef==0 ) goto update_cleanup;
  104015. aRegIdx = aXRef+pTab->nCol;
  104016. aToOpen = (u8*)(aRegIdx+nIdx);
  104017. memset(aToOpen, 1, nIdx+1);
  104018. aToOpen[nIdx+1] = 0;
  104019. for(i=0; i<pTab->nCol; i++) aXRef[i] = -1;
  104020. /* Initialize the name-context */
  104021. memset(&sNC, 0, sizeof(sNC));
  104022. sNC.pParse = pParse;
  104023. sNC.pSrcList = pTabList;
  104024. /* Resolve the column names in all the expressions of the
  104025. ** of the UPDATE statement. Also find the column index
  104026. ** for each column to be updated in the pChanges array. For each
  104027. ** column to be updated, make sure we have authorization to change
  104028. ** that column.
  104029. */
  104030. chngRowid = chngPk = 0;
  104031. for(i=0; i<pChanges->nExpr; i++){
  104032. if( sqlite3ResolveExprNames(&sNC, pChanges->a[i].pExpr) ){
  104033. goto update_cleanup;
  104034. }
  104035. for(j=0; j<pTab->nCol; j++){
  104036. if( sqlite3StrICmp(pTab->aCol[j].zName, pChanges->a[i].zName)==0 ){
  104037. if( j==pTab->iPKey ){
  104038. chngRowid = 1;
  104039. pRowidExpr = pChanges->a[i].pExpr;
  104040. }else if( pPk && (pTab->aCol[j].colFlags & COLFLAG_PRIMKEY)!=0 ){
  104041. chngPk = 1;
  104042. }
  104043. aXRef[j] = i;
  104044. break;
  104045. }
  104046. }
  104047. if( j>=pTab->nCol ){
  104048. if( pPk==0 && sqlite3IsRowid(pChanges->a[i].zName) ){
  104049. j = -1;
  104050. chngRowid = 1;
  104051. pRowidExpr = pChanges->a[i].pExpr;
  104052. }else{
  104053. sqlite3ErrorMsg(pParse, "no such column: %s", pChanges->a[i].zName);
  104054. pParse->checkSchema = 1;
  104055. goto update_cleanup;
  104056. }
  104057. }
  104058. #ifndef SQLITE_OMIT_AUTHORIZATION
  104059. {
  104060. int rc;
  104061. rc = sqlite3AuthCheck(pParse, SQLITE_UPDATE, pTab->zName,
  104062. j<0 ? "ROWID" : pTab->aCol[j].zName,
  104063. db->aDb[iDb].zName);
  104064. if( rc==SQLITE_DENY ){
  104065. goto update_cleanup;
  104066. }else if( rc==SQLITE_IGNORE ){
  104067. aXRef[j] = -1;
  104068. }
  104069. }
  104070. #endif
  104071. }
  104072. assert( (chngRowid & chngPk)==0 );
  104073. assert( chngRowid==0 || chngRowid==1 );
  104074. assert( chngPk==0 || chngPk==1 );
  104075. chngKey = chngRowid + chngPk;
  104076. /* The SET expressions are not actually used inside the WHERE loop.
  104077. ** So reset the colUsed mask
  104078. */
  104079. pTabList->a[0].colUsed = 0;
  104080. hasFK = sqlite3FkRequired(pParse, pTab, aXRef, chngKey);
  104081. /* There is one entry in the aRegIdx[] array for each index on the table
  104082. ** being updated. Fill in aRegIdx[] with a register number that will hold
  104083. ** the key for accessing each index.
  104084. */
  104085. for(j=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, j++){
  104086. int reg;
  104087. if( chngKey || hasFK || pIdx->pPartIdxWhere || pIdx==pPk ){
  104088. reg = ++pParse->nMem;
  104089. }else{
  104090. reg = 0;
  104091. for(i=0; i<pIdx->nKeyCol; i++){
  104092. if( aXRef[pIdx->aiColumn[i]]>=0 ){
  104093. reg = ++pParse->nMem;
  104094. break;
  104095. }
  104096. }
  104097. }
  104098. if( reg==0 ) aToOpen[j+1] = 0;
  104099. aRegIdx[j] = reg;
  104100. }
  104101. /* Begin generating code. */
  104102. v = sqlite3GetVdbe(pParse);
  104103. if( v==0 ) goto update_cleanup;
  104104. if( pParse->nested==0 ) sqlite3VdbeCountChanges(v);
  104105. sqlite3BeginWriteOperation(pParse, 1, iDb);
  104106. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104107. /* Virtual tables must be handled separately */
  104108. if( IsVirtual(pTab) ){
  104109. updateVirtualTable(pParse, pTabList, pTab, pChanges, pRowidExpr, aXRef,
  104110. pWhere, onError);
  104111. pWhere = 0;
  104112. pTabList = 0;
  104113. goto update_cleanup;
  104114. }
  104115. #endif
  104116. /* Allocate required registers. */
  104117. regRowSet = ++pParse->nMem;
  104118. regOldRowid = regNewRowid = ++pParse->nMem;
  104119. if( chngPk || pTrigger || hasFK ){
  104120. regOld = pParse->nMem + 1;
  104121. pParse->nMem += pTab->nCol;
  104122. }
  104123. if( chngKey || pTrigger || hasFK ){
  104124. regNewRowid = ++pParse->nMem;
  104125. }
  104126. regNew = pParse->nMem + 1;
  104127. pParse->nMem += pTab->nCol;
  104128. /* Start the view context. */
  104129. if( isView ){
  104130. sqlite3AuthContextPush(pParse, &sContext, pTab->zName);
  104131. }
  104132. /* If we are trying to update a view, realize that view into
  104133. ** an ephemeral table.
  104134. */
  104135. #if !defined(SQLITE_OMIT_VIEW) && !defined(SQLITE_OMIT_TRIGGER)
  104136. if( isView ){
  104137. sqlite3MaterializeView(pParse, pTab, pWhere, iDataCur);
  104138. }
  104139. #endif
  104140. /* Resolve the column names in all the expressions in the
  104141. ** WHERE clause.
  104142. */
  104143. if( sqlite3ResolveExprNames(&sNC, pWhere) ){
  104144. goto update_cleanup;
  104145. }
  104146. /* Begin the database scan
  104147. */
  104148. if( HasRowid(pTab) ){
  104149. sqlite3VdbeAddOp3(v, OP_Null, 0, regRowSet, regOldRowid);
  104150. pWInfo = sqlite3WhereBegin(
  104151. pParse, pTabList, pWhere, 0, 0, WHERE_ONEPASS_DESIRED, iIdxCur
  104152. );
  104153. if( pWInfo==0 ) goto update_cleanup;
  104154. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  104155. /* Remember the rowid of every item to be updated.
  104156. */
  104157. sqlite3VdbeAddOp2(v, OP_Rowid, iDataCur, regOldRowid);
  104158. if( !okOnePass ){
  104159. sqlite3VdbeAddOp2(v, OP_RowSetAdd, regRowSet, regOldRowid);
  104160. }
  104161. /* End the database scan loop.
  104162. */
  104163. sqlite3WhereEnd(pWInfo);
  104164. }else{
  104165. int iPk; /* First of nPk memory cells holding PRIMARY KEY value */
  104166. i16 nPk; /* Number of components of the PRIMARY KEY */
  104167. int addrOpen; /* Address of the OpenEphemeral instruction */
  104168. assert( pPk!=0 );
  104169. nPk = pPk->nKeyCol;
  104170. iPk = pParse->nMem+1;
  104171. pParse->nMem += nPk;
  104172. regKey = ++pParse->nMem;
  104173. iEph = pParse->nTab++;
  104174. sqlite3VdbeAddOp2(v, OP_Null, 0, iPk);
  104175. addrOpen = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iEph, nPk);
  104176. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  104177. pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, 0, 0,
  104178. WHERE_ONEPASS_DESIRED, iIdxCur);
  104179. if( pWInfo==0 ) goto update_cleanup;
  104180. okOnePass = sqlite3WhereOkOnePass(pWInfo, aiCurOnePass);
  104181. for(i=0; i<nPk; i++){
  104182. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, pPk->aiColumn[i],
  104183. iPk+i);
  104184. }
  104185. if( okOnePass ){
  104186. sqlite3VdbeChangeToNoop(v, addrOpen);
  104187. nKey = nPk;
  104188. regKey = iPk;
  104189. }else{
  104190. sqlite3VdbeAddOp4(v, OP_MakeRecord, iPk, nPk, regKey,
  104191. sqlite3IndexAffinityStr(v, pPk), nPk);
  104192. sqlite3VdbeAddOp2(v, OP_IdxInsert, iEph, regKey);
  104193. }
  104194. sqlite3WhereEnd(pWInfo);
  104195. }
  104196. /* Initialize the count of updated rows
  104197. */
  104198. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab ){
  104199. regRowCount = ++pParse->nMem;
  104200. sqlite3VdbeAddOp2(v, OP_Integer, 0, regRowCount);
  104201. }
  104202. labelBreak = sqlite3VdbeMakeLabel(v);
  104203. if( !isView ){
  104204. /*
  104205. ** Open every index that needs updating. Note that if any
  104206. ** index could potentially invoke a REPLACE conflict resolution
  104207. ** action, then we need to open all indices because we might need
  104208. ** to be deleting some records.
  104209. */
  104210. if( onError==OE_Replace ){
  104211. memset(aToOpen, 1, nIdx+1);
  104212. }else{
  104213. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  104214. if( pIdx->onError==OE_Replace ){
  104215. memset(aToOpen, 1, nIdx+1);
  104216. break;
  104217. }
  104218. }
  104219. }
  104220. if( okOnePass ){
  104221. if( aiCurOnePass[0]>=0 ) aToOpen[aiCurOnePass[0]-iBaseCur] = 0;
  104222. if( aiCurOnePass[1]>=0 ) aToOpen[aiCurOnePass[1]-iBaseCur] = 0;
  104223. }
  104224. sqlite3OpenTableAndIndices(pParse, pTab, OP_OpenWrite, iBaseCur, aToOpen,
  104225. 0, 0);
  104226. }
  104227. /* Top of the update loop */
  104228. if( okOnePass ){
  104229. if( aToOpen[iDataCur-iBaseCur] && !isView ){
  104230. assert( pPk );
  104231. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelBreak, regKey, nKey);
  104232. VdbeCoverageNeverTaken(v);
  104233. }
  104234. labelContinue = labelBreak;
  104235. sqlite3VdbeAddOp2(v, OP_IsNull, pPk ? regKey : regOldRowid, labelBreak);
  104236. VdbeCoverageIf(v, pPk==0);
  104237. VdbeCoverageIf(v, pPk!=0);
  104238. }else if( pPk ){
  104239. labelContinue = sqlite3VdbeMakeLabel(v);
  104240. sqlite3VdbeAddOp2(v, OP_Rewind, iEph, labelBreak); VdbeCoverage(v);
  104241. addrTop = sqlite3VdbeAddOp2(v, OP_RowKey, iEph, regKey);
  104242. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue, regKey, 0);
  104243. VdbeCoverage(v);
  104244. }else{
  104245. labelContinue = sqlite3VdbeAddOp3(v, OP_RowSetRead, regRowSet, labelBreak,
  104246. regOldRowid);
  104247. VdbeCoverage(v);
  104248. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  104249. VdbeCoverage(v);
  104250. }
  104251. /* If the record number will change, set register regNewRowid to
  104252. ** contain the new value. If the record number is not being modified,
  104253. ** then regNewRowid is the same register as regOldRowid, which is
  104254. ** already populated. */
  104255. assert( chngKey || pTrigger || hasFK || regOldRowid==regNewRowid );
  104256. if( chngRowid ){
  104257. sqlite3ExprCode(pParse, pRowidExpr, regNewRowid);
  104258. sqlite3VdbeAddOp1(v, OP_MustBeInt, regNewRowid); VdbeCoverage(v);
  104259. }
  104260. /* Compute the old pre-UPDATE content of the row being changed, if that
  104261. ** information is needed */
  104262. if( chngPk || hasFK || pTrigger ){
  104263. u32 oldmask = (hasFK ? sqlite3FkOldmask(pParse, pTab) : 0);
  104264. oldmask |= sqlite3TriggerColmask(pParse,
  104265. pTrigger, pChanges, 0, TRIGGER_BEFORE|TRIGGER_AFTER, pTab, onError
  104266. );
  104267. for(i=0; i<pTab->nCol; i++){
  104268. if( oldmask==0xffffffff
  104269. || (i<32 && (oldmask & MASKBIT32(i))!=0)
  104270. || (pTab->aCol[i].colFlags & COLFLAG_PRIMKEY)!=0
  104271. ){
  104272. testcase( oldmask!=0xffffffff && i==31 );
  104273. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regOld+i);
  104274. }else{
  104275. sqlite3VdbeAddOp2(v, OP_Null, 0, regOld+i);
  104276. }
  104277. }
  104278. if( chngRowid==0 && pPk==0 ){
  104279. sqlite3VdbeAddOp2(v, OP_Copy, regOldRowid, regNewRowid);
  104280. }
  104281. }
  104282. /* Populate the array of registers beginning at regNew with the new
  104283. ** row data. This array is used to check constants, create the new
  104284. ** table and index records, and as the values for any new.* references
  104285. ** made by triggers.
  104286. **
  104287. ** If there are one or more BEFORE triggers, then do not populate the
  104288. ** registers associated with columns that are (a) not modified by
  104289. ** this UPDATE statement and (b) not accessed by new.* references. The
  104290. ** values for registers not modified by the UPDATE must be reloaded from
  104291. ** the database after the BEFORE triggers are fired anyway (as the trigger
  104292. ** may have modified them). So not loading those that are not going to
  104293. ** be used eliminates some redundant opcodes.
  104294. */
  104295. newmask = sqlite3TriggerColmask(
  104296. pParse, pTrigger, pChanges, 1, TRIGGER_BEFORE, pTab, onError
  104297. );
  104298. /*sqlite3VdbeAddOp3(v, OP_Null, 0, regNew, regNew+pTab->nCol-1);*/
  104299. for(i=0; i<pTab->nCol; i++){
  104300. if( i==pTab->iPKey ){
  104301. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  104302. }else{
  104303. j = aXRef[i];
  104304. if( j>=0 ){
  104305. sqlite3ExprCode(pParse, pChanges->a[j].pExpr, regNew+i);
  104306. }else if( 0==(tmask&TRIGGER_BEFORE) || i>31 || (newmask & MASKBIT32(i)) ){
  104307. /* This branch loads the value of a column that will not be changed
  104308. ** into a register. This is done if there are no BEFORE triggers, or
  104309. ** if there are one or more BEFORE triggers that use this value via
  104310. ** a new.* reference in a trigger program.
  104311. */
  104312. testcase( i==31 );
  104313. testcase( i==32 );
  104314. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  104315. }else{
  104316. sqlite3VdbeAddOp2(v, OP_Null, 0, regNew+i);
  104317. }
  104318. }
  104319. }
  104320. /* Fire any BEFORE UPDATE triggers. This happens before constraints are
  104321. ** verified. One could argue that this is wrong.
  104322. */
  104323. if( tmask&TRIGGER_BEFORE ){
  104324. sqlite3TableAffinity(v, pTab, regNew);
  104325. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  104326. TRIGGER_BEFORE, pTab, regOldRowid, onError, labelContinue);
  104327. /* The row-trigger may have deleted the row being updated. In this
  104328. ** case, jump to the next row. No updates or AFTER triggers are
  104329. ** required. This behavior - what happens when the row being updated
  104330. ** is deleted or renamed by a BEFORE trigger - is left undefined in the
  104331. ** documentation.
  104332. */
  104333. if( pPk ){
  104334. sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, labelContinue,regKey,nKey);
  104335. VdbeCoverage(v);
  104336. }else{
  104337. sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, labelContinue, regOldRowid);
  104338. VdbeCoverage(v);
  104339. }
  104340. /* If it did not delete it, the row-trigger may still have modified
  104341. ** some of the columns of the row being updated. Load the values for
  104342. ** all columns not modified by the update statement into their
  104343. ** registers in case this has happened.
  104344. */
  104345. for(i=0; i<pTab->nCol; i++){
  104346. if( aXRef[i]<0 && i!=pTab->iPKey ){
  104347. sqlite3ExprCodeGetColumnOfTable(v, pTab, iDataCur, i, regNew+i);
  104348. }
  104349. }
  104350. }
  104351. if( !isView ){
  104352. int j1 = 0; /* Address of jump instruction */
  104353. int bReplace = 0; /* True if REPLACE conflict resolution might happen */
  104354. /* Do constraint checks. */
  104355. assert( regOldRowid>0 );
  104356. sqlite3GenerateConstraintChecks(pParse, pTab, aRegIdx, iDataCur, iIdxCur,
  104357. regNewRowid, regOldRowid, chngKey, onError, labelContinue, &bReplace);
  104358. /* Do FK constraint checks. */
  104359. if( hasFK ){
  104360. sqlite3FkCheck(pParse, pTab, regOldRowid, 0, aXRef, chngKey);
  104361. }
  104362. /* Delete the index entries associated with the current record. */
  104363. if( bReplace || chngKey ){
  104364. if( pPk ){
  104365. j1 = sqlite3VdbeAddOp4Int(v, OP_NotFound, iDataCur, 0, regKey, nKey);
  104366. }else{
  104367. j1 = sqlite3VdbeAddOp3(v, OP_NotExists, iDataCur, 0, regOldRowid);
  104368. }
  104369. VdbeCoverageNeverTaken(v);
  104370. }
  104371. sqlite3GenerateRowIndexDelete(pParse, pTab, iDataCur, iIdxCur, aRegIdx);
  104372. /* If changing the record number, delete the old record. */
  104373. if( hasFK || chngKey || pPk!=0 ){
  104374. sqlite3VdbeAddOp2(v, OP_Delete, iDataCur, 0);
  104375. }
  104376. if( bReplace || chngKey ){
  104377. sqlite3VdbeJumpHere(v, j1);
  104378. }
  104379. if( hasFK ){
  104380. sqlite3FkCheck(pParse, pTab, 0, regNewRowid, aXRef, chngKey);
  104381. }
  104382. /* Insert the new index entries and the new record. */
  104383. sqlite3CompleteInsertion(pParse, pTab, iDataCur, iIdxCur,
  104384. regNewRowid, aRegIdx, 1, 0, 0);
  104385. /* Do any ON CASCADE, SET NULL or SET DEFAULT operations required to
  104386. ** handle rows (possibly in other tables) that refer via a foreign key
  104387. ** to the row just updated. */
  104388. if( hasFK ){
  104389. sqlite3FkActions(pParse, pTab, pChanges, regOldRowid, aXRef, chngKey);
  104390. }
  104391. }
  104392. /* Increment the row counter
  104393. */
  104394. if( (db->flags & SQLITE_CountRows) && !pParse->pTriggerTab){
  104395. sqlite3VdbeAddOp2(v, OP_AddImm, regRowCount, 1);
  104396. }
  104397. sqlite3CodeRowTrigger(pParse, pTrigger, TK_UPDATE, pChanges,
  104398. TRIGGER_AFTER, pTab, regOldRowid, onError, labelContinue);
  104399. /* Repeat the above with the next record to be updated, until
  104400. ** all record selected by the WHERE clause have been updated.
  104401. */
  104402. if( okOnePass ){
  104403. /* Nothing to do at end-of-loop for a single-pass */
  104404. }else if( pPk ){
  104405. sqlite3VdbeResolveLabel(v, labelContinue);
  104406. sqlite3VdbeAddOp2(v, OP_Next, iEph, addrTop); VdbeCoverage(v);
  104407. }else{
  104408. sqlite3VdbeAddOp2(v, OP_Goto, 0, labelContinue);
  104409. }
  104410. sqlite3VdbeResolveLabel(v, labelBreak);
  104411. /* Close all tables */
  104412. for(i=0, pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext, i++){
  104413. assert( aRegIdx );
  104414. if( aToOpen[i+1] ){
  104415. sqlite3VdbeAddOp2(v, OP_Close, iIdxCur+i, 0);
  104416. }
  104417. }
  104418. if( iDataCur<iIdxCur ) sqlite3VdbeAddOp2(v, OP_Close, iDataCur, 0);
  104419. /* Update the sqlite_sequence table by storing the content of the
  104420. ** maximum rowid counter values recorded while inserting into
  104421. ** autoincrement tables.
  104422. */
  104423. if( pParse->nested==0 && pParse->pTriggerTab==0 ){
  104424. sqlite3AutoincrementEnd(pParse);
  104425. }
  104426. /*
  104427. ** Return the number of rows that were changed. If this routine is
  104428. ** generating code because of a call to sqlite3NestedParse(), do not
  104429. ** invoke the callback function.
  104430. */
  104431. if( (db->flags&SQLITE_CountRows) && !pParse->pTriggerTab && !pParse->nested ){
  104432. sqlite3VdbeAddOp2(v, OP_ResultRow, regRowCount, 1);
  104433. sqlite3VdbeSetNumCols(v, 1);
  104434. sqlite3VdbeSetColName(v, 0, COLNAME_NAME, "rows updated", SQLITE_STATIC);
  104435. }
  104436. update_cleanup:
  104437. sqlite3AuthContextPop(&sContext);
  104438. sqlite3DbFree(db, aXRef); /* Also frees aRegIdx[] and aToOpen[] */
  104439. sqlite3SrcListDelete(db, pTabList);
  104440. sqlite3ExprListDelete(db, pChanges);
  104441. sqlite3ExprDelete(db, pWhere);
  104442. return;
  104443. }
  104444. /* Make sure "isView" and other macros defined above are undefined. Otherwise
  104445. ** they may interfere with compilation of other functions in this file
  104446. ** (or in another file, if this file becomes part of the amalgamation). */
  104447. #ifdef isView
  104448. #undef isView
  104449. #endif
  104450. #ifdef pTrigger
  104451. #undef pTrigger
  104452. #endif
  104453. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104454. /*
  104455. ** Generate code for an UPDATE of a virtual table.
  104456. **
  104457. ** The strategy is that we create an ephemeral table that contains
  104458. ** for each row to be changed:
  104459. **
  104460. ** (A) The original rowid of that row.
  104461. ** (B) The revised rowid for the row. (note1)
  104462. ** (C) The content of every column in the row.
  104463. **
  104464. ** Then we loop over this ephemeral table and for each row in
  104465. ** the ephemeral table call VUpdate.
  104466. **
  104467. ** When finished, drop the ephemeral table.
  104468. **
  104469. ** (note1) Actually, if we know in advance that (A) is always the same
  104470. ** as (B) we only store (A), then duplicate (A) when pulling
  104471. ** it out of the ephemeral table before calling VUpdate.
  104472. */
  104473. static void updateVirtualTable(
  104474. Parse *pParse, /* The parsing context */
  104475. SrcList *pSrc, /* The virtual table to be modified */
  104476. Table *pTab, /* The virtual table */
  104477. ExprList *pChanges, /* The columns to change in the UPDATE statement */
  104478. Expr *pRowid, /* Expression used to recompute the rowid */
  104479. int *aXRef, /* Mapping from columns of pTab to entries in pChanges */
  104480. Expr *pWhere, /* WHERE clause of the UPDATE statement */
  104481. int onError /* ON CONFLICT strategy */
  104482. ){
  104483. Vdbe *v = pParse->pVdbe; /* Virtual machine under construction */
  104484. ExprList *pEList = 0; /* The result set of the SELECT statement */
  104485. Select *pSelect = 0; /* The SELECT statement */
  104486. Expr *pExpr; /* Temporary expression */
  104487. int ephemTab; /* Table holding the result of the SELECT */
  104488. int i; /* Loop counter */
  104489. int addr; /* Address of top of loop */
  104490. int iReg; /* First register in set passed to OP_VUpdate */
  104491. sqlite3 *db = pParse->db; /* Database connection */
  104492. const char *pVTab = (const char*)sqlite3GetVTable(db, pTab);
  104493. SelectDest dest;
  104494. /* Construct the SELECT statement that will find the new values for
  104495. ** all updated rows.
  104496. */
  104497. pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ID, "_rowid_"));
  104498. if( pRowid ){
  104499. pEList = sqlite3ExprListAppend(pParse, pEList,
  104500. sqlite3ExprDup(db, pRowid, 0));
  104501. }
  104502. assert( pTab->iPKey<0 );
  104503. for(i=0; i<pTab->nCol; i++){
  104504. if( aXRef[i]>=0 ){
  104505. pExpr = sqlite3ExprDup(db, pChanges->a[aXRef[i]].pExpr, 0);
  104506. }else{
  104507. pExpr = sqlite3Expr(db, TK_ID, pTab->aCol[i].zName);
  104508. }
  104509. pEList = sqlite3ExprListAppend(pParse, pEList, pExpr);
  104510. }
  104511. pSelect = sqlite3SelectNew(pParse, pEList, pSrc, pWhere, 0, 0, 0, 0, 0, 0);
  104512. /* Create the ephemeral table into which the update results will
  104513. ** be stored.
  104514. */
  104515. assert( v );
  104516. ephemTab = pParse->nTab++;
  104517. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, ephemTab, pTab->nCol+1+(pRowid!=0));
  104518. sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
  104519. /* fill the ephemeral table
  104520. */
  104521. sqlite3SelectDestInit(&dest, SRT_Table, ephemTab);
  104522. sqlite3Select(pParse, pSelect, &dest);
  104523. /* Generate code to scan the ephemeral table and call VUpdate. */
  104524. iReg = ++pParse->nMem;
  104525. pParse->nMem += pTab->nCol+1;
  104526. addr = sqlite3VdbeAddOp2(v, OP_Rewind, ephemTab, 0); VdbeCoverage(v);
  104527. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, 0, iReg);
  104528. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, (pRowid?1:0), iReg+1);
  104529. for(i=0; i<pTab->nCol; i++){
  104530. sqlite3VdbeAddOp3(v, OP_Column, ephemTab, i+1+(pRowid!=0), iReg+2+i);
  104531. }
  104532. sqlite3VtabMakeWritable(pParse, pTab);
  104533. sqlite3VdbeAddOp4(v, OP_VUpdate, 0, pTab->nCol+2, iReg, pVTab, P4_VTAB);
  104534. sqlite3VdbeChangeP5(v, onError==OE_Default ? OE_Abort : onError);
  104535. sqlite3MayAbort(pParse);
  104536. sqlite3VdbeAddOp2(v, OP_Next, ephemTab, addr+1); VdbeCoverage(v);
  104537. sqlite3VdbeJumpHere(v, addr);
  104538. sqlite3VdbeAddOp2(v, OP_Close, ephemTab, 0);
  104539. /* Cleanup */
  104540. sqlite3SelectDelete(db, pSelect);
  104541. }
  104542. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  104543. /************** End of update.c **********************************************/
  104544. /************** Begin file vacuum.c ******************************************/
  104545. /*
  104546. ** 2003 April 6
  104547. **
  104548. ** The author disclaims copyright to this source code. In place of
  104549. ** a legal notice, here is a blessing:
  104550. **
  104551. ** May you do good and not evil.
  104552. ** May you find forgiveness for yourself and forgive others.
  104553. ** May you share freely, never taking more than you give.
  104554. **
  104555. *************************************************************************
  104556. ** This file contains code used to implement the VACUUM command.
  104557. **
  104558. ** Most of the code in this file may be omitted by defining the
  104559. ** SQLITE_OMIT_VACUUM macro.
  104560. */
  104561. #if !defined(SQLITE_OMIT_VACUUM) && !defined(SQLITE_OMIT_ATTACH)
  104562. /*
  104563. ** Finalize a prepared statement. If there was an error, store the
  104564. ** text of the error message in *pzErrMsg. Return the result code.
  104565. */
  104566. static int vacuumFinalize(sqlite3 *db, sqlite3_stmt *pStmt, char **pzErrMsg){
  104567. int rc;
  104568. rc = sqlite3VdbeFinalize((Vdbe*)pStmt);
  104569. if( rc ){
  104570. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  104571. }
  104572. return rc;
  104573. }
  104574. /*
  104575. ** Execute zSql on database db. Return an error code.
  104576. */
  104577. static int execSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  104578. sqlite3_stmt *pStmt;
  104579. VVA_ONLY( int rc; )
  104580. if( !zSql ){
  104581. return SQLITE_NOMEM;
  104582. }
  104583. if( SQLITE_OK!=sqlite3_prepare(db, zSql, -1, &pStmt, 0) ){
  104584. sqlite3SetString(pzErrMsg, db, sqlite3_errmsg(db));
  104585. return sqlite3_errcode(db);
  104586. }
  104587. VVA_ONLY( rc = ) sqlite3_step(pStmt);
  104588. assert( rc!=SQLITE_ROW || (db->flags&SQLITE_CountRows) );
  104589. return vacuumFinalize(db, pStmt, pzErrMsg);
  104590. }
  104591. /*
  104592. ** Execute zSql on database db. The statement returns exactly
  104593. ** one column. Execute this as SQL on the same database.
  104594. */
  104595. static int execExecSql(sqlite3 *db, char **pzErrMsg, const char *zSql){
  104596. sqlite3_stmt *pStmt;
  104597. int rc;
  104598. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  104599. if( rc!=SQLITE_OK ) return rc;
  104600. while( SQLITE_ROW==sqlite3_step(pStmt) ){
  104601. rc = execSql(db, pzErrMsg, (char*)sqlite3_column_text(pStmt, 0));
  104602. if( rc!=SQLITE_OK ){
  104603. vacuumFinalize(db, pStmt, pzErrMsg);
  104604. return rc;
  104605. }
  104606. }
  104607. return vacuumFinalize(db, pStmt, pzErrMsg);
  104608. }
  104609. /*
  104610. ** The VACUUM command is used to clean up the database,
  104611. ** collapse free space, etc. It is modelled after the VACUUM command
  104612. ** in PostgreSQL. The VACUUM command works as follows:
  104613. **
  104614. ** (1) Create a new transient database file
  104615. ** (2) Copy all content from the database being vacuumed into
  104616. ** the new transient database file
  104617. ** (3) Copy content from the transient database back into the
  104618. ** original database.
  104619. **
  104620. ** The transient database requires temporary disk space approximately
  104621. ** equal to the size of the original database. The copy operation of
  104622. ** step (3) requires additional temporary disk space approximately equal
  104623. ** to the size of the original database for the rollback journal.
  104624. ** Hence, temporary disk space that is approximately 2x the size of the
  104625. ** original database is required. Every page of the database is written
  104626. ** approximately 3 times: Once for step (2) and twice for step (3).
  104627. ** Two writes per page are required in step (3) because the original
  104628. ** database content must be written into the rollback journal prior to
  104629. ** overwriting the database with the vacuumed content.
  104630. **
  104631. ** Only 1x temporary space and only 1x writes would be required if
  104632. ** the copy of step (3) were replace by deleting the original database
  104633. ** and renaming the transient database as the original. But that will
  104634. ** not work if other processes are attached to the original database.
  104635. ** And a power loss in between deleting the original and renaming the
  104636. ** transient would cause the database file to appear to be deleted
  104637. ** following reboot.
  104638. */
  104639. SQLITE_PRIVATE void sqlite3Vacuum(Parse *pParse){
  104640. Vdbe *v = sqlite3GetVdbe(pParse);
  104641. if( v ){
  104642. sqlite3VdbeAddOp2(v, OP_Vacuum, 0, 0);
  104643. sqlite3VdbeUsesBtree(v, 0);
  104644. }
  104645. return;
  104646. }
  104647. /*
  104648. ** This routine implements the OP_Vacuum opcode of the VDBE.
  104649. */
  104650. SQLITE_PRIVATE int sqlite3RunVacuum(char **pzErrMsg, sqlite3 *db){
  104651. int rc = SQLITE_OK; /* Return code from service routines */
  104652. Btree *pMain; /* The database being vacuumed */
  104653. Btree *pTemp; /* The temporary database we vacuum into */
  104654. char *zSql = 0; /* SQL statements */
  104655. int saved_flags; /* Saved value of the db->flags */
  104656. int saved_nChange; /* Saved value of db->nChange */
  104657. int saved_nTotalChange; /* Saved value of db->nTotalChange */
  104658. void (*saved_xTrace)(void*,const char*); /* Saved db->xTrace */
  104659. Db *pDb = 0; /* Database to detach at end of vacuum */
  104660. int isMemDb; /* True if vacuuming a :memory: database */
  104661. int nRes; /* Bytes of reserved space at the end of each page */
  104662. int nDb; /* Number of attached databases */
  104663. if( !db->autoCommit ){
  104664. sqlite3SetString(pzErrMsg, db, "cannot VACUUM from within a transaction");
  104665. return SQLITE_ERROR;
  104666. }
  104667. if( db->nVdbeActive>1 ){
  104668. sqlite3SetString(pzErrMsg, db,"cannot VACUUM - SQL statements in progress");
  104669. return SQLITE_ERROR;
  104670. }
  104671. /* Save the current value of the database flags so that it can be
  104672. ** restored before returning. Then set the writable-schema flag, and
  104673. ** disable CHECK and foreign key constraints. */
  104674. saved_flags = db->flags;
  104675. saved_nChange = db->nChange;
  104676. saved_nTotalChange = db->nTotalChange;
  104677. saved_xTrace = db->xTrace;
  104678. db->flags |= SQLITE_WriteSchema | SQLITE_IgnoreChecks | SQLITE_PreferBuiltin;
  104679. db->flags &= ~(SQLITE_ForeignKeys | SQLITE_ReverseOrder);
  104680. db->xTrace = 0;
  104681. pMain = db->aDb[0].pBt;
  104682. isMemDb = sqlite3PagerIsMemdb(sqlite3BtreePager(pMain));
  104683. /* Attach the temporary database as 'vacuum_db'. The synchronous pragma
  104684. ** can be set to 'off' for this file, as it is not recovered if a crash
  104685. ** occurs anyway. The integrity of the database is maintained by a
  104686. ** (possibly synchronous) transaction opened on the main database before
  104687. ** sqlite3BtreeCopyFile() is called.
  104688. **
  104689. ** An optimisation would be to use a non-journaled pager.
  104690. ** (Later:) I tried setting "PRAGMA vacuum_db.journal_mode=OFF" but
  104691. ** that actually made the VACUUM run slower. Very little journalling
  104692. ** actually occurs when doing a vacuum since the vacuum_db is initially
  104693. ** empty. Only the journal header is written. Apparently it takes more
  104694. ** time to parse and run the PRAGMA to turn journalling off than it does
  104695. ** to write the journal header file.
  104696. */
  104697. nDb = db->nDb;
  104698. if( sqlite3TempInMemory(db) ){
  104699. zSql = "ATTACH ':memory:' AS vacuum_db;";
  104700. }else{
  104701. zSql = "ATTACH '' AS vacuum_db;";
  104702. }
  104703. rc = execSql(db, pzErrMsg, zSql);
  104704. if( db->nDb>nDb ){
  104705. pDb = &db->aDb[db->nDb-1];
  104706. assert( strcmp(pDb->zName,"vacuum_db")==0 );
  104707. }
  104708. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104709. pTemp = db->aDb[db->nDb-1].pBt;
  104710. /* The call to execSql() to attach the temp database has left the file
  104711. ** locked (as there was more than one active statement when the transaction
  104712. ** to read the schema was concluded. Unlock it here so that this doesn't
  104713. ** cause problems for the call to BtreeSetPageSize() below. */
  104714. sqlite3BtreeCommit(pTemp);
  104715. nRes = sqlite3BtreeGetReserve(pMain);
  104716. /* A VACUUM cannot change the pagesize of an encrypted database. */
  104717. #ifdef SQLITE_HAS_CODEC
  104718. if( db->nextPagesize ){
  104719. extern void sqlite3CodecGetKey(sqlite3*, int, void**, int*);
  104720. int nKey;
  104721. char *zKey;
  104722. sqlite3CodecGetKey(db, 0, (void**)&zKey, &nKey);
  104723. if( nKey ) db->nextPagesize = 0;
  104724. }
  104725. #endif
  104726. rc = execSql(db, pzErrMsg, "PRAGMA vacuum_db.synchronous=OFF");
  104727. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104728. /* Begin a transaction and take an exclusive lock on the main database
  104729. ** file. This is done before the sqlite3BtreeGetPageSize(pMain) call below,
  104730. ** to ensure that we do not try to change the page-size on a WAL database.
  104731. */
  104732. rc = execSql(db, pzErrMsg, "BEGIN;");
  104733. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104734. rc = sqlite3BtreeBeginTrans(pMain, 2);
  104735. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104736. /* Do not attempt to change the page size for a WAL database */
  104737. if( sqlite3PagerGetJournalMode(sqlite3BtreePager(pMain))
  104738. ==PAGER_JOURNALMODE_WAL ){
  104739. db->nextPagesize = 0;
  104740. }
  104741. if( sqlite3BtreeSetPageSize(pTemp, sqlite3BtreeGetPageSize(pMain), nRes, 0)
  104742. || (!isMemDb && sqlite3BtreeSetPageSize(pTemp, db->nextPagesize, nRes, 0))
  104743. || NEVER(db->mallocFailed)
  104744. ){
  104745. rc = SQLITE_NOMEM;
  104746. goto end_of_vacuum;
  104747. }
  104748. #ifndef SQLITE_OMIT_AUTOVACUUM
  104749. sqlite3BtreeSetAutoVacuum(pTemp, db->nextAutovac>=0 ? db->nextAutovac :
  104750. sqlite3BtreeGetAutoVacuum(pMain));
  104751. #endif
  104752. /* Query the schema of the main database. Create a mirror schema
  104753. ** in the temporary database.
  104754. */
  104755. rc = execExecSql(db, pzErrMsg,
  104756. "SELECT 'CREATE TABLE vacuum_db.' || substr(sql,14) "
  104757. " FROM sqlite_master WHERE type='table' AND name!='sqlite_sequence'"
  104758. " AND coalesce(rootpage,1)>0"
  104759. );
  104760. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104761. rc = execExecSql(db, pzErrMsg,
  104762. "SELECT 'CREATE INDEX vacuum_db.' || substr(sql,14)"
  104763. " FROM sqlite_master WHERE sql LIKE 'CREATE INDEX %' ");
  104764. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104765. rc = execExecSql(db, pzErrMsg,
  104766. "SELECT 'CREATE UNIQUE INDEX vacuum_db.' || substr(sql,21) "
  104767. " FROM sqlite_master WHERE sql LIKE 'CREATE UNIQUE INDEX %'");
  104768. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104769. /* Loop through the tables in the main database. For each, do
  104770. ** an "INSERT INTO vacuum_db.xxx SELECT * FROM main.xxx;" to copy
  104771. ** the contents to the temporary database.
  104772. */
  104773. rc = execExecSql(db, pzErrMsg,
  104774. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  104775. "|| ' SELECT * FROM main.' || quote(name) || ';'"
  104776. "FROM main.sqlite_master "
  104777. "WHERE type = 'table' AND name!='sqlite_sequence' "
  104778. " AND coalesce(rootpage,1)>0"
  104779. );
  104780. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104781. /* Copy over the sequence table
  104782. */
  104783. rc = execExecSql(db, pzErrMsg,
  104784. "SELECT 'DELETE FROM vacuum_db.' || quote(name) || ';' "
  104785. "FROM vacuum_db.sqlite_master WHERE name='sqlite_sequence' "
  104786. );
  104787. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104788. rc = execExecSql(db, pzErrMsg,
  104789. "SELECT 'INSERT INTO vacuum_db.' || quote(name) "
  104790. "|| ' SELECT * FROM main.' || quote(name) || ';' "
  104791. "FROM vacuum_db.sqlite_master WHERE name=='sqlite_sequence';"
  104792. );
  104793. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104794. /* Copy the triggers, views, and virtual tables from the main database
  104795. ** over to the temporary database. None of these objects has any
  104796. ** associated storage, so all we have to do is copy their entries
  104797. ** from the SQLITE_MASTER table.
  104798. */
  104799. rc = execSql(db, pzErrMsg,
  104800. "INSERT INTO vacuum_db.sqlite_master "
  104801. " SELECT type, name, tbl_name, rootpage, sql"
  104802. " FROM main.sqlite_master"
  104803. " WHERE type='view' OR type='trigger'"
  104804. " OR (type='table' AND rootpage=0)"
  104805. );
  104806. if( rc ) goto end_of_vacuum;
  104807. /* At this point, there is a write transaction open on both the
  104808. ** vacuum database and the main database. Assuming no error occurs,
  104809. ** both transactions are closed by this block - the main database
  104810. ** transaction by sqlite3BtreeCopyFile() and the other by an explicit
  104811. ** call to sqlite3BtreeCommit().
  104812. */
  104813. {
  104814. u32 meta;
  104815. int i;
  104816. /* This array determines which meta meta values are preserved in the
  104817. ** vacuum. Even entries are the meta value number and odd entries
  104818. ** are an increment to apply to the meta value after the vacuum.
  104819. ** The increment is used to increase the schema cookie so that other
  104820. ** connections to the same database will know to reread the schema.
  104821. */
  104822. static const unsigned char aCopy[] = {
  104823. BTREE_SCHEMA_VERSION, 1, /* Add one to the old schema cookie */
  104824. BTREE_DEFAULT_CACHE_SIZE, 0, /* Preserve the default page cache size */
  104825. BTREE_TEXT_ENCODING, 0, /* Preserve the text encoding */
  104826. BTREE_USER_VERSION, 0, /* Preserve the user version */
  104827. BTREE_APPLICATION_ID, 0, /* Preserve the application id */
  104828. };
  104829. assert( 1==sqlite3BtreeIsInTrans(pTemp) );
  104830. assert( 1==sqlite3BtreeIsInTrans(pMain) );
  104831. /* Copy Btree meta values */
  104832. for(i=0; i<ArraySize(aCopy); i+=2){
  104833. /* GetMeta() and UpdateMeta() cannot fail in this context because
  104834. ** we already have page 1 loaded into cache and marked dirty. */
  104835. sqlite3BtreeGetMeta(pMain, aCopy[i], &meta);
  104836. rc = sqlite3BtreeUpdateMeta(pTemp, aCopy[i], meta+aCopy[i+1]);
  104837. if( NEVER(rc!=SQLITE_OK) ) goto end_of_vacuum;
  104838. }
  104839. rc = sqlite3BtreeCopyFile(pMain, pTemp);
  104840. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104841. rc = sqlite3BtreeCommit(pTemp);
  104842. if( rc!=SQLITE_OK ) goto end_of_vacuum;
  104843. #ifndef SQLITE_OMIT_AUTOVACUUM
  104844. sqlite3BtreeSetAutoVacuum(pMain, sqlite3BtreeGetAutoVacuum(pTemp));
  104845. #endif
  104846. }
  104847. assert( rc==SQLITE_OK );
  104848. rc = sqlite3BtreeSetPageSize(pMain, sqlite3BtreeGetPageSize(pTemp), nRes,1);
  104849. end_of_vacuum:
  104850. /* Restore the original value of db->flags */
  104851. db->flags = saved_flags;
  104852. db->nChange = saved_nChange;
  104853. db->nTotalChange = saved_nTotalChange;
  104854. db->xTrace = saved_xTrace;
  104855. sqlite3BtreeSetPageSize(pMain, -1, -1, 1);
  104856. /* Currently there is an SQL level transaction open on the vacuum
  104857. ** database. No locks are held on any other files (since the main file
  104858. ** was committed at the btree level). So it safe to end the transaction
  104859. ** by manually setting the autoCommit flag to true and detaching the
  104860. ** vacuum database. The vacuum_db journal file is deleted when the pager
  104861. ** is closed by the DETACH.
  104862. */
  104863. db->autoCommit = 1;
  104864. if( pDb ){
  104865. sqlite3BtreeClose(pDb->pBt);
  104866. pDb->pBt = 0;
  104867. pDb->pSchema = 0;
  104868. }
  104869. /* This both clears the schemas and reduces the size of the db->aDb[]
  104870. ** array. */
  104871. sqlite3ResetAllSchemasOfConnection(db);
  104872. return rc;
  104873. }
  104874. #endif /* SQLITE_OMIT_VACUUM && SQLITE_OMIT_ATTACH */
  104875. /************** End of vacuum.c **********************************************/
  104876. /************** Begin file vtab.c ********************************************/
  104877. /*
  104878. ** 2006 June 10
  104879. **
  104880. ** The author disclaims copyright to this source code. In place of
  104881. ** a legal notice, here is a blessing:
  104882. **
  104883. ** May you do good and not evil.
  104884. ** May you find forgiveness for yourself and forgive others.
  104885. ** May you share freely, never taking more than you give.
  104886. **
  104887. *************************************************************************
  104888. ** This file contains code used to help implement virtual tables.
  104889. */
  104890. #ifndef SQLITE_OMIT_VIRTUALTABLE
  104891. /*
  104892. ** Before a virtual table xCreate() or xConnect() method is invoked, the
  104893. ** sqlite3.pVtabCtx member variable is set to point to an instance of
  104894. ** this struct allocated on the stack. It is used by the implementation of
  104895. ** the sqlite3_declare_vtab() and sqlite3_vtab_config() APIs, both of which
  104896. ** are invoked only from within xCreate and xConnect methods.
  104897. */
  104898. struct VtabCtx {
  104899. VTable *pVTable; /* The virtual table being constructed */
  104900. Table *pTab; /* The Table object to which the virtual table belongs */
  104901. };
  104902. /*
  104903. ** The actual function that does the work of creating a new module.
  104904. ** This function implements the sqlite3_create_module() and
  104905. ** sqlite3_create_module_v2() interfaces.
  104906. */
  104907. static int createModule(
  104908. sqlite3 *db, /* Database in which module is registered */
  104909. const char *zName, /* Name assigned to this module */
  104910. const sqlite3_module *pModule, /* The definition of the module */
  104911. void *pAux, /* Context pointer for xCreate/xConnect */
  104912. void (*xDestroy)(void *) /* Module destructor function */
  104913. ){
  104914. int rc = SQLITE_OK;
  104915. int nName;
  104916. sqlite3_mutex_enter(db->mutex);
  104917. nName = sqlite3Strlen30(zName);
  104918. if( sqlite3HashFind(&db->aModule, zName) ){
  104919. rc = SQLITE_MISUSE_BKPT;
  104920. }else{
  104921. Module *pMod;
  104922. pMod = (Module *)sqlite3DbMallocRaw(db, sizeof(Module) + nName + 1);
  104923. if( pMod ){
  104924. Module *pDel;
  104925. char *zCopy = (char *)(&pMod[1]);
  104926. memcpy(zCopy, zName, nName+1);
  104927. pMod->zName = zCopy;
  104928. pMod->pModule = pModule;
  104929. pMod->pAux = pAux;
  104930. pMod->xDestroy = xDestroy;
  104931. pDel = (Module *)sqlite3HashInsert(&db->aModule,zCopy,(void*)pMod);
  104932. assert( pDel==0 || pDel==pMod );
  104933. if( pDel ){
  104934. db->mallocFailed = 1;
  104935. sqlite3DbFree(db, pDel);
  104936. }
  104937. }
  104938. }
  104939. rc = sqlite3ApiExit(db, rc);
  104940. if( rc!=SQLITE_OK && xDestroy ) xDestroy(pAux);
  104941. sqlite3_mutex_leave(db->mutex);
  104942. return rc;
  104943. }
  104944. /*
  104945. ** External API function used to create a new virtual-table module.
  104946. */
  104947. SQLITE_API int sqlite3_create_module(
  104948. sqlite3 *db, /* Database in which module is registered */
  104949. const char *zName, /* Name assigned to this module */
  104950. const sqlite3_module *pModule, /* The definition of the module */
  104951. void *pAux /* Context pointer for xCreate/xConnect */
  104952. ){
  104953. return createModule(db, zName, pModule, pAux, 0);
  104954. }
  104955. /*
  104956. ** External API function used to create a new virtual-table module.
  104957. */
  104958. SQLITE_API int sqlite3_create_module_v2(
  104959. sqlite3 *db, /* Database in which module is registered */
  104960. const char *zName, /* Name assigned to this module */
  104961. const sqlite3_module *pModule, /* The definition of the module */
  104962. void *pAux, /* Context pointer for xCreate/xConnect */
  104963. void (*xDestroy)(void *) /* Module destructor function */
  104964. ){
  104965. return createModule(db, zName, pModule, pAux, xDestroy);
  104966. }
  104967. /*
  104968. ** Lock the virtual table so that it cannot be disconnected.
  104969. ** Locks nest. Every lock should have a corresponding unlock.
  104970. ** If an unlock is omitted, resources leaks will occur.
  104971. **
  104972. ** If a disconnect is attempted while a virtual table is locked,
  104973. ** the disconnect is deferred until all locks have been removed.
  104974. */
  104975. SQLITE_PRIVATE void sqlite3VtabLock(VTable *pVTab){
  104976. pVTab->nRef++;
  104977. }
  104978. /*
  104979. ** pTab is a pointer to a Table structure representing a virtual-table.
  104980. ** Return a pointer to the VTable object used by connection db to access
  104981. ** this virtual-table, if one has been created, or NULL otherwise.
  104982. */
  104983. SQLITE_PRIVATE VTable *sqlite3GetVTable(sqlite3 *db, Table *pTab){
  104984. VTable *pVtab;
  104985. assert( IsVirtual(pTab) );
  104986. for(pVtab=pTab->pVTable; pVtab && pVtab->db!=db; pVtab=pVtab->pNext);
  104987. return pVtab;
  104988. }
  104989. /*
  104990. ** Decrement the ref-count on a virtual table object. When the ref-count
  104991. ** reaches zero, call the xDisconnect() method to delete the object.
  104992. */
  104993. SQLITE_PRIVATE void sqlite3VtabUnlock(VTable *pVTab){
  104994. sqlite3 *db = pVTab->db;
  104995. assert( db );
  104996. assert( pVTab->nRef>0 );
  104997. assert( db->magic==SQLITE_MAGIC_OPEN || db->magic==SQLITE_MAGIC_ZOMBIE );
  104998. pVTab->nRef--;
  104999. if( pVTab->nRef==0 ){
  105000. sqlite3_vtab *p = pVTab->pVtab;
  105001. if( p ){
  105002. p->pModule->xDisconnect(p);
  105003. }
  105004. sqlite3DbFree(db, pVTab);
  105005. }
  105006. }
  105007. /*
  105008. ** Table p is a virtual table. This function moves all elements in the
  105009. ** p->pVTable list to the sqlite3.pDisconnect lists of their associated
  105010. ** database connections to be disconnected at the next opportunity.
  105011. ** Except, if argument db is not NULL, then the entry associated with
  105012. ** connection db is left in the p->pVTable list.
  105013. */
  105014. static VTable *vtabDisconnectAll(sqlite3 *db, Table *p){
  105015. VTable *pRet = 0;
  105016. VTable *pVTable = p->pVTable;
  105017. p->pVTable = 0;
  105018. /* Assert that the mutex (if any) associated with the BtShared database
  105019. ** that contains table p is held by the caller. See header comments
  105020. ** above function sqlite3VtabUnlockList() for an explanation of why
  105021. ** this makes it safe to access the sqlite3.pDisconnect list of any
  105022. ** database connection that may have an entry in the p->pVTable list.
  105023. */
  105024. assert( db==0 || sqlite3SchemaMutexHeld(db, 0, p->pSchema) );
  105025. while( pVTable ){
  105026. sqlite3 *db2 = pVTable->db;
  105027. VTable *pNext = pVTable->pNext;
  105028. assert( db2 );
  105029. if( db2==db ){
  105030. pRet = pVTable;
  105031. p->pVTable = pRet;
  105032. pRet->pNext = 0;
  105033. }else{
  105034. pVTable->pNext = db2->pDisconnect;
  105035. db2->pDisconnect = pVTable;
  105036. }
  105037. pVTable = pNext;
  105038. }
  105039. assert( !db || pRet );
  105040. return pRet;
  105041. }
  105042. /*
  105043. ** Table *p is a virtual table. This function removes the VTable object
  105044. ** for table *p associated with database connection db from the linked
  105045. ** list in p->pVTab. It also decrements the VTable ref count. This is
  105046. ** used when closing database connection db to free all of its VTable
  105047. ** objects without disturbing the rest of the Schema object (which may
  105048. ** be being used by other shared-cache connections).
  105049. */
  105050. SQLITE_PRIVATE void sqlite3VtabDisconnect(sqlite3 *db, Table *p){
  105051. VTable **ppVTab;
  105052. assert( IsVirtual(p) );
  105053. assert( sqlite3BtreeHoldsAllMutexes(db) );
  105054. assert( sqlite3_mutex_held(db->mutex) );
  105055. for(ppVTab=&p->pVTable; *ppVTab; ppVTab=&(*ppVTab)->pNext){
  105056. if( (*ppVTab)->db==db ){
  105057. VTable *pVTab = *ppVTab;
  105058. *ppVTab = pVTab->pNext;
  105059. sqlite3VtabUnlock(pVTab);
  105060. break;
  105061. }
  105062. }
  105063. }
  105064. /*
  105065. ** Disconnect all the virtual table objects in the sqlite3.pDisconnect list.
  105066. **
  105067. ** This function may only be called when the mutexes associated with all
  105068. ** shared b-tree databases opened using connection db are held by the
  105069. ** caller. This is done to protect the sqlite3.pDisconnect list. The
  105070. ** sqlite3.pDisconnect list is accessed only as follows:
  105071. **
  105072. ** 1) By this function. In this case, all BtShared mutexes and the mutex
  105073. ** associated with the database handle itself must be held.
  105074. **
  105075. ** 2) By function vtabDisconnectAll(), when it adds a VTable entry to
  105076. ** the sqlite3.pDisconnect list. In this case either the BtShared mutex
  105077. ** associated with the database the virtual table is stored in is held
  105078. ** or, if the virtual table is stored in a non-sharable database, then
  105079. ** the database handle mutex is held.
  105080. **
  105081. ** As a result, a sqlite3.pDisconnect cannot be accessed simultaneously
  105082. ** by multiple threads. It is thread-safe.
  105083. */
  105084. SQLITE_PRIVATE void sqlite3VtabUnlockList(sqlite3 *db){
  105085. VTable *p = db->pDisconnect;
  105086. db->pDisconnect = 0;
  105087. assert( sqlite3BtreeHoldsAllMutexes(db) );
  105088. assert( sqlite3_mutex_held(db->mutex) );
  105089. if( p ){
  105090. sqlite3ExpirePreparedStatements(db);
  105091. do {
  105092. VTable *pNext = p->pNext;
  105093. sqlite3VtabUnlock(p);
  105094. p = pNext;
  105095. }while( p );
  105096. }
  105097. }
  105098. /*
  105099. ** Clear any and all virtual-table information from the Table record.
  105100. ** This routine is called, for example, just before deleting the Table
  105101. ** record.
  105102. **
  105103. ** Since it is a virtual-table, the Table structure contains a pointer
  105104. ** to the head of a linked list of VTable structures. Each VTable
  105105. ** structure is associated with a single sqlite3* user of the schema.
  105106. ** The reference count of the VTable structure associated with database
  105107. ** connection db is decremented immediately (which may lead to the
  105108. ** structure being xDisconnected and free). Any other VTable structures
  105109. ** in the list are moved to the sqlite3.pDisconnect list of the associated
  105110. ** database connection.
  105111. */
  105112. SQLITE_PRIVATE void sqlite3VtabClear(sqlite3 *db, Table *p){
  105113. if( !db || db->pnBytesFreed==0 ) vtabDisconnectAll(0, p);
  105114. if( p->azModuleArg ){
  105115. int i;
  105116. for(i=0; i<p->nModuleArg; i++){
  105117. if( i!=1 ) sqlite3DbFree(db, p->azModuleArg[i]);
  105118. }
  105119. sqlite3DbFree(db, p->azModuleArg);
  105120. }
  105121. }
  105122. /*
  105123. ** Add a new module argument to pTable->azModuleArg[].
  105124. ** The string is not copied - the pointer is stored. The
  105125. ** string will be freed automatically when the table is
  105126. ** deleted.
  105127. */
  105128. static void addModuleArgument(sqlite3 *db, Table *pTable, char *zArg){
  105129. int i = pTable->nModuleArg++;
  105130. int nBytes = sizeof(char *)*(1+pTable->nModuleArg);
  105131. char **azModuleArg;
  105132. azModuleArg = sqlite3DbRealloc(db, pTable->azModuleArg, nBytes);
  105133. if( azModuleArg==0 ){
  105134. int j;
  105135. for(j=0; j<i; j++){
  105136. sqlite3DbFree(db, pTable->azModuleArg[j]);
  105137. }
  105138. sqlite3DbFree(db, zArg);
  105139. sqlite3DbFree(db, pTable->azModuleArg);
  105140. pTable->nModuleArg = 0;
  105141. }else{
  105142. azModuleArg[i] = zArg;
  105143. azModuleArg[i+1] = 0;
  105144. }
  105145. pTable->azModuleArg = azModuleArg;
  105146. }
  105147. /*
  105148. ** The parser calls this routine when it first sees a CREATE VIRTUAL TABLE
  105149. ** statement. The module name has been parsed, but the optional list
  105150. ** of parameters that follow the module name are still pending.
  105151. */
  105152. SQLITE_PRIVATE void sqlite3VtabBeginParse(
  105153. Parse *pParse, /* Parsing context */
  105154. Token *pName1, /* Name of new table, or database name */
  105155. Token *pName2, /* Name of new table or NULL */
  105156. Token *pModuleName, /* Name of the module for the virtual table */
  105157. int ifNotExists /* No error if the table already exists */
  105158. ){
  105159. int iDb; /* The database the table is being created in */
  105160. Table *pTable; /* The new virtual table */
  105161. sqlite3 *db; /* Database connection */
  105162. sqlite3StartTable(pParse, pName1, pName2, 0, 0, 1, ifNotExists);
  105163. pTable = pParse->pNewTable;
  105164. if( pTable==0 ) return;
  105165. assert( 0==pTable->pIndex );
  105166. db = pParse->db;
  105167. iDb = sqlite3SchemaToIndex(db, pTable->pSchema);
  105168. assert( iDb>=0 );
  105169. pTable->tabFlags |= TF_Virtual;
  105170. pTable->nModuleArg = 0;
  105171. addModuleArgument(db, pTable, sqlite3NameFromToken(db, pModuleName));
  105172. addModuleArgument(db, pTable, 0);
  105173. addModuleArgument(db, pTable, sqlite3DbStrDup(db, pTable->zName));
  105174. pParse->sNameToken.n = (int)(&pModuleName->z[pModuleName->n] - pName1->z);
  105175. #ifndef SQLITE_OMIT_AUTHORIZATION
  105176. /* Creating a virtual table invokes the authorization callback twice.
  105177. ** The first invocation, to obtain permission to INSERT a row into the
  105178. ** sqlite_master table, has already been made by sqlite3StartTable().
  105179. ** The second call, to obtain permission to create the table, is made now.
  105180. */
  105181. if( pTable->azModuleArg ){
  105182. sqlite3AuthCheck(pParse, SQLITE_CREATE_VTABLE, pTable->zName,
  105183. pTable->azModuleArg[0], pParse->db->aDb[iDb].zName);
  105184. }
  105185. #endif
  105186. }
  105187. /*
  105188. ** This routine takes the module argument that has been accumulating
  105189. ** in pParse->zArg[] and appends it to the list of arguments on the
  105190. ** virtual table currently under construction in pParse->pTable.
  105191. */
  105192. static void addArgumentToVtab(Parse *pParse){
  105193. if( pParse->sArg.z && pParse->pNewTable ){
  105194. const char *z = (const char*)pParse->sArg.z;
  105195. int n = pParse->sArg.n;
  105196. sqlite3 *db = pParse->db;
  105197. addModuleArgument(db, pParse->pNewTable, sqlite3DbStrNDup(db, z, n));
  105198. }
  105199. }
  105200. /*
  105201. ** The parser calls this routine after the CREATE VIRTUAL TABLE statement
  105202. ** has been completely parsed.
  105203. */
  105204. SQLITE_PRIVATE void sqlite3VtabFinishParse(Parse *pParse, Token *pEnd){
  105205. Table *pTab = pParse->pNewTable; /* The table being constructed */
  105206. sqlite3 *db = pParse->db; /* The database connection */
  105207. if( pTab==0 ) return;
  105208. addArgumentToVtab(pParse);
  105209. pParse->sArg.z = 0;
  105210. if( pTab->nModuleArg<1 ) return;
  105211. /* If the CREATE VIRTUAL TABLE statement is being entered for the
  105212. ** first time (in other words if the virtual table is actually being
  105213. ** created now instead of just being read out of sqlite_master) then
  105214. ** do additional initialization work and store the statement text
  105215. ** in the sqlite_master table.
  105216. */
  105217. if( !db->init.busy ){
  105218. char *zStmt;
  105219. char *zWhere;
  105220. int iDb;
  105221. Vdbe *v;
  105222. /* Compute the complete text of the CREATE VIRTUAL TABLE statement */
  105223. if( pEnd ){
  105224. pParse->sNameToken.n = (int)(pEnd->z - pParse->sNameToken.z) + pEnd->n;
  105225. }
  105226. zStmt = sqlite3MPrintf(db, "CREATE VIRTUAL TABLE %T", &pParse->sNameToken);
  105227. /* A slot for the record has already been allocated in the
  105228. ** SQLITE_MASTER table. We just need to update that slot with all
  105229. ** the information we've collected.
  105230. **
  105231. ** The VM register number pParse->regRowid holds the rowid of an
  105232. ** entry in the sqlite_master table tht was created for this vtab
  105233. ** by sqlite3StartTable().
  105234. */
  105235. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105236. sqlite3NestedParse(pParse,
  105237. "UPDATE %Q.%s "
  105238. "SET type='table', name=%Q, tbl_name=%Q, rootpage=0, sql=%Q "
  105239. "WHERE rowid=#%d",
  105240. db->aDb[iDb].zName, SCHEMA_TABLE(iDb),
  105241. pTab->zName,
  105242. pTab->zName,
  105243. zStmt,
  105244. pParse->regRowid
  105245. );
  105246. sqlite3DbFree(db, zStmt);
  105247. v = sqlite3GetVdbe(pParse);
  105248. sqlite3ChangeCookie(pParse, iDb);
  105249. sqlite3VdbeAddOp2(v, OP_Expire, 0, 0);
  105250. zWhere = sqlite3MPrintf(db, "name='%q' AND type='table'", pTab->zName);
  105251. sqlite3VdbeAddParseSchemaOp(v, iDb, zWhere);
  105252. sqlite3VdbeAddOp4(v, OP_VCreate, iDb, 0, 0,
  105253. pTab->zName, sqlite3Strlen30(pTab->zName) + 1);
  105254. }
  105255. /* If we are rereading the sqlite_master table create the in-memory
  105256. ** record of the table. The xConnect() method is not called until
  105257. ** the first time the virtual table is used in an SQL statement. This
  105258. ** allows a schema that contains virtual tables to be loaded before
  105259. ** the required virtual table implementations are registered. */
  105260. else {
  105261. Table *pOld;
  105262. Schema *pSchema = pTab->pSchema;
  105263. const char *zName = pTab->zName;
  105264. assert( sqlite3SchemaMutexHeld(db, 0, pSchema) );
  105265. pOld = sqlite3HashInsert(&pSchema->tblHash, zName, pTab);
  105266. if( pOld ){
  105267. db->mallocFailed = 1;
  105268. assert( pTab==pOld ); /* Malloc must have failed inside HashInsert() */
  105269. return;
  105270. }
  105271. pParse->pNewTable = 0;
  105272. }
  105273. }
  105274. /*
  105275. ** The parser calls this routine when it sees the first token
  105276. ** of an argument to the module name in a CREATE VIRTUAL TABLE statement.
  105277. */
  105278. SQLITE_PRIVATE void sqlite3VtabArgInit(Parse *pParse){
  105279. addArgumentToVtab(pParse);
  105280. pParse->sArg.z = 0;
  105281. pParse->sArg.n = 0;
  105282. }
  105283. /*
  105284. ** The parser calls this routine for each token after the first token
  105285. ** in an argument to the module name in a CREATE VIRTUAL TABLE statement.
  105286. */
  105287. SQLITE_PRIVATE void sqlite3VtabArgExtend(Parse *pParse, Token *p){
  105288. Token *pArg = &pParse->sArg;
  105289. if( pArg->z==0 ){
  105290. pArg->z = p->z;
  105291. pArg->n = p->n;
  105292. }else{
  105293. assert(pArg->z < p->z);
  105294. pArg->n = (int)(&p->z[p->n] - pArg->z);
  105295. }
  105296. }
  105297. /*
  105298. ** Invoke a virtual table constructor (either xCreate or xConnect). The
  105299. ** pointer to the function to invoke is passed as the fourth parameter
  105300. ** to this procedure.
  105301. */
  105302. static int vtabCallConstructor(
  105303. sqlite3 *db,
  105304. Table *pTab,
  105305. Module *pMod,
  105306. int (*xConstruct)(sqlite3*,void*,int,const char*const*,sqlite3_vtab**,char**),
  105307. char **pzErr
  105308. ){
  105309. VtabCtx sCtx, *pPriorCtx;
  105310. VTable *pVTable;
  105311. int rc;
  105312. const char *const*azArg = (const char *const*)pTab->azModuleArg;
  105313. int nArg = pTab->nModuleArg;
  105314. char *zErr = 0;
  105315. char *zModuleName = sqlite3MPrintf(db, "%s", pTab->zName);
  105316. int iDb;
  105317. if( !zModuleName ){
  105318. return SQLITE_NOMEM;
  105319. }
  105320. pVTable = sqlite3DbMallocZero(db, sizeof(VTable));
  105321. if( !pVTable ){
  105322. sqlite3DbFree(db, zModuleName);
  105323. return SQLITE_NOMEM;
  105324. }
  105325. pVTable->db = db;
  105326. pVTable->pMod = pMod;
  105327. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  105328. pTab->azModuleArg[1] = db->aDb[iDb].zName;
  105329. /* Invoke the virtual table constructor */
  105330. assert( &db->pVtabCtx );
  105331. assert( xConstruct );
  105332. sCtx.pTab = pTab;
  105333. sCtx.pVTable = pVTable;
  105334. pPriorCtx = db->pVtabCtx;
  105335. db->pVtabCtx = &sCtx;
  105336. rc = xConstruct(db, pMod->pAux, nArg, azArg, &pVTable->pVtab, &zErr);
  105337. db->pVtabCtx = pPriorCtx;
  105338. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  105339. if( SQLITE_OK!=rc ){
  105340. if( zErr==0 ){
  105341. *pzErr = sqlite3MPrintf(db, "vtable constructor failed: %s", zModuleName);
  105342. }else {
  105343. *pzErr = sqlite3MPrintf(db, "%s", zErr);
  105344. sqlite3_free(zErr);
  105345. }
  105346. sqlite3DbFree(db, pVTable);
  105347. }else if( ALWAYS(pVTable->pVtab) ){
  105348. /* Justification of ALWAYS(): A correct vtab constructor must allocate
  105349. ** the sqlite3_vtab object if successful. */
  105350. memset(pVTable->pVtab, 0, sizeof(pVTable->pVtab[0]));
  105351. pVTable->pVtab->pModule = pMod->pModule;
  105352. pVTable->nRef = 1;
  105353. if( sCtx.pTab ){
  105354. const char *zFormat = "vtable constructor did not declare schema: %s";
  105355. *pzErr = sqlite3MPrintf(db, zFormat, pTab->zName);
  105356. sqlite3VtabUnlock(pVTable);
  105357. rc = SQLITE_ERROR;
  105358. }else{
  105359. int iCol;
  105360. /* If everything went according to plan, link the new VTable structure
  105361. ** into the linked list headed by pTab->pVTable. Then loop through the
  105362. ** columns of the table to see if any of them contain the token "hidden".
  105363. ** If so, set the Column COLFLAG_HIDDEN flag and remove the token from
  105364. ** the type string. */
  105365. pVTable->pNext = pTab->pVTable;
  105366. pTab->pVTable = pVTable;
  105367. for(iCol=0; iCol<pTab->nCol; iCol++){
  105368. char *zType = pTab->aCol[iCol].zType;
  105369. int nType;
  105370. int i = 0;
  105371. if( !zType ) continue;
  105372. nType = sqlite3Strlen30(zType);
  105373. if( sqlite3StrNICmp("hidden", zType, 6)||(zType[6] && zType[6]!=' ') ){
  105374. for(i=0; i<nType; i++){
  105375. if( (0==sqlite3StrNICmp(" hidden", &zType[i], 7))
  105376. && (zType[i+7]=='\0' || zType[i+7]==' ')
  105377. ){
  105378. i++;
  105379. break;
  105380. }
  105381. }
  105382. }
  105383. if( i<nType ){
  105384. int j;
  105385. int nDel = 6 + (zType[i+6] ? 1 : 0);
  105386. for(j=i; (j+nDel)<=nType; j++){
  105387. zType[j] = zType[j+nDel];
  105388. }
  105389. if( zType[i]=='\0' && i>0 ){
  105390. assert(zType[i-1]==' ');
  105391. zType[i-1] = '\0';
  105392. }
  105393. pTab->aCol[iCol].colFlags |= COLFLAG_HIDDEN;
  105394. }
  105395. }
  105396. }
  105397. }
  105398. sqlite3DbFree(db, zModuleName);
  105399. return rc;
  105400. }
  105401. /*
  105402. ** This function is invoked by the parser to call the xConnect() method
  105403. ** of the virtual table pTab. If an error occurs, an error code is returned
  105404. ** and an error left in pParse.
  105405. **
  105406. ** This call is a no-op if table pTab is not a virtual table.
  105407. */
  105408. SQLITE_PRIVATE int sqlite3VtabCallConnect(Parse *pParse, Table *pTab){
  105409. sqlite3 *db = pParse->db;
  105410. const char *zMod;
  105411. Module *pMod;
  105412. int rc;
  105413. assert( pTab );
  105414. if( (pTab->tabFlags & TF_Virtual)==0 || sqlite3GetVTable(db, pTab) ){
  105415. return SQLITE_OK;
  105416. }
  105417. /* Locate the required virtual table module */
  105418. zMod = pTab->azModuleArg[0];
  105419. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  105420. if( !pMod ){
  105421. const char *zModule = pTab->azModuleArg[0];
  105422. sqlite3ErrorMsg(pParse, "no such module: %s", zModule);
  105423. rc = SQLITE_ERROR;
  105424. }else{
  105425. char *zErr = 0;
  105426. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xConnect, &zErr);
  105427. if( rc!=SQLITE_OK ){
  105428. sqlite3ErrorMsg(pParse, "%s", zErr);
  105429. }
  105430. sqlite3DbFree(db, zErr);
  105431. }
  105432. return rc;
  105433. }
  105434. /*
  105435. ** Grow the db->aVTrans[] array so that there is room for at least one
  105436. ** more v-table. Return SQLITE_NOMEM if a malloc fails, or SQLITE_OK otherwise.
  105437. */
  105438. static int growVTrans(sqlite3 *db){
  105439. const int ARRAY_INCR = 5;
  105440. /* Grow the sqlite3.aVTrans array if required */
  105441. if( (db->nVTrans%ARRAY_INCR)==0 ){
  105442. VTable **aVTrans;
  105443. int nBytes = sizeof(sqlite3_vtab *) * (db->nVTrans + ARRAY_INCR);
  105444. aVTrans = sqlite3DbRealloc(db, (void *)db->aVTrans, nBytes);
  105445. if( !aVTrans ){
  105446. return SQLITE_NOMEM;
  105447. }
  105448. memset(&aVTrans[db->nVTrans], 0, sizeof(sqlite3_vtab *)*ARRAY_INCR);
  105449. db->aVTrans = aVTrans;
  105450. }
  105451. return SQLITE_OK;
  105452. }
  105453. /*
  105454. ** Add the virtual table pVTab to the array sqlite3.aVTrans[]. Space should
  105455. ** have already been reserved using growVTrans().
  105456. */
  105457. static void addToVTrans(sqlite3 *db, VTable *pVTab){
  105458. /* Add pVtab to the end of sqlite3.aVTrans */
  105459. db->aVTrans[db->nVTrans++] = pVTab;
  105460. sqlite3VtabLock(pVTab);
  105461. }
  105462. /*
  105463. ** This function is invoked by the vdbe to call the xCreate method
  105464. ** of the virtual table named zTab in database iDb.
  105465. **
  105466. ** If an error occurs, *pzErr is set to point an an English language
  105467. ** description of the error and an SQLITE_XXX error code is returned.
  105468. ** In this case the caller must call sqlite3DbFree(db, ) on *pzErr.
  105469. */
  105470. SQLITE_PRIVATE int sqlite3VtabCallCreate(sqlite3 *db, int iDb, const char *zTab, char **pzErr){
  105471. int rc = SQLITE_OK;
  105472. Table *pTab;
  105473. Module *pMod;
  105474. const char *zMod;
  105475. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  105476. assert( pTab && (pTab->tabFlags & TF_Virtual)!=0 && !pTab->pVTable );
  105477. /* Locate the required virtual table module */
  105478. zMod = pTab->azModuleArg[0];
  105479. pMod = (Module*)sqlite3HashFind(&db->aModule, zMod);
  105480. /* If the module has been registered and includes a Create method,
  105481. ** invoke it now. If the module has not been registered, return an
  105482. ** error. Otherwise, do nothing.
  105483. */
  105484. if( !pMod ){
  105485. *pzErr = sqlite3MPrintf(db, "no such module: %s", zMod);
  105486. rc = SQLITE_ERROR;
  105487. }else{
  105488. rc = vtabCallConstructor(db, pTab, pMod, pMod->pModule->xCreate, pzErr);
  105489. }
  105490. /* Justification of ALWAYS(): The xConstructor method is required to
  105491. ** create a valid sqlite3_vtab if it returns SQLITE_OK. */
  105492. if( rc==SQLITE_OK && ALWAYS(sqlite3GetVTable(db, pTab)) ){
  105493. rc = growVTrans(db);
  105494. if( rc==SQLITE_OK ){
  105495. addToVTrans(db, sqlite3GetVTable(db, pTab));
  105496. }
  105497. }
  105498. return rc;
  105499. }
  105500. /*
  105501. ** This function is used to set the schema of a virtual table. It is only
  105502. ** valid to call this function from within the xCreate() or xConnect() of a
  105503. ** virtual table module.
  105504. */
  105505. SQLITE_API int sqlite3_declare_vtab(sqlite3 *db, const char *zCreateTable){
  105506. Parse *pParse;
  105507. int rc = SQLITE_OK;
  105508. Table *pTab;
  105509. char *zErr = 0;
  105510. sqlite3_mutex_enter(db->mutex);
  105511. if( !db->pVtabCtx || !(pTab = db->pVtabCtx->pTab) ){
  105512. sqlite3Error(db, SQLITE_MISUSE);
  105513. sqlite3_mutex_leave(db->mutex);
  105514. return SQLITE_MISUSE_BKPT;
  105515. }
  105516. assert( (pTab->tabFlags & TF_Virtual)!=0 );
  105517. pParse = sqlite3StackAllocZero(db, sizeof(*pParse));
  105518. if( pParse==0 ){
  105519. rc = SQLITE_NOMEM;
  105520. }else{
  105521. pParse->declareVtab = 1;
  105522. pParse->db = db;
  105523. pParse->nQueryLoop = 1;
  105524. if( SQLITE_OK==sqlite3RunParser(pParse, zCreateTable, &zErr)
  105525. && pParse->pNewTable
  105526. && !db->mallocFailed
  105527. && !pParse->pNewTable->pSelect
  105528. && (pParse->pNewTable->tabFlags & TF_Virtual)==0
  105529. ){
  105530. if( !pTab->aCol ){
  105531. pTab->aCol = pParse->pNewTable->aCol;
  105532. pTab->nCol = pParse->pNewTable->nCol;
  105533. pParse->pNewTable->nCol = 0;
  105534. pParse->pNewTable->aCol = 0;
  105535. }
  105536. db->pVtabCtx->pTab = 0;
  105537. }else{
  105538. sqlite3ErrorWithMsg(db, SQLITE_ERROR, (zErr ? "%s" : 0), zErr);
  105539. sqlite3DbFree(db, zErr);
  105540. rc = SQLITE_ERROR;
  105541. }
  105542. pParse->declareVtab = 0;
  105543. if( pParse->pVdbe ){
  105544. sqlite3VdbeFinalize(pParse->pVdbe);
  105545. }
  105546. sqlite3DeleteTable(db, pParse->pNewTable);
  105547. sqlite3ParserReset(pParse);
  105548. sqlite3StackFree(db, pParse);
  105549. }
  105550. assert( (rc&0xff)==rc );
  105551. rc = sqlite3ApiExit(db, rc);
  105552. sqlite3_mutex_leave(db->mutex);
  105553. return rc;
  105554. }
  105555. /*
  105556. ** This function is invoked by the vdbe to call the xDestroy method
  105557. ** of the virtual table named zTab in database iDb. This occurs
  105558. ** when a DROP TABLE is mentioned.
  105559. **
  105560. ** This call is a no-op if zTab is not a virtual table.
  105561. */
  105562. SQLITE_PRIVATE int sqlite3VtabCallDestroy(sqlite3 *db, int iDb, const char *zTab){
  105563. int rc = SQLITE_OK;
  105564. Table *pTab;
  105565. pTab = sqlite3FindTable(db, zTab, db->aDb[iDb].zName);
  105566. if( ALWAYS(pTab!=0 && pTab->pVTable!=0) ){
  105567. VTable *p = vtabDisconnectAll(db, pTab);
  105568. assert( rc==SQLITE_OK );
  105569. rc = p->pMod->pModule->xDestroy(p->pVtab);
  105570. /* Remove the sqlite3_vtab* from the aVTrans[] array, if applicable */
  105571. if( rc==SQLITE_OK ){
  105572. assert( pTab->pVTable==p && p->pNext==0 );
  105573. p->pVtab = 0;
  105574. pTab->pVTable = 0;
  105575. sqlite3VtabUnlock(p);
  105576. }
  105577. }
  105578. return rc;
  105579. }
  105580. /*
  105581. ** This function invokes either the xRollback or xCommit method
  105582. ** of each of the virtual tables in the sqlite3.aVTrans array. The method
  105583. ** called is identified by the second argument, "offset", which is
  105584. ** the offset of the method to call in the sqlite3_module structure.
  105585. **
  105586. ** The array is cleared after invoking the callbacks.
  105587. */
  105588. static void callFinaliser(sqlite3 *db, int offset){
  105589. int i;
  105590. if( db->aVTrans ){
  105591. for(i=0; i<db->nVTrans; i++){
  105592. VTable *pVTab = db->aVTrans[i];
  105593. sqlite3_vtab *p = pVTab->pVtab;
  105594. if( p ){
  105595. int (*x)(sqlite3_vtab *);
  105596. x = *(int (**)(sqlite3_vtab *))((char *)p->pModule + offset);
  105597. if( x ) x(p);
  105598. }
  105599. pVTab->iSavepoint = 0;
  105600. sqlite3VtabUnlock(pVTab);
  105601. }
  105602. sqlite3DbFree(db, db->aVTrans);
  105603. db->nVTrans = 0;
  105604. db->aVTrans = 0;
  105605. }
  105606. }
  105607. /*
  105608. ** Invoke the xSync method of all virtual tables in the sqlite3.aVTrans
  105609. ** array. Return the error code for the first error that occurs, or
  105610. ** SQLITE_OK if all xSync operations are successful.
  105611. **
  105612. ** If an error message is available, leave it in p->zErrMsg.
  105613. */
  105614. SQLITE_PRIVATE int sqlite3VtabSync(sqlite3 *db, Vdbe *p){
  105615. int i;
  105616. int rc = SQLITE_OK;
  105617. VTable **aVTrans = db->aVTrans;
  105618. db->aVTrans = 0;
  105619. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  105620. int (*x)(sqlite3_vtab *);
  105621. sqlite3_vtab *pVtab = aVTrans[i]->pVtab;
  105622. if( pVtab && (x = pVtab->pModule->xSync)!=0 ){
  105623. rc = x(pVtab);
  105624. sqlite3VtabImportErrmsg(p, pVtab);
  105625. }
  105626. }
  105627. db->aVTrans = aVTrans;
  105628. return rc;
  105629. }
  105630. /*
  105631. ** Invoke the xRollback method of all virtual tables in the
  105632. ** sqlite3.aVTrans array. Then clear the array itself.
  105633. */
  105634. SQLITE_PRIVATE int sqlite3VtabRollback(sqlite3 *db){
  105635. callFinaliser(db, offsetof(sqlite3_module,xRollback));
  105636. return SQLITE_OK;
  105637. }
  105638. /*
  105639. ** Invoke the xCommit method of all virtual tables in the
  105640. ** sqlite3.aVTrans array. Then clear the array itself.
  105641. */
  105642. SQLITE_PRIVATE int sqlite3VtabCommit(sqlite3 *db){
  105643. callFinaliser(db, offsetof(sqlite3_module,xCommit));
  105644. return SQLITE_OK;
  105645. }
  105646. /*
  105647. ** If the virtual table pVtab supports the transaction interface
  105648. ** (xBegin/xRollback/xCommit and optionally xSync) and a transaction is
  105649. ** not currently open, invoke the xBegin method now.
  105650. **
  105651. ** If the xBegin call is successful, place the sqlite3_vtab pointer
  105652. ** in the sqlite3.aVTrans array.
  105653. */
  105654. SQLITE_PRIVATE int sqlite3VtabBegin(sqlite3 *db, VTable *pVTab){
  105655. int rc = SQLITE_OK;
  105656. const sqlite3_module *pModule;
  105657. /* Special case: If db->aVTrans is NULL and db->nVTrans is greater
  105658. ** than zero, then this function is being called from within a
  105659. ** virtual module xSync() callback. It is illegal to write to
  105660. ** virtual module tables in this case, so return SQLITE_LOCKED.
  105661. */
  105662. if( sqlite3VtabInSync(db) ){
  105663. return SQLITE_LOCKED;
  105664. }
  105665. if( !pVTab ){
  105666. return SQLITE_OK;
  105667. }
  105668. pModule = pVTab->pVtab->pModule;
  105669. if( pModule->xBegin ){
  105670. int i;
  105671. /* If pVtab is already in the aVTrans array, return early */
  105672. for(i=0; i<db->nVTrans; i++){
  105673. if( db->aVTrans[i]==pVTab ){
  105674. return SQLITE_OK;
  105675. }
  105676. }
  105677. /* Invoke the xBegin method. If successful, add the vtab to the
  105678. ** sqlite3.aVTrans[] array. */
  105679. rc = growVTrans(db);
  105680. if( rc==SQLITE_OK ){
  105681. rc = pModule->xBegin(pVTab->pVtab);
  105682. if( rc==SQLITE_OK ){
  105683. addToVTrans(db, pVTab);
  105684. }
  105685. }
  105686. }
  105687. return rc;
  105688. }
  105689. /*
  105690. ** Invoke either the xSavepoint, xRollbackTo or xRelease method of all
  105691. ** virtual tables that currently have an open transaction. Pass iSavepoint
  105692. ** as the second argument to the virtual table method invoked.
  105693. **
  105694. ** If op is SAVEPOINT_BEGIN, the xSavepoint method is invoked. If it is
  105695. ** SAVEPOINT_ROLLBACK, the xRollbackTo method. Otherwise, if op is
  105696. ** SAVEPOINT_RELEASE, then the xRelease method of each virtual table with
  105697. ** an open transaction is invoked.
  105698. **
  105699. ** If any virtual table method returns an error code other than SQLITE_OK,
  105700. ** processing is abandoned and the error returned to the caller of this
  105701. ** function immediately. If all calls to virtual table methods are successful,
  105702. ** SQLITE_OK is returned.
  105703. */
  105704. SQLITE_PRIVATE int sqlite3VtabSavepoint(sqlite3 *db, int op, int iSavepoint){
  105705. int rc = SQLITE_OK;
  105706. assert( op==SAVEPOINT_RELEASE||op==SAVEPOINT_ROLLBACK||op==SAVEPOINT_BEGIN );
  105707. assert( iSavepoint>=0 );
  105708. if( db->aVTrans ){
  105709. int i;
  105710. for(i=0; rc==SQLITE_OK && i<db->nVTrans; i++){
  105711. VTable *pVTab = db->aVTrans[i];
  105712. const sqlite3_module *pMod = pVTab->pMod->pModule;
  105713. if( pVTab->pVtab && pMod->iVersion>=2 ){
  105714. int (*xMethod)(sqlite3_vtab *, int);
  105715. switch( op ){
  105716. case SAVEPOINT_BEGIN:
  105717. xMethod = pMod->xSavepoint;
  105718. pVTab->iSavepoint = iSavepoint+1;
  105719. break;
  105720. case SAVEPOINT_ROLLBACK:
  105721. xMethod = pMod->xRollbackTo;
  105722. break;
  105723. default:
  105724. xMethod = pMod->xRelease;
  105725. break;
  105726. }
  105727. if( xMethod && pVTab->iSavepoint>iSavepoint ){
  105728. rc = xMethod(pVTab->pVtab, iSavepoint);
  105729. }
  105730. }
  105731. }
  105732. }
  105733. return rc;
  105734. }
  105735. /*
  105736. ** The first parameter (pDef) is a function implementation. The
  105737. ** second parameter (pExpr) is the first argument to this function.
  105738. ** If pExpr is a column in a virtual table, then let the virtual
  105739. ** table implementation have an opportunity to overload the function.
  105740. **
  105741. ** This routine is used to allow virtual table implementations to
  105742. ** overload MATCH, LIKE, GLOB, and REGEXP operators.
  105743. **
  105744. ** Return either the pDef argument (indicating no change) or a
  105745. ** new FuncDef structure that is marked as ephemeral using the
  105746. ** SQLITE_FUNC_EPHEM flag.
  105747. */
  105748. SQLITE_PRIVATE FuncDef *sqlite3VtabOverloadFunction(
  105749. sqlite3 *db, /* Database connection for reporting malloc problems */
  105750. FuncDef *pDef, /* Function to possibly overload */
  105751. int nArg, /* Number of arguments to the function */
  105752. Expr *pExpr /* First argument to the function */
  105753. ){
  105754. Table *pTab;
  105755. sqlite3_vtab *pVtab;
  105756. sqlite3_module *pMod;
  105757. void (*xFunc)(sqlite3_context*,int,sqlite3_value**) = 0;
  105758. void *pArg = 0;
  105759. FuncDef *pNew;
  105760. int rc = 0;
  105761. char *zLowerName;
  105762. unsigned char *z;
  105763. /* Check to see the left operand is a column in a virtual table */
  105764. if( NEVER(pExpr==0) ) return pDef;
  105765. if( pExpr->op!=TK_COLUMN ) return pDef;
  105766. pTab = pExpr->pTab;
  105767. if( NEVER(pTab==0) ) return pDef;
  105768. if( (pTab->tabFlags & TF_Virtual)==0 ) return pDef;
  105769. pVtab = sqlite3GetVTable(db, pTab)->pVtab;
  105770. assert( pVtab!=0 );
  105771. assert( pVtab->pModule!=0 );
  105772. pMod = (sqlite3_module *)pVtab->pModule;
  105773. if( pMod->xFindFunction==0 ) return pDef;
  105774. /* Call the xFindFunction method on the virtual table implementation
  105775. ** to see if the implementation wants to overload this function
  105776. */
  105777. zLowerName = sqlite3DbStrDup(db, pDef->zName);
  105778. if( zLowerName ){
  105779. for(z=(unsigned char*)zLowerName; *z; z++){
  105780. *z = sqlite3UpperToLower[*z];
  105781. }
  105782. rc = pMod->xFindFunction(pVtab, nArg, zLowerName, &xFunc, &pArg);
  105783. sqlite3DbFree(db, zLowerName);
  105784. }
  105785. if( rc==0 ){
  105786. return pDef;
  105787. }
  105788. /* Create a new ephemeral function definition for the overloaded
  105789. ** function */
  105790. pNew = sqlite3DbMallocZero(db, sizeof(*pNew)
  105791. + sqlite3Strlen30(pDef->zName) + 1);
  105792. if( pNew==0 ){
  105793. return pDef;
  105794. }
  105795. *pNew = *pDef;
  105796. pNew->zName = (char *)&pNew[1];
  105797. memcpy(pNew->zName, pDef->zName, sqlite3Strlen30(pDef->zName)+1);
  105798. pNew->xFunc = xFunc;
  105799. pNew->pUserData = pArg;
  105800. pNew->funcFlags |= SQLITE_FUNC_EPHEM;
  105801. return pNew;
  105802. }
  105803. /*
  105804. ** Make sure virtual table pTab is contained in the pParse->apVirtualLock[]
  105805. ** array so that an OP_VBegin will get generated for it. Add pTab to the
  105806. ** array if it is missing. If pTab is already in the array, this routine
  105807. ** is a no-op.
  105808. */
  105809. SQLITE_PRIVATE void sqlite3VtabMakeWritable(Parse *pParse, Table *pTab){
  105810. Parse *pToplevel = sqlite3ParseToplevel(pParse);
  105811. int i, n;
  105812. Table **apVtabLock;
  105813. assert( IsVirtual(pTab) );
  105814. for(i=0; i<pToplevel->nVtabLock; i++){
  105815. if( pTab==pToplevel->apVtabLock[i] ) return;
  105816. }
  105817. n = (pToplevel->nVtabLock+1)*sizeof(pToplevel->apVtabLock[0]);
  105818. apVtabLock = sqlite3_realloc(pToplevel->apVtabLock, n);
  105819. if( apVtabLock ){
  105820. pToplevel->apVtabLock = apVtabLock;
  105821. pToplevel->apVtabLock[pToplevel->nVtabLock++] = pTab;
  105822. }else{
  105823. pToplevel->db->mallocFailed = 1;
  105824. }
  105825. }
  105826. /*
  105827. ** Return the ON CONFLICT resolution mode in effect for the virtual
  105828. ** table update operation currently in progress.
  105829. **
  105830. ** The results of this routine are undefined unless it is called from
  105831. ** within an xUpdate method.
  105832. */
  105833. SQLITE_API int sqlite3_vtab_on_conflict(sqlite3 *db){
  105834. static const unsigned char aMap[] = {
  105835. SQLITE_ROLLBACK, SQLITE_ABORT, SQLITE_FAIL, SQLITE_IGNORE, SQLITE_REPLACE
  105836. };
  105837. assert( OE_Rollback==1 && OE_Abort==2 && OE_Fail==3 );
  105838. assert( OE_Ignore==4 && OE_Replace==5 );
  105839. assert( db->vtabOnConflict>=1 && db->vtabOnConflict<=5 );
  105840. return (int)aMap[db->vtabOnConflict-1];
  105841. }
  105842. /*
  105843. ** Call from within the xCreate() or xConnect() methods to provide
  105844. ** the SQLite core with additional information about the behavior
  105845. ** of the virtual table being implemented.
  105846. */
  105847. SQLITE_API int sqlite3_vtab_config(sqlite3 *db, int op, ...){
  105848. va_list ap;
  105849. int rc = SQLITE_OK;
  105850. sqlite3_mutex_enter(db->mutex);
  105851. va_start(ap, op);
  105852. switch( op ){
  105853. case SQLITE_VTAB_CONSTRAINT_SUPPORT: {
  105854. VtabCtx *p = db->pVtabCtx;
  105855. if( !p ){
  105856. rc = SQLITE_MISUSE_BKPT;
  105857. }else{
  105858. assert( p->pTab==0 || (p->pTab->tabFlags & TF_Virtual)!=0 );
  105859. p->pVTable->bConstraint = (u8)va_arg(ap, int);
  105860. }
  105861. break;
  105862. }
  105863. default:
  105864. rc = SQLITE_MISUSE_BKPT;
  105865. break;
  105866. }
  105867. va_end(ap);
  105868. if( rc!=SQLITE_OK ) sqlite3Error(db, rc);
  105869. sqlite3_mutex_leave(db->mutex);
  105870. return rc;
  105871. }
  105872. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  105873. /************** End of vtab.c ************************************************/
  105874. /************** Begin file where.c *******************************************/
  105875. /*
  105876. ** 2001 September 15
  105877. **
  105878. ** The author disclaims copyright to this source code. In place of
  105879. ** a legal notice, here is a blessing:
  105880. **
  105881. ** May you do good and not evil.
  105882. ** May you find forgiveness for yourself and forgive others.
  105883. ** May you share freely, never taking more than you give.
  105884. **
  105885. *************************************************************************
  105886. ** This module contains C code that generates VDBE code used to process
  105887. ** the WHERE clause of SQL statements. This module is responsible for
  105888. ** generating the code that loops through a table looking for applicable
  105889. ** rows. Indices are selected and used to speed the search when doing
  105890. ** so is applicable. Because this module is responsible for selecting
  105891. ** indices, you might also think of this module as the "query optimizer".
  105892. */
  105893. /************** Include whereInt.h in the middle of where.c ******************/
  105894. /************** Begin file whereInt.h ****************************************/
  105895. /*
  105896. ** 2013-11-12
  105897. **
  105898. ** The author disclaims copyright to this source code. In place of
  105899. ** a legal notice, here is a blessing:
  105900. **
  105901. ** May you do good and not evil.
  105902. ** May you find forgiveness for yourself and forgive others.
  105903. ** May you share freely, never taking more than you give.
  105904. **
  105905. *************************************************************************
  105906. **
  105907. ** This file contains structure and macro definitions for the query
  105908. ** planner logic in "where.c". These definitions are broken out into
  105909. ** a separate source file for easier editing.
  105910. */
  105911. /*
  105912. ** Trace output macros
  105913. */
  105914. #if defined(SQLITE_TEST) || defined(SQLITE_DEBUG)
  105915. /***/ int sqlite3WhereTrace = 0;
  105916. #endif
  105917. #if defined(SQLITE_DEBUG) \
  105918. && (defined(SQLITE_TEST) || defined(SQLITE_ENABLE_WHERETRACE))
  105919. # define WHERETRACE(K,X) if(sqlite3WhereTrace&(K)) sqlite3DebugPrintf X
  105920. # define WHERETRACE_ENABLED 1
  105921. #else
  105922. # define WHERETRACE(K,X)
  105923. #endif
  105924. /* Forward references
  105925. */
  105926. typedef struct WhereClause WhereClause;
  105927. typedef struct WhereMaskSet WhereMaskSet;
  105928. typedef struct WhereOrInfo WhereOrInfo;
  105929. typedef struct WhereAndInfo WhereAndInfo;
  105930. typedef struct WhereLevel WhereLevel;
  105931. typedef struct WhereLoop WhereLoop;
  105932. typedef struct WherePath WherePath;
  105933. typedef struct WhereTerm WhereTerm;
  105934. typedef struct WhereLoopBuilder WhereLoopBuilder;
  105935. typedef struct WhereScan WhereScan;
  105936. typedef struct WhereOrCost WhereOrCost;
  105937. typedef struct WhereOrSet WhereOrSet;
  105938. /*
  105939. ** This object contains information needed to implement a single nested
  105940. ** loop in WHERE clause.
  105941. **
  105942. ** Contrast this object with WhereLoop. This object describes the
  105943. ** implementation of the loop. WhereLoop describes the algorithm.
  105944. ** This object contains a pointer to the WhereLoop algorithm as one of
  105945. ** its elements.
  105946. **
  105947. ** The WhereInfo object contains a single instance of this object for
  105948. ** each term in the FROM clause (which is to say, for each of the
  105949. ** nested loops as implemented). The order of WhereLevel objects determines
  105950. ** the loop nested order, with WhereInfo.a[0] being the outer loop and
  105951. ** WhereInfo.a[WhereInfo.nLevel-1] being the inner loop.
  105952. */
  105953. struct WhereLevel {
  105954. int iLeftJoin; /* Memory cell used to implement LEFT OUTER JOIN */
  105955. int iTabCur; /* The VDBE cursor used to access the table */
  105956. int iIdxCur; /* The VDBE cursor used to access pIdx */
  105957. int addrBrk; /* Jump here to break out of the loop */
  105958. int addrNxt; /* Jump here to start the next IN combination */
  105959. int addrSkip; /* Jump here for next iteration of skip-scan */
  105960. int addrCont; /* Jump here to continue with the next loop cycle */
  105961. int addrFirst; /* First instruction of interior of the loop */
  105962. int addrBody; /* Beginning of the body of this loop */
  105963. u8 iFrom; /* Which entry in the FROM clause */
  105964. u8 op, p3, p5; /* Opcode, P3 & P5 of the opcode that ends the loop */
  105965. int p1, p2; /* Operands of the opcode used to ends the loop */
  105966. union { /* Information that depends on pWLoop->wsFlags */
  105967. struct {
  105968. int nIn; /* Number of entries in aInLoop[] */
  105969. struct InLoop {
  105970. int iCur; /* The VDBE cursor used by this IN operator */
  105971. int addrInTop; /* Top of the IN loop */
  105972. u8 eEndLoopOp; /* IN Loop terminator. OP_Next or OP_Prev */
  105973. } *aInLoop; /* Information about each nested IN operator */
  105974. } in; /* Used when pWLoop->wsFlags&WHERE_IN_ABLE */
  105975. Index *pCovidx; /* Possible covering index for WHERE_MULTI_OR */
  105976. } u;
  105977. struct WhereLoop *pWLoop; /* The selected WhereLoop object */
  105978. Bitmask notReady; /* FROM entries not usable at this level */
  105979. };
  105980. /*
  105981. ** Each instance of this object represents an algorithm for evaluating one
  105982. ** term of a join. Every term of the FROM clause will have at least
  105983. ** one corresponding WhereLoop object (unless INDEXED BY constraints
  105984. ** prevent a query solution - which is an error) and many terms of the
  105985. ** FROM clause will have multiple WhereLoop objects, each describing a
  105986. ** potential way of implementing that FROM-clause term, together with
  105987. ** dependencies and cost estimates for using the chosen algorithm.
  105988. **
  105989. ** Query planning consists of building up a collection of these WhereLoop
  105990. ** objects, then computing a particular sequence of WhereLoop objects, with
  105991. ** one WhereLoop object per FROM clause term, that satisfy all dependencies
  105992. ** and that minimize the overall cost.
  105993. */
  105994. struct WhereLoop {
  105995. Bitmask prereq; /* Bitmask of other loops that must run first */
  105996. Bitmask maskSelf; /* Bitmask identifying table iTab */
  105997. #ifdef SQLITE_DEBUG
  105998. char cId; /* Symbolic ID of this loop for debugging use */
  105999. #endif
  106000. u8 iTab; /* Position in FROM clause of table for this loop */
  106001. u8 iSortIdx; /* Sorting index number. 0==None */
  106002. LogEst rSetup; /* One-time setup cost (ex: create transient index) */
  106003. LogEst rRun; /* Cost of running each loop */
  106004. LogEst nOut; /* Estimated number of output rows */
  106005. union {
  106006. struct { /* Information for internal btree tables */
  106007. u16 nEq; /* Number of equality constraints */
  106008. u16 nSkip; /* Number of initial index columns to skip */
  106009. Index *pIndex; /* Index used, or NULL */
  106010. } btree;
  106011. struct { /* Information for virtual tables */
  106012. int idxNum; /* Index number */
  106013. u8 needFree; /* True if sqlite3_free(idxStr) is needed */
  106014. i8 isOrdered; /* True if satisfies ORDER BY */
  106015. u16 omitMask; /* Terms that may be omitted */
  106016. char *idxStr; /* Index identifier string */
  106017. } vtab;
  106018. } u;
  106019. u32 wsFlags; /* WHERE_* flags describing the plan */
  106020. u16 nLTerm; /* Number of entries in aLTerm[] */
  106021. /**** whereLoopXfer() copies fields above ***********************/
  106022. # define WHERE_LOOP_XFER_SZ offsetof(WhereLoop,nLSlot)
  106023. u16 nLSlot; /* Number of slots allocated for aLTerm[] */
  106024. WhereTerm **aLTerm; /* WhereTerms used */
  106025. WhereLoop *pNextLoop; /* Next WhereLoop object in the WhereClause */
  106026. WhereTerm *aLTermSpace[4]; /* Initial aLTerm[] space */
  106027. };
  106028. /* This object holds the prerequisites and the cost of running a
  106029. ** subquery on one operand of an OR operator in the WHERE clause.
  106030. ** See WhereOrSet for additional information
  106031. */
  106032. struct WhereOrCost {
  106033. Bitmask prereq; /* Prerequisites */
  106034. LogEst rRun; /* Cost of running this subquery */
  106035. LogEst nOut; /* Number of outputs for this subquery */
  106036. };
  106037. /* The WhereOrSet object holds a set of possible WhereOrCosts that
  106038. ** correspond to the subquery(s) of OR-clause processing. Only the
  106039. ** best N_OR_COST elements are retained.
  106040. */
  106041. #define N_OR_COST 3
  106042. struct WhereOrSet {
  106043. u16 n; /* Number of valid a[] entries */
  106044. WhereOrCost a[N_OR_COST]; /* Set of best costs */
  106045. };
  106046. /* Forward declaration of methods */
  106047. static int whereLoopResize(sqlite3*, WhereLoop*, int);
  106048. /*
  106049. ** Each instance of this object holds a sequence of WhereLoop objects
  106050. ** that implement some or all of a query plan.
  106051. **
  106052. ** Think of each WhereLoop object as a node in a graph with arcs
  106053. ** showing dependencies and costs for travelling between nodes. (That is
  106054. ** not a completely accurate description because WhereLoop costs are a
  106055. ** vector, not a scalar, and because dependencies are many-to-one, not
  106056. ** one-to-one as are graph nodes. But it is a useful visualization aid.)
  106057. ** Then a WherePath object is a path through the graph that visits some
  106058. ** or all of the WhereLoop objects once.
  106059. **
  106060. ** The "solver" works by creating the N best WherePath objects of length
  106061. ** 1. Then using those as a basis to compute the N best WherePath objects
  106062. ** of length 2. And so forth until the length of WherePaths equals the
  106063. ** number of nodes in the FROM clause. The best (lowest cost) WherePath
  106064. ** at the end is the chosen query plan.
  106065. */
  106066. struct WherePath {
  106067. Bitmask maskLoop; /* Bitmask of all WhereLoop objects in this path */
  106068. Bitmask revLoop; /* aLoop[]s that should be reversed for ORDER BY */
  106069. LogEst nRow; /* Estimated number of rows generated by this path */
  106070. LogEst rCost; /* Total cost of this path */
  106071. LogEst rUnsorted; /* Total cost of this path ignoring sorting costs */
  106072. i8 isOrdered; /* No. of ORDER BY terms satisfied. -1 for unknown */
  106073. WhereLoop **aLoop; /* Array of WhereLoop objects implementing this path */
  106074. };
  106075. /*
  106076. ** The query generator uses an array of instances of this structure to
  106077. ** help it analyze the subexpressions of the WHERE clause. Each WHERE
  106078. ** clause subexpression is separated from the others by AND operators,
  106079. ** usually, or sometimes subexpressions separated by OR.
  106080. **
  106081. ** All WhereTerms are collected into a single WhereClause structure.
  106082. ** The following identity holds:
  106083. **
  106084. ** WhereTerm.pWC->a[WhereTerm.idx] == WhereTerm
  106085. **
  106086. ** When a term is of the form:
  106087. **
  106088. ** X <op> <expr>
  106089. **
  106090. ** where X is a column name and <op> is one of certain operators,
  106091. ** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
  106092. ** cursor number and column number for X. WhereTerm.eOperator records
  106093. ** the <op> using a bitmask encoding defined by WO_xxx below. The
  106094. ** use of a bitmask encoding for the operator allows us to search
  106095. ** quickly for terms that match any of several different operators.
  106096. **
  106097. ** A WhereTerm might also be two or more subterms connected by OR:
  106098. **
  106099. ** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
  106100. **
  106101. ** In this second case, wtFlag has the TERM_ORINFO bit set and eOperator==WO_OR
  106102. ** and the WhereTerm.u.pOrInfo field points to auxiliary information that
  106103. ** is collected about the OR clause.
  106104. **
  106105. ** If a term in the WHERE clause does not match either of the two previous
  106106. ** categories, then eOperator==0. The WhereTerm.pExpr field is still set
  106107. ** to the original subexpression content and wtFlags is set up appropriately
  106108. ** but no other fields in the WhereTerm object are meaningful.
  106109. **
  106110. ** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
  106111. ** but they do so indirectly. A single WhereMaskSet structure translates
  106112. ** cursor number into bits and the translated bit is stored in the prereq
  106113. ** fields. The translation is used in order to maximize the number of
  106114. ** bits that will fit in a Bitmask. The VDBE cursor numbers might be
  106115. ** spread out over the non-negative integers. For example, the cursor
  106116. ** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
  106117. ** translates these sparse cursor numbers into consecutive integers
  106118. ** beginning with 0 in order to make the best possible use of the available
  106119. ** bits in the Bitmask. So, in the example above, the cursor numbers
  106120. ** would be mapped into integers 0 through 7.
  106121. **
  106122. ** The number of terms in a join is limited by the number of bits
  106123. ** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
  106124. ** is only able to process joins with 64 or fewer tables.
  106125. */
  106126. struct WhereTerm {
  106127. Expr *pExpr; /* Pointer to the subexpression that is this term */
  106128. int iParent; /* Disable pWC->a[iParent] when this term disabled */
  106129. int leftCursor; /* Cursor number of X in "X <op> <expr>" */
  106130. union {
  106131. int leftColumn; /* Column number of X in "X <op> <expr>" */
  106132. WhereOrInfo *pOrInfo; /* Extra information if (eOperator & WO_OR)!=0 */
  106133. WhereAndInfo *pAndInfo; /* Extra information if (eOperator& WO_AND)!=0 */
  106134. } u;
  106135. LogEst truthProb; /* Probability of truth for this expression */
  106136. u16 eOperator; /* A WO_xx value describing <op> */
  106137. u8 wtFlags; /* TERM_xxx bit flags. See below */
  106138. u8 nChild; /* Number of children that must disable us */
  106139. WhereClause *pWC; /* The clause this term is part of */
  106140. Bitmask prereqRight; /* Bitmask of tables used by pExpr->pRight */
  106141. Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
  106142. };
  106143. /*
  106144. ** Allowed values of WhereTerm.wtFlags
  106145. */
  106146. #define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, pExpr) */
  106147. #define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
  106148. #define TERM_CODED 0x04 /* This term is already coded */
  106149. #define TERM_COPIED 0x08 /* Has a child */
  106150. #define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
  106151. #define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
  106152. #define TERM_OR_OK 0x40 /* Used during OR-clause processing */
  106153. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106154. # define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
  106155. #else
  106156. # define TERM_VNULL 0x00 /* Disabled if not using stat3 */
  106157. #endif
  106158. /*
  106159. ** An instance of the WhereScan object is used as an iterator for locating
  106160. ** terms in the WHERE clause that are useful to the query planner.
  106161. */
  106162. struct WhereScan {
  106163. WhereClause *pOrigWC; /* Original, innermost WhereClause */
  106164. WhereClause *pWC; /* WhereClause currently being scanned */
  106165. char *zCollName; /* Required collating sequence, if not NULL */
  106166. char idxaff; /* Must match this affinity, if zCollName!=NULL */
  106167. unsigned char nEquiv; /* Number of entries in aEquiv[] */
  106168. unsigned char iEquiv; /* Next unused slot in aEquiv[] */
  106169. u32 opMask; /* Acceptable operators */
  106170. int k; /* Resume scanning at this->pWC->a[this->k] */
  106171. int aEquiv[22]; /* Cursor,Column pairs for equivalence classes */
  106172. };
  106173. /*
  106174. ** An instance of the following structure holds all information about a
  106175. ** WHERE clause. Mostly this is a container for one or more WhereTerms.
  106176. **
  106177. ** Explanation of pOuter: For a WHERE clause of the form
  106178. **
  106179. ** a AND ((b AND c) OR (d AND e)) AND f
  106180. **
  106181. ** There are separate WhereClause objects for the whole clause and for
  106182. ** the subclauses "(b AND c)" and "(d AND e)". The pOuter field of the
  106183. ** subclauses points to the WhereClause object for the whole clause.
  106184. */
  106185. struct WhereClause {
  106186. WhereInfo *pWInfo; /* WHERE clause processing context */
  106187. WhereClause *pOuter; /* Outer conjunction */
  106188. u8 op; /* Split operator. TK_AND or TK_OR */
  106189. int nTerm; /* Number of terms */
  106190. int nSlot; /* Number of entries in a[] */
  106191. WhereTerm *a; /* Each a[] describes a term of the WHERE cluase */
  106192. #if defined(SQLITE_SMALL_STACK)
  106193. WhereTerm aStatic[1]; /* Initial static space for a[] */
  106194. #else
  106195. WhereTerm aStatic[8]; /* Initial static space for a[] */
  106196. #endif
  106197. };
  106198. /*
  106199. ** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
  106200. ** a dynamically allocated instance of the following structure.
  106201. */
  106202. struct WhereOrInfo {
  106203. WhereClause wc; /* Decomposition into subterms */
  106204. Bitmask indexable; /* Bitmask of all indexable tables in the clause */
  106205. };
  106206. /*
  106207. ** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
  106208. ** a dynamically allocated instance of the following structure.
  106209. */
  106210. struct WhereAndInfo {
  106211. WhereClause wc; /* The subexpression broken out */
  106212. };
  106213. /*
  106214. ** An instance of the following structure keeps track of a mapping
  106215. ** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
  106216. **
  106217. ** The VDBE cursor numbers are small integers contained in
  106218. ** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
  106219. ** clause, the cursor numbers might not begin with 0 and they might
  106220. ** contain gaps in the numbering sequence. But we want to make maximum
  106221. ** use of the bits in our bitmasks. This structure provides a mapping
  106222. ** from the sparse cursor numbers into consecutive integers beginning
  106223. ** with 0.
  106224. **
  106225. ** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
  106226. ** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
  106227. **
  106228. ** For example, if the WHERE clause expression used these VDBE
  106229. ** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
  106230. ** would map those cursor numbers into bits 0 through 5.
  106231. **
  106232. ** Note that the mapping is not necessarily ordered. In the example
  106233. ** above, the mapping might go like this: 4->3, 5->1, 8->2, 29->0,
  106234. ** 57->5, 73->4. Or one of 719 other combinations might be used. It
  106235. ** does not really matter. What is important is that sparse cursor
  106236. ** numbers all get mapped into bit numbers that begin with 0 and contain
  106237. ** no gaps.
  106238. */
  106239. struct WhereMaskSet {
  106240. int n; /* Number of assigned cursor values */
  106241. int ix[BMS]; /* Cursor assigned to each bit */
  106242. };
  106243. /*
  106244. ** This object is a convenience wrapper holding all information needed
  106245. ** to construct WhereLoop objects for a particular query.
  106246. */
  106247. struct WhereLoopBuilder {
  106248. WhereInfo *pWInfo; /* Information about this WHERE */
  106249. WhereClause *pWC; /* WHERE clause terms */
  106250. ExprList *pOrderBy; /* ORDER BY clause */
  106251. WhereLoop *pNew; /* Template WhereLoop */
  106252. WhereOrSet *pOrSet; /* Record best loops here, if not NULL */
  106253. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  106254. UnpackedRecord *pRec; /* Probe for stat4 (if required) */
  106255. int nRecValid; /* Number of valid fields currently in pRec */
  106256. #endif
  106257. };
  106258. /*
  106259. ** The WHERE clause processing routine has two halves. The
  106260. ** first part does the start of the WHERE loop and the second
  106261. ** half does the tail of the WHERE loop. An instance of
  106262. ** this structure is returned by the first half and passed
  106263. ** into the second half to give some continuity.
  106264. **
  106265. ** An instance of this object holds the complete state of the query
  106266. ** planner.
  106267. */
  106268. struct WhereInfo {
  106269. Parse *pParse; /* Parsing and code generating context */
  106270. SrcList *pTabList; /* List of tables in the join */
  106271. ExprList *pOrderBy; /* The ORDER BY clause or NULL */
  106272. ExprList *pResultSet; /* Result set. DISTINCT operates on these */
  106273. WhereLoop *pLoops; /* List of all WhereLoop objects */
  106274. Bitmask revMask; /* Mask of ORDER BY terms that need reversing */
  106275. LogEst nRowOut; /* Estimated number of output rows */
  106276. u16 wctrlFlags; /* Flags originally passed to sqlite3WhereBegin() */
  106277. i8 nOBSat; /* Number of ORDER BY terms satisfied by indices */
  106278. u8 sorted; /* True if really sorted (not just grouped) */
  106279. u8 okOnePass; /* Ok to use one-pass algorithm for UPDATE/DELETE */
  106280. u8 untestedTerms; /* Not all WHERE terms resolved by outer loop */
  106281. u8 eDistinct; /* One of the WHERE_DISTINCT_* values below */
  106282. u8 nLevel; /* Number of nested loop */
  106283. int iTop; /* The very beginning of the WHERE loop */
  106284. int iContinue; /* Jump here to continue with next record */
  106285. int iBreak; /* Jump here to break out of the loop */
  106286. int savedNQueryLoop; /* pParse->nQueryLoop outside the WHERE loop */
  106287. int aiCurOnePass[2]; /* OP_OpenWrite cursors for the ONEPASS opt */
  106288. WhereMaskSet sMaskSet; /* Map cursor numbers to bitmasks */
  106289. WhereClause sWC; /* Decomposition of the WHERE clause */
  106290. WhereLevel a[1]; /* Information about each nest loop in WHERE */
  106291. };
  106292. /*
  106293. ** Bitmasks for the operators on WhereTerm objects. These are all
  106294. ** operators that are of interest to the query planner. An
  106295. ** OR-ed combination of these values can be used when searching for
  106296. ** particular WhereTerms within a WhereClause.
  106297. */
  106298. #define WO_IN 0x001
  106299. #define WO_EQ 0x002
  106300. #define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
  106301. #define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
  106302. #define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
  106303. #define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
  106304. #define WO_MATCH 0x040
  106305. #define WO_ISNULL 0x080
  106306. #define WO_OR 0x100 /* Two or more OR-connected terms */
  106307. #define WO_AND 0x200 /* Two or more AND-connected terms */
  106308. #define WO_EQUIV 0x400 /* Of the form A==B, both columns */
  106309. #define WO_NOOP 0x800 /* This term does not restrict search space */
  106310. #define WO_ALL 0xfff /* Mask of all possible WO_* values */
  106311. #define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
  106312. /*
  106313. ** These are definitions of bits in the WhereLoop.wsFlags field.
  106314. ** The particular combination of bits in each WhereLoop help to
  106315. ** determine the algorithm that WhereLoop represents.
  106316. */
  106317. #define WHERE_COLUMN_EQ 0x00000001 /* x=EXPR */
  106318. #define WHERE_COLUMN_RANGE 0x00000002 /* x<EXPR and/or x>EXPR */
  106319. #define WHERE_COLUMN_IN 0x00000004 /* x IN (...) */
  106320. #define WHERE_COLUMN_NULL 0x00000008 /* x IS NULL */
  106321. #define WHERE_CONSTRAINT 0x0000000f /* Any of the WHERE_COLUMN_xxx values */
  106322. #define WHERE_TOP_LIMIT 0x00000010 /* x<EXPR or x<=EXPR constraint */
  106323. #define WHERE_BTM_LIMIT 0x00000020 /* x>EXPR or x>=EXPR constraint */
  106324. #define WHERE_BOTH_LIMIT 0x00000030 /* Both x>EXPR and x<EXPR */
  106325. #define WHERE_IDX_ONLY 0x00000040 /* Use index only - omit table */
  106326. #define WHERE_IPK 0x00000100 /* x is the INTEGER PRIMARY KEY */
  106327. #define WHERE_INDEXED 0x00000200 /* WhereLoop.u.btree.pIndex is valid */
  106328. #define WHERE_VIRTUALTABLE 0x00000400 /* WhereLoop.u.vtab is valid */
  106329. #define WHERE_IN_ABLE 0x00000800 /* Able to support an IN operator */
  106330. #define WHERE_ONEROW 0x00001000 /* Selects no more than one row */
  106331. #define WHERE_MULTI_OR 0x00002000 /* OR using multiple indices */
  106332. #define WHERE_AUTO_INDEX 0x00004000 /* Uses an ephemeral index */
  106333. #define WHERE_SKIPSCAN 0x00008000 /* Uses the skip-scan algorithm */
  106334. #define WHERE_UNQ_WANTED 0x00010000 /* WHERE_ONEROW would have been helpful*/
  106335. /************** End of whereInt.h ********************************************/
  106336. /************** Continuing where we left off in where.c **********************/
  106337. /*
  106338. ** Return the estimated number of output rows from a WHERE clause
  106339. */
  106340. SQLITE_PRIVATE u64 sqlite3WhereOutputRowCount(WhereInfo *pWInfo){
  106341. return sqlite3LogEstToInt(pWInfo->nRowOut);
  106342. }
  106343. /*
  106344. ** Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
  106345. ** WHERE clause returns outputs for DISTINCT processing.
  106346. */
  106347. SQLITE_PRIVATE int sqlite3WhereIsDistinct(WhereInfo *pWInfo){
  106348. return pWInfo->eDistinct;
  106349. }
  106350. /*
  106351. ** Return TRUE if the WHERE clause returns rows in ORDER BY order.
  106352. ** Return FALSE if the output needs to be sorted.
  106353. */
  106354. SQLITE_PRIVATE int sqlite3WhereIsOrdered(WhereInfo *pWInfo){
  106355. return pWInfo->nOBSat;
  106356. }
  106357. /*
  106358. ** Return the VDBE address or label to jump to in order to continue
  106359. ** immediately with the next row of a WHERE clause.
  106360. */
  106361. SQLITE_PRIVATE int sqlite3WhereContinueLabel(WhereInfo *pWInfo){
  106362. assert( pWInfo->iContinue!=0 );
  106363. return pWInfo->iContinue;
  106364. }
  106365. /*
  106366. ** Return the VDBE address or label to jump to in order to break
  106367. ** out of a WHERE loop.
  106368. */
  106369. SQLITE_PRIVATE int sqlite3WhereBreakLabel(WhereInfo *pWInfo){
  106370. return pWInfo->iBreak;
  106371. }
  106372. /*
  106373. ** Return TRUE if an UPDATE or DELETE statement can operate directly on
  106374. ** the rowids returned by a WHERE clause. Return FALSE if doing an
  106375. ** UPDATE or DELETE might change subsequent WHERE clause results.
  106376. **
  106377. ** If the ONEPASS optimization is used (if this routine returns true)
  106378. ** then also write the indices of open cursors used by ONEPASS
  106379. ** into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
  106380. ** table and iaCur[1] gets the cursor used by an auxiliary index.
  106381. ** Either value may be -1, indicating that cursor is not used.
  106382. ** Any cursors returned will have been opened for writing.
  106383. **
  106384. ** aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
  106385. ** unable to use the ONEPASS optimization.
  106386. */
  106387. SQLITE_PRIVATE int sqlite3WhereOkOnePass(WhereInfo *pWInfo, int *aiCur){
  106388. memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int)*2);
  106389. return pWInfo->okOnePass;
  106390. }
  106391. /*
  106392. ** Move the content of pSrc into pDest
  106393. */
  106394. static void whereOrMove(WhereOrSet *pDest, WhereOrSet *pSrc){
  106395. pDest->n = pSrc->n;
  106396. memcpy(pDest->a, pSrc->a, pDest->n*sizeof(pDest->a[0]));
  106397. }
  106398. /*
  106399. ** Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
  106400. **
  106401. ** The new entry might overwrite an existing entry, or it might be
  106402. ** appended, or it might be discarded. Do whatever is the right thing
  106403. ** so that pSet keeps the N_OR_COST best entries seen so far.
  106404. */
  106405. static int whereOrInsert(
  106406. WhereOrSet *pSet, /* The WhereOrSet to be updated */
  106407. Bitmask prereq, /* Prerequisites of the new entry */
  106408. LogEst rRun, /* Run-cost of the new entry */
  106409. LogEst nOut /* Number of outputs for the new entry */
  106410. ){
  106411. u16 i;
  106412. WhereOrCost *p;
  106413. for(i=pSet->n, p=pSet->a; i>0; i--, p++){
  106414. if( rRun<=p->rRun && (prereq & p->prereq)==prereq ){
  106415. goto whereOrInsert_done;
  106416. }
  106417. if( p->rRun<=rRun && (p->prereq & prereq)==p->prereq ){
  106418. return 0;
  106419. }
  106420. }
  106421. if( pSet->n<N_OR_COST ){
  106422. p = &pSet->a[pSet->n++];
  106423. p->nOut = nOut;
  106424. }else{
  106425. p = pSet->a;
  106426. for(i=1; i<pSet->n; i++){
  106427. if( p->rRun>pSet->a[i].rRun ) p = pSet->a + i;
  106428. }
  106429. if( p->rRun<=rRun ) return 0;
  106430. }
  106431. whereOrInsert_done:
  106432. p->prereq = prereq;
  106433. p->rRun = rRun;
  106434. if( p->nOut>nOut ) p->nOut = nOut;
  106435. return 1;
  106436. }
  106437. /*
  106438. ** Initialize a preallocated WhereClause structure.
  106439. */
  106440. static void whereClauseInit(
  106441. WhereClause *pWC, /* The WhereClause to be initialized */
  106442. WhereInfo *pWInfo /* The WHERE processing context */
  106443. ){
  106444. pWC->pWInfo = pWInfo;
  106445. pWC->pOuter = 0;
  106446. pWC->nTerm = 0;
  106447. pWC->nSlot = ArraySize(pWC->aStatic);
  106448. pWC->a = pWC->aStatic;
  106449. }
  106450. /* Forward reference */
  106451. static void whereClauseClear(WhereClause*);
  106452. /*
  106453. ** Deallocate all memory associated with a WhereOrInfo object.
  106454. */
  106455. static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
  106456. whereClauseClear(&p->wc);
  106457. sqlite3DbFree(db, p);
  106458. }
  106459. /*
  106460. ** Deallocate all memory associated with a WhereAndInfo object.
  106461. */
  106462. static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
  106463. whereClauseClear(&p->wc);
  106464. sqlite3DbFree(db, p);
  106465. }
  106466. /*
  106467. ** Deallocate a WhereClause structure. The WhereClause structure
  106468. ** itself is not freed. This routine is the inverse of whereClauseInit().
  106469. */
  106470. static void whereClauseClear(WhereClause *pWC){
  106471. int i;
  106472. WhereTerm *a;
  106473. sqlite3 *db = pWC->pWInfo->pParse->db;
  106474. for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
  106475. if( a->wtFlags & TERM_DYNAMIC ){
  106476. sqlite3ExprDelete(db, a->pExpr);
  106477. }
  106478. if( a->wtFlags & TERM_ORINFO ){
  106479. whereOrInfoDelete(db, a->u.pOrInfo);
  106480. }else if( a->wtFlags & TERM_ANDINFO ){
  106481. whereAndInfoDelete(db, a->u.pAndInfo);
  106482. }
  106483. }
  106484. if( pWC->a!=pWC->aStatic ){
  106485. sqlite3DbFree(db, pWC->a);
  106486. }
  106487. }
  106488. /*
  106489. ** Add a single new WhereTerm entry to the WhereClause object pWC.
  106490. ** The new WhereTerm object is constructed from Expr p and with wtFlags.
  106491. ** The index in pWC->a[] of the new WhereTerm is returned on success.
  106492. ** 0 is returned if the new WhereTerm could not be added due to a memory
  106493. ** allocation error. The memory allocation failure will be recorded in
  106494. ** the db->mallocFailed flag so that higher-level functions can detect it.
  106495. **
  106496. ** This routine will increase the size of the pWC->a[] array as necessary.
  106497. **
  106498. ** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
  106499. ** for freeing the expression p is assumed by the WhereClause object pWC.
  106500. ** This is true even if this routine fails to allocate a new WhereTerm.
  106501. **
  106502. ** WARNING: This routine might reallocate the space used to store
  106503. ** WhereTerms. All pointers to WhereTerms should be invalidated after
  106504. ** calling this routine. Such pointers may be reinitialized by referencing
  106505. ** the pWC->a[] array.
  106506. */
  106507. static int whereClauseInsert(WhereClause *pWC, Expr *p, u8 wtFlags){
  106508. WhereTerm *pTerm;
  106509. int idx;
  106510. testcase( wtFlags & TERM_VIRTUAL );
  106511. if( pWC->nTerm>=pWC->nSlot ){
  106512. WhereTerm *pOld = pWC->a;
  106513. sqlite3 *db = pWC->pWInfo->pParse->db;
  106514. pWC->a = sqlite3DbMallocRaw(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
  106515. if( pWC->a==0 ){
  106516. if( wtFlags & TERM_DYNAMIC ){
  106517. sqlite3ExprDelete(db, p);
  106518. }
  106519. pWC->a = pOld;
  106520. return 0;
  106521. }
  106522. memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
  106523. if( pOld!=pWC->aStatic ){
  106524. sqlite3DbFree(db, pOld);
  106525. }
  106526. pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
  106527. }
  106528. pTerm = &pWC->a[idx = pWC->nTerm++];
  106529. if( p && ExprHasProperty(p, EP_Unlikely) ){
  106530. pTerm->truthProb = sqlite3LogEst(p->iTable) - 99;
  106531. }else{
  106532. pTerm->truthProb = 1;
  106533. }
  106534. pTerm->pExpr = sqlite3ExprSkipCollate(p);
  106535. pTerm->wtFlags = wtFlags;
  106536. pTerm->pWC = pWC;
  106537. pTerm->iParent = -1;
  106538. return idx;
  106539. }
  106540. /*
  106541. ** This routine identifies subexpressions in the WHERE clause where
  106542. ** each subexpression is separated by the AND operator or some other
  106543. ** operator specified in the op parameter. The WhereClause structure
  106544. ** is filled with pointers to subexpressions. For example:
  106545. **
  106546. ** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
  106547. ** \________/ \_______________/ \________________/
  106548. ** slot[0] slot[1] slot[2]
  106549. **
  106550. ** The original WHERE clause in pExpr is unaltered. All this routine
  106551. ** does is make slot[] entries point to substructure within pExpr.
  106552. **
  106553. ** In the previous sentence and in the diagram, "slot[]" refers to
  106554. ** the WhereClause.a[] array. The slot[] array grows as needed to contain
  106555. ** all terms of the WHERE clause.
  106556. */
  106557. static void whereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
  106558. pWC->op = op;
  106559. if( pExpr==0 ) return;
  106560. if( pExpr->op!=op ){
  106561. whereClauseInsert(pWC, pExpr, 0);
  106562. }else{
  106563. whereSplit(pWC, pExpr->pLeft, op);
  106564. whereSplit(pWC, pExpr->pRight, op);
  106565. }
  106566. }
  106567. /*
  106568. ** Initialize a WhereMaskSet object
  106569. */
  106570. #define initMaskSet(P) (P)->n=0
  106571. /*
  106572. ** Return the bitmask for the given cursor number. Return 0 if
  106573. ** iCursor is not in the set.
  106574. */
  106575. static Bitmask getMask(WhereMaskSet *pMaskSet, int iCursor){
  106576. int i;
  106577. assert( pMaskSet->n<=(int)sizeof(Bitmask)*8 );
  106578. for(i=0; i<pMaskSet->n; i++){
  106579. if( pMaskSet->ix[i]==iCursor ){
  106580. return MASKBIT(i);
  106581. }
  106582. }
  106583. return 0;
  106584. }
  106585. /*
  106586. ** Create a new mask for cursor iCursor.
  106587. **
  106588. ** There is one cursor per table in the FROM clause. The number of
  106589. ** tables in the FROM clause is limited by a test early in the
  106590. ** sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
  106591. ** array will never overflow.
  106592. */
  106593. static void createMask(WhereMaskSet *pMaskSet, int iCursor){
  106594. assert( pMaskSet->n < ArraySize(pMaskSet->ix) );
  106595. pMaskSet->ix[pMaskSet->n++] = iCursor;
  106596. }
  106597. /*
  106598. ** These routines walk (recursively) an expression tree and generate
  106599. ** a bitmask indicating which tables are used in that expression
  106600. ** tree.
  106601. */
  106602. static Bitmask exprListTableUsage(WhereMaskSet*, ExprList*);
  106603. static Bitmask exprSelectTableUsage(WhereMaskSet*, Select*);
  106604. static Bitmask exprTableUsage(WhereMaskSet *pMaskSet, Expr *p){
  106605. Bitmask mask = 0;
  106606. if( p==0 ) return 0;
  106607. if( p->op==TK_COLUMN ){
  106608. mask = getMask(pMaskSet, p->iTable);
  106609. return mask;
  106610. }
  106611. mask = exprTableUsage(pMaskSet, p->pRight);
  106612. mask |= exprTableUsage(pMaskSet, p->pLeft);
  106613. if( ExprHasProperty(p, EP_xIsSelect) ){
  106614. mask |= exprSelectTableUsage(pMaskSet, p->x.pSelect);
  106615. }else{
  106616. mask |= exprListTableUsage(pMaskSet, p->x.pList);
  106617. }
  106618. return mask;
  106619. }
  106620. static Bitmask exprListTableUsage(WhereMaskSet *pMaskSet, ExprList *pList){
  106621. int i;
  106622. Bitmask mask = 0;
  106623. if( pList ){
  106624. for(i=0; i<pList->nExpr; i++){
  106625. mask |= exprTableUsage(pMaskSet, pList->a[i].pExpr);
  106626. }
  106627. }
  106628. return mask;
  106629. }
  106630. static Bitmask exprSelectTableUsage(WhereMaskSet *pMaskSet, Select *pS){
  106631. Bitmask mask = 0;
  106632. while( pS ){
  106633. SrcList *pSrc = pS->pSrc;
  106634. mask |= exprListTableUsage(pMaskSet, pS->pEList);
  106635. mask |= exprListTableUsage(pMaskSet, pS->pGroupBy);
  106636. mask |= exprListTableUsage(pMaskSet, pS->pOrderBy);
  106637. mask |= exprTableUsage(pMaskSet, pS->pWhere);
  106638. mask |= exprTableUsage(pMaskSet, pS->pHaving);
  106639. if( ALWAYS(pSrc!=0) ){
  106640. int i;
  106641. for(i=0; i<pSrc->nSrc; i++){
  106642. mask |= exprSelectTableUsage(pMaskSet, pSrc->a[i].pSelect);
  106643. mask |= exprTableUsage(pMaskSet, pSrc->a[i].pOn);
  106644. }
  106645. }
  106646. pS = pS->pPrior;
  106647. }
  106648. return mask;
  106649. }
  106650. /*
  106651. ** Return TRUE if the given operator is one of the operators that is
  106652. ** allowed for an indexable WHERE clause term. The allowed operators are
  106653. ** "=", "<", ">", "<=", ">=", "IN", and "IS NULL"
  106654. */
  106655. static int allowedOp(int op){
  106656. assert( TK_GT>TK_EQ && TK_GT<TK_GE );
  106657. assert( TK_LT>TK_EQ && TK_LT<TK_GE );
  106658. assert( TK_LE>TK_EQ && TK_LE<TK_GE );
  106659. assert( TK_GE==TK_EQ+4 );
  106660. return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL;
  106661. }
  106662. /*
  106663. ** Commute a comparison operator. Expressions of the form "X op Y"
  106664. ** are converted into "Y op X".
  106665. **
  106666. ** If left/right precedence rules come into play when determining the
  106667. ** collating sequence, then COLLATE operators are adjusted to ensure
  106668. ** that the collating sequence does not change. For example:
  106669. ** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
  106670. ** the left hand side of a comparison overrides any collation sequence
  106671. ** attached to the right. For the same reason the EP_Collate flag
  106672. ** is not commuted.
  106673. */
  106674. static void exprCommute(Parse *pParse, Expr *pExpr){
  106675. u16 expRight = (pExpr->pRight->flags & EP_Collate);
  106676. u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
  106677. assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
  106678. if( expRight==expLeft ){
  106679. /* Either X and Y both have COLLATE operator or neither do */
  106680. if( expRight ){
  106681. /* Both X and Y have COLLATE operators. Make sure X is always
  106682. ** used by clearing the EP_Collate flag from Y. */
  106683. pExpr->pRight->flags &= ~EP_Collate;
  106684. }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
  106685. /* Neither X nor Y have COLLATE operators, but X has a non-default
  106686. ** collating sequence. So add the EP_Collate marker on X to cause
  106687. ** it to be searched first. */
  106688. pExpr->pLeft->flags |= EP_Collate;
  106689. }
  106690. }
  106691. SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
  106692. if( pExpr->op>=TK_GT ){
  106693. assert( TK_LT==TK_GT+2 );
  106694. assert( TK_GE==TK_LE+2 );
  106695. assert( TK_GT>TK_EQ );
  106696. assert( TK_GT<TK_LE );
  106697. assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
  106698. pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
  106699. }
  106700. }
  106701. /*
  106702. ** Translate from TK_xx operator to WO_xx bitmask.
  106703. */
  106704. static u16 operatorMask(int op){
  106705. u16 c;
  106706. assert( allowedOp(op) );
  106707. if( op==TK_IN ){
  106708. c = WO_IN;
  106709. }else if( op==TK_ISNULL ){
  106710. c = WO_ISNULL;
  106711. }else{
  106712. assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
  106713. c = (u16)(WO_EQ<<(op-TK_EQ));
  106714. }
  106715. assert( op!=TK_ISNULL || c==WO_ISNULL );
  106716. assert( op!=TK_IN || c==WO_IN );
  106717. assert( op!=TK_EQ || c==WO_EQ );
  106718. assert( op!=TK_LT || c==WO_LT );
  106719. assert( op!=TK_LE || c==WO_LE );
  106720. assert( op!=TK_GT || c==WO_GT );
  106721. assert( op!=TK_GE || c==WO_GE );
  106722. return c;
  106723. }
  106724. /*
  106725. ** Advance to the next WhereTerm that matches according to the criteria
  106726. ** established when the pScan object was initialized by whereScanInit().
  106727. ** Return NULL if there are no more matching WhereTerms.
  106728. */
  106729. static WhereTerm *whereScanNext(WhereScan *pScan){
  106730. int iCur; /* The cursor on the LHS of the term */
  106731. int iColumn; /* The column on the LHS of the term. -1 for IPK */
  106732. Expr *pX; /* An expression being tested */
  106733. WhereClause *pWC; /* Shorthand for pScan->pWC */
  106734. WhereTerm *pTerm; /* The term being tested */
  106735. int k = pScan->k; /* Where to start scanning */
  106736. while( pScan->iEquiv<=pScan->nEquiv ){
  106737. iCur = pScan->aEquiv[pScan->iEquiv-2];
  106738. iColumn = pScan->aEquiv[pScan->iEquiv-1];
  106739. while( (pWC = pScan->pWC)!=0 ){
  106740. for(pTerm=pWC->a+k; k<pWC->nTerm; k++, pTerm++){
  106741. if( pTerm->leftCursor==iCur
  106742. && pTerm->u.leftColumn==iColumn
  106743. && (pScan->iEquiv<=2 || !ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  106744. ){
  106745. if( (pTerm->eOperator & WO_EQUIV)!=0
  106746. && pScan->nEquiv<ArraySize(pScan->aEquiv)
  106747. ){
  106748. int j;
  106749. pX = sqlite3ExprSkipCollate(pTerm->pExpr->pRight);
  106750. assert( pX->op==TK_COLUMN );
  106751. for(j=0; j<pScan->nEquiv; j+=2){
  106752. if( pScan->aEquiv[j]==pX->iTable
  106753. && pScan->aEquiv[j+1]==pX->iColumn ){
  106754. break;
  106755. }
  106756. }
  106757. if( j==pScan->nEquiv ){
  106758. pScan->aEquiv[j] = pX->iTable;
  106759. pScan->aEquiv[j+1] = pX->iColumn;
  106760. pScan->nEquiv += 2;
  106761. }
  106762. }
  106763. if( (pTerm->eOperator & pScan->opMask)!=0 ){
  106764. /* Verify the affinity and collating sequence match */
  106765. if( pScan->zCollName && (pTerm->eOperator & WO_ISNULL)==0 ){
  106766. CollSeq *pColl;
  106767. Parse *pParse = pWC->pWInfo->pParse;
  106768. pX = pTerm->pExpr;
  106769. if( !sqlite3IndexAffinityOk(pX, pScan->idxaff) ){
  106770. continue;
  106771. }
  106772. assert(pX->pLeft);
  106773. pColl = sqlite3BinaryCompareCollSeq(pParse,
  106774. pX->pLeft, pX->pRight);
  106775. if( pColl==0 ) pColl = pParse->db->pDfltColl;
  106776. if( sqlite3StrICmp(pColl->zName, pScan->zCollName) ){
  106777. continue;
  106778. }
  106779. }
  106780. if( (pTerm->eOperator & WO_EQ)!=0
  106781. && (pX = pTerm->pExpr->pRight)->op==TK_COLUMN
  106782. && pX->iTable==pScan->aEquiv[0]
  106783. && pX->iColumn==pScan->aEquiv[1]
  106784. ){
  106785. continue;
  106786. }
  106787. pScan->k = k+1;
  106788. return pTerm;
  106789. }
  106790. }
  106791. }
  106792. pScan->pWC = pScan->pWC->pOuter;
  106793. k = 0;
  106794. }
  106795. pScan->pWC = pScan->pOrigWC;
  106796. k = 0;
  106797. pScan->iEquiv += 2;
  106798. }
  106799. return 0;
  106800. }
  106801. /*
  106802. ** Initialize a WHERE clause scanner object. Return a pointer to the
  106803. ** first match. Return NULL if there are no matches.
  106804. **
  106805. ** The scanner will be searching the WHERE clause pWC. It will look
  106806. ** for terms of the form "X <op> <expr>" where X is column iColumn of table
  106807. ** iCur. The <op> must be one of the operators described by opMask.
  106808. **
  106809. ** If the search is for X and the WHERE clause contains terms of the
  106810. ** form X=Y then this routine might also return terms of the form
  106811. ** "Y <op> <expr>". The number of levels of transitivity is limited,
  106812. ** but is enough to handle most commonly occurring SQL statements.
  106813. **
  106814. ** If X is not the INTEGER PRIMARY KEY then X must be compatible with
  106815. ** index pIdx.
  106816. */
  106817. static WhereTerm *whereScanInit(
  106818. WhereScan *pScan, /* The WhereScan object being initialized */
  106819. WhereClause *pWC, /* The WHERE clause to be scanned */
  106820. int iCur, /* Cursor to scan for */
  106821. int iColumn, /* Column to scan for */
  106822. u32 opMask, /* Operator(s) to scan for */
  106823. Index *pIdx /* Must be compatible with this index */
  106824. ){
  106825. int j;
  106826. /* memset(pScan, 0, sizeof(*pScan)); */
  106827. pScan->pOrigWC = pWC;
  106828. pScan->pWC = pWC;
  106829. if( pIdx && iColumn>=0 ){
  106830. pScan->idxaff = pIdx->pTable->aCol[iColumn].affinity;
  106831. for(j=0; pIdx->aiColumn[j]!=iColumn; j++){
  106832. if( NEVER(j>pIdx->nColumn) ) return 0;
  106833. }
  106834. pScan->zCollName = pIdx->azColl[j];
  106835. }else{
  106836. pScan->idxaff = 0;
  106837. pScan->zCollName = 0;
  106838. }
  106839. pScan->opMask = opMask;
  106840. pScan->k = 0;
  106841. pScan->aEquiv[0] = iCur;
  106842. pScan->aEquiv[1] = iColumn;
  106843. pScan->nEquiv = 2;
  106844. pScan->iEquiv = 2;
  106845. return whereScanNext(pScan);
  106846. }
  106847. /*
  106848. ** Search for a term in the WHERE clause that is of the form "X <op> <expr>"
  106849. ** where X is a reference to the iColumn of table iCur and <op> is one of
  106850. ** the WO_xx operator codes specified by the op parameter.
  106851. ** Return a pointer to the term. Return 0 if not found.
  106852. **
  106853. ** The term returned might by Y=<expr> if there is another constraint in
  106854. ** the WHERE clause that specifies that X=Y. Any such constraints will be
  106855. ** identified by the WO_EQUIV bit in the pTerm->eOperator field. The
  106856. ** aEquiv[] array holds X and all its equivalents, with each SQL variable
  106857. ** taking up two slots in aEquiv[]. The first slot is for the cursor number
  106858. ** and the second is for the column number. There are 22 slots in aEquiv[]
  106859. ** so that means we can look for X plus up to 10 other equivalent values.
  106860. ** Hence a search for X will return <expr> if X=A1 and A1=A2 and A2=A3
  106861. ** and ... and A9=A10 and A10=<expr>.
  106862. **
  106863. ** If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
  106864. ** then try for the one with no dependencies on <expr> - in other words where
  106865. ** <expr> is a constant expression of some kind. Only return entries of
  106866. ** the form "X <op> Y" where Y is a column in another table if no terms of
  106867. ** the form "X <op> <const-expr>" exist. If no terms with a constant RHS
  106868. ** exist, try to return a term that does not use WO_EQUIV.
  106869. */
  106870. static WhereTerm *findTerm(
  106871. WhereClause *pWC, /* The WHERE clause to be searched */
  106872. int iCur, /* Cursor number of LHS */
  106873. int iColumn, /* Column number of LHS */
  106874. Bitmask notReady, /* RHS must not overlap with this mask */
  106875. u32 op, /* Mask of WO_xx values describing operator */
  106876. Index *pIdx /* Must be compatible with this index, if not NULL */
  106877. ){
  106878. WhereTerm *pResult = 0;
  106879. WhereTerm *p;
  106880. WhereScan scan;
  106881. p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
  106882. while( p ){
  106883. if( (p->prereqRight & notReady)==0 ){
  106884. if( p->prereqRight==0 && (p->eOperator&WO_EQ)!=0 ){
  106885. return p;
  106886. }
  106887. if( pResult==0 ) pResult = p;
  106888. }
  106889. p = whereScanNext(&scan);
  106890. }
  106891. return pResult;
  106892. }
  106893. /* Forward reference */
  106894. static void exprAnalyze(SrcList*, WhereClause*, int);
  106895. /*
  106896. ** Call exprAnalyze on all terms in a WHERE clause.
  106897. */
  106898. static void exprAnalyzeAll(
  106899. SrcList *pTabList, /* the FROM clause */
  106900. WhereClause *pWC /* the WHERE clause to be analyzed */
  106901. ){
  106902. int i;
  106903. for(i=pWC->nTerm-1; i>=0; i--){
  106904. exprAnalyze(pTabList, pWC, i);
  106905. }
  106906. }
  106907. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  106908. /*
  106909. ** Check to see if the given expression is a LIKE or GLOB operator that
  106910. ** can be optimized using inequality constraints. Return TRUE if it is
  106911. ** so and false if not.
  106912. **
  106913. ** In order for the operator to be optimizible, the RHS must be a string
  106914. ** literal that does not begin with a wildcard.
  106915. */
  106916. static int isLikeOrGlob(
  106917. Parse *pParse, /* Parsing and code generating context */
  106918. Expr *pExpr, /* Test this expression */
  106919. Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
  106920. int *pisComplete, /* True if the only wildcard is % in the last character */
  106921. int *pnoCase /* True if uppercase is equivalent to lowercase */
  106922. ){
  106923. const char *z = 0; /* String on RHS of LIKE operator */
  106924. Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
  106925. ExprList *pList; /* List of operands to the LIKE operator */
  106926. int c; /* One character in z[] */
  106927. int cnt; /* Number of non-wildcard prefix characters */
  106928. char wc[3]; /* Wildcard characters */
  106929. sqlite3 *db = pParse->db; /* Database connection */
  106930. sqlite3_value *pVal = 0;
  106931. int op; /* Opcode of pRight */
  106932. if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
  106933. return 0;
  106934. }
  106935. #ifdef SQLITE_EBCDIC
  106936. if( *pnoCase ) return 0;
  106937. #endif
  106938. pList = pExpr->x.pList;
  106939. pLeft = pList->a[1].pExpr;
  106940. if( pLeft->op!=TK_COLUMN
  106941. || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
  106942. || IsVirtual(pLeft->pTab)
  106943. ){
  106944. /* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
  106945. ** be the name of an indexed column with TEXT affinity. */
  106946. return 0;
  106947. }
  106948. assert( pLeft->iColumn!=(-1) ); /* Because IPK never has AFF_TEXT */
  106949. pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
  106950. op = pRight->op;
  106951. if( op==TK_VARIABLE ){
  106952. Vdbe *pReprepare = pParse->pReprepare;
  106953. int iCol = pRight->iColumn;
  106954. pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_NONE);
  106955. if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
  106956. z = (char *)sqlite3_value_text(pVal);
  106957. }
  106958. sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
  106959. assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
  106960. }else if( op==TK_STRING ){
  106961. z = pRight->u.zToken;
  106962. }
  106963. if( z ){
  106964. cnt = 0;
  106965. while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
  106966. cnt++;
  106967. }
  106968. if( cnt!=0 && 255!=(u8)z[cnt-1] ){
  106969. Expr *pPrefix;
  106970. *pisComplete = c==wc[0] && z[cnt+1]==0;
  106971. pPrefix = sqlite3Expr(db, TK_STRING, z);
  106972. if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
  106973. *ppPrefix = pPrefix;
  106974. if( op==TK_VARIABLE ){
  106975. Vdbe *v = pParse->pVdbe;
  106976. sqlite3VdbeSetVarmask(v, pRight->iColumn);
  106977. if( *pisComplete && pRight->u.zToken[1] ){
  106978. /* If the rhs of the LIKE expression is a variable, and the current
  106979. ** value of the variable means there is no need to invoke the LIKE
  106980. ** function, then no OP_Variable will be added to the program.
  106981. ** This causes problems for the sqlite3_bind_parameter_name()
  106982. ** API. To work around them, add a dummy OP_Variable here.
  106983. */
  106984. int r1 = sqlite3GetTempReg(pParse);
  106985. sqlite3ExprCodeTarget(pParse, pRight, r1);
  106986. sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
  106987. sqlite3ReleaseTempReg(pParse, r1);
  106988. }
  106989. }
  106990. }else{
  106991. z = 0;
  106992. }
  106993. }
  106994. sqlite3ValueFree(pVal);
  106995. return (z!=0);
  106996. }
  106997. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  106998. #ifndef SQLITE_OMIT_VIRTUALTABLE
  106999. /*
  107000. ** Check to see if the given expression is of the form
  107001. **
  107002. ** column MATCH expr
  107003. **
  107004. ** If it is then return TRUE. If not, return FALSE.
  107005. */
  107006. static int isMatchOfColumn(
  107007. Expr *pExpr /* Test this expression */
  107008. ){
  107009. ExprList *pList;
  107010. if( pExpr->op!=TK_FUNCTION ){
  107011. return 0;
  107012. }
  107013. if( sqlite3StrICmp(pExpr->u.zToken,"match")!=0 ){
  107014. return 0;
  107015. }
  107016. pList = pExpr->x.pList;
  107017. if( pList->nExpr!=2 ){
  107018. return 0;
  107019. }
  107020. if( pList->a[1].pExpr->op != TK_COLUMN ){
  107021. return 0;
  107022. }
  107023. return 1;
  107024. }
  107025. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  107026. /*
  107027. ** If the pBase expression originated in the ON or USING clause of
  107028. ** a join, then transfer the appropriate markings over to derived.
  107029. */
  107030. static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
  107031. if( pDerived ){
  107032. pDerived->flags |= pBase->flags & EP_FromJoin;
  107033. pDerived->iRightJoinTable = pBase->iRightJoinTable;
  107034. }
  107035. }
  107036. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  107037. /*
  107038. ** Analyze a term that consists of two or more OR-connected
  107039. ** subterms. So in:
  107040. **
  107041. ** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
  107042. ** ^^^^^^^^^^^^^^^^^^^^
  107043. **
  107044. ** This routine analyzes terms such as the middle term in the above example.
  107045. ** A WhereOrTerm object is computed and attached to the term under
  107046. ** analysis, regardless of the outcome of the analysis. Hence:
  107047. **
  107048. ** WhereTerm.wtFlags |= TERM_ORINFO
  107049. ** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
  107050. **
  107051. ** The term being analyzed must have two or more of OR-connected subterms.
  107052. ** A single subterm might be a set of AND-connected sub-subterms.
  107053. ** Examples of terms under analysis:
  107054. **
  107055. ** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
  107056. ** (B) x=expr1 OR expr2=x OR x=expr3
  107057. ** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
  107058. ** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
  107059. ** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
  107060. **
  107061. ** CASE 1:
  107062. **
  107063. ** If all subterms are of the form T.C=expr for some single column of C and
  107064. ** a single table T (as shown in example B above) then create a new virtual
  107065. ** term that is an equivalent IN expression. In other words, if the term
  107066. ** being analyzed is:
  107067. **
  107068. ** x = expr1 OR expr2 = x OR x = expr3
  107069. **
  107070. ** then create a new virtual term like this:
  107071. **
  107072. ** x IN (expr1,expr2,expr3)
  107073. **
  107074. ** CASE 2:
  107075. **
  107076. ** If all subterms are indexable by a single table T, then set
  107077. **
  107078. ** WhereTerm.eOperator = WO_OR
  107079. ** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
  107080. **
  107081. ** A subterm is "indexable" if it is of the form
  107082. ** "T.C <op> <expr>" where C is any column of table T and
  107083. ** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
  107084. ** A subterm is also indexable if it is an AND of two or more
  107085. ** subsubterms at least one of which is indexable. Indexable AND
  107086. ** subterms have their eOperator set to WO_AND and they have
  107087. ** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
  107088. **
  107089. ** From another point of view, "indexable" means that the subterm could
  107090. ** potentially be used with an index if an appropriate index exists.
  107091. ** This analysis does not consider whether or not the index exists; that
  107092. ** is decided elsewhere. This analysis only looks at whether subterms
  107093. ** appropriate for indexing exist.
  107094. **
  107095. ** All examples A through E above satisfy case 2. But if a term
  107096. ** also satisfies case 1 (such as B) we know that the optimizer will
  107097. ** always prefer case 1, so in that case we pretend that case 2 is not
  107098. ** satisfied.
  107099. **
  107100. ** It might be the case that multiple tables are indexable. For example,
  107101. ** (E) above is indexable on tables P, Q, and R.
  107102. **
  107103. ** Terms that satisfy case 2 are candidates for lookup by using
  107104. ** separate indices to find rowids for each subterm and composing
  107105. ** the union of all rowids using a RowSet object. This is similar
  107106. ** to "bitmap indices" in other database engines.
  107107. **
  107108. ** OTHERWISE:
  107109. **
  107110. ** If neither case 1 nor case 2 apply, then leave the eOperator set to
  107111. ** zero. This term is not useful for search.
  107112. */
  107113. static void exprAnalyzeOrTerm(
  107114. SrcList *pSrc, /* the FROM clause */
  107115. WhereClause *pWC, /* the complete WHERE clause */
  107116. int idxTerm /* Index of the OR-term to be analyzed */
  107117. ){
  107118. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  107119. Parse *pParse = pWInfo->pParse; /* Parser context */
  107120. sqlite3 *db = pParse->db; /* Database connection */
  107121. WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
  107122. Expr *pExpr = pTerm->pExpr; /* The expression of the term */
  107123. int i; /* Loop counters */
  107124. WhereClause *pOrWc; /* Breakup of pTerm into subterms */
  107125. WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
  107126. WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
  107127. Bitmask chngToIN; /* Tables that might satisfy case 1 */
  107128. Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
  107129. /*
  107130. ** Break the OR clause into its separate subterms. The subterms are
  107131. ** stored in a WhereClause structure containing within the WhereOrInfo
  107132. ** object that is attached to the original OR clause term.
  107133. */
  107134. assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
  107135. assert( pExpr->op==TK_OR );
  107136. pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
  107137. if( pOrInfo==0 ) return;
  107138. pTerm->wtFlags |= TERM_ORINFO;
  107139. pOrWc = &pOrInfo->wc;
  107140. whereClauseInit(pOrWc, pWInfo);
  107141. whereSplit(pOrWc, pExpr, TK_OR);
  107142. exprAnalyzeAll(pSrc, pOrWc);
  107143. if( db->mallocFailed ) return;
  107144. assert( pOrWc->nTerm>=2 );
  107145. /*
  107146. ** Compute the set of tables that might satisfy cases 1 or 2.
  107147. */
  107148. indexable = ~(Bitmask)0;
  107149. chngToIN = ~(Bitmask)0;
  107150. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
  107151. if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
  107152. WhereAndInfo *pAndInfo;
  107153. assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
  107154. chngToIN = 0;
  107155. pAndInfo = sqlite3DbMallocRaw(db, sizeof(*pAndInfo));
  107156. if( pAndInfo ){
  107157. WhereClause *pAndWC;
  107158. WhereTerm *pAndTerm;
  107159. int j;
  107160. Bitmask b = 0;
  107161. pOrTerm->u.pAndInfo = pAndInfo;
  107162. pOrTerm->wtFlags |= TERM_ANDINFO;
  107163. pOrTerm->eOperator = WO_AND;
  107164. pAndWC = &pAndInfo->wc;
  107165. whereClauseInit(pAndWC, pWC->pWInfo);
  107166. whereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
  107167. exprAnalyzeAll(pSrc, pAndWC);
  107168. pAndWC->pOuter = pWC;
  107169. testcase( db->mallocFailed );
  107170. if( !db->mallocFailed ){
  107171. for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
  107172. assert( pAndTerm->pExpr );
  107173. if( allowedOp(pAndTerm->pExpr->op) ){
  107174. b |= getMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
  107175. }
  107176. }
  107177. }
  107178. indexable &= b;
  107179. }
  107180. }else if( pOrTerm->wtFlags & TERM_COPIED ){
  107181. /* Skip this term for now. We revisit it when we process the
  107182. ** corresponding TERM_VIRTUAL term */
  107183. }else{
  107184. Bitmask b;
  107185. b = getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
  107186. if( pOrTerm->wtFlags & TERM_VIRTUAL ){
  107187. WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
  107188. b |= getMask(&pWInfo->sMaskSet, pOther->leftCursor);
  107189. }
  107190. indexable &= b;
  107191. if( (pOrTerm->eOperator & WO_EQ)==0 ){
  107192. chngToIN = 0;
  107193. }else{
  107194. chngToIN &= b;
  107195. }
  107196. }
  107197. }
  107198. /*
  107199. ** Record the set of tables that satisfy case 2. The set might be
  107200. ** empty.
  107201. */
  107202. pOrInfo->indexable = indexable;
  107203. pTerm->eOperator = indexable==0 ? 0 : WO_OR;
  107204. /*
  107205. ** chngToIN holds a set of tables that *might* satisfy case 1. But
  107206. ** we have to do some additional checking to see if case 1 really
  107207. ** is satisfied.
  107208. **
  107209. ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
  107210. ** that there is no possibility of transforming the OR clause into an
  107211. ** IN operator because one or more terms in the OR clause contain
  107212. ** something other than == on a column in the single table. The 1-bit
  107213. ** case means that every term of the OR clause is of the form
  107214. ** "table.column=expr" for some single table. The one bit that is set
  107215. ** will correspond to the common table. We still need to check to make
  107216. ** sure the same column is used on all terms. The 2-bit case is when
  107217. ** the all terms are of the form "table1.column=table2.column". It
  107218. ** might be possible to form an IN operator with either table1.column
  107219. ** or table2.column as the LHS if either is common to every term of
  107220. ** the OR clause.
  107221. **
  107222. ** Note that terms of the form "table.column1=table.column2" (the
  107223. ** same table on both sizes of the ==) cannot be optimized.
  107224. */
  107225. if( chngToIN ){
  107226. int okToChngToIN = 0; /* True if the conversion to IN is valid */
  107227. int iColumn = -1; /* Column index on lhs of IN operator */
  107228. int iCursor = -1; /* Table cursor common to all terms */
  107229. int j = 0; /* Loop counter */
  107230. /* Search for a table and column that appears on one side or the
  107231. ** other of the == operator in every subterm. That table and column
  107232. ** will be recorded in iCursor and iColumn. There might not be any
  107233. ** such table and column. Set okToChngToIN if an appropriate table
  107234. ** and column is found but leave okToChngToIN false if not found.
  107235. */
  107236. for(j=0; j<2 && !okToChngToIN; j++){
  107237. pOrTerm = pOrWc->a;
  107238. for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
  107239. assert( pOrTerm->eOperator & WO_EQ );
  107240. pOrTerm->wtFlags &= ~TERM_OR_OK;
  107241. if( pOrTerm->leftCursor==iCursor ){
  107242. /* This is the 2-bit case and we are on the second iteration and
  107243. ** current term is from the first iteration. So skip this term. */
  107244. assert( j==1 );
  107245. continue;
  107246. }
  107247. if( (chngToIN & getMask(&pWInfo->sMaskSet, pOrTerm->leftCursor))==0 ){
  107248. /* This term must be of the form t1.a==t2.b where t2 is in the
  107249. ** chngToIN set but t1 is not. This term will be either preceded
  107250. ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
  107251. ** and use its inversion. */
  107252. testcase( pOrTerm->wtFlags & TERM_COPIED );
  107253. testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
  107254. assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
  107255. continue;
  107256. }
  107257. iColumn = pOrTerm->u.leftColumn;
  107258. iCursor = pOrTerm->leftCursor;
  107259. break;
  107260. }
  107261. if( i<0 ){
  107262. /* No candidate table+column was found. This can only occur
  107263. ** on the second iteration */
  107264. assert( j==1 );
  107265. assert( IsPowerOfTwo(chngToIN) );
  107266. assert( chngToIN==getMask(&pWInfo->sMaskSet, iCursor) );
  107267. break;
  107268. }
  107269. testcase( j==1 );
  107270. /* We have found a candidate table and column. Check to see if that
  107271. ** table and column is common to every term in the OR clause */
  107272. okToChngToIN = 1;
  107273. for(; i>=0 && okToChngToIN; i--, pOrTerm++){
  107274. assert( pOrTerm->eOperator & WO_EQ );
  107275. if( pOrTerm->leftCursor!=iCursor ){
  107276. pOrTerm->wtFlags &= ~TERM_OR_OK;
  107277. }else if( pOrTerm->u.leftColumn!=iColumn ){
  107278. okToChngToIN = 0;
  107279. }else{
  107280. int affLeft, affRight;
  107281. /* If the right-hand side is also a column, then the affinities
  107282. ** of both right and left sides must be such that no type
  107283. ** conversions are required on the right. (Ticket #2249)
  107284. */
  107285. affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
  107286. affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
  107287. if( affRight!=0 && affRight!=affLeft ){
  107288. okToChngToIN = 0;
  107289. }else{
  107290. pOrTerm->wtFlags |= TERM_OR_OK;
  107291. }
  107292. }
  107293. }
  107294. }
  107295. /* At this point, okToChngToIN is true if original pTerm satisfies
  107296. ** case 1. In that case, construct a new virtual term that is
  107297. ** pTerm converted into an IN operator.
  107298. */
  107299. if( okToChngToIN ){
  107300. Expr *pDup; /* A transient duplicate expression */
  107301. ExprList *pList = 0; /* The RHS of the IN operator */
  107302. Expr *pLeft = 0; /* The LHS of the IN operator */
  107303. Expr *pNew; /* The complete IN operator */
  107304. for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
  107305. if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
  107306. assert( pOrTerm->eOperator & WO_EQ );
  107307. assert( pOrTerm->leftCursor==iCursor );
  107308. assert( pOrTerm->u.leftColumn==iColumn );
  107309. pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
  107310. pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
  107311. pLeft = pOrTerm->pExpr->pLeft;
  107312. }
  107313. assert( pLeft!=0 );
  107314. pDup = sqlite3ExprDup(db, pLeft, 0);
  107315. pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0, 0);
  107316. if( pNew ){
  107317. int idxNew;
  107318. transferJoinMarkings(pNew, pExpr);
  107319. assert( !ExprHasProperty(pNew, EP_xIsSelect) );
  107320. pNew->x.pList = pList;
  107321. idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
  107322. testcase( idxNew==0 );
  107323. exprAnalyze(pSrc, pWC, idxNew);
  107324. pTerm = &pWC->a[idxTerm];
  107325. pWC->a[idxNew].iParent = idxTerm;
  107326. pTerm->nChild = 1;
  107327. }else{
  107328. sqlite3ExprListDelete(db, pList);
  107329. }
  107330. pTerm->eOperator = WO_NOOP; /* case 1 trumps case 2 */
  107331. }
  107332. }
  107333. }
  107334. #endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
  107335. /*
  107336. ** The input to this routine is an WhereTerm structure with only the
  107337. ** "pExpr" field filled in. The job of this routine is to analyze the
  107338. ** subexpression and populate all the other fields of the WhereTerm
  107339. ** structure.
  107340. **
  107341. ** If the expression is of the form "<expr> <op> X" it gets commuted
  107342. ** to the standard form of "X <op> <expr>".
  107343. **
  107344. ** If the expression is of the form "X <op> Y" where both X and Y are
  107345. ** columns, then the original expression is unchanged and a new virtual
  107346. ** term of the form "Y <op> X" is added to the WHERE clause and
  107347. ** analyzed separately. The original term is marked with TERM_COPIED
  107348. ** and the new term is marked with TERM_DYNAMIC (because it's pExpr
  107349. ** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
  107350. ** is a commuted copy of a prior term.) The original term has nChild=1
  107351. ** and the copy has idxParent set to the index of the original term.
  107352. */
  107353. static void exprAnalyze(
  107354. SrcList *pSrc, /* the FROM clause */
  107355. WhereClause *pWC, /* the WHERE clause */
  107356. int idxTerm /* Index of the term to be analyzed */
  107357. ){
  107358. WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
  107359. WhereTerm *pTerm; /* The term to be analyzed */
  107360. WhereMaskSet *pMaskSet; /* Set of table index masks */
  107361. Expr *pExpr; /* The expression to be analyzed */
  107362. Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
  107363. Bitmask prereqAll; /* Prerequesites of pExpr */
  107364. Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
  107365. Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
  107366. int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
  107367. int noCase = 0; /* LIKE/GLOB distinguishes case */
  107368. int op; /* Top-level operator. pExpr->op */
  107369. Parse *pParse = pWInfo->pParse; /* Parsing context */
  107370. sqlite3 *db = pParse->db; /* Database connection */
  107371. if( db->mallocFailed ){
  107372. return;
  107373. }
  107374. pTerm = &pWC->a[idxTerm];
  107375. pMaskSet = &pWInfo->sMaskSet;
  107376. pExpr = pTerm->pExpr;
  107377. assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
  107378. prereqLeft = exprTableUsage(pMaskSet, pExpr->pLeft);
  107379. op = pExpr->op;
  107380. if( op==TK_IN ){
  107381. assert( pExpr->pRight==0 );
  107382. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  107383. pTerm->prereqRight = exprSelectTableUsage(pMaskSet, pExpr->x.pSelect);
  107384. }else{
  107385. pTerm->prereqRight = exprListTableUsage(pMaskSet, pExpr->x.pList);
  107386. }
  107387. }else if( op==TK_ISNULL ){
  107388. pTerm->prereqRight = 0;
  107389. }else{
  107390. pTerm->prereqRight = exprTableUsage(pMaskSet, pExpr->pRight);
  107391. }
  107392. prereqAll = exprTableUsage(pMaskSet, pExpr);
  107393. if( ExprHasProperty(pExpr, EP_FromJoin) ){
  107394. Bitmask x = getMask(pMaskSet, pExpr->iRightJoinTable);
  107395. prereqAll |= x;
  107396. extraRight = x-1; /* ON clause terms may not be used with an index
  107397. ** on left table of a LEFT JOIN. Ticket #3015 */
  107398. }
  107399. pTerm->prereqAll = prereqAll;
  107400. pTerm->leftCursor = -1;
  107401. pTerm->iParent = -1;
  107402. pTerm->eOperator = 0;
  107403. if( allowedOp(op) ){
  107404. Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
  107405. Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
  107406. u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
  107407. if( pLeft->op==TK_COLUMN ){
  107408. pTerm->leftCursor = pLeft->iTable;
  107409. pTerm->u.leftColumn = pLeft->iColumn;
  107410. pTerm->eOperator = operatorMask(op) & opMask;
  107411. }
  107412. if( pRight && pRight->op==TK_COLUMN ){
  107413. WhereTerm *pNew;
  107414. Expr *pDup;
  107415. u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
  107416. if( pTerm->leftCursor>=0 ){
  107417. int idxNew;
  107418. pDup = sqlite3ExprDup(db, pExpr, 0);
  107419. if( db->mallocFailed ){
  107420. sqlite3ExprDelete(db, pDup);
  107421. return;
  107422. }
  107423. idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
  107424. if( idxNew==0 ) return;
  107425. pNew = &pWC->a[idxNew];
  107426. pNew->iParent = idxTerm;
  107427. pTerm = &pWC->a[idxTerm];
  107428. pTerm->nChild = 1;
  107429. pTerm->wtFlags |= TERM_COPIED;
  107430. if( pExpr->op==TK_EQ
  107431. && !ExprHasProperty(pExpr, EP_FromJoin)
  107432. && OptimizationEnabled(db, SQLITE_Transitive)
  107433. ){
  107434. pTerm->eOperator |= WO_EQUIV;
  107435. eExtraOp = WO_EQUIV;
  107436. }
  107437. }else{
  107438. pDup = pExpr;
  107439. pNew = pTerm;
  107440. }
  107441. exprCommute(pParse, pDup);
  107442. pLeft = sqlite3ExprSkipCollate(pDup->pLeft);
  107443. pNew->leftCursor = pLeft->iTable;
  107444. pNew->u.leftColumn = pLeft->iColumn;
  107445. testcase( (prereqLeft | extraRight) != prereqLeft );
  107446. pNew->prereqRight = prereqLeft | extraRight;
  107447. pNew->prereqAll = prereqAll;
  107448. pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
  107449. }
  107450. }
  107451. #ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
  107452. /* If a term is the BETWEEN operator, create two new virtual terms
  107453. ** that define the range that the BETWEEN implements. For example:
  107454. **
  107455. ** a BETWEEN b AND c
  107456. **
  107457. ** is converted into:
  107458. **
  107459. ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
  107460. **
  107461. ** The two new terms are added onto the end of the WhereClause object.
  107462. ** The new terms are "dynamic" and are children of the original BETWEEN
  107463. ** term. That means that if the BETWEEN term is coded, the children are
  107464. ** skipped. Or, if the children are satisfied by an index, the original
  107465. ** BETWEEN term is skipped.
  107466. */
  107467. else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
  107468. ExprList *pList = pExpr->x.pList;
  107469. int i;
  107470. static const u8 ops[] = {TK_GE, TK_LE};
  107471. assert( pList!=0 );
  107472. assert( pList->nExpr==2 );
  107473. for(i=0; i<2; i++){
  107474. Expr *pNewExpr;
  107475. int idxNew;
  107476. pNewExpr = sqlite3PExpr(pParse, ops[i],
  107477. sqlite3ExprDup(db, pExpr->pLeft, 0),
  107478. sqlite3ExprDup(db, pList->a[i].pExpr, 0), 0);
  107479. transferJoinMarkings(pNewExpr, pExpr);
  107480. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  107481. testcase( idxNew==0 );
  107482. exprAnalyze(pSrc, pWC, idxNew);
  107483. pTerm = &pWC->a[idxTerm];
  107484. pWC->a[idxNew].iParent = idxTerm;
  107485. }
  107486. pTerm->nChild = 2;
  107487. }
  107488. #endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
  107489. #if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
  107490. /* Analyze a term that is composed of two or more subterms connected by
  107491. ** an OR operator.
  107492. */
  107493. else if( pExpr->op==TK_OR ){
  107494. assert( pWC->op==TK_AND );
  107495. exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
  107496. pTerm = &pWC->a[idxTerm];
  107497. }
  107498. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  107499. #ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
  107500. /* Add constraints to reduce the search space on a LIKE or GLOB
  107501. ** operator.
  107502. **
  107503. ** A like pattern of the form "x LIKE 'abc%'" is changed into constraints
  107504. **
  107505. ** x>='abc' AND x<'abd' AND x LIKE 'abc%'
  107506. **
  107507. ** The last character of the prefix "abc" is incremented to form the
  107508. ** termination condition "abd".
  107509. */
  107510. if( pWC->op==TK_AND
  107511. && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
  107512. ){
  107513. Expr *pLeft; /* LHS of LIKE/GLOB operator */
  107514. Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
  107515. Expr *pNewExpr1;
  107516. Expr *pNewExpr2;
  107517. int idxNew1;
  107518. int idxNew2;
  107519. Token sCollSeqName; /* Name of collating sequence */
  107520. pLeft = pExpr->x.pList->a[1].pExpr;
  107521. pStr2 = sqlite3ExprDup(db, pStr1, 0);
  107522. if( !db->mallocFailed ){
  107523. u8 c, *pC; /* Last character before the first wildcard */
  107524. pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
  107525. c = *pC;
  107526. if( noCase ){
  107527. /* The point is to increment the last character before the first
  107528. ** wildcard. But if we increment '@', that will push it into the
  107529. ** alphabetic range where case conversions will mess up the
  107530. ** inequality. To avoid this, make sure to also run the full
  107531. ** LIKE on all candidate expressions by clearing the isComplete flag
  107532. */
  107533. if( c=='A'-1 ) isComplete = 0;
  107534. c = sqlite3UpperToLower[c];
  107535. }
  107536. *pC = c + 1;
  107537. }
  107538. sCollSeqName.z = noCase ? "NOCASE" : "BINARY";
  107539. sCollSeqName.n = 6;
  107540. pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
  107541. pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
  107542. sqlite3ExprAddCollateToken(pParse,pNewExpr1,&sCollSeqName),
  107543. pStr1, 0);
  107544. transferJoinMarkings(pNewExpr1, pExpr);
  107545. idxNew1 = whereClauseInsert(pWC, pNewExpr1, TERM_VIRTUAL|TERM_DYNAMIC);
  107546. testcase( idxNew1==0 );
  107547. exprAnalyze(pSrc, pWC, idxNew1);
  107548. pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
  107549. pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
  107550. sqlite3ExprAddCollateToken(pParse,pNewExpr2,&sCollSeqName),
  107551. pStr2, 0);
  107552. transferJoinMarkings(pNewExpr2, pExpr);
  107553. idxNew2 = whereClauseInsert(pWC, pNewExpr2, TERM_VIRTUAL|TERM_DYNAMIC);
  107554. testcase( idxNew2==0 );
  107555. exprAnalyze(pSrc, pWC, idxNew2);
  107556. pTerm = &pWC->a[idxTerm];
  107557. if( isComplete ){
  107558. pWC->a[idxNew1].iParent = idxTerm;
  107559. pWC->a[idxNew2].iParent = idxTerm;
  107560. pTerm->nChild = 2;
  107561. }
  107562. }
  107563. #endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
  107564. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107565. /* Add a WO_MATCH auxiliary term to the constraint set if the
  107566. ** current expression is of the form: column MATCH expr.
  107567. ** This information is used by the xBestIndex methods of
  107568. ** virtual tables. The native query optimizer does not attempt
  107569. ** to do anything with MATCH functions.
  107570. */
  107571. if( isMatchOfColumn(pExpr) ){
  107572. int idxNew;
  107573. Expr *pRight, *pLeft;
  107574. WhereTerm *pNewTerm;
  107575. Bitmask prereqColumn, prereqExpr;
  107576. pRight = pExpr->x.pList->a[0].pExpr;
  107577. pLeft = pExpr->x.pList->a[1].pExpr;
  107578. prereqExpr = exprTableUsage(pMaskSet, pRight);
  107579. prereqColumn = exprTableUsage(pMaskSet, pLeft);
  107580. if( (prereqExpr & prereqColumn)==0 ){
  107581. Expr *pNewExpr;
  107582. pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
  107583. 0, sqlite3ExprDup(db, pRight, 0), 0);
  107584. idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
  107585. testcase( idxNew==0 );
  107586. pNewTerm = &pWC->a[idxNew];
  107587. pNewTerm->prereqRight = prereqExpr;
  107588. pNewTerm->leftCursor = pLeft->iTable;
  107589. pNewTerm->u.leftColumn = pLeft->iColumn;
  107590. pNewTerm->eOperator = WO_MATCH;
  107591. pNewTerm->iParent = idxTerm;
  107592. pTerm = &pWC->a[idxTerm];
  107593. pTerm->nChild = 1;
  107594. pTerm->wtFlags |= TERM_COPIED;
  107595. pNewTerm->prereqAll = pTerm->prereqAll;
  107596. }
  107597. }
  107598. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  107599. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  107600. /* When sqlite_stat3 histogram data is available an operator of the
  107601. ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
  107602. ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
  107603. ** virtual term of that form.
  107604. **
  107605. ** Note that the virtual term must be tagged with TERM_VNULL. This
  107606. ** TERM_VNULL tag will suppress the not-null check at the beginning
  107607. ** of the loop. Without the TERM_VNULL flag, the not-null check at
  107608. ** the start of the loop will prevent any results from being returned.
  107609. */
  107610. if( pExpr->op==TK_NOTNULL
  107611. && pExpr->pLeft->op==TK_COLUMN
  107612. && pExpr->pLeft->iColumn>=0
  107613. && OptimizationEnabled(db, SQLITE_Stat3)
  107614. ){
  107615. Expr *pNewExpr;
  107616. Expr *pLeft = pExpr->pLeft;
  107617. int idxNew;
  107618. WhereTerm *pNewTerm;
  107619. pNewExpr = sqlite3PExpr(pParse, TK_GT,
  107620. sqlite3ExprDup(db, pLeft, 0),
  107621. sqlite3PExpr(pParse, TK_NULL, 0, 0, 0), 0);
  107622. idxNew = whereClauseInsert(pWC, pNewExpr,
  107623. TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
  107624. if( idxNew ){
  107625. pNewTerm = &pWC->a[idxNew];
  107626. pNewTerm->prereqRight = 0;
  107627. pNewTerm->leftCursor = pLeft->iTable;
  107628. pNewTerm->u.leftColumn = pLeft->iColumn;
  107629. pNewTerm->eOperator = WO_GT;
  107630. pNewTerm->iParent = idxTerm;
  107631. pTerm = &pWC->a[idxTerm];
  107632. pTerm->nChild = 1;
  107633. pTerm->wtFlags |= TERM_COPIED;
  107634. pNewTerm->prereqAll = pTerm->prereqAll;
  107635. }
  107636. }
  107637. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  107638. /* Prevent ON clause terms of a LEFT JOIN from being used to drive
  107639. ** an index for tables to the left of the join.
  107640. */
  107641. pTerm->prereqRight |= extraRight;
  107642. }
  107643. /*
  107644. ** This function searches pList for an entry that matches the iCol-th column
  107645. ** of index pIdx.
  107646. **
  107647. ** If such an expression is found, its index in pList->a[] is returned. If
  107648. ** no expression is found, -1 is returned.
  107649. */
  107650. static int findIndexCol(
  107651. Parse *pParse, /* Parse context */
  107652. ExprList *pList, /* Expression list to search */
  107653. int iBase, /* Cursor for table associated with pIdx */
  107654. Index *pIdx, /* Index to match column of */
  107655. int iCol /* Column of index to match */
  107656. ){
  107657. int i;
  107658. const char *zColl = pIdx->azColl[iCol];
  107659. for(i=0; i<pList->nExpr; i++){
  107660. Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
  107661. if( p->op==TK_COLUMN
  107662. && p->iColumn==pIdx->aiColumn[iCol]
  107663. && p->iTable==iBase
  107664. ){
  107665. CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
  107666. if( ALWAYS(pColl) && 0==sqlite3StrICmp(pColl->zName, zColl) ){
  107667. return i;
  107668. }
  107669. }
  107670. }
  107671. return -1;
  107672. }
  107673. /*
  107674. ** Return true if the DISTINCT expression-list passed as the third argument
  107675. ** is redundant.
  107676. **
  107677. ** A DISTINCT list is redundant if the database contains some subset of
  107678. ** columns that are unique and non-null.
  107679. */
  107680. static int isDistinctRedundant(
  107681. Parse *pParse, /* Parsing context */
  107682. SrcList *pTabList, /* The FROM clause */
  107683. WhereClause *pWC, /* The WHERE clause */
  107684. ExprList *pDistinct /* The result set that needs to be DISTINCT */
  107685. ){
  107686. Table *pTab;
  107687. Index *pIdx;
  107688. int i;
  107689. int iBase;
  107690. /* If there is more than one table or sub-select in the FROM clause of
  107691. ** this query, then it will not be possible to show that the DISTINCT
  107692. ** clause is redundant. */
  107693. if( pTabList->nSrc!=1 ) return 0;
  107694. iBase = pTabList->a[0].iCursor;
  107695. pTab = pTabList->a[0].pTab;
  107696. /* If any of the expressions is an IPK column on table iBase, then return
  107697. ** true. Note: The (p->iTable==iBase) part of this test may be false if the
  107698. ** current SELECT is a correlated sub-query.
  107699. */
  107700. for(i=0; i<pDistinct->nExpr; i++){
  107701. Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
  107702. if( p->op==TK_COLUMN && p->iTable==iBase && p->iColumn<0 ) return 1;
  107703. }
  107704. /* Loop through all indices on the table, checking each to see if it makes
  107705. ** the DISTINCT qualifier redundant. It does so if:
  107706. **
  107707. ** 1. The index is itself UNIQUE, and
  107708. **
  107709. ** 2. All of the columns in the index are either part of the pDistinct
  107710. ** list, or else the WHERE clause contains a term of the form "col=X",
  107711. ** where X is a constant value. The collation sequences of the
  107712. ** comparison and select-list expressions must match those of the index.
  107713. **
  107714. ** 3. All of those index columns for which the WHERE clause does not
  107715. ** contain a "col=X" term are subject to a NOT NULL constraint.
  107716. */
  107717. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  107718. if( !IsUniqueIndex(pIdx) ) continue;
  107719. for(i=0; i<pIdx->nKeyCol; i++){
  107720. i16 iCol = pIdx->aiColumn[i];
  107721. if( 0==findTerm(pWC, iBase, iCol, ~(Bitmask)0, WO_EQ, pIdx) ){
  107722. int iIdxCol = findIndexCol(pParse, pDistinct, iBase, pIdx, i);
  107723. if( iIdxCol<0 || pTab->aCol[iCol].notNull==0 ){
  107724. break;
  107725. }
  107726. }
  107727. }
  107728. if( i==pIdx->nKeyCol ){
  107729. /* This index implies that the DISTINCT qualifier is redundant. */
  107730. return 1;
  107731. }
  107732. }
  107733. return 0;
  107734. }
  107735. /*
  107736. ** Estimate the logarithm of the input value to base 2.
  107737. */
  107738. static LogEst estLog(LogEst N){
  107739. return N<=10 ? 0 : sqlite3LogEst(N) - 33;
  107740. }
  107741. /*
  107742. ** Two routines for printing the content of an sqlite3_index_info
  107743. ** structure. Used for testing and debugging only. If neither
  107744. ** SQLITE_TEST or SQLITE_DEBUG are defined, then these routines
  107745. ** are no-ops.
  107746. */
  107747. #if !defined(SQLITE_OMIT_VIRTUALTABLE) && defined(WHERETRACE_ENABLED)
  107748. static void TRACE_IDX_INPUTS(sqlite3_index_info *p){
  107749. int i;
  107750. if( !sqlite3WhereTrace ) return;
  107751. for(i=0; i<p->nConstraint; i++){
  107752. sqlite3DebugPrintf(" constraint[%d]: col=%d termid=%d op=%d usabled=%d\n",
  107753. i,
  107754. p->aConstraint[i].iColumn,
  107755. p->aConstraint[i].iTermOffset,
  107756. p->aConstraint[i].op,
  107757. p->aConstraint[i].usable);
  107758. }
  107759. for(i=0; i<p->nOrderBy; i++){
  107760. sqlite3DebugPrintf(" orderby[%d]: col=%d desc=%d\n",
  107761. i,
  107762. p->aOrderBy[i].iColumn,
  107763. p->aOrderBy[i].desc);
  107764. }
  107765. }
  107766. static void TRACE_IDX_OUTPUTS(sqlite3_index_info *p){
  107767. int i;
  107768. if( !sqlite3WhereTrace ) return;
  107769. for(i=0; i<p->nConstraint; i++){
  107770. sqlite3DebugPrintf(" usage[%d]: argvIdx=%d omit=%d\n",
  107771. i,
  107772. p->aConstraintUsage[i].argvIndex,
  107773. p->aConstraintUsage[i].omit);
  107774. }
  107775. sqlite3DebugPrintf(" idxNum=%d\n", p->idxNum);
  107776. sqlite3DebugPrintf(" idxStr=%s\n", p->idxStr);
  107777. sqlite3DebugPrintf(" orderByConsumed=%d\n", p->orderByConsumed);
  107778. sqlite3DebugPrintf(" estimatedCost=%g\n", p->estimatedCost);
  107779. sqlite3DebugPrintf(" estimatedRows=%lld\n", p->estimatedRows);
  107780. }
  107781. #else
  107782. #define TRACE_IDX_INPUTS(A)
  107783. #define TRACE_IDX_OUTPUTS(A)
  107784. #endif
  107785. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  107786. /*
  107787. ** Return TRUE if the WHERE clause term pTerm is of a form where it
  107788. ** could be used with an index to access pSrc, assuming an appropriate
  107789. ** index existed.
  107790. */
  107791. static int termCanDriveIndex(
  107792. WhereTerm *pTerm, /* WHERE clause term to check */
  107793. struct SrcList_item *pSrc, /* Table we are trying to access */
  107794. Bitmask notReady /* Tables in outer loops of the join */
  107795. ){
  107796. char aff;
  107797. if( pTerm->leftCursor!=pSrc->iCursor ) return 0;
  107798. if( (pTerm->eOperator & WO_EQ)==0 ) return 0;
  107799. if( (pTerm->prereqRight & notReady)!=0 ) return 0;
  107800. if( pTerm->u.leftColumn<0 ) return 0;
  107801. aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
  107802. if( !sqlite3IndexAffinityOk(pTerm->pExpr, aff) ) return 0;
  107803. return 1;
  107804. }
  107805. #endif
  107806. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  107807. /*
  107808. ** Generate code to construct the Index object for an automatic index
  107809. ** and to set up the WhereLevel object pLevel so that the code generator
  107810. ** makes use of the automatic index.
  107811. */
  107812. static void constructAutomaticIndex(
  107813. Parse *pParse, /* The parsing context */
  107814. WhereClause *pWC, /* The WHERE clause */
  107815. struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
  107816. Bitmask notReady, /* Mask of cursors that are not available */
  107817. WhereLevel *pLevel /* Write new index here */
  107818. ){
  107819. int nKeyCol; /* Number of columns in the constructed index */
  107820. WhereTerm *pTerm; /* A single term of the WHERE clause */
  107821. WhereTerm *pWCEnd; /* End of pWC->a[] */
  107822. Index *pIdx; /* Object describing the transient index */
  107823. Vdbe *v; /* Prepared statement under construction */
  107824. int addrInit; /* Address of the initialization bypass jump */
  107825. Table *pTable; /* The table being indexed */
  107826. int addrTop; /* Top of the index fill loop */
  107827. int regRecord; /* Register holding an index record */
  107828. int n; /* Column counter */
  107829. int i; /* Loop counter */
  107830. int mxBitCol; /* Maximum column in pSrc->colUsed */
  107831. CollSeq *pColl; /* Collating sequence to on a column */
  107832. WhereLoop *pLoop; /* The Loop object */
  107833. char *zNotUsed; /* Extra space on the end of pIdx */
  107834. Bitmask idxCols; /* Bitmap of columns used for indexing */
  107835. Bitmask extraCols; /* Bitmap of additional columns */
  107836. u8 sentWarning = 0; /* True if a warnning has been issued */
  107837. /* Generate code to skip over the creation and initialization of the
  107838. ** transient index on 2nd and subsequent iterations of the loop. */
  107839. v = pParse->pVdbe;
  107840. assert( v!=0 );
  107841. addrInit = sqlite3CodeOnce(pParse); VdbeCoverage(v);
  107842. /* Count the number of columns that will be added to the index
  107843. ** and used to match WHERE clause constraints */
  107844. nKeyCol = 0;
  107845. pTable = pSrc->pTab;
  107846. pWCEnd = &pWC->a[pWC->nTerm];
  107847. pLoop = pLevel->pWLoop;
  107848. idxCols = 0;
  107849. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  107850. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  107851. int iCol = pTerm->u.leftColumn;
  107852. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  107853. testcase( iCol==BMS );
  107854. testcase( iCol==BMS-1 );
  107855. if( !sentWarning ){
  107856. sqlite3_log(SQLITE_WARNING_AUTOINDEX,
  107857. "automatic index on %s(%s)", pTable->zName,
  107858. pTable->aCol[iCol].zName);
  107859. sentWarning = 1;
  107860. }
  107861. if( (idxCols & cMask)==0 ){
  107862. if( whereLoopResize(pParse->db, pLoop, nKeyCol+1) ) return;
  107863. pLoop->aLTerm[nKeyCol++] = pTerm;
  107864. idxCols |= cMask;
  107865. }
  107866. }
  107867. }
  107868. assert( nKeyCol>0 );
  107869. pLoop->u.btree.nEq = pLoop->nLTerm = nKeyCol;
  107870. pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
  107871. | WHERE_AUTO_INDEX;
  107872. /* Count the number of additional columns needed to create a
  107873. ** covering index. A "covering index" is an index that contains all
  107874. ** columns that are needed by the query. With a covering index, the
  107875. ** original table never needs to be accessed. Automatic indices must
  107876. ** be a covering index because the index will not be updated if the
  107877. ** original table changes and the index and table cannot both be used
  107878. ** if they go out of sync.
  107879. */
  107880. extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS-1));
  107881. mxBitCol = (pTable->nCol >= BMS-1) ? BMS-1 : pTable->nCol;
  107882. testcase( pTable->nCol==BMS-1 );
  107883. testcase( pTable->nCol==BMS-2 );
  107884. for(i=0; i<mxBitCol; i++){
  107885. if( extraCols & MASKBIT(i) ) nKeyCol++;
  107886. }
  107887. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  107888. nKeyCol += pTable->nCol - BMS + 1;
  107889. }
  107890. pLoop->wsFlags |= WHERE_COLUMN_EQ | WHERE_IDX_ONLY;
  107891. /* Construct the Index object to describe this index */
  107892. pIdx = sqlite3AllocateIndexObject(pParse->db, nKeyCol+1, 0, &zNotUsed);
  107893. if( pIdx==0 ) return;
  107894. pLoop->u.btree.pIndex = pIdx;
  107895. pIdx->zName = "auto-index";
  107896. pIdx->pTable = pTable;
  107897. n = 0;
  107898. idxCols = 0;
  107899. for(pTerm=pWC->a; pTerm<pWCEnd; pTerm++){
  107900. if( termCanDriveIndex(pTerm, pSrc, notReady) ){
  107901. int iCol = pTerm->u.leftColumn;
  107902. Bitmask cMask = iCol>=BMS ? MASKBIT(BMS-1) : MASKBIT(iCol);
  107903. testcase( iCol==BMS-1 );
  107904. testcase( iCol==BMS );
  107905. if( (idxCols & cMask)==0 ){
  107906. Expr *pX = pTerm->pExpr;
  107907. idxCols |= cMask;
  107908. pIdx->aiColumn[n] = pTerm->u.leftColumn;
  107909. pColl = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pX->pRight);
  107910. pIdx->azColl[n] = ALWAYS(pColl) ? pColl->zName : "BINARY";
  107911. n++;
  107912. }
  107913. }
  107914. }
  107915. assert( (u32)n==pLoop->u.btree.nEq );
  107916. /* Add additional columns needed to make the automatic index into
  107917. ** a covering index */
  107918. for(i=0; i<mxBitCol; i++){
  107919. if( extraCols & MASKBIT(i) ){
  107920. pIdx->aiColumn[n] = i;
  107921. pIdx->azColl[n] = "BINARY";
  107922. n++;
  107923. }
  107924. }
  107925. if( pSrc->colUsed & MASKBIT(BMS-1) ){
  107926. for(i=BMS-1; i<pTable->nCol; i++){
  107927. pIdx->aiColumn[n] = i;
  107928. pIdx->azColl[n] = "BINARY";
  107929. n++;
  107930. }
  107931. }
  107932. assert( n==nKeyCol );
  107933. pIdx->aiColumn[n] = -1;
  107934. pIdx->azColl[n] = "BINARY";
  107935. /* Create the automatic index */
  107936. assert( pLevel->iIdxCur>=0 );
  107937. pLevel->iIdxCur = pParse->nTab++;
  107938. sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol+1);
  107939. sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
  107940. VdbeComment((v, "for %s", pTable->zName));
  107941. /* Fill the automatic index with content */
  107942. addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur); VdbeCoverage(v);
  107943. regRecord = sqlite3GetTempReg(pParse);
  107944. sqlite3GenerateIndexKey(pParse, pIdx, pLevel->iTabCur, regRecord, 0, 0, 0, 0);
  107945. sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
  107946. sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  107947. sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop+1); VdbeCoverage(v);
  107948. sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
  107949. sqlite3VdbeJumpHere(v, addrTop);
  107950. sqlite3ReleaseTempReg(pParse, regRecord);
  107951. /* Jump here when skipping the initialization */
  107952. sqlite3VdbeJumpHere(v, addrInit);
  107953. }
  107954. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  107955. #ifndef SQLITE_OMIT_VIRTUALTABLE
  107956. /*
  107957. ** Allocate and populate an sqlite3_index_info structure. It is the
  107958. ** responsibility of the caller to eventually release the structure
  107959. ** by passing the pointer returned by this function to sqlite3_free().
  107960. */
  107961. static sqlite3_index_info *allocateIndexInfo(
  107962. Parse *pParse,
  107963. WhereClause *pWC,
  107964. struct SrcList_item *pSrc,
  107965. ExprList *pOrderBy
  107966. ){
  107967. int i, j;
  107968. int nTerm;
  107969. struct sqlite3_index_constraint *pIdxCons;
  107970. struct sqlite3_index_orderby *pIdxOrderBy;
  107971. struct sqlite3_index_constraint_usage *pUsage;
  107972. WhereTerm *pTerm;
  107973. int nOrderBy;
  107974. sqlite3_index_info *pIdxInfo;
  107975. /* Count the number of possible WHERE clause constraints referring
  107976. ** to this virtual table */
  107977. for(i=nTerm=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  107978. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  107979. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  107980. testcase( pTerm->eOperator & WO_IN );
  107981. testcase( pTerm->eOperator & WO_ISNULL );
  107982. testcase( pTerm->eOperator & WO_ALL );
  107983. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
  107984. if( pTerm->wtFlags & TERM_VNULL ) continue;
  107985. nTerm++;
  107986. }
  107987. /* If the ORDER BY clause contains only columns in the current
  107988. ** virtual table then allocate space for the aOrderBy part of
  107989. ** the sqlite3_index_info structure.
  107990. */
  107991. nOrderBy = 0;
  107992. if( pOrderBy ){
  107993. int n = pOrderBy->nExpr;
  107994. for(i=0; i<n; i++){
  107995. Expr *pExpr = pOrderBy->a[i].pExpr;
  107996. if( pExpr->op!=TK_COLUMN || pExpr->iTable!=pSrc->iCursor ) break;
  107997. }
  107998. if( i==n){
  107999. nOrderBy = n;
  108000. }
  108001. }
  108002. /* Allocate the sqlite3_index_info structure
  108003. */
  108004. pIdxInfo = sqlite3DbMallocZero(pParse->db, sizeof(*pIdxInfo)
  108005. + (sizeof(*pIdxCons) + sizeof(*pUsage))*nTerm
  108006. + sizeof(*pIdxOrderBy)*nOrderBy );
  108007. if( pIdxInfo==0 ){
  108008. sqlite3ErrorMsg(pParse, "out of memory");
  108009. return 0;
  108010. }
  108011. /* Initialize the structure. The sqlite3_index_info structure contains
  108012. ** many fields that are declared "const" to prevent xBestIndex from
  108013. ** changing them. We have to do some funky casting in order to
  108014. ** initialize those fields.
  108015. */
  108016. pIdxCons = (struct sqlite3_index_constraint*)&pIdxInfo[1];
  108017. pIdxOrderBy = (struct sqlite3_index_orderby*)&pIdxCons[nTerm];
  108018. pUsage = (struct sqlite3_index_constraint_usage*)&pIdxOrderBy[nOrderBy];
  108019. *(int*)&pIdxInfo->nConstraint = nTerm;
  108020. *(int*)&pIdxInfo->nOrderBy = nOrderBy;
  108021. *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint = pIdxCons;
  108022. *(struct sqlite3_index_orderby**)&pIdxInfo->aOrderBy = pIdxOrderBy;
  108023. *(struct sqlite3_index_constraint_usage**)&pIdxInfo->aConstraintUsage =
  108024. pUsage;
  108025. for(i=j=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  108026. u8 op;
  108027. if( pTerm->leftCursor != pSrc->iCursor ) continue;
  108028. assert( IsPowerOfTwo(pTerm->eOperator & ~WO_EQUIV) );
  108029. testcase( pTerm->eOperator & WO_IN );
  108030. testcase( pTerm->eOperator & WO_ISNULL );
  108031. testcase( pTerm->eOperator & WO_ALL );
  108032. if( (pTerm->eOperator & ~(WO_ISNULL|WO_EQUIV))==0 ) continue;
  108033. if( pTerm->wtFlags & TERM_VNULL ) continue;
  108034. pIdxCons[j].iColumn = pTerm->u.leftColumn;
  108035. pIdxCons[j].iTermOffset = i;
  108036. op = (u8)pTerm->eOperator & WO_ALL;
  108037. if( op==WO_IN ) op = WO_EQ;
  108038. pIdxCons[j].op = op;
  108039. /* The direct assignment in the previous line is possible only because
  108040. ** the WO_ and SQLITE_INDEX_CONSTRAINT_ codes are identical. The
  108041. ** following asserts verify this fact. */
  108042. assert( WO_EQ==SQLITE_INDEX_CONSTRAINT_EQ );
  108043. assert( WO_LT==SQLITE_INDEX_CONSTRAINT_LT );
  108044. assert( WO_LE==SQLITE_INDEX_CONSTRAINT_LE );
  108045. assert( WO_GT==SQLITE_INDEX_CONSTRAINT_GT );
  108046. assert( WO_GE==SQLITE_INDEX_CONSTRAINT_GE );
  108047. assert( WO_MATCH==SQLITE_INDEX_CONSTRAINT_MATCH );
  108048. assert( pTerm->eOperator & (WO_IN|WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE|WO_MATCH) );
  108049. j++;
  108050. }
  108051. for(i=0; i<nOrderBy; i++){
  108052. Expr *pExpr = pOrderBy->a[i].pExpr;
  108053. pIdxOrderBy[i].iColumn = pExpr->iColumn;
  108054. pIdxOrderBy[i].desc = pOrderBy->a[i].sortOrder;
  108055. }
  108056. return pIdxInfo;
  108057. }
  108058. /*
  108059. ** The table object reference passed as the second argument to this function
  108060. ** must represent a virtual table. This function invokes the xBestIndex()
  108061. ** method of the virtual table with the sqlite3_index_info object that
  108062. ** comes in as the 3rd argument to this function.
  108063. **
  108064. ** If an error occurs, pParse is populated with an error message and a
  108065. ** non-zero value is returned. Otherwise, 0 is returned and the output
  108066. ** part of the sqlite3_index_info structure is left populated.
  108067. **
  108068. ** Whether or not an error is returned, it is the responsibility of the
  108069. ** caller to eventually free p->idxStr if p->needToFreeIdxStr indicates
  108070. ** that this is required.
  108071. */
  108072. static int vtabBestIndex(Parse *pParse, Table *pTab, sqlite3_index_info *p){
  108073. sqlite3_vtab *pVtab = sqlite3GetVTable(pParse->db, pTab)->pVtab;
  108074. int i;
  108075. int rc;
  108076. TRACE_IDX_INPUTS(p);
  108077. rc = pVtab->pModule->xBestIndex(pVtab, p);
  108078. TRACE_IDX_OUTPUTS(p);
  108079. if( rc!=SQLITE_OK ){
  108080. if( rc==SQLITE_NOMEM ){
  108081. pParse->db->mallocFailed = 1;
  108082. }else if( !pVtab->zErrMsg ){
  108083. sqlite3ErrorMsg(pParse, "%s", sqlite3ErrStr(rc));
  108084. }else{
  108085. sqlite3ErrorMsg(pParse, "%s", pVtab->zErrMsg);
  108086. }
  108087. }
  108088. sqlite3_free(pVtab->zErrMsg);
  108089. pVtab->zErrMsg = 0;
  108090. for(i=0; i<p->nConstraint; i++){
  108091. if( !p->aConstraint[i].usable && p->aConstraintUsage[i].argvIndex>0 ){
  108092. sqlite3ErrorMsg(pParse,
  108093. "table %s: xBestIndex returned an invalid plan", pTab->zName);
  108094. }
  108095. }
  108096. return pParse->nErr;
  108097. }
  108098. #endif /* !defined(SQLITE_OMIT_VIRTUALTABLE) */
  108099. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108100. /*
  108101. ** Estimate the location of a particular key among all keys in an
  108102. ** index. Store the results in aStat as follows:
  108103. **
  108104. ** aStat[0] Est. number of rows less than pVal
  108105. ** aStat[1] Est. number of rows equal to pVal
  108106. **
  108107. ** Return SQLITE_OK on success.
  108108. */
  108109. static void whereKeyStats(
  108110. Parse *pParse, /* Database connection */
  108111. Index *pIdx, /* Index to consider domain of */
  108112. UnpackedRecord *pRec, /* Vector of values to consider */
  108113. int roundUp, /* Round up if true. Round down if false */
  108114. tRowcnt *aStat /* OUT: stats written here */
  108115. ){
  108116. IndexSample *aSample = pIdx->aSample;
  108117. int iCol; /* Index of required stats in anEq[] etc. */
  108118. int iMin = 0; /* Smallest sample not yet tested */
  108119. int i = pIdx->nSample; /* Smallest sample larger than or equal to pRec */
  108120. int iTest; /* Next sample to test */
  108121. int res; /* Result of comparison operation */
  108122. #ifndef SQLITE_DEBUG
  108123. UNUSED_PARAMETER( pParse );
  108124. #endif
  108125. assert( pRec!=0 );
  108126. iCol = pRec->nField - 1;
  108127. assert( pIdx->nSample>0 );
  108128. assert( pRec->nField>0 && iCol<pIdx->nSampleCol );
  108129. do{
  108130. iTest = (iMin+i)/2;
  108131. res = sqlite3VdbeRecordCompare(aSample[iTest].n, aSample[iTest].p, pRec);
  108132. if( res<0 ){
  108133. iMin = iTest+1;
  108134. }else{
  108135. i = iTest;
  108136. }
  108137. }while( res && iMin<i );
  108138. #ifdef SQLITE_DEBUG
  108139. /* The following assert statements check that the binary search code
  108140. ** above found the right answer. This block serves no purpose other
  108141. ** than to invoke the asserts. */
  108142. if( res==0 ){
  108143. /* If (res==0) is true, then sample $i must be equal to pRec */
  108144. assert( i<pIdx->nSample );
  108145. assert( 0==sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)
  108146. || pParse->db->mallocFailed );
  108147. }else{
  108148. /* Otherwise, pRec must be smaller than sample $i and larger than
  108149. ** sample ($i-1). */
  108150. assert( i==pIdx->nSample
  108151. || sqlite3VdbeRecordCompare(aSample[i].n, aSample[i].p, pRec)>0
  108152. || pParse->db->mallocFailed );
  108153. assert( i==0
  108154. || sqlite3VdbeRecordCompare(aSample[i-1].n, aSample[i-1].p, pRec)<0
  108155. || pParse->db->mallocFailed );
  108156. }
  108157. #endif /* ifdef SQLITE_DEBUG */
  108158. /* At this point, aSample[i] is the first sample that is greater than
  108159. ** or equal to pVal. Or if i==pIdx->nSample, then all samples are less
  108160. ** than pVal. If aSample[i]==pVal, then res==0.
  108161. */
  108162. if( res==0 ){
  108163. aStat[0] = aSample[i].anLt[iCol];
  108164. aStat[1] = aSample[i].anEq[iCol];
  108165. }else{
  108166. tRowcnt iLower, iUpper, iGap;
  108167. if( i==0 ){
  108168. iLower = 0;
  108169. iUpper = aSample[0].anLt[iCol];
  108170. }else{
  108171. i64 nRow0 = sqlite3LogEstToInt(pIdx->aiRowLogEst[0]);
  108172. iUpper = i>=pIdx->nSample ? nRow0 : aSample[i].anLt[iCol];
  108173. iLower = aSample[i-1].anEq[iCol] + aSample[i-1].anLt[iCol];
  108174. }
  108175. aStat[1] = pIdx->aAvgEq[iCol];
  108176. if( iLower>=iUpper ){
  108177. iGap = 0;
  108178. }else{
  108179. iGap = iUpper - iLower;
  108180. }
  108181. if( roundUp ){
  108182. iGap = (iGap*2)/3;
  108183. }else{
  108184. iGap = iGap/3;
  108185. }
  108186. aStat[0] = iLower + iGap;
  108187. }
  108188. }
  108189. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108190. /*
  108191. ** If it is not NULL, pTerm is a term that provides an upper or lower
  108192. ** bound on a range scan. Without considering pTerm, it is estimated
  108193. ** that the scan will visit nNew rows. This function returns the number
  108194. ** estimated to be visited after taking pTerm into account.
  108195. **
  108196. ** If the user explicitly specified a likelihood() value for this term,
  108197. ** then the return value is the likelihood multiplied by the number of
  108198. ** input rows. Otherwise, this function assumes that an "IS NOT NULL" term
  108199. ** has a likelihood of 0.50, and any other term a likelihood of 0.25.
  108200. */
  108201. static LogEst whereRangeAdjust(WhereTerm *pTerm, LogEst nNew){
  108202. LogEst nRet = nNew;
  108203. if( pTerm ){
  108204. if( pTerm->truthProb<=0 ){
  108205. nRet += pTerm->truthProb;
  108206. }else if( (pTerm->wtFlags & TERM_VNULL)==0 ){
  108207. nRet -= 20; assert( 20==sqlite3LogEst(4) );
  108208. }
  108209. }
  108210. return nRet;
  108211. }
  108212. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108213. /*
  108214. ** This function is called to estimate the number of rows visited by a
  108215. ** range-scan on a skip-scan index. For example:
  108216. **
  108217. ** CREATE INDEX i1 ON t1(a, b, c);
  108218. ** SELECT * FROM t1 WHERE a=? AND c BETWEEN ? AND ?;
  108219. **
  108220. ** Value pLoop->nOut is currently set to the estimated number of rows
  108221. ** visited for scanning (a=? AND b=?). This function reduces that estimate
  108222. ** by some factor to account for the (c BETWEEN ? AND ?) expression based
  108223. ** on the stat4 data for the index. this scan will be peformed multiple
  108224. ** times (once for each (a,b) combination that matches a=?) is dealt with
  108225. ** by the caller.
  108226. **
  108227. ** It does this by scanning through all stat4 samples, comparing values
  108228. ** extracted from pLower and pUpper with the corresponding column in each
  108229. ** sample. If L and U are the number of samples found to be less than or
  108230. ** equal to the values extracted from pLower and pUpper respectively, and
  108231. ** N is the total number of samples, the pLoop->nOut value is adjusted
  108232. ** as follows:
  108233. **
  108234. ** nOut = nOut * ( min(U - L, 1) / N )
  108235. **
  108236. ** If pLower is NULL, or a value cannot be extracted from the term, L is
  108237. ** set to zero. If pUpper is NULL, or a value cannot be extracted from it,
  108238. ** U is set to N.
  108239. **
  108240. ** Normally, this function sets *pbDone to 1 before returning. However,
  108241. ** if no value can be extracted from either pLower or pUpper (and so the
  108242. ** estimate of the number of rows delivered remains unchanged), *pbDone
  108243. ** is left as is.
  108244. **
  108245. ** If an error occurs, an SQLite error code is returned. Otherwise,
  108246. ** SQLITE_OK.
  108247. */
  108248. static int whereRangeSkipScanEst(
  108249. Parse *pParse, /* Parsing & code generating context */
  108250. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  108251. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  108252. WhereLoop *pLoop, /* Update the .nOut value of this loop */
  108253. int *pbDone /* Set to true if at least one expr. value extracted */
  108254. ){
  108255. Index *p = pLoop->u.btree.pIndex;
  108256. int nEq = pLoop->u.btree.nEq;
  108257. sqlite3 *db = pParse->db;
  108258. int nLower = -1;
  108259. int nUpper = p->nSample+1;
  108260. int rc = SQLITE_OK;
  108261. int iCol = p->aiColumn[nEq];
  108262. u8 aff = iCol>=0 ? p->pTable->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
  108263. CollSeq *pColl;
  108264. sqlite3_value *p1 = 0; /* Value extracted from pLower */
  108265. sqlite3_value *p2 = 0; /* Value extracted from pUpper */
  108266. sqlite3_value *pVal = 0; /* Value extracted from record */
  108267. pColl = sqlite3LocateCollSeq(pParse, p->azColl[nEq]);
  108268. if( pLower ){
  108269. rc = sqlite3Stat4ValueFromExpr(pParse, pLower->pExpr->pRight, aff, &p1);
  108270. nLower = 0;
  108271. }
  108272. if( pUpper && rc==SQLITE_OK ){
  108273. rc = sqlite3Stat4ValueFromExpr(pParse, pUpper->pExpr->pRight, aff, &p2);
  108274. nUpper = p2 ? 0 : p->nSample;
  108275. }
  108276. if( p1 || p2 ){
  108277. int i;
  108278. int nDiff;
  108279. for(i=0; rc==SQLITE_OK && i<p->nSample; i++){
  108280. rc = sqlite3Stat4Column(db, p->aSample[i].p, p->aSample[i].n, nEq, &pVal);
  108281. if( rc==SQLITE_OK && p1 ){
  108282. int res = sqlite3MemCompare(p1, pVal, pColl);
  108283. if( res>=0 ) nLower++;
  108284. }
  108285. if( rc==SQLITE_OK && p2 ){
  108286. int res = sqlite3MemCompare(p2, pVal, pColl);
  108287. if( res>=0 ) nUpper++;
  108288. }
  108289. }
  108290. nDiff = (nUpper - nLower);
  108291. if( nDiff<=0 ) nDiff = 1;
  108292. /* If there is both an upper and lower bound specified, and the
  108293. ** comparisons indicate that they are close together, use the fallback
  108294. ** method (assume that the scan visits 1/64 of the rows) for estimating
  108295. ** the number of rows visited. Otherwise, estimate the number of rows
  108296. ** using the method described in the header comment for this function. */
  108297. if( nDiff!=1 || pUpper==0 || pLower==0 ){
  108298. int nAdjust = (sqlite3LogEst(p->nSample) - sqlite3LogEst(nDiff));
  108299. pLoop->nOut -= nAdjust;
  108300. *pbDone = 1;
  108301. WHERETRACE(0x10, ("range skip-scan regions: %u..%u adjust=%d est=%d\n",
  108302. nLower, nUpper, nAdjust*-1, pLoop->nOut));
  108303. }
  108304. }else{
  108305. assert( *pbDone==0 );
  108306. }
  108307. sqlite3ValueFree(p1);
  108308. sqlite3ValueFree(p2);
  108309. sqlite3ValueFree(pVal);
  108310. return rc;
  108311. }
  108312. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108313. /*
  108314. ** This function is used to estimate the number of rows that will be visited
  108315. ** by scanning an index for a range of values. The range may have an upper
  108316. ** bound, a lower bound, or both. The WHERE clause terms that set the upper
  108317. ** and lower bounds are represented by pLower and pUpper respectively. For
  108318. ** example, assuming that index p is on t1(a):
  108319. **
  108320. ** ... FROM t1 WHERE a > ? AND a < ? ...
  108321. ** |_____| |_____|
  108322. ** | |
  108323. ** pLower pUpper
  108324. **
  108325. ** If either of the upper or lower bound is not present, then NULL is passed in
  108326. ** place of the corresponding WhereTerm.
  108327. **
  108328. ** The value in (pBuilder->pNew->u.btree.nEq) is the index of the index
  108329. ** column subject to the range constraint. Or, equivalently, the number of
  108330. ** equality constraints optimized by the proposed index scan. For example,
  108331. ** assuming index p is on t1(a, b), and the SQL query is:
  108332. **
  108333. ** ... FROM t1 WHERE a = ? AND b > ? AND b < ? ...
  108334. **
  108335. ** then nEq is set to 1 (as the range restricted column, b, is the second
  108336. ** left-most column of the index). Or, if the query is:
  108337. **
  108338. ** ... FROM t1 WHERE a > ? AND a < ? ...
  108339. **
  108340. ** then nEq is set to 0.
  108341. **
  108342. ** When this function is called, *pnOut is set to the sqlite3LogEst() of the
  108343. ** number of rows that the index scan is expected to visit without
  108344. ** considering the range constraints. If nEq is 0, this is the number of
  108345. ** rows in the index. Assuming no error occurs, *pnOut is adjusted (reduced)
  108346. ** to account for the range constraints pLower and pUpper.
  108347. **
  108348. ** In the absence of sqlite_stat4 ANALYZE data, or if such data cannot be
  108349. ** used, a single range inequality reduces the search space by a factor of 4.
  108350. ** and a pair of constraints (x>? AND x<?) reduces the expected number of
  108351. ** rows visited by a factor of 64.
  108352. */
  108353. static int whereRangeScanEst(
  108354. Parse *pParse, /* Parsing & code generating context */
  108355. WhereLoopBuilder *pBuilder,
  108356. WhereTerm *pLower, /* Lower bound on the range. ex: "x>123" Might be NULL */
  108357. WhereTerm *pUpper, /* Upper bound on the range. ex: "x<455" Might be NULL */
  108358. WhereLoop *pLoop /* Modify the .nOut and maybe .rRun fields */
  108359. ){
  108360. int rc = SQLITE_OK;
  108361. int nOut = pLoop->nOut;
  108362. LogEst nNew;
  108363. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108364. Index *p = pLoop->u.btree.pIndex;
  108365. int nEq = pLoop->u.btree.nEq;
  108366. if( p->nSample>0
  108367. && nEq<p->nSampleCol
  108368. && OptimizationEnabled(pParse->db, SQLITE_Stat3)
  108369. ){
  108370. if( nEq==pBuilder->nRecValid ){
  108371. UnpackedRecord *pRec = pBuilder->pRec;
  108372. tRowcnt a[2];
  108373. u8 aff;
  108374. /* Variable iLower will be set to the estimate of the number of rows in
  108375. ** the index that are less than the lower bound of the range query. The
  108376. ** lower bound being the concatenation of $P and $L, where $P is the
  108377. ** key-prefix formed by the nEq values matched against the nEq left-most
  108378. ** columns of the index, and $L is the value in pLower.
  108379. **
  108380. ** Or, if pLower is NULL or $L cannot be extracted from it (because it
  108381. ** is not a simple variable or literal value), the lower bound of the
  108382. ** range is $P. Due to a quirk in the way whereKeyStats() works, even
  108383. ** if $L is available, whereKeyStats() is called for both ($P) and
  108384. ** ($P:$L) and the larger of the two returned values used.
  108385. **
  108386. ** Similarly, iUpper is to be set to the estimate of the number of rows
  108387. ** less than the upper bound of the range query. Where the upper bound
  108388. ** is either ($P) or ($P:$U). Again, even if $U is available, both values
  108389. ** of iUpper are requested of whereKeyStats() and the smaller used.
  108390. */
  108391. tRowcnt iLower;
  108392. tRowcnt iUpper;
  108393. if( pRec ){
  108394. testcase( pRec->nField!=pBuilder->nRecValid );
  108395. pRec->nField = pBuilder->nRecValid;
  108396. }
  108397. if( nEq==p->nKeyCol ){
  108398. aff = SQLITE_AFF_INTEGER;
  108399. }else{
  108400. aff = p->pTable->aCol[p->aiColumn[nEq]].affinity;
  108401. }
  108402. /* Determine iLower and iUpper using ($P) only. */
  108403. if( nEq==0 ){
  108404. iLower = 0;
  108405. iUpper = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  108406. }else{
  108407. /* Note: this call could be optimized away - since the same values must
  108408. ** have been requested when testing key $P in whereEqualScanEst(). */
  108409. whereKeyStats(pParse, p, pRec, 0, a);
  108410. iLower = a[0];
  108411. iUpper = a[0] + a[1];
  108412. }
  108413. assert( pLower==0 || (pLower->eOperator & (WO_GT|WO_GE))!=0 );
  108414. assert( pUpper==0 || (pUpper->eOperator & (WO_LT|WO_LE))!=0 );
  108415. assert( p->aSortOrder!=0 );
  108416. if( p->aSortOrder[nEq] ){
  108417. /* The roles of pLower and pUpper are swapped for a DESC index */
  108418. SWAP(WhereTerm*, pLower, pUpper);
  108419. }
  108420. /* If possible, improve on the iLower estimate using ($P:$L). */
  108421. if( pLower ){
  108422. int bOk; /* True if value is extracted from pExpr */
  108423. Expr *pExpr = pLower->pExpr->pRight;
  108424. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  108425. if( rc==SQLITE_OK && bOk ){
  108426. tRowcnt iNew;
  108427. whereKeyStats(pParse, p, pRec, 0, a);
  108428. iNew = a[0] + ((pLower->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  108429. if( iNew>iLower ) iLower = iNew;
  108430. nOut--;
  108431. pLower = 0;
  108432. }
  108433. }
  108434. /* If possible, improve on the iUpper estimate using ($P:$U). */
  108435. if( pUpper ){
  108436. int bOk; /* True if value is extracted from pExpr */
  108437. Expr *pExpr = pUpper->pExpr->pRight;
  108438. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq, &bOk);
  108439. if( rc==SQLITE_OK && bOk ){
  108440. tRowcnt iNew;
  108441. whereKeyStats(pParse, p, pRec, 1, a);
  108442. iNew = a[0] + ((pUpper->eOperator & (WO_GT|WO_LE)) ? a[1] : 0);
  108443. if( iNew<iUpper ) iUpper = iNew;
  108444. nOut--;
  108445. pUpper = 0;
  108446. }
  108447. }
  108448. pBuilder->pRec = pRec;
  108449. if( rc==SQLITE_OK ){
  108450. if( iUpper>iLower ){
  108451. nNew = sqlite3LogEst(iUpper - iLower);
  108452. }else{
  108453. nNew = 10; assert( 10==sqlite3LogEst(2) );
  108454. }
  108455. if( nNew<nOut ){
  108456. nOut = nNew;
  108457. }
  108458. WHERETRACE(0x10, ("STAT4 range scan: %u..%u est=%d\n",
  108459. (u32)iLower, (u32)iUpper, nOut));
  108460. }
  108461. }else{
  108462. int bDone = 0;
  108463. rc = whereRangeSkipScanEst(pParse, pLower, pUpper, pLoop, &bDone);
  108464. if( bDone ) return rc;
  108465. }
  108466. }
  108467. #else
  108468. UNUSED_PARAMETER(pParse);
  108469. UNUSED_PARAMETER(pBuilder);
  108470. assert( pLower || pUpper );
  108471. #endif
  108472. assert( pUpper==0 || (pUpper->wtFlags & TERM_VNULL)==0 );
  108473. nNew = whereRangeAdjust(pLower, nOut);
  108474. nNew = whereRangeAdjust(pUpper, nNew);
  108475. /* TUNING: If there is both an upper and lower limit, assume the range is
  108476. ** reduced by an additional 75%. This means that, by default, an open-ended
  108477. ** range query (e.g. col > ?) is assumed to match 1/4 of the rows in the
  108478. ** index. While a closed range (e.g. col BETWEEN ? AND ?) is estimated to
  108479. ** match 1/64 of the index. */
  108480. if( pLower && pUpper ) nNew -= 20;
  108481. nOut -= (pLower!=0) + (pUpper!=0);
  108482. if( nNew<10 ) nNew = 10;
  108483. if( nNew<nOut ) nOut = nNew;
  108484. #if defined(WHERETRACE_ENABLED)
  108485. if( pLoop->nOut>nOut ){
  108486. WHERETRACE(0x10,("Range scan lowers nOut from %d to %d\n",
  108487. pLoop->nOut, nOut));
  108488. }
  108489. #endif
  108490. pLoop->nOut = (LogEst)nOut;
  108491. return rc;
  108492. }
  108493. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108494. /*
  108495. ** Estimate the number of rows that will be returned based on
  108496. ** an equality constraint x=VALUE and where that VALUE occurs in
  108497. ** the histogram data. This only works when x is the left-most
  108498. ** column of an index and sqlite_stat3 histogram data is available
  108499. ** for that index. When pExpr==NULL that means the constraint is
  108500. ** "x IS NULL" instead of "x=VALUE".
  108501. **
  108502. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  108503. ** If unable to make an estimate, leave *pnRow unchanged and return
  108504. ** non-zero.
  108505. **
  108506. ** This routine can fail if it is unable to load a collating sequence
  108507. ** required for string comparison, or if unable to allocate memory
  108508. ** for a UTF conversion required for comparison. The error is stored
  108509. ** in the pParse structure.
  108510. */
  108511. static int whereEqualScanEst(
  108512. Parse *pParse, /* Parsing & code generating context */
  108513. WhereLoopBuilder *pBuilder,
  108514. Expr *pExpr, /* Expression for VALUE in the x=VALUE constraint */
  108515. tRowcnt *pnRow /* Write the revised row estimate here */
  108516. ){
  108517. Index *p = pBuilder->pNew->u.btree.pIndex;
  108518. int nEq = pBuilder->pNew->u.btree.nEq;
  108519. UnpackedRecord *pRec = pBuilder->pRec;
  108520. u8 aff; /* Column affinity */
  108521. int rc; /* Subfunction return code */
  108522. tRowcnt a[2]; /* Statistics */
  108523. int bOk;
  108524. assert( nEq>=1 );
  108525. assert( nEq<=p->nColumn );
  108526. assert( p->aSample!=0 );
  108527. assert( p->nSample>0 );
  108528. assert( pBuilder->nRecValid<nEq );
  108529. /* If values are not available for all fields of the index to the left
  108530. ** of this one, no estimate can be made. Return SQLITE_NOTFOUND. */
  108531. if( pBuilder->nRecValid<(nEq-1) ){
  108532. return SQLITE_NOTFOUND;
  108533. }
  108534. /* This is an optimization only. The call to sqlite3Stat4ProbeSetValue()
  108535. ** below would return the same value. */
  108536. if( nEq>=p->nColumn ){
  108537. *pnRow = 1;
  108538. return SQLITE_OK;
  108539. }
  108540. aff = p->pTable->aCol[p->aiColumn[nEq-1]].affinity;
  108541. rc = sqlite3Stat4ProbeSetValue(pParse, p, &pRec, pExpr, aff, nEq-1, &bOk);
  108542. pBuilder->pRec = pRec;
  108543. if( rc!=SQLITE_OK ) return rc;
  108544. if( bOk==0 ) return SQLITE_NOTFOUND;
  108545. pBuilder->nRecValid = nEq;
  108546. whereKeyStats(pParse, p, pRec, 0, a);
  108547. WHERETRACE(0x10,("equality scan regions: %d\n", (int)a[1]));
  108548. *pnRow = a[1];
  108549. return rc;
  108550. }
  108551. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108552. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  108553. /*
  108554. ** Estimate the number of rows that will be returned based on
  108555. ** an IN constraint where the right-hand side of the IN operator
  108556. ** is a list of values. Example:
  108557. **
  108558. ** WHERE x IN (1,2,3,4)
  108559. **
  108560. ** Write the estimated row count into *pnRow and return SQLITE_OK.
  108561. ** If unable to make an estimate, leave *pnRow unchanged and return
  108562. ** non-zero.
  108563. **
  108564. ** This routine can fail if it is unable to load a collating sequence
  108565. ** required for string comparison, or if unable to allocate memory
  108566. ** for a UTF conversion required for comparison. The error is stored
  108567. ** in the pParse structure.
  108568. */
  108569. static int whereInScanEst(
  108570. Parse *pParse, /* Parsing & code generating context */
  108571. WhereLoopBuilder *pBuilder,
  108572. ExprList *pList, /* The value list on the RHS of "x IN (v1,v2,v3,...)" */
  108573. tRowcnt *pnRow /* Write the revised row estimate here */
  108574. ){
  108575. Index *p = pBuilder->pNew->u.btree.pIndex;
  108576. i64 nRow0 = sqlite3LogEstToInt(p->aiRowLogEst[0]);
  108577. int nRecValid = pBuilder->nRecValid;
  108578. int rc = SQLITE_OK; /* Subfunction return code */
  108579. tRowcnt nEst; /* Number of rows for a single term */
  108580. tRowcnt nRowEst = 0; /* New estimate of the number of rows */
  108581. int i; /* Loop counter */
  108582. assert( p->aSample!=0 );
  108583. for(i=0; rc==SQLITE_OK && i<pList->nExpr; i++){
  108584. nEst = nRow0;
  108585. rc = whereEqualScanEst(pParse, pBuilder, pList->a[i].pExpr, &nEst);
  108586. nRowEst += nEst;
  108587. pBuilder->nRecValid = nRecValid;
  108588. }
  108589. if( rc==SQLITE_OK ){
  108590. if( nRowEst > nRow0 ) nRowEst = nRow0;
  108591. *pnRow = nRowEst;
  108592. WHERETRACE(0x10,("IN row estimate: est=%d\n", nRowEst));
  108593. }
  108594. assert( pBuilder->nRecValid==nRecValid );
  108595. return rc;
  108596. }
  108597. #endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
  108598. /*
  108599. ** Disable a term in the WHERE clause. Except, do not disable the term
  108600. ** if it controls a LEFT OUTER JOIN and it did not originate in the ON
  108601. ** or USING clause of that join.
  108602. **
  108603. ** Consider the term t2.z='ok' in the following queries:
  108604. **
  108605. ** (1) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x WHERE t2.z='ok'
  108606. ** (2) SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.x AND t2.z='ok'
  108607. ** (3) SELECT * FROM t1, t2 WHERE t1.a=t2.x AND t2.z='ok'
  108608. **
  108609. ** The t2.z='ok' is disabled in the in (2) because it originates
  108610. ** in the ON clause. The term is disabled in (3) because it is not part
  108611. ** of a LEFT OUTER JOIN. In (1), the term is not disabled.
  108612. **
  108613. ** Disabling a term causes that term to not be tested in the inner loop
  108614. ** of the join. Disabling is an optimization. When terms are satisfied
  108615. ** by indices, we disable them to prevent redundant tests in the inner
  108616. ** loop. We would get the correct results if nothing were ever disabled,
  108617. ** but joins might run a little slower. The trick is to disable as much
  108618. ** as we can without disabling too much. If we disabled in (1), we'd get
  108619. ** the wrong answer. See ticket #813.
  108620. */
  108621. static void disableTerm(WhereLevel *pLevel, WhereTerm *pTerm){
  108622. if( pTerm
  108623. && (pTerm->wtFlags & TERM_CODED)==0
  108624. && (pLevel->iLeftJoin==0 || ExprHasProperty(pTerm->pExpr, EP_FromJoin))
  108625. && (pLevel->notReady & pTerm->prereqAll)==0
  108626. ){
  108627. pTerm->wtFlags |= TERM_CODED;
  108628. if( pTerm->iParent>=0 ){
  108629. WhereTerm *pOther = &pTerm->pWC->a[pTerm->iParent];
  108630. if( (--pOther->nChild)==0 ){
  108631. disableTerm(pLevel, pOther);
  108632. }
  108633. }
  108634. }
  108635. }
  108636. /*
  108637. ** Code an OP_Affinity opcode to apply the column affinity string zAff
  108638. ** to the n registers starting at base.
  108639. **
  108640. ** As an optimization, SQLITE_AFF_NONE entries (which are no-ops) at the
  108641. ** beginning and end of zAff are ignored. If all entries in zAff are
  108642. ** SQLITE_AFF_NONE, then no code gets generated.
  108643. **
  108644. ** This routine makes its own copy of zAff so that the caller is free
  108645. ** to modify zAff after this routine returns.
  108646. */
  108647. static void codeApplyAffinity(Parse *pParse, int base, int n, char *zAff){
  108648. Vdbe *v = pParse->pVdbe;
  108649. if( zAff==0 ){
  108650. assert( pParse->db->mallocFailed );
  108651. return;
  108652. }
  108653. assert( v!=0 );
  108654. /* Adjust base and n to skip over SQLITE_AFF_NONE entries at the beginning
  108655. ** and end of the affinity string.
  108656. */
  108657. while( n>0 && zAff[0]==SQLITE_AFF_NONE ){
  108658. n--;
  108659. base++;
  108660. zAff++;
  108661. }
  108662. while( n>1 && zAff[n-1]==SQLITE_AFF_NONE ){
  108663. n--;
  108664. }
  108665. /* Code the OP_Affinity opcode if there is anything left to do. */
  108666. if( n>0 ){
  108667. sqlite3VdbeAddOp2(v, OP_Affinity, base, n);
  108668. sqlite3VdbeChangeP4(v, -1, zAff, n);
  108669. sqlite3ExprCacheAffinityChange(pParse, base, n);
  108670. }
  108671. }
  108672. /*
  108673. ** Generate code for a single equality term of the WHERE clause. An equality
  108674. ** term can be either X=expr or X IN (...). pTerm is the term to be
  108675. ** coded.
  108676. **
  108677. ** The current value for the constraint is left in register iReg.
  108678. **
  108679. ** For a constraint of the form X=expr, the expression is evaluated and its
  108680. ** result is left on the stack. For constraints of the form X IN (...)
  108681. ** this routine sets up a loop that will iterate over all values of X.
  108682. */
  108683. static int codeEqualityTerm(
  108684. Parse *pParse, /* The parsing context */
  108685. WhereTerm *pTerm, /* The term of the WHERE clause to be coded */
  108686. WhereLevel *pLevel, /* The level of the FROM clause we are working on */
  108687. int iEq, /* Index of the equality term within this level */
  108688. int bRev, /* True for reverse-order IN operations */
  108689. int iTarget /* Attempt to leave results in this register */
  108690. ){
  108691. Expr *pX = pTerm->pExpr;
  108692. Vdbe *v = pParse->pVdbe;
  108693. int iReg; /* Register holding results */
  108694. assert( iTarget>0 );
  108695. if( pX->op==TK_EQ ){
  108696. iReg = sqlite3ExprCodeTarget(pParse, pX->pRight, iTarget);
  108697. }else if( pX->op==TK_ISNULL ){
  108698. iReg = iTarget;
  108699. sqlite3VdbeAddOp2(v, OP_Null, 0, iReg);
  108700. #ifndef SQLITE_OMIT_SUBQUERY
  108701. }else{
  108702. int eType;
  108703. int iTab;
  108704. struct InLoop *pIn;
  108705. WhereLoop *pLoop = pLevel->pWLoop;
  108706. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0
  108707. && pLoop->u.btree.pIndex!=0
  108708. && pLoop->u.btree.pIndex->aSortOrder[iEq]
  108709. ){
  108710. testcase( iEq==0 );
  108711. testcase( bRev );
  108712. bRev = !bRev;
  108713. }
  108714. assert( pX->op==TK_IN );
  108715. iReg = iTarget;
  108716. eType = sqlite3FindInIndex(pParse, pX, IN_INDEX_LOOP, 0);
  108717. if( eType==IN_INDEX_INDEX_DESC ){
  108718. testcase( bRev );
  108719. bRev = !bRev;
  108720. }
  108721. iTab = pX->iTable;
  108722. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iTab, 0);
  108723. VdbeCoverageIf(v, bRev);
  108724. VdbeCoverageIf(v, !bRev);
  108725. assert( (pLoop->wsFlags & WHERE_MULTI_OR)==0 );
  108726. pLoop->wsFlags |= WHERE_IN_ABLE;
  108727. if( pLevel->u.in.nIn==0 ){
  108728. pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  108729. }
  108730. pLevel->u.in.nIn++;
  108731. pLevel->u.in.aInLoop =
  108732. sqlite3DbReallocOrFree(pParse->db, pLevel->u.in.aInLoop,
  108733. sizeof(pLevel->u.in.aInLoop[0])*pLevel->u.in.nIn);
  108734. pIn = pLevel->u.in.aInLoop;
  108735. if( pIn ){
  108736. pIn += pLevel->u.in.nIn - 1;
  108737. pIn->iCur = iTab;
  108738. if( eType==IN_INDEX_ROWID ){
  108739. pIn->addrInTop = sqlite3VdbeAddOp2(v, OP_Rowid, iTab, iReg);
  108740. }else{
  108741. pIn->addrInTop = sqlite3VdbeAddOp3(v, OP_Column, iTab, 0, iReg);
  108742. }
  108743. pIn->eEndLoopOp = bRev ? OP_PrevIfOpen : OP_NextIfOpen;
  108744. sqlite3VdbeAddOp1(v, OP_IsNull, iReg); VdbeCoverage(v);
  108745. }else{
  108746. pLevel->u.in.nIn = 0;
  108747. }
  108748. #endif
  108749. }
  108750. disableTerm(pLevel, pTerm);
  108751. return iReg;
  108752. }
  108753. /*
  108754. ** Generate code that will evaluate all == and IN constraints for an
  108755. ** index scan.
  108756. **
  108757. ** For example, consider table t1(a,b,c,d,e,f) with index i1(a,b,c).
  108758. ** Suppose the WHERE clause is this: a==5 AND b IN (1,2,3) AND c>5 AND c<10
  108759. ** The index has as many as three equality constraints, but in this
  108760. ** example, the third "c" value is an inequality. So only two
  108761. ** constraints are coded. This routine will generate code to evaluate
  108762. ** a==5 and b IN (1,2,3). The current values for a and b will be stored
  108763. ** in consecutive registers and the index of the first register is returned.
  108764. **
  108765. ** In the example above nEq==2. But this subroutine works for any value
  108766. ** of nEq including 0. If nEq==0, this routine is nearly a no-op.
  108767. ** The only thing it does is allocate the pLevel->iMem memory cell and
  108768. ** compute the affinity string.
  108769. **
  108770. ** The nExtraReg parameter is 0 or 1. It is 0 if all WHERE clause constraints
  108771. ** are == or IN and are covered by the nEq. nExtraReg is 1 if there is
  108772. ** an inequality constraint (such as the "c>=5 AND c<10" in the example) that
  108773. ** occurs after the nEq quality constraints.
  108774. **
  108775. ** This routine allocates a range of nEq+nExtraReg memory cells and returns
  108776. ** the index of the first memory cell in that range. The code that
  108777. ** calls this routine will use that memory range to store keys for
  108778. ** start and termination conditions of the loop.
  108779. ** key value of the loop. If one or more IN operators appear, then
  108780. ** this routine allocates an additional nEq memory cells for internal
  108781. ** use.
  108782. **
  108783. ** Before returning, *pzAff is set to point to a buffer containing a
  108784. ** copy of the column affinity string of the index allocated using
  108785. ** sqlite3DbMalloc(). Except, entries in the copy of the string associated
  108786. ** with equality constraints that use NONE affinity are set to
  108787. ** SQLITE_AFF_NONE. This is to deal with SQL such as the following:
  108788. **
  108789. ** CREATE TABLE t1(a TEXT PRIMARY KEY, b);
  108790. ** SELECT ... FROM t1 AS t2, t1 WHERE t1.a = t2.b;
  108791. **
  108792. ** In the example above, the index on t1(a) has TEXT affinity. But since
  108793. ** the right hand side of the equality constraint (t2.b) has NONE affinity,
  108794. ** no conversion should be attempted before using a t2.b value as part of
  108795. ** a key to search the index. Hence the first byte in the returned affinity
  108796. ** string in this example would be set to SQLITE_AFF_NONE.
  108797. */
  108798. static int codeAllEqualityTerms(
  108799. Parse *pParse, /* Parsing context */
  108800. WhereLevel *pLevel, /* Which nested loop of the FROM we are coding */
  108801. int bRev, /* Reverse the order of IN operators */
  108802. int nExtraReg, /* Number of extra registers to allocate */
  108803. char **pzAff /* OUT: Set to point to affinity string */
  108804. ){
  108805. u16 nEq; /* The number of == or IN constraints to code */
  108806. u16 nSkip; /* Number of left-most columns to skip */
  108807. Vdbe *v = pParse->pVdbe; /* The vm under construction */
  108808. Index *pIdx; /* The index being used for this loop */
  108809. WhereTerm *pTerm; /* A single constraint term */
  108810. WhereLoop *pLoop; /* The WhereLoop object */
  108811. int j; /* Loop counter */
  108812. int regBase; /* Base register */
  108813. int nReg; /* Number of registers to allocate */
  108814. char *zAff; /* Affinity string to return */
  108815. /* This module is only called on query plans that use an index. */
  108816. pLoop = pLevel->pWLoop;
  108817. assert( (pLoop->wsFlags & WHERE_VIRTUALTABLE)==0 );
  108818. nEq = pLoop->u.btree.nEq;
  108819. nSkip = pLoop->u.btree.nSkip;
  108820. pIdx = pLoop->u.btree.pIndex;
  108821. assert( pIdx!=0 );
  108822. /* Figure out how many memory cells we will need then allocate them.
  108823. */
  108824. regBase = pParse->nMem + 1;
  108825. nReg = pLoop->u.btree.nEq + nExtraReg;
  108826. pParse->nMem += nReg;
  108827. zAff = sqlite3DbStrDup(pParse->db, sqlite3IndexAffinityStr(v, pIdx));
  108828. if( !zAff ){
  108829. pParse->db->mallocFailed = 1;
  108830. }
  108831. if( nSkip ){
  108832. int iIdxCur = pLevel->iIdxCur;
  108833. sqlite3VdbeAddOp1(v, (bRev?OP_Last:OP_Rewind), iIdxCur);
  108834. VdbeCoverageIf(v, bRev==0);
  108835. VdbeCoverageIf(v, bRev!=0);
  108836. VdbeComment((v, "begin skip-scan on %s", pIdx->zName));
  108837. j = sqlite3VdbeAddOp0(v, OP_Goto);
  108838. pLevel->addrSkip = sqlite3VdbeAddOp4Int(v, (bRev?OP_SeekLT:OP_SeekGT),
  108839. iIdxCur, 0, regBase, nSkip);
  108840. VdbeCoverageIf(v, bRev==0);
  108841. VdbeCoverageIf(v, bRev!=0);
  108842. sqlite3VdbeJumpHere(v, j);
  108843. for(j=0; j<nSkip; j++){
  108844. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, j, regBase+j);
  108845. assert( pIdx->aiColumn[j]>=0 );
  108846. VdbeComment((v, "%s", pIdx->pTable->aCol[pIdx->aiColumn[j]].zName));
  108847. }
  108848. }
  108849. /* Evaluate the equality constraints
  108850. */
  108851. assert( zAff==0 || (int)strlen(zAff)>=nEq );
  108852. for(j=nSkip; j<nEq; j++){
  108853. int r1;
  108854. pTerm = pLoop->aLTerm[j];
  108855. assert( pTerm!=0 );
  108856. /* The following testcase is true for indices with redundant columns.
  108857. ** Ex: CREATE INDEX i1 ON t1(a,b,a); SELECT * FROM t1 WHERE a=0 AND b=0; */
  108858. testcase( (pTerm->wtFlags & TERM_CODED)!=0 );
  108859. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  108860. r1 = codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, regBase+j);
  108861. if( r1!=regBase+j ){
  108862. if( nReg==1 ){
  108863. sqlite3ReleaseTempReg(pParse, regBase);
  108864. regBase = r1;
  108865. }else{
  108866. sqlite3VdbeAddOp2(v, OP_SCopy, r1, regBase+j);
  108867. }
  108868. }
  108869. testcase( pTerm->eOperator & WO_ISNULL );
  108870. testcase( pTerm->eOperator & WO_IN );
  108871. if( (pTerm->eOperator & (WO_ISNULL|WO_IN))==0 ){
  108872. Expr *pRight = pTerm->pExpr->pRight;
  108873. if( sqlite3ExprCanBeNull(pRight) ){
  108874. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+j, pLevel->addrBrk);
  108875. VdbeCoverage(v);
  108876. }
  108877. if( zAff ){
  108878. if( sqlite3CompareAffinity(pRight, zAff[j])==SQLITE_AFF_NONE ){
  108879. zAff[j] = SQLITE_AFF_NONE;
  108880. }
  108881. if( sqlite3ExprNeedsNoAffinityChange(pRight, zAff[j]) ){
  108882. zAff[j] = SQLITE_AFF_NONE;
  108883. }
  108884. }
  108885. }
  108886. }
  108887. *pzAff = zAff;
  108888. return regBase;
  108889. }
  108890. #ifndef SQLITE_OMIT_EXPLAIN
  108891. /*
  108892. ** This routine is a helper for explainIndexRange() below
  108893. **
  108894. ** pStr holds the text of an expression that we are building up one term
  108895. ** at a time. This routine adds a new term to the end of the expression.
  108896. ** Terms are separated by AND so add the "AND" text for second and subsequent
  108897. ** terms only.
  108898. */
  108899. static void explainAppendTerm(
  108900. StrAccum *pStr, /* The text expression being built */
  108901. int iTerm, /* Index of this term. First is zero */
  108902. const char *zColumn, /* Name of the column */
  108903. const char *zOp /* Name of the operator */
  108904. ){
  108905. if( iTerm ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  108906. sqlite3StrAccumAppendAll(pStr, zColumn);
  108907. sqlite3StrAccumAppend(pStr, zOp, 1);
  108908. sqlite3StrAccumAppend(pStr, "?", 1);
  108909. }
  108910. /*
  108911. ** Argument pLevel describes a strategy for scanning table pTab. This
  108912. ** function appends text to pStr that describes the subset of table
  108913. ** rows scanned by the strategy in the form of an SQL expression.
  108914. **
  108915. ** For example, if the query:
  108916. **
  108917. ** SELECT * FROM t1 WHERE a=1 AND b>2;
  108918. **
  108919. ** is run and there is an index on (a, b), then this function returns a
  108920. ** string similar to:
  108921. **
  108922. ** "a=? AND b>?"
  108923. */
  108924. static void explainIndexRange(StrAccum *pStr, WhereLoop *pLoop, Table *pTab){
  108925. Index *pIndex = pLoop->u.btree.pIndex;
  108926. u16 nEq = pLoop->u.btree.nEq;
  108927. u16 nSkip = pLoop->u.btree.nSkip;
  108928. int i, j;
  108929. Column *aCol = pTab->aCol;
  108930. i16 *aiColumn = pIndex->aiColumn;
  108931. if( nEq==0 && (pLoop->wsFlags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))==0 ) return;
  108932. sqlite3StrAccumAppend(pStr, " (", 2);
  108933. for(i=0; i<nEq; i++){
  108934. char *z = aiColumn[i] < 0 ? "rowid" : aCol[aiColumn[i]].zName;
  108935. if( i>=nSkip ){
  108936. explainAppendTerm(pStr, i, z, "=");
  108937. }else{
  108938. if( i ) sqlite3StrAccumAppend(pStr, " AND ", 5);
  108939. sqlite3XPrintf(pStr, 0, "ANY(%s)", z);
  108940. }
  108941. }
  108942. j = i;
  108943. if( pLoop->wsFlags&WHERE_BTM_LIMIT ){
  108944. char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
  108945. explainAppendTerm(pStr, i++, z, ">");
  108946. }
  108947. if( pLoop->wsFlags&WHERE_TOP_LIMIT ){
  108948. char *z = aiColumn[j] < 0 ? "rowid" : aCol[aiColumn[j]].zName;
  108949. explainAppendTerm(pStr, i, z, "<");
  108950. }
  108951. sqlite3StrAccumAppend(pStr, ")", 1);
  108952. }
  108953. /*
  108954. ** This function is a no-op unless currently processing an EXPLAIN QUERY PLAN
  108955. ** command. If the query being compiled is an EXPLAIN QUERY PLAN, a single
  108956. ** record is added to the output to describe the table scan strategy in
  108957. ** pLevel.
  108958. */
  108959. static void explainOneScan(
  108960. Parse *pParse, /* Parse context */
  108961. SrcList *pTabList, /* Table list this loop refers to */
  108962. WhereLevel *pLevel, /* Scan to write OP_Explain opcode for */
  108963. int iLevel, /* Value for "level" column of output */
  108964. int iFrom, /* Value for "from" column of output */
  108965. u16 wctrlFlags /* Flags passed to sqlite3WhereBegin() */
  108966. ){
  108967. #ifndef SQLITE_DEBUG
  108968. if( pParse->explain==2 )
  108969. #endif
  108970. {
  108971. struct SrcList_item *pItem = &pTabList->a[pLevel->iFrom];
  108972. Vdbe *v = pParse->pVdbe; /* VM being constructed */
  108973. sqlite3 *db = pParse->db; /* Database handle */
  108974. int iId = pParse->iSelectId; /* Select id (left-most output column) */
  108975. int isSearch; /* True for a SEARCH. False for SCAN. */
  108976. WhereLoop *pLoop; /* The controlling WhereLoop object */
  108977. u32 flags; /* Flags that describe this loop */
  108978. char *zMsg; /* Text to add to EQP output */
  108979. StrAccum str; /* EQP output string */
  108980. char zBuf[100]; /* Initial space for EQP output string */
  108981. pLoop = pLevel->pWLoop;
  108982. flags = pLoop->wsFlags;
  108983. if( (flags&WHERE_MULTI_OR) || (wctrlFlags&WHERE_ONETABLE_ONLY) ) return;
  108984. isSearch = (flags&(WHERE_BTM_LIMIT|WHERE_TOP_LIMIT))!=0
  108985. || ((flags&WHERE_VIRTUALTABLE)==0 && (pLoop->u.btree.nEq>0))
  108986. || (wctrlFlags&(WHERE_ORDERBY_MIN|WHERE_ORDERBY_MAX));
  108987. sqlite3StrAccumInit(&str, zBuf, sizeof(zBuf), SQLITE_MAX_LENGTH);
  108988. str.db = db;
  108989. sqlite3StrAccumAppendAll(&str, isSearch ? "SEARCH" : "SCAN");
  108990. if( pItem->pSelect ){
  108991. sqlite3XPrintf(&str, 0, " SUBQUERY %d", pItem->iSelectId);
  108992. }else{
  108993. sqlite3XPrintf(&str, 0, " TABLE %s", pItem->zName);
  108994. }
  108995. if( pItem->zAlias ){
  108996. sqlite3XPrintf(&str, 0, " AS %s", pItem->zAlias);
  108997. }
  108998. if( (flags & (WHERE_IPK|WHERE_VIRTUALTABLE))==0 ){
  108999. const char *zFmt = 0;
  109000. Index *pIdx;
  109001. assert( pLoop->u.btree.pIndex!=0 );
  109002. pIdx = pLoop->u.btree.pIndex;
  109003. assert( !(flags&WHERE_AUTO_INDEX) || (flags&WHERE_IDX_ONLY) );
  109004. if( !HasRowid(pItem->pTab) && IsPrimaryKeyIndex(pIdx) ){
  109005. if( isSearch ){
  109006. zFmt = "PRIMARY KEY";
  109007. }
  109008. }else if( flags & WHERE_AUTO_INDEX ){
  109009. zFmt = "AUTOMATIC COVERING INDEX";
  109010. }else if( flags & WHERE_IDX_ONLY ){
  109011. zFmt = "COVERING INDEX %s";
  109012. }else{
  109013. zFmt = "INDEX %s";
  109014. }
  109015. if( zFmt ){
  109016. sqlite3StrAccumAppend(&str, " USING ", 7);
  109017. sqlite3XPrintf(&str, 0, zFmt, pIdx->zName);
  109018. explainIndexRange(&str, pLoop, pItem->pTab);
  109019. }
  109020. }else if( (flags & WHERE_IPK)!=0 && (flags & WHERE_CONSTRAINT)!=0 ){
  109021. const char *zRange;
  109022. if( flags&(WHERE_COLUMN_EQ|WHERE_COLUMN_IN) ){
  109023. zRange = "(rowid=?)";
  109024. }else if( (flags&WHERE_BOTH_LIMIT)==WHERE_BOTH_LIMIT ){
  109025. zRange = "(rowid>? AND rowid<?)";
  109026. }else if( flags&WHERE_BTM_LIMIT ){
  109027. zRange = "(rowid>?)";
  109028. }else{
  109029. assert( flags&WHERE_TOP_LIMIT);
  109030. zRange = "(rowid<?)";
  109031. }
  109032. sqlite3StrAccumAppendAll(&str, " USING INTEGER PRIMARY KEY ");
  109033. sqlite3StrAccumAppendAll(&str, zRange);
  109034. }
  109035. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109036. else if( (flags & WHERE_VIRTUALTABLE)!=0 ){
  109037. sqlite3XPrintf(&str, 0, " VIRTUAL TABLE INDEX %d:%s",
  109038. pLoop->u.vtab.idxNum, pLoop->u.vtab.idxStr);
  109039. }
  109040. #endif
  109041. #ifdef SQLITE_EXPLAIN_ESTIMATED_ROWS
  109042. if( pLoop->nOut>=10 ){
  109043. sqlite3XPrintf(&str, 0, " (~%llu rows)", sqlite3LogEstToInt(pLoop->nOut));
  109044. }else{
  109045. sqlite3StrAccumAppend(&str, " (~1 row)", 9);
  109046. }
  109047. #endif
  109048. zMsg = sqlite3StrAccumFinish(&str);
  109049. sqlite3VdbeAddOp4(v, OP_Explain, iId, iLevel, iFrom, zMsg, P4_DYNAMIC);
  109050. }
  109051. }
  109052. #else
  109053. # define explainOneScan(u,v,w,x,y,z)
  109054. #endif /* SQLITE_OMIT_EXPLAIN */
  109055. /*
  109056. ** Generate code for the start of the iLevel-th loop in the WHERE clause
  109057. ** implementation described by pWInfo.
  109058. */
  109059. static Bitmask codeOneLoopStart(
  109060. WhereInfo *pWInfo, /* Complete information about the WHERE clause */
  109061. int iLevel, /* Which level of pWInfo->a[] should be coded */
  109062. Bitmask notReady /* Which tables are currently available */
  109063. ){
  109064. int j, k; /* Loop counters */
  109065. int iCur; /* The VDBE cursor for the table */
  109066. int addrNxt; /* Where to jump to continue with the next IN case */
  109067. int omitTable; /* True if we use the index only */
  109068. int bRev; /* True if we need to scan in reverse order */
  109069. WhereLevel *pLevel; /* The where level to be coded */
  109070. WhereLoop *pLoop; /* The WhereLoop object being coded */
  109071. WhereClause *pWC; /* Decomposition of the entire WHERE clause */
  109072. WhereTerm *pTerm; /* A WHERE clause term */
  109073. Parse *pParse; /* Parsing context */
  109074. sqlite3 *db; /* Database connection */
  109075. Vdbe *v; /* The prepared stmt under constructions */
  109076. struct SrcList_item *pTabItem; /* FROM clause term being coded */
  109077. int addrBrk; /* Jump here to break out of the loop */
  109078. int addrCont; /* Jump here to continue with next cycle */
  109079. int iRowidReg = 0; /* Rowid is stored in this register, if not zero */
  109080. int iReleaseReg = 0; /* Temp register to free before returning */
  109081. pParse = pWInfo->pParse;
  109082. v = pParse->pVdbe;
  109083. pWC = &pWInfo->sWC;
  109084. db = pParse->db;
  109085. pLevel = &pWInfo->a[iLevel];
  109086. pLoop = pLevel->pWLoop;
  109087. pTabItem = &pWInfo->pTabList->a[pLevel->iFrom];
  109088. iCur = pTabItem->iCursor;
  109089. pLevel->notReady = notReady & ~getMask(&pWInfo->sMaskSet, iCur);
  109090. bRev = (pWInfo->revMask>>iLevel)&1;
  109091. omitTable = (pLoop->wsFlags & WHERE_IDX_ONLY)!=0
  109092. && (pWInfo->wctrlFlags & WHERE_FORCE_TABLE)==0;
  109093. VdbeModuleComment((v, "Begin WHERE-loop%d: %s",iLevel,pTabItem->pTab->zName));
  109094. /* Create labels for the "break" and "continue" instructions
  109095. ** for the current loop. Jump to addrBrk to break out of a loop.
  109096. ** Jump to cont to go immediately to the next iteration of the
  109097. ** loop.
  109098. **
  109099. ** When there is an IN operator, we also have a "addrNxt" label that
  109100. ** means to continue with the next IN value combination. When
  109101. ** there are no IN operators in the constraints, the "addrNxt" label
  109102. ** is the same as "addrBrk".
  109103. */
  109104. addrBrk = pLevel->addrBrk = pLevel->addrNxt = sqlite3VdbeMakeLabel(v);
  109105. addrCont = pLevel->addrCont = sqlite3VdbeMakeLabel(v);
  109106. /* If this is the right table of a LEFT OUTER JOIN, allocate and
  109107. ** initialize a memory cell that records if this table matches any
  109108. ** row of the left table of the join.
  109109. */
  109110. if( pLevel->iFrom>0 && (pTabItem[0].jointype & JT_LEFT)!=0 ){
  109111. pLevel->iLeftJoin = ++pParse->nMem;
  109112. sqlite3VdbeAddOp2(v, OP_Integer, 0, pLevel->iLeftJoin);
  109113. VdbeComment((v, "init LEFT JOIN no-match flag"));
  109114. }
  109115. /* Special case of a FROM clause subquery implemented as a co-routine */
  109116. if( pTabItem->viaCoroutine ){
  109117. int regYield = pTabItem->regReturn;
  109118. sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0, pTabItem->addrFillSub);
  109119. pLevel->p2 = sqlite3VdbeAddOp2(v, OP_Yield, regYield, addrBrk);
  109120. VdbeCoverage(v);
  109121. VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
  109122. pLevel->op = OP_Goto;
  109123. }else
  109124. #ifndef SQLITE_OMIT_VIRTUALTABLE
  109125. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  109126. /* Case 1: The table is a virtual-table. Use the VFilter and VNext
  109127. ** to access the data.
  109128. */
  109129. int iReg; /* P3 Value for OP_VFilter */
  109130. int addrNotFound;
  109131. int nConstraint = pLoop->nLTerm;
  109132. sqlite3ExprCachePush(pParse);
  109133. iReg = sqlite3GetTempRange(pParse, nConstraint+2);
  109134. addrNotFound = pLevel->addrBrk;
  109135. for(j=0; j<nConstraint; j++){
  109136. int iTarget = iReg+j+2;
  109137. pTerm = pLoop->aLTerm[j];
  109138. if( pTerm==0 ) continue;
  109139. if( pTerm->eOperator & WO_IN ){
  109140. codeEqualityTerm(pParse, pTerm, pLevel, j, bRev, iTarget);
  109141. addrNotFound = pLevel->addrNxt;
  109142. }else{
  109143. sqlite3ExprCode(pParse, pTerm->pExpr->pRight, iTarget);
  109144. }
  109145. }
  109146. sqlite3VdbeAddOp2(v, OP_Integer, pLoop->u.vtab.idxNum, iReg);
  109147. sqlite3VdbeAddOp2(v, OP_Integer, nConstraint, iReg+1);
  109148. sqlite3VdbeAddOp4(v, OP_VFilter, iCur, addrNotFound, iReg,
  109149. pLoop->u.vtab.idxStr,
  109150. pLoop->u.vtab.needFree ? P4_MPRINTF : P4_STATIC);
  109151. VdbeCoverage(v);
  109152. pLoop->u.vtab.needFree = 0;
  109153. for(j=0; j<nConstraint && j<16; j++){
  109154. if( (pLoop->u.vtab.omitMask>>j)&1 ){
  109155. disableTerm(pLevel, pLoop->aLTerm[j]);
  109156. }
  109157. }
  109158. pLevel->op = OP_VNext;
  109159. pLevel->p1 = iCur;
  109160. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  109161. sqlite3ReleaseTempRange(pParse, iReg, nConstraint+2);
  109162. sqlite3ExprCachePop(pParse);
  109163. }else
  109164. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  109165. if( (pLoop->wsFlags & WHERE_IPK)!=0
  109166. && (pLoop->wsFlags & (WHERE_COLUMN_IN|WHERE_COLUMN_EQ))!=0
  109167. ){
  109168. /* Case 2: We can directly reference a single row using an
  109169. ** equality comparison against the ROWID field. Or
  109170. ** we reference multiple rows using a "rowid IN (...)"
  109171. ** construct.
  109172. */
  109173. assert( pLoop->u.btree.nEq==1 );
  109174. pTerm = pLoop->aLTerm[0];
  109175. assert( pTerm!=0 );
  109176. assert( pTerm->pExpr!=0 );
  109177. assert( omitTable==0 );
  109178. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  109179. iReleaseReg = ++pParse->nMem;
  109180. iRowidReg = codeEqualityTerm(pParse, pTerm, pLevel, 0, bRev, iReleaseReg);
  109181. if( iRowidReg!=iReleaseReg ) sqlite3ReleaseTempReg(pParse, iReleaseReg);
  109182. addrNxt = pLevel->addrNxt;
  109183. sqlite3VdbeAddOp2(v, OP_MustBeInt, iRowidReg, addrNxt); VdbeCoverage(v);
  109184. sqlite3VdbeAddOp3(v, OP_NotExists, iCur, addrNxt, iRowidReg);
  109185. VdbeCoverage(v);
  109186. sqlite3ExprCacheAffinityChange(pParse, iRowidReg, 1);
  109187. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  109188. VdbeComment((v, "pk"));
  109189. pLevel->op = OP_Noop;
  109190. }else if( (pLoop->wsFlags & WHERE_IPK)!=0
  109191. && (pLoop->wsFlags & WHERE_COLUMN_RANGE)!=0
  109192. ){
  109193. /* Case 3: We have an inequality comparison against the ROWID field.
  109194. */
  109195. int testOp = OP_Noop;
  109196. int start;
  109197. int memEndValue = 0;
  109198. WhereTerm *pStart, *pEnd;
  109199. assert( omitTable==0 );
  109200. j = 0;
  109201. pStart = pEnd = 0;
  109202. if( pLoop->wsFlags & WHERE_BTM_LIMIT ) pStart = pLoop->aLTerm[j++];
  109203. if( pLoop->wsFlags & WHERE_TOP_LIMIT ) pEnd = pLoop->aLTerm[j++];
  109204. assert( pStart!=0 || pEnd!=0 );
  109205. if( bRev ){
  109206. pTerm = pStart;
  109207. pStart = pEnd;
  109208. pEnd = pTerm;
  109209. }
  109210. if( pStart ){
  109211. Expr *pX; /* The expression that defines the start bound */
  109212. int r1, rTemp; /* Registers for holding the start boundary */
  109213. /* The following constant maps TK_xx codes into corresponding
  109214. ** seek opcodes. It depends on a particular ordering of TK_xx
  109215. */
  109216. const u8 aMoveOp[] = {
  109217. /* TK_GT */ OP_SeekGT,
  109218. /* TK_LE */ OP_SeekLE,
  109219. /* TK_LT */ OP_SeekLT,
  109220. /* TK_GE */ OP_SeekGE
  109221. };
  109222. assert( TK_LE==TK_GT+1 ); /* Make sure the ordering.. */
  109223. assert( TK_LT==TK_GT+2 ); /* ... of the TK_xx values... */
  109224. assert( TK_GE==TK_GT+3 ); /* ... is correcct. */
  109225. assert( (pStart->wtFlags & TERM_VNULL)==0 );
  109226. testcase( pStart->wtFlags & TERM_VIRTUAL );
  109227. pX = pStart->pExpr;
  109228. assert( pX!=0 );
  109229. testcase( pStart->leftCursor!=iCur ); /* transitive constraints */
  109230. r1 = sqlite3ExprCodeTemp(pParse, pX->pRight, &rTemp);
  109231. sqlite3VdbeAddOp3(v, aMoveOp[pX->op-TK_GT], iCur, addrBrk, r1);
  109232. VdbeComment((v, "pk"));
  109233. VdbeCoverageIf(v, pX->op==TK_GT);
  109234. VdbeCoverageIf(v, pX->op==TK_LE);
  109235. VdbeCoverageIf(v, pX->op==TK_LT);
  109236. VdbeCoverageIf(v, pX->op==TK_GE);
  109237. sqlite3ExprCacheAffinityChange(pParse, r1, 1);
  109238. sqlite3ReleaseTempReg(pParse, rTemp);
  109239. disableTerm(pLevel, pStart);
  109240. }else{
  109241. sqlite3VdbeAddOp2(v, bRev ? OP_Last : OP_Rewind, iCur, addrBrk);
  109242. VdbeCoverageIf(v, bRev==0);
  109243. VdbeCoverageIf(v, bRev!=0);
  109244. }
  109245. if( pEnd ){
  109246. Expr *pX;
  109247. pX = pEnd->pExpr;
  109248. assert( pX!=0 );
  109249. assert( (pEnd->wtFlags & TERM_VNULL)==0 );
  109250. testcase( pEnd->leftCursor!=iCur ); /* Transitive constraints */
  109251. testcase( pEnd->wtFlags & TERM_VIRTUAL );
  109252. memEndValue = ++pParse->nMem;
  109253. sqlite3ExprCode(pParse, pX->pRight, memEndValue);
  109254. if( pX->op==TK_LT || pX->op==TK_GT ){
  109255. testOp = bRev ? OP_Le : OP_Ge;
  109256. }else{
  109257. testOp = bRev ? OP_Lt : OP_Gt;
  109258. }
  109259. disableTerm(pLevel, pEnd);
  109260. }
  109261. start = sqlite3VdbeCurrentAddr(v);
  109262. pLevel->op = bRev ? OP_Prev : OP_Next;
  109263. pLevel->p1 = iCur;
  109264. pLevel->p2 = start;
  109265. assert( pLevel->p5==0 );
  109266. if( testOp!=OP_Noop ){
  109267. iRowidReg = ++pParse->nMem;
  109268. sqlite3VdbeAddOp2(v, OP_Rowid, iCur, iRowidReg);
  109269. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  109270. sqlite3VdbeAddOp3(v, testOp, memEndValue, addrBrk, iRowidReg);
  109271. VdbeCoverageIf(v, testOp==OP_Le);
  109272. VdbeCoverageIf(v, testOp==OP_Lt);
  109273. VdbeCoverageIf(v, testOp==OP_Ge);
  109274. VdbeCoverageIf(v, testOp==OP_Gt);
  109275. sqlite3VdbeChangeP5(v, SQLITE_AFF_NUMERIC | SQLITE_JUMPIFNULL);
  109276. }
  109277. }else if( pLoop->wsFlags & WHERE_INDEXED ){
  109278. /* Case 4: A scan using an index.
  109279. **
  109280. ** The WHERE clause may contain zero or more equality
  109281. ** terms ("==" or "IN" operators) that refer to the N
  109282. ** left-most columns of the index. It may also contain
  109283. ** inequality constraints (>, <, >= or <=) on the indexed
  109284. ** column that immediately follows the N equalities. Only
  109285. ** the right-most column can be an inequality - the rest must
  109286. ** use the "==" and "IN" operators. For example, if the
  109287. ** index is on (x,y,z), then the following clauses are all
  109288. ** optimized:
  109289. **
  109290. ** x=5
  109291. ** x=5 AND y=10
  109292. ** x=5 AND y<10
  109293. ** x=5 AND y>5 AND y<10
  109294. ** x=5 AND y=5 AND z<=10
  109295. **
  109296. ** The z<10 term of the following cannot be used, only
  109297. ** the x=5 term:
  109298. **
  109299. ** x=5 AND z<10
  109300. **
  109301. ** N may be zero if there are inequality constraints.
  109302. ** If there are no inequality constraints, then N is at
  109303. ** least one.
  109304. **
  109305. ** This case is also used when there are no WHERE clause
  109306. ** constraints but an index is selected anyway, in order
  109307. ** to force the output order to conform to an ORDER BY.
  109308. */
  109309. static const u8 aStartOp[] = {
  109310. 0,
  109311. 0,
  109312. OP_Rewind, /* 2: (!start_constraints && startEq && !bRev) */
  109313. OP_Last, /* 3: (!start_constraints && startEq && bRev) */
  109314. OP_SeekGT, /* 4: (start_constraints && !startEq && !bRev) */
  109315. OP_SeekLT, /* 5: (start_constraints && !startEq && bRev) */
  109316. OP_SeekGE, /* 6: (start_constraints && startEq && !bRev) */
  109317. OP_SeekLE /* 7: (start_constraints && startEq && bRev) */
  109318. };
  109319. static const u8 aEndOp[] = {
  109320. OP_IdxGE, /* 0: (end_constraints && !bRev && !endEq) */
  109321. OP_IdxGT, /* 1: (end_constraints && !bRev && endEq) */
  109322. OP_IdxLE, /* 2: (end_constraints && bRev && !endEq) */
  109323. OP_IdxLT, /* 3: (end_constraints && bRev && endEq) */
  109324. };
  109325. u16 nEq = pLoop->u.btree.nEq; /* Number of == or IN terms */
  109326. int regBase; /* Base register holding constraint values */
  109327. WhereTerm *pRangeStart = 0; /* Inequality constraint at range start */
  109328. WhereTerm *pRangeEnd = 0; /* Inequality constraint at range end */
  109329. int startEq; /* True if range start uses ==, >= or <= */
  109330. int endEq; /* True if range end uses ==, >= or <= */
  109331. int start_constraints; /* Start of range is constrained */
  109332. int nConstraint; /* Number of constraint terms */
  109333. Index *pIdx; /* The index we will be using */
  109334. int iIdxCur; /* The VDBE cursor for the index */
  109335. int nExtraReg = 0; /* Number of extra registers needed */
  109336. int op; /* Instruction opcode */
  109337. char *zStartAff; /* Affinity for start of range constraint */
  109338. char cEndAff = 0; /* Affinity for end of range constraint */
  109339. u8 bSeekPastNull = 0; /* True to seek past initial nulls */
  109340. u8 bStopAtNull = 0; /* Add condition to terminate at NULLs */
  109341. pIdx = pLoop->u.btree.pIndex;
  109342. iIdxCur = pLevel->iIdxCur;
  109343. assert( nEq>=pLoop->u.btree.nSkip );
  109344. /* If this loop satisfies a sort order (pOrderBy) request that
  109345. ** was passed to this function to implement a "SELECT min(x) ..."
  109346. ** query, then the caller will only allow the loop to run for
  109347. ** a single iteration. This means that the first row returned
  109348. ** should not have a NULL value stored in 'x'. If column 'x' is
  109349. ** the first one after the nEq equality constraints in the index,
  109350. ** this requires some special handling.
  109351. */
  109352. assert( pWInfo->pOrderBy==0
  109353. || pWInfo->pOrderBy->nExpr==1
  109354. || (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)==0 );
  109355. if( (pWInfo->wctrlFlags&WHERE_ORDERBY_MIN)!=0
  109356. && pWInfo->nOBSat>0
  109357. && (pIdx->nKeyCol>nEq)
  109358. ){
  109359. assert( pLoop->u.btree.nSkip==0 );
  109360. bSeekPastNull = 1;
  109361. nExtraReg = 1;
  109362. }
  109363. /* Find any inequality constraint terms for the start and end
  109364. ** of the range.
  109365. */
  109366. j = nEq;
  109367. if( pLoop->wsFlags & WHERE_BTM_LIMIT ){
  109368. pRangeStart = pLoop->aLTerm[j++];
  109369. nExtraReg = 1;
  109370. }
  109371. if( pLoop->wsFlags & WHERE_TOP_LIMIT ){
  109372. pRangeEnd = pLoop->aLTerm[j++];
  109373. nExtraReg = 1;
  109374. if( pRangeStart==0
  109375. && (j = pIdx->aiColumn[nEq])>=0
  109376. && pIdx->pTable->aCol[j].notNull==0
  109377. ){
  109378. bSeekPastNull = 1;
  109379. }
  109380. }
  109381. assert( pRangeEnd==0 || (pRangeEnd->wtFlags & TERM_VNULL)==0 );
  109382. /* Generate code to evaluate all constraint terms using == or IN
  109383. ** and store the values of those terms in an array of registers
  109384. ** starting at regBase.
  109385. */
  109386. regBase = codeAllEqualityTerms(pParse,pLevel,bRev,nExtraReg,&zStartAff);
  109387. assert( zStartAff==0 || sqlite3Strlen30(zStartAff)>=nEq );
  109388. if( zStartAff ) cEndAff = zStartAff[nEq];
  109389. addrNxt = pLevel->addrNxt;
  109390. /* If we are doing a reverse order scan on an ascending index, or
  109391. ** a forward order scan on a descending index, interchange the
  109392. ** start and end terms (pRangeStart and pRangeEnd).
  109393. */
  109394. if( (nEq<pIdx->nKeyCol && bRev==(pIdx->aSortOrder[nEq]==SQLITE_SO_ASC))
  109395. || (bRev && pIdx->nKeyCol==nEq)
  109396. ){
  109397. SWAP(WhereTerm *, pRangeEnd, pRangeStart);
  109398. SWAP(u8, bSeekPastNull, bStopAtNull);
  109399. }
  109400. testcase( pRangeStart && (pRangeStart->eOperator & WO_LE)!=0 );
  109401. testcase( pRangeStart && (pRangeStart->eOperator & WO_GE)!=0 );
  109402. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_LE)!=0 );
  109403. testcase( pRangeEnd && (pRangeEnd->eOperator & WO_GE)!=0 );
  109404. startEq = !pRangeStart || pRangeStart->eOperator & (WO_LE|WO_GE);
  109405. endEq = !pRangeEnd || pRangeEnd->eOperator & (WO_LE|WO_GE);
  109406. start_constraints = pRangeStart || nEq>0;
  109407. /* Seek the index cursor to the start of the range. */
  109408. nConstraint = nEq;
  109409. if( pRangeStart ){
  109410. Expr *pRight = pRangeStart->pExpr->pRight;
  109411. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  109412. if( (pRangeStart->wtFlags & TERM_VNULL)==0
  109413. && sqlite3ExprCanBeNull(pRight)
  109414. ){
  109415. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  109416. VdbeCoverage(v);
  109417. }
  109418. if( zStartAff ){
  109419. if( sqlite3CompareAffinity(pRight, zStartAff[nEq])==SQLITE_AFF_NONE){
  109420. /* Since the comparison is to be performed with no conversions
  109421. ** applied to the operands, set the affinity to apply to pRight to
  109422. ** SQLITE_AFF_NONE. */
  109423. zStartAff[nEq] = SQLITE_AFF_NONE;
  109424. }
  109425. if( sqlite3ExprNeedsNoAffinityChange(pRight, zStartAff[nEq]) ){
  109426. zStartAff[nEq] = SQLITE_AFF_NONE;
  109427. }
  109428. }
  109429. nConstraint++;
  109430. testcase( pRangeStart->wtFlags & TERM_VIRTUAL );
  109431. }else if( bSeekPastNull ){
  109432. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  109433. nConstraint++;
  109434. startEq = 0;
  109435. start_constraints = 1;
  109436. }
  109437. codeApplyAffinity(pParse, regBase, nConstraint - bSeekPastNull, zStartAff);
  109438. op = aStartOp[(start_constraints<<2) + (startEq<<1) + bRev];
  109439. assert( op!=0 );
  109440. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  109441. VdbeCoverage(v);
  109442. VdbeCoverageIf(v, op==OP_Rewind); testcase( op==OP_Rewind );
  109443. VdbeCoverageIf(v, op==OP_Last); testcase( op==OP_Last );
  109444. VdbeCoverageIf(v, op==OP_SeekGT); testcase( op==OP_SeekGT );
  109445. VdbeCoverageIf(v, op==OP_SeekGE); testcase( op==OP_SeekGE );
  109446. VdbeCoverageIf(v, op==OP_SeekLE); testcase( op==OP_SeekLE );
  109447. VdbeCoverageIf(v, op==OP_SeekLT); testcase( op==OP_SeekLT );
  109448. /* Load the value for the inequality constraint at the end of the
  109449. ** range (if any).
  109450. */
  109451. nConstraint = nEq;
  109452. if( pRangeEnd ){
  109453. Expr *pRight = pRangeEnd->pExpr->pRight;
  109454. sqlite3ExprCacheRemove(pParse, regBase+nEq, 1);
  109455. sqlite3ExprCode(pParse, pRight, regBase+nEq);
  109456. if( (pRangeEnd->wtFlags & TERM_VNULL)==0
  109457. && sqlite3ExprCanBeNull(pRight)
  109458. ){
  109459. sqlite3VdbeAddOp2(v, OP_IsNull, regBase+nEq, addrNxt);
  109460. VdbeCoverage(v);
  109461. }
  109462. if( sqlite3CompareAffinity(pRight, cEndAff)!=SQLITE_AFF_NONE
  109463. && !sqlite3ExprNeedsNoAffinityChange(pRight, cEndAff)
  109464. ){
  109465. codeApplyAffinity(pParse, regBase+nEq, 1, &cEndAff);
  109466. }
  109467. nConstraint++;
  109468. testcase( pRangeEnd->wtFlags & TERM_VIRTUAL );
  109469. }else if( bStopAtNull ){
  109470. sqlite3VdbeAddOp2(v, OP_Null, 0, regBase+nEq);
  109471. endEq = 0;
  109472. nConstraint++;
  109473. }
  109474. sqlite3DbFree(db, zStartAff);
  109475. /* Top of the loop body */
  109476. pLevel->p2 = sqlite3VdbeCurrentAddr(v);
  109477. /* Check if the index cursor is past the end of the range. */
  109478. if( nConstraint ){
  109479. op = aEndOp[bRev*2 + endEq];
  109480. sqlite3VdbeAddOp4Int(v, op, iIdxCur, addrNxt, regBase, nConstraint);
  109481. testcase( op==OP_IdxGT ); VdbeCoverageIf(v, op==OP_IdxGT );
  109482. testcase( op==OP_IdxGE ); VdbeCoverageIf(v, op==OP_IdxGE );
  109483. testcase( op==OP_IdxLT ); VdbeCoverageIf(v, op==OP_IdxLT );
  109484. testcase( op==OP_IdxLE ); VdbeCoverageIf(v, op==OP_IdxLE );
  109485. }
  109486. /* Seek the table cursor, if required */
  109487. disableTerm(pLevel, pRangeStart);
  109488. disableTerm(pLevel, pRangeEnd);
  109489. if( omitTable ){
  109490. /* pIdx is a covering index. No need to access the main table. */
  109491. }else if( HasRowid(pIdx->pTable) ){
  109492. iRowidReg = ++pParse->nMem;
  109493. sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, iRowidReg);
  109494. sqlite3ExprCacheStore(pParse, iCur, -1, iRowidReg);
  109495. sqlite3VdbeAddOp2(v, OP_Seek, iCur, iRowidReg); /* Deferred seek */
  109496. }else if( iCur!=iIdxCur ){
  109497. Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
  109498. iRowidReg = sqlite3GetTempRange(pParse, pPk->nKeyCol);
  109499. for(j=0; j<pPk->nKeyCol; j++){
  109500. k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
  109501. sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, iRowidReg+j);
  109502. }
  109503. sqlite3VdbeAddOp4Int(v, OP_NotFound, iCur, addrCont,
  109504. iRowidReg, pPk->nKeyCol); VdbeCoverage(v);
  109505. }
  109506. /* Record the instruction used to terminate the loop. Disable
  109507. ** WHERE clause terms made redundant by the index range scan.
  109508. */
  109509. if( pLoop->wsFlags & WHERE_ONEROW ){
  109510. pLevel->op = OP_Noop;
  109511. }else if( bRev ){
  109512. pLevel->op = OP_Prev;
  109513. }else{
  109514. pLevel->op = OP_Next;
  109515. }
  109516. pLevel->p1 = iIdxCur;
  109517. pLevel->p3 = (pLoop->wsFlags&WHERE_UNQ_WANTED)!=0 ? 1:0;
  109518. if( (pLoop->wsFlags & WHERE_CONSTRAINT)==0 ){
  109519. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  109520. }else{
  109521. assert( pLevel->p5==0 );
  109522. }
  109523. }else
  109524. #ifndef SQLITE_OMIT_OR_OPTIMIZATION
  109525. if( pLoop->wsFlags & WHERE_MULTI_OR ){
  109526. /* Case 5: Two or more separately indexed terms connected by OR
  109527. **
  109528. ** Example:
  109529. **
  109530. ** CREATE TABLE t1(a,b,c,d);
  109531. ** CREATE INDEX i1 ON t1(a);
  109532. ** CREATE INDEX i2 ON t1(b);
  109533. ** CREATE INDEX i3 ON t1(c);
  109534. **
  109535. ** SELECT * FROM t1 WHERE a=5 OR b=7 OR (c=11 AND d=13)
  109536. **
  109537. ** In the example, there are three indexed terms connected by OR.
  109538. ** The top of the loop looks like this:
  109539. **
  109540. ** Null 1 # Zero the rowset in reg 1
  109541. **
  109542. ** Then, for each indexed term, the following. The arguments to
  109543. ** RowSetTest are such that the rowid of the current row is inserted
  109544. ** into the RowSet. If it is already present, control skips the
  109545. ** Gosub opcode and jumps straight to the code generated by WhereEnd().
  109546. **
  109547. ** sqlite3WhereBegin(<term>)
  109548. ** RowSetTest # Insert rowid into rowset
  109549. ** Gosub 2 A
  109550. ** sqlite3WhereEnd()
  109551. **
  109552. ** Following the above, code to terminate the loop. Label A, the target
  109553. ** of the Gosub above, jumps to the instruction right after the Goto.
  109554. **
  109555. ** Null 1 # Zero the rowset in reg 1
  109556. ** Goto B # The loop is finished.
  109557. **
  109558. ** A: <loop body> # Return data, whatever.
  109559. **
  109560. ** Return 2 # Jump back to the Gosub
  109561. **
  109562. ** B: <after the loop>
  109563. **
  109564. ** Added 2014-05-26: If the table is a WITHOUT ROWID table, then
  109565. ** use an ephemeral index instead of a RowSet to record the primary
  109566. ** keys of the rows we have already seen.
  109567. **
  109568. */
  109569. WhereClause *pOrWc; /* The OR-clause broken out into subterms */
  109570. SrcList *pOrTab; /* Shortened table list or OR-clause generation */
  109571. Index *pCov = 0; /* Potential covering index (or NULL) */
  109572. int iCovCur = pParse->nTab++; /* Cursor used for index scans (if any) */
  109573. int regReturn = ++pParse->nMem; /* Register used with OP_Gosub */
  109574. int regRowset = 0; /* Register for RowSet object */
  109575. int regRowid = 0; /* Register holding rowid */
  109576. int iLoopBody = sqlite3VdbeMakeLabel(v); /* Start of loop body */
  109577. int iRetInit; /* Address of regReturn init */
  109578. int untestedTerms = 0; /* Some terms not completely tested */
  109579. int ii; /* Loop counter */
  109580. u16 wctrlFlags; /* Flags for sub-WHERE clause */
  109581. Expr *pAndExpr = 0; /* An ".. AND (...)" expression */
  109582. Table *pTab = pTabItem->pTab;
  109583. pTerm = pLoop->aLTerm[0];
  109584. assert( pTerm!=0 );
  109585. assert( pTerm->eOperator & WO_OR );
  109586. assert( (pTerm->wtFlags & TERM_ORINFO)!=0 );
  109587. pOrWc = &pTerm->u.pOrInfo->wc;
  109588. pLevel->op = OP_Return;
  109589. pLevel->p1 = regReturn;
  109590. /* Set up a new SrcList in pOrTab containing the table being scanned
  109591. ** by this loop in the a[0] slot and all notReady tables in a[1..] slots.
  109592. ** This becomes the SrcList in the recursive call to sqlite3WhereBegin().
  109593. */
  109594. if( pWInfo->nLevel>1 ){
  109595. int nNotReady; /* The number of notReady tables */
  109596. struct SrcList_item *origSrc; /* Original list of tables */
  109597. nNotReady = pWInfo->nLevel - iLevel - 1;
  109598. pOrTab = sqlite3StackAllocRaw(db,
  109599. sizeof(*pOrTab)+ nNotReady*sizeof(pOrTab->a[0]));
  109600. if( pOrTab==0 ) return notReady;
  109601. pOrTab->nAlloc = (u8)(nNotReady + 1);
  109602. pOrTab->nSrc = pOrTab->nAlloc;
  109603. memcpy(pOrTab->a, pTabItem, sizeof(*pTabItem));
  109604. origSrc = pWInfo->pTabList->a;
  109605. for(k=1; k<=nNotReady; k++){
  109606. memcpy(&pOrTab->a[k], &origSrc[pLevel[k].iFrom], sizeof(pOrTab->a[k]));
  109607. }
  109608. }else{
  109609. pOrTab = pWInfo->pTabList;
  109610. }
  109611. /* Initialize the rowset register to contain NULL. An SQL NULL is
  109612. ** equivalent to an empty rowset. Or, create an ephemeral index
  109613. ** capable of holding primary keys in the case of a WITHOUT ROWID.
  109614. **
  109615. ** Also initialize regReturn to contain the address of the instruction
  109616. ** immediately following the OP_Return at the bottom of the loop. This
  109617. ** is required in a few obscure LEFT JOIN cases where control jumps
  109618. ** over the top of the loop into the body of it. In this case the
  109619. ** correct response for the end-of-loop code (the OP_Return) is to
  109620. ** fall through to the next instruction, just as an OP_Next does if
  109621. ** called on an uninitialized cursor.
  109622. */
  109623. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  109624. if( HasRowid(pTab) ){
  109625. regRowset = ++pParse->nMem;
  109626. sqlite3VdbeAddOp2(v, OP_Null, 0, regRowset);
  109627. }else{
  109628. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  109629. regRowset = pParse->nTab++;
  109630. sqlite3VdbeAddOp2(v, OP_OpenEphemeral, regRowset, pPk->nKeyCol);
  109631. sqlite3VdbeSetP4KeyInfo(pParse, pPk);
  109632. }
  109633. regRowid = ++pParse->nMem;
  109634. }
  109635. iRetInit = sqlite3VdbeAddOp2(v, OP_Integer, 0, regReturn);
  109636. /* If the original WHERE clause is z of the form: (x1 OR x2 OR ...) AND y
  109637. ** Then for every term xN, evaluate as the subexpression: xN AND z
  109638. ** That way, terms in y that are factored into the disjunction will
  109639. ** be picked up by the recursive calls to sqlite3WhereBegin() below.
  109640. **
  109641. ** Actually, each subexpression is converted to "xN AND w" where w is
  109642. ** the "interesting" terms of z - terms that did not originate in the
  109643. ** ON or USING clause of a LEFT JOIN, and terms that are usable as
  109644. ** indices.
  109645. **
  109646. ** This optimization also only applies if the (x1 OR x2 OR ...) term
  109647. ** is not contained in the ON clause of a LEFT JOIN.
  109648. ** See ticket http://www.sqlite.org/src/info/f2369304e4
  109649. */
  109650. if( pWC->nTerm>1 ){
  109651. int iTerm;
  109652. for(iTerm=0; iTerm<pWC->nTerm; iTerm++){
  109653. Expr *pExpr = pWC->a[iTerm].pExpr;
  109654. if( &pWC->a[iTerm] == pTerm ) continue;
  109655. if( ExprHasProperty(pExpr, EP_FromJoin) ) continue;
  109656. testcase( pWC->a[iTerm].wtFlags & TERM_ORINFO );
  109657. testcase( pWC->a[iTerm].wtFlags & TERM_VIRTUAL );
  109658. if( pWC->a[iTerm].wtFlags & (TERM_ORINFO|TERM_VIRTUAL) ) continue;
  109659. if( (pWC->a[iTerm].eOperator & WO_ALL)==0 ) continue;
  109660. pExpr = sqlite3ExprDup(db, pExpr, 0);
  109661. pAndExpr = sqlite3ExprAnd(db, pAndExpr, pExpr);
  109662. }
  109663. if( pAndExpr ){
  109664. pAndExpr = sqlite3PExpr(pParse, TK_AND, 0, pAndExpr, 0);
  109665. }
  109666. }
  109667. /* Run a separate WHERE clause for each term of the OR clause. After
  109668. ** eliminating duplicates from other WHERE clauses, the action for each
  109669. ** sub-WHERE clause is to to invoke the main loop body as a subroutine.
  109670. */
  109671. wctrlFlags = WHERE_OMIT_OPEN_CLOSE
  109672. | WHERE_FORCE_TABLE
  109673. | WHERE_ONETABLE_ONLY;
  109674. for(ii=0; ii<pOrWc->nTerm; ii++){
  109675. WhereTerm *pOrTerm = &pOrWc->a[ii];
  109676. if( pOrTerm->leftCursor==iCur || (pOrTerm->eOperator & WO_AND)!=0 ){
  109677. WhereInfo *pSubWInfo; /* Info for single OR-term scan */
  109678. Expr *pOrExpr = pOrTerm->pExpr; /* Current OR clause term */
  109679. int j1 = 0; /* Address of jump operation */
  109680. if( pAndExpr && !ExprHasProperty(pOrExpr, EP_FromJoin) ){
  109681. pAndExpr->pLeft = pOrExpr;
  109682. pOrExpr = pAndExpr;
  109683. }
  109684. /* Loop through table entries that match term pOrTerm. */
  109685. WHERETRACE(0xffff, ("Subplan for OR-clause:\n"));
  109686. pSubWInfo = sqlite3WhereBegin(pParse, pOrTab, pOrExpr, 0, 0,
  109687. wctrlFlags, iCovCur);
  109688. assert( pSubWInfo || pParse->nErr || db->mallocFailed );
  109689. if( pSubWInfo ){
  109690. WhereLoop *pSubLoop;
  109691. explainOneScan(
  109692. pParse, pOrTab, &pSubWInfo->a[0], iLevel, pLevel->iFrom, 0
  109693. );
  109694. /* This is the sub-WHERE clause body. First skip over
  109695. ** duplicate rows from prior sub-WHERE clauses, and record the
  109696. ** rowid (or PRIMARY KEY) for the current row so that the same
  109697. ** row will be skipped in subsequent sub-WHERE clauses.
  109698. */
  109699. if( (pWInfo->wctrlFlags & WHERE_DUPLICATES_OK)==0 ){
  109700. int r;
  109701. int iSet = ((ii==pOrWc->nTerm-1)?-1:ii);
  109702. if( HasRowid(pTab) ){
  109703. r = sqlite3ExprCodeGetColumn(pParse, pTab, -1, iCur, regRowid, 0);
  109704. j1 = sqlite3VdbeAddOp4Int(v, OP_RowSetTest, regRowset, 0, r,iSet);
  109705. VdbeCoverage(v);
  109706. }else{
  109707. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  109708. int nPk = pPk->nKeyCol;
  109709. int iPk;
  109710. /* Read the PK into an array of temp registers. */
  109711. r = sqlite3GetTempRange(pParse, nPk);
  109712. for(iPk=0; iPk<nPk; iPk++){
  109713. int iCol = pPk->aiColumn[iPk];
  109714. sqlite3ExprCodeGetColumn(pParse, pTab, iCol, iCur, r+iPk, 0);
  109715. }
  109716. /* Check if the temp table already contains this key. If so,
  109717. ** the row has already been included in the result set and
  109718. ** can be ignored (by jumping past the Gosub below). Otherwise,
  109719. ** insert the key into the temp table and proceed with processing
  109720. ** the row.
  109721. **
  109722. ** Use some of the same optimizations as OP_RowSetTest: If iSet
  109723. ** is zero, assume that the key cannot already be present in
  109724. ** the temp table. And if iSet is -1, assume that there is no
  109725. ** need to insert the key into the temp table, as it will never
  109726. ** be tested for. */
  109727. if( iSet ){
  109728. j1 = sqlite3VdbeAddOp4Int(v, OP_Found, regRowset, 0, r, nPk);
  109729. VdbeCoverage(v);
  109730. }
  109731. if( iSet>=0 ){
  109732. sqlite3VdbeAddOp3(v, OP_MakeRecord, r, nPk, regRowid);
  109733. sqlite3VdbeAddOp3(v, OP_IdxInsert, regRowset, regRowid, 0);
  109734. if( iSet ) sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
  109735. }
  109736. /* Release the array of temp registers */
  109737. sqlite3ReleaseTempRange(pParse, r, nPk);
  109738. }
  109739. }
  109740. /* Invoke the main loop body as a subroutine */
  109741. sqlite3VdbeAddOp2(v, OP_Gosub, regReturn, iLoopBody);
  109742. /* Jump here (skipping the main loop body subroutine) if the
  109743. ** current sub-WHERE row is a duplicate from prior sub-WHEREs. */
  109744. if( j1 ) sqlite3VdbeJumpHere(v, j1);
  109745. /* The pSubWInfo->untestedTerms flag means that this OR term
  109746. ** contained one or more AND term from a notReady table. The
  109747. ** terms from the notReady table could not be tested and will
  109748. ** need to be tested later.
  109749. */
  109750. if( pSubWInfo->untestedTerms ) untestedTerms = 1;
  109751. /* If all of the OR-connected terms are optimized using the same
  109752. ** index, and the index is opened using the same cursor number
  109753. ** by each call to sqlite3WhereBegin() made by this loop, it may
  109754. ** be possible to use that index as a covering index.
  109755. **
  109756. ** If the call to sqlite3WhereBegin() above resulted in a scan that
  109757. ** uses an index, and this is either the first OR-connected term
  109758. ** processed or the index is the same as that used by all previous
  109759. ** terms, set pCov to the candidate covering index. Otherwise, set
  109760. ** pCov to NULL to indicate that no candidate covering index will
  109761. ** be available.
  109762. */
  109763. pSubLoop = pSubWInfo->a[0].pWLoop;
  109764. assert( (pSubLoop->wsFlags & WHERE_AUTO_INDEX)==0 );
  109765. if( (pSubLoop->wsFlags & WHERE_INDEXED)!=0
  109766. && (ii==0 || pSubLoop->u.btree.pIndex==pCov)
  109767. && (HasRowid(pTab) || !IsPrimaryKeyIndex(pSubLoop->u.btree.pIndex))
  109768. ){
  109769. assert( pSubWInfo->a[0].iIdxCur==iCovCur );
  109770. pCov = pSubLoop->u.btree.pIndex;
  109771. wctrlFlags |= WHERE_REOPEN_IDX;
  109772. }else{
  109773. pCov = 0;
  109774. }
  109775. /* Finish the loop through table entries that match term pOrTerm. */
  109776. sqlite3WhereEnd(pSubWInfo);
  109777. }
  109778. }
  109779. }
  109780. pLevel->u.pCovidx = pCov;
  109781. if( pCov ) pLevel->iIdxCur = iCovCur;
  109782. if( pAndExpr ){
  109783. pAndExpr->pLeft = 0;
  109784. sqlite3ExprDelete(db, pAndExpr);
  109785. }
  109786. sqlite3VdbeChangeP1(v, iRetInit, sqlite3VdbeCurrentAddr(v));
  109787. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrBrk);
  109788. sqlite3VdbeResolveLabel(v, iLoopBody);
  109789. if( pWInfo->nLevel>1 ) sqlite3StackFree(db, pOrTab);
  109790. if( !untestedTerms ) disableTerm(pLevel, pTerm);
  109791. }else
  109792. #endif /* SQLITE_OMIT_OR_OPTIMIZATION */
  109793. {
  109794. /* Case 6: There is no usable index. We must do a complete
  109795. ** scan of the entire table.
  109796. */
  109797. static const u8 aStep[] = { OP_Next, OP_Prev };
  109798. static const u8 aStart[] = { OP_Rewind, OP_Last };
  109799. assert( bRev==0 || bRev==1 );
  109800. if( pTabItem->isRecursive ){
  109801. /* Tables marked isRecursive have only a single row that is stored in
  109802. ** a pseudo-cursor. No need to Rewind or Next such cursors. */
  109803. pLevel->op = OP_Noop;
  109804. }else{
  109805. pLevel->op = aStep[bRev];
  109806. pLevel->p1 = iCur;
  109807. pLevel->p2 = 1 + sqlite3VdbeAddOp2(v, aStart[bRev], iCur, addrBrk);
  109808. VdbeCoverageIf(v, bRev==0);
  109809. VdbeCoverageIf(v, bRev!=0);
  109810. pLevel->p5 = SQLITE_STMTSTATUS_FULLSCAN_STEP;
  109811. }
  109812. }
  109813. /* Insert code to test every subexpression that can be completely
  109814. ** computed using the current set of tables.
  109815. */
  109816. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  109817. Expr *pE;
  109818. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  109819. testcase( pTerm->wtFlags & TERM_CODED );
  109820. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  109821. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  109822. testcase( pWInfo->untestedTerms==0
  109823. && (pWInfo->wctrlFlags & WHERE_ONETABLE_ONLY)!=0 );
  109824. pWInfo->untestedTerms = 1;
  109825. continue;
  109826. }
  109827. pE = pTerm->pExpr;
  109828. assert( pE!=0 );
  109829. if( pLevel->iLeftJoin && !ExprHasProperty(pE, EP_FromJoin) ){
  109830. continue;
  109831. }
  109832. sqlite3ExprIfFalse(pParse, pE, addrCont, SQLITE_JUMPIFNULL);
  109833. pTerm->wtFlags |= TERM_CODED;
  109834. }
  109835. /* Insert code to test for implied constraints based on transitivity
  109836. ** of the "==" operator.
  109837. **
  109838. ** Example: If the WHERE clause contains "t1.a=t2.b" and "t2.b=123"
  109839. ** and we are coding the t1 loop and the t2 loop has not yet coded,
  109840. ** then we cannot use the "t1.a=t2.b" constraint, but we can code
  109841. ** the implied "t1.a=123" constraint.
  109842. */
  109843. for(pTerm=pWC->a, j=pWC->nTerm; j>0; j--, pTerm++){
  109844. Expr *pE, *pEAlt;
  109845. WhereTerm *pAlt;
  109846. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  109847. if( pTerm->eOperator!=(WO_EQUIV|WO_EQ) ) continue;
  109848. if( pTerm->leftCursor!=iCur ) continue;
  109849. if( pLevel->iLeftJoin ) continue;
  109850. pE = pTerm->pExpr;
  109851. assert( !ExprHasProperty(pE, EP_FromJoin) );
  109852. assert( (pTerm->prereqRight & pLevel->notReady)!=0 );
  109853. pAlt = findTerm(pWC, iCur, pTerm->u.leftColumn, notReady, WO_EQ|WO_IN, 0);
  109854. if( pAlt==0 ) continue;
  109855. if( pAlt->wtFlags & (TERM_CODED) ) continue;
  109856. testcase( pAlt->eOperator & WO_EQ );
  109857. testcase( pAlt->eOperator & WO_IN );
  109858. VdbeModuleComment((v, "begin transitive constraint"));
  109859. pEAlt = sqlite3StackAllocRaw(db, sizeof(*pEAlt));
  109860. if( pEAlt ){
  109861. *pEAlt = *pAlt->pExpr;
  109862. pEAlt->pLeft = pE->pLeft;
  109863. sqlite3ExprIfFalse(pParse, pEAlt, addrCont, SQLITE_JUMPIFNULL);
  109864. sqlite3StackFree(db, pEAlt);
  109865. }
  109866. }
  109867. /* For a LEFT OUTER JOIN, generate code that will record the fact that
  109868. ** at least one row of the right table has matched the left table.
  109869. */
  109870. if( pLevel->iLeftJoin ){
  109871. pLevel->addrFirst = sqlite3VdbeCurrentAddr(v);
  109872. sqlite3VdbeAddOp2(v, OP_Integer, 1, pLevel->iLeftJoin);
  109873. VdbeComment((v, "record LEFT JOIN hit"));
  109874. sqlite3ExprCacheClear(pParse);
  109875. for(pTerm=pWC->a, j=0; j<pWC->nTerm; j++, pTerm++){
  109876. testcase( pTerm->wtFlags & TERM_VIRTUAL );
  109877. testcase( pTerm->wtFlags & TERM_CODED );
  109878. if( pTerm->wtFlags & (TERM_VIRTUAL|TERM_CODED) ) continue;
  109879. if( (pTerm->prereqAll & pLevel->notReady)!=0 ){
  109880. assert( pWInfo->untestedTerms );
  109881. continue;
  109882. }
  109883. assert( pTerm->pExpr );
  109884. sqlite3ExprIfFalse(pParse, pTerm->pExpr, addrCont, SQLITE_JUMPIFNULL);
  109885. pTerm->wtFlags |= TERM_CODED;
  109886. }
  109887. }
  109888. return pLevel->notReady;
  109889. }
  109890. #ifdef WHERETRACE_ENABLED
  109891. /*
  109892. ** Print the content of a WhereTerm object
  109893. */
  109894. static void whereTermPrint(WhereTerm *pTerm, int iTerm){
  109895. if( pTerm==0 ){
  109896. sqlite3DebugPrintf("TERM-%-3d NULL\n", iTerm);
  109897. }else{
  109898. char zType[4];
  109899. memcpy(zType, "...", 4);
  109900. if( pTerm->wtFlags & TERM_VIRTUAL ) zType[0] = 'V';
  109901. if( pTerm->eOperator & WO_EQUIV ) zType[1] = 'E';
  109902. if( ExprHasProperty(pTerm->pExpr, EP_FromJoin) ) zType[2] = 'L';
  109903. sqlite3DebugPrintf("TERM-%-3d %p %s cursor=%-3d prob=%-3d op=0x%03x\n",
  109904. iTerm, pTerm, zType, pTerm->leftCursor, pTerm->truthProb,
  109905. pTerm->eOperator);
  109906. sqlite3TreeViewExpr(0, pTerm->pExpr, 0);
  109907. }
  109908. }
  109909. #endif
  109910. #ifdef WHERETRACE_ENABLED
  109911. /*
  109912. ** Print a WhereLoop object for debugging purposes
  109913. */
  109914. static void whereLoopPrint(WhereLoop *p, WhereClause *pWC){
  109915. WhereInfo *pWInfo = pWC->pWInfo;
  109916. int nb = 1+(pWInfo->pTabList->nSrc+7)/8;
  109917. struct SrcList_item *pItem = pWInfo->pTabList->a + p->iTab;
  109918. Table *pTab = pItem->pTab;
  109919. sqlite3DebugPrintf("%c%2d.%0*llx.%0*llx", p->cId,
  109920. p->iTab, nb, p->maskSelf, nb, p->prereq);
  109921. sqlite3DebugPrintf(" %12s",
  109922. pItem->zAlias ? pItem->zAlias : pTab->zName);
  109923. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  109924. const char *zName;
  109925. if( p->u.btree.pIndex && (zName = p->u.btree.pIndex->zName)!=0 ){
  109926. if( strncmp(zName, "sqlite_autoindex_", 17)==0 ){
  109927. int i = sqlite3Strlen30(zName) - 1;
  109928. while( zName[i]!='_' ) i--;
  109929. zName += i;
  109930. }
  109931. sqlite3DebugPrintf(".%-16s %2d", zName, p->u.btree.nEq);
  109932. }else{
  109933. sqlite3DebugPrintf("%20s","");
  109934. }
  109935. }else{
  109936. char *z;
  109937. if( p->u.vtab.idxStr ){
  109938. z = sqlite3_mprintf("(%d,\"%s\",%x)",
  109939. p->u.vtab.idxNum, p->u.vtab.idxStr, p->u.vtab.omitMask);
  109940. }else{
  109941. z = sqlite3_mprintf("(%d,%x)", p->u.vtab.idxNum, p->u.vtab.omitMask);
  109942. }
  109943. sqlite3DebugPrintf(" %-19s", z);
  109944. sqlite3_free(z);
  109945. }
  109946. if( p->wsFlags & WHERE_SKIPSCAN ){
  109947. sqlite3DebugPrintf(" f %05x %d-%d", p->wsFlags, p->nLTerm,p->u.btree.nSkip);
  109948. }else{
  109949. sqlite3DebugPrintf(" f %05x N %d", p->wsFlags, p->nLTerm);
  109950. }
  109951. sqlite3DebugPrintf(" cost %d,%d,%d\n", p->rSetup, p->rRun, p->nOut);
  109952. if( p->nLTerm && (sqlite3WhereTrace & 0x100)!=0 ){
  109953. int i;
  109954. for(i=0; i<p->nLTerm; i++){
  109955. whereTermPrint(p->aLTerm[i], i);
  109956. }
  109957. }
  109958. }
  109959. #endif
  109960. /*
  109961. ** Convert bulk memory into a valid WhereLoop that can be passed
  109962. ** to whereLoopClear harmlessly.
  109963. */
  109964. static void whereLoopInit(WhereLoop *p){
  109965. p->aLTerm = p->aLTermSpace;
  109966. p->nLTerm = 0;
  109967. p->nLSlot = ArraySize(p->aLTermSpace);
  109968. p->wsFlags = 0;
  109969. }
  109970. /*
  109971. ** Clear the WhereLoop.u union. Leave WhereLoop.pLTerm intact.
  109972. */
  109973. static void whereLoopClearUnion(sqlite3 *db, WhereLoop *p){
  109974. if( p->wsFlags & (WHERE_VIRTUALTABLE|WHERE_AUTO_INDEX) ){
  109975. if( (p->wsFlags & WHERE_VIRTUALTABLE)!=0 && p->u.vtab.needFree ){
  109976. sqlite3_free(p->u.vtab.idxStr);
  109977. p->u.vtab.needFree = 0;
  109978. p->u.vtab.idxStr = 0;
  109979. }else if( (p->wsFlags & WHERE_AUTO_INDEX)!=0 && p->u.btree.pIndex!=0 ){
  109980. sqlite3DbFree(db, p->u.btree.pIndex->zColAff);
  109981. sqlite3KeyInfoUnref(p->u.btree.pIndex->pKeyInfo);
  109982. sqlite3DbFree(db, p->u.btree.pIndex);
  109983. p->u.btree.pIndex = 0;
  109984. }
  109985. }
  109986. }
  109987. /*
  109988. ** Deallocate internal memory used by a WhereLoop object
  109989. */
  109990. static void whereLoopClear(sqlite3 *db, WhereLoop *p){
  109991. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  109992. whereLoopClearUnion(db, p);
  109993. whereLoopInit(p);
  109994. }
  109995. /*
  109996. ** Increase the memory allocation for pLoop->aLTerm[] to be at least n.
  109997. */
  109998. static int whereLoopResize(sqlite3 *db, WhereLoop *p, int n){
  109999. WhereTerm **paNew;
  110000. if( p->nLSlot>=n ) return SQLITE_OK;
  110001. n = (n+7)&~7;
  110002. paNew = sqlite3DbMallocRaw(db, sizeof(p->aLTerm[0])*n);
  110003. if( paNew==0 ) return SQLITE_NOMEM;
  110004. memcpy(paNew, p->aLTerm, sizeof(p->aLTerm[0])*p->nLSlot);
  110005. if( p->aLTerm!=p->aLTermSpace ) sqlite3DbFree(db, p->aLTerm);
  110006. p->aLTerm = paNew;
  110007. p->nLSlot = n;
  110008. return SQLITE_OK;
  110009. }
  110010. /*
  110011. ** Transfer content from the second pLoop into the first.
  110012. */
  110013. static int whereLoopXfer(sqlite3 *db, WhereLoop *pTo, WhereLoop *pFrom){
  110014. whereLoopClearUnion(db, pTo);
  110015. if( whereLoopResize(db, pTo, pFrom->nLTerm) ){
  110016. memset(&pTo->u, 0, sizeof(pTo->u));
  110017. return SQLITE_NOMEM;
  110018. }
  110019. memcpy(pTo, pFrom, WHERE_LOOP_XFER_SZ);
  110020. memcpy(pTo->aLTerm, pFrom->aLTerm, pTo->nLTerm*sizeof(pTo->aLTerm[0]));
  110021. if( pFrom->wsFlags & WHERE_VIRTUALTABLE ){
  110022. pFrom->u.vtab.needFree = 0;
  110023. }else if( (pFrom->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  110024. pFrom->u.btree.pIndex = 0;
  110025. }
  110026. return SQLITE_OK;
  110027. }
  110028. /*
  110029. ** Delete a WhereLoop object
  110030. */
  110031. static void whereLoopDelete(sqlite3 *db, WhereLoop *p){
  110032. whereLoopClear(db, p);
  110033. sqlite3DbFree(db, p);
  110034. }
  110035. /*
  110036. ** Free a WhereInfo structure
  110037. */
  110038. static void whereInfoFree(sqlite3 *db, WhereInfo *pWInfo){
  110039. if( ALWAYS(pWInfo) ){
  110040. whereClauseClear(&pWInfo->sWC);
  110041. while( pWInfo->pLoops ){
  110042. WhereLoop *p = pWInfo->pLoops;
  110043. pWInfo->pLoops = p->pNextLoop;
  110044. whereLoopDelete(db, p);
  110045. }
  110046. sqlite3DbFree(db, pWInfo);
  110047. }
  110048. }
  110049. /*
  110050. ** Return TRUE if both of the following are true:
  110051. **
  110052. ** (1) X has the same or lower cost that Y
  110053. ** (2) X is a proper subset of Y
  110054. **
  110055. ** By "proper subset" we mean that X uses fewer WHERE clause terms
  110056. ** than Y and that every WHERE clause term used by X is also used
  110057. ** by Y.
  110058. **
  110059. ** If X is a proper subset of Y then Y is a better choice and ought
  110060. ** to have a lower cost. This routine returns TRUE when that cost
  110061. ** relationship is inverted and needs to be adjusted.
  110062. */
  110063. static int whereLoopCheaperProperSubset(
  110064. const WhereLoop *pX, /* First WhereLoop to compare */
  110065. const WhereLoop *pY /* Compare against this WhereLoop */
  110066. ){
  110067. int i, j;
  110068. if( pX->nLTerm >= pY->nLTerm ) return 0; /* X is not a subset of Y */
  110069. if( pX->rRun >= pY->rRun ){
  110070. if( pX->rRun > pY->rRun ) return 0; /* X costs more than Y */
  110071. if( pX->nOut > pY->nOut ) return 0; /* X costs more than Y */
  110072. }
  110073. for(i=pX->nLTerm-1; i>=0; i--){
  110074. for(j=pY->nLTerm-1; j>=0; j--){
  110075. if( pY->aLTerm[j]==pX->aLTerm[i] ) break;
  110076. }
  110077. if( j<0 ) return 0; /* X not a subset of Y since term X[i] not used by Y */
  110078. }
  110079. return 1; /* All conditions meet */
  110080. }
  110081. /*
  110082. ** Try to adjust the cost of WhereLoop pTemplate upwards or downwards so
  110083. ** that:
  110084. **
  110085. ** (1) pTemplate costs less than any other WhereLoops that are a proper
  110086. ** subset of pTemplate
  110087. **
  110088. ** (2) pTemplate costs more than any other WhereLoops for which pTemplate
  110089. ** is a proper subset.
  110090. **
  110091. ** To say "WhereLoop X is a proper subset of Y" means that X uses fewer
  110092. ** WHERE clause terms than Y and that every WHERE clause term used by X is
  110093. ** also used by Y.
  110094. **
  110095. ** This adjustment is omitted for SKIPSCAN loops. In a SKIPSCAN loop, the
  110096. ** WhereLoop.nLTerm field is not an accurate measure of the number of WHERE
  110097. ** clause terms covered, since some of the first nLTerm entries in aLTerm[]
  110098. ** will be NULL (because they are skipped). That makes it more difficult
  110099. ** to compare the loops. We could add extra code to do the comparison, and
  110100. ** perhaps we will someday. But SKIPSCAN is sufficiently uncommon, and this
  110101. ** adjustment is sufficient minor, that it is very difficult to construct
  110102. ** a test case where the extra code would improve the query plan. Better
  110103. ** to avoid the added complexity and just omit cost adjustments to SKIPSCAN
  110104. ** loops.
  110105. */
  110106. static void whereLoopAdjustCost(const WhereLoop *p, WhereLoop *pTemplate){
  110107. if( (pTemplate->wsFlags & WHERE_INDEXED)==0 ) return;
  110108. if( (pTemplate->wsFlags & WHERE_SKIPSCAN)!=0 ) return;
  110109. for(; p; p=p->pNextLoop){
  110110. if( p->iTab!=pTemplate->iTab ) continue;
  110111. if( (p->wsFlags & WHERE_INDEXED)==0 ) continue;
  110112. if( (p->wsFlags & WHERE_SKIPSCAN)!=0 ) continue;
  110113. if( whereLoopCheaperProperSubset(p, pTemplate) ){
  110114. /* Adjust pTemplate cost downward so that it is cheaper than its
  110115. ** subset p */
  110116. pTemplate->rRun = p->rRun;
  110117. pTemplate->nOut = p->nOut - 1;
  110118. }else if( whereLoopCheaperProperSubset(pTemplate, p) ){
  110119. /* Adjust pTemplate cost upward so that it is costlier than p since
  110120. ** pTemplate is a proper subset of p */
  110121. pTemplate->rRun = p->rRun;
  110122. pTemplate->nOut = p->nOut + 1;
  110123. }
  110124. }
  110125. }
  110126. /*
  110127. ** Search the list of WhereLoops in *ppPrev looking for one that can be
  110128. ** supplanted by pTemplate.
  110129. **
  110130. ** Return NULL if the WhereLoop list contains an entry that can supplant
  110131. ** pTemplate, in other words if pTemplate does not belong on the list.
  110132. **
  110133. ** If pX is a WhereLoop that pTemplate can supplant, then return the
  110134. ** link that points to pX.
  110135. **
  110136. ** If pTemplate cannot supplant any existing element of the list but needs
  110137. ** to be added to the list, then return a pointer to the tail of the list.
  110138. */
  110139. static WhereLoop **whereLoopFindLesser(
  110140. WhereLoop **ppPrev,
  110141. const WhereLoop *pTemplate
  110142. ){
  110143. WhereLoop *p;
  110144. for(p=(*ppPrev); p; ppPrev=&p->pNextLoop, p=*ppPrev){
  110145. if( p->iTab!=pTemplate->iTab || p->iSortIdx!=pTemplate->iSortIdx ){
  110146. /* If either the iTab or iSortIdx values for two WhereLoop are different
  110147. ** then those WhereLoops need to be considered separately. Neither is
  110148. ** a candidate to replace the other. */
  110149. continue;
  110150. }
  110151. /* In the current implementation, the rSetup value is either zero
  110152. ** or the cost of building an automatic index (NlogN) and the NlogN
  110153. ** is the same for compatible WhereLoops. */
  110154. assert( p->rSetup==0 || pTemplate->rSetup==0
  110155. || p->rSetup==pTemplate->rSetup );
  110156. /* whereLoopAddBtree() always generates and inserts the automatic index
  110157. ** case first. Hence compatible candidate WhereLoops never have a larger
  110158. ** rSetup. Call this SETUP-INVARIANT */
  110159. assert( p->rSetup>=pTemplate->rSetup );
  110160. /* Any loop using an appliation-defined index (or PRIMARY KEY or
  110161. ** UNIQUE constraint) with one or more == constraints is better
  110162. ** than an automatic index. */
  110163. if( (p->wsFlags & WHERE_AUTO_INDEX)!=0
  110164. && (pTemplate->wsFlags & WHERE_INDEXED)!=0
  110165. && (pTemplate->wsFlags & WHERE_COLUMN_EQ)!=0
  110166. && (p->prereq & pTemplate->prereq)==pTemplate->prereq
  110167. ){
  110168. break;
  110169. }
  110170. /* If existing WhereLoop p is better than pTemplate, pTemplate can be
  110171. ** discarded. WhereLoop p is better if:
  110172. ** (1) p has no more dependencies than pTemplate, and
  110173. ** (2) p has an equal or lower cost than pTemplate
  110174. */
  110175. if( (p->prereq & pTemplate->prereq)==p->prereq /* (1) */
  110176. && p->rSetup<=pTemplate->rSetup /* (2a) */
  110177. && p->rRun<=pTemplate->rRun /* (2b) */
  110178. && p->nOut<=pTemplate->nOut /* (2c) */
  110179. ){
  110180. return 0; /* Discard pTemplate */
  110181. }
  110182. /* If pTemplate is always better than p, then cause p to be overwritten
  110183. ** with pTemplate. pTemplate is better than p if:
  110184. ** (1) pTemplate has no more dependences than p, and
  110185. ** (2) pTemplate has an equal or lower cost than p.
  110186. */
  110187. if( (p->prereq & pTemplate->prereq)==pTemplate->prereq /* (1) */
  110188. && p->rRun>=pTemplate->rRun /* (2a) */
  110189. && p->nOut>=pTemplate->nOut /* (2b) */
  110190. ){
  110191. assert( p->rSetup>=pTemplate->rSetup ); /* SETUP-INVARIANT above */
  110192. break; /* Cause p to be overwritten by pTemplate */
  110193. }
  110194. }
  110195. return ppPrev;
  110196. }
  110197. /*
  110198. ** Insert or replace a WhereLoop entry using the template supplied.
  110199. **
  110200. ** An existing WhereLoop entry might be overwritten if the new template
  110201. ** is better and has fewer dependencies. Or the template will be ignored
  110202. ** and no insert will occur if an existing WhereLoop is faster and has
  110203. ** fewer dependencies than the template. Otherwise a new WhereLoop is
  110204. ** added based on the template.
  110205. **
  110206. ** If pBuilder->pOrSet is not NULL then we care about only the
  110207. ** prerequisites and rRun and nOut costs of the N best loops. That
  110208. ** information is gathered in the pBuilder->pOrSet object. This special
  110209. ** processing mode is used only for OR clause processing.
  110210. **
  110211. ** When accumulating multiple loops (when pBuilder->pOrSet is NULL) we
  110212. ** still might overwrite similar loops with the new template if the
  110213. ** new template is better. Loops may be overwritten if the following
  110214. ** conditions are met:
  110215. **
  110216. ** (1) They have the same iTab.
  110217. ** (2) They have the same iSortIdx.
  110218. ** (3) The template has same or fewer dependencies than the current loop
  110219. ** (4) The template has the same or lower cost than the current loop
  110220. */
  110221. static int whereLoopInsert(WhereLoopBuilder *pBuilder, WhereLoop *pTemplate){
  110222. WhereLoop **ppPrev, *p;
  110223. WhereInfo *pWInfo = pBuilder->pWInfo;
  110224. sqlite3 *db = pWInfo->pParse->db;
  110225. /* If pBuilder->pOrSet is defined, then only keep track of the costs
  110226. ** and prereqs.
  110227. */
  110228. if( pBuilder->pOrSet!=0 ){
  110229. #if WHERETRACE_ENABLED
  110230. u16 n = pBuilder->pOrSet->n;
  110231. int x =
  110232. #endif
  110233. whereOrInsert(pBuilder->pOrSet, pTemplate->prereq, pTemplate->rRun,
  110234. pTemplate->nOut);
  110235. #if WHERETRACE_ENABLED /* 0x8 */
  110236. if( sqlite3WhereTrace & 0x8 ){
  110237. sqlite3DebugPrintf(x?" or-%d: ":" or-X: ", n);
  110238. whereLoopPrint(pTemplate, pBuilder->pWC);
  110239. }
  110240. #endif
  110241. return SQLITE_OK;
  110242. }
  110243. /* Look for an existing WhereLoop to replace with pTemplate
  110244. */
  110245. whereLoopAdjustCost(pWInfo->pLoops, pTemplate);
  110246. ppPrev = whereLoopFindLesser(&pWInfo->pLoops, pTemplate);
  110247. if( ppPrev==0 ){
  110248. /* There already exists a WhereLoop on the list that is better
  110249. ** than pTemplate, so just ignore pTemplate */
  110250. #if WHERETRACE_ENABLED /* 0x8 */
  110251. if( sqlite3WhereTrace & 0x8 ){
  110252. sqlite3DebugPrintf(" skip: ");
  110253. whereLoopPrint(pTemplate, pBuilder->pWC);
  110254. }
  110255. #endif
  110256. return SQLITE_OK;
  110257. }else{
  110258. p = *ppPrev;
  110259. }
  110260. /* If we reach this point it means that either p[] should be overwritten
  110261. ** with pTemplate[] if p[] exists, or if p==NULL then allocate a new
  110262. ** WhereLoop and insert it.
  110263. */
  110264. #if WHERETRACE_ENABLED /* 0x8 */
  110265. if( sqlite3WhereTrace & 0x8 ){
  110266. if( p!=0 ){
  110267. sqlite3DebugPrintf("replace: ");
  110268. whereLoopPrint(p, pBuilder->pWC);
  110269. }
  110270. sqlite3DebugPrintf(" add: ");
  110271. whereLoopPrint(pTemplate, pBuilder->pWC);
  110272. }
  110273. #endif
  110274. if( p==0 ){
  110275. /* Allocate a new WhereLoop to add to the end of the list */
  110276. *ppPrev = p = sqlite3DbMallocRaw(db, sizeof(WhereLoop));
  110277. if( p==0 ) return SQLITE_NOMEM;
  110278. whereLoopInit(p);
  110279. p->pNextLoop = 0;
  110280. }else{
  110281. /* We will be overwriting WhereLoop p[]. But before we do, first
  110282. ** go through the rest of the list and delete any other entries besides
  110283. ** p[] that are also supplated by pTemplate */
  110284. WhereLoop **ppTail = &p->pNextLoop;
  110285. WhereLoop *pToDel;
  110286. while( *ppTail ){
  110287. ppTail = whereLoopFindLesser(ppTail, pTemplate);
  110288. if( ppTail==0 ) break;
  110289. pToDel = *ppTail;
  110290. if( pToDel==0 ) break;
  110291. *ppTail = pToDel->pNextLoop;
  110292. #if WHERETRACE_ENABLED /* 0x8 */
  110293. if( sqlite3WhereTrace & 0x8 ){
  110294. sqlite3DebugPrintf(" delete: ");
  110295. whereLoopPrint(pToDel, pBuilder->pWC);
  110296. }
  110297. #endif
  110298. whereLoopDelete(db, pToDel);
  110299. }
  110300. }
  110301. whereLoopXfer(db, p, pTemplate);
  110302. if( (p->wsFlags & WHERE_VIRTUALTABLE)==0 ){
  110303. Index *pIndex = p->u.btree.pIndex;
  110304. if( pIndex && pIndex->tnum==0 ){
  110305. p->u.btree.pIndex = 0;
  110306. }
  110307. }
  110308. return SQLITE_OK;
  110309. }
  110310. /*
  110311. ** Adjust the WhereLoop.nOut value downward to account for terms of the
  110312. ** WHERE clause that reference the loop but which are not used by an
  110313. ** index.
  110314. **
  110315. ** In the current implementation, the first extra WHERE clause term reduces
  110316. ** the number of output rows by a factor of 10 and each additional term
  110317. ** reduces the number of output rows by sqrt(2).
  110318. */
  110319. static void whereLoopOutputAdjust(
  110320. WhereClause *pWC, /* The WHERE clause */
  110321. WhereLoop *pLoop, /* The loop to adjust downward */
  110322. LogEst nRow /* Number of rows in the entire table */
  110323. ){
  110324. WhereTerm *pTerm, *pX;
  110325. Bitmask notAllowed = ~(pLoop->prereq|pLoop->maskSelf);
  110326. int i, j;
  110327. int nEq = 0; /* Number of = constraints not within likely()/unlikely() */
  110328. for(i=pWC->nTerm, pTerm=pWC->a; i>0; i--, pTerm++){
  110329. if( (pTerm->wtFlags & TERM_VIRTUAL)!=0 ) break;
  110330. if( (pTerm->prereqAll & pLoop->maskSelf)==0 ) continue;
  110331. if( (pTerm->prereqAll & notAllowed)!=0 ) continue;
  110332. for(j=pLoop->nLTerm-1; j>=0; j--){
  110333. pX = pLoop->aLTerm[j];
  110334. if( pX==0 ) continue;
  110335. if( pX==pTerm ) break;
  110336. if( pX->iParent>=0 && (&pWC->a[pX->iParent])==pTerm ) break;
  110337. }
  110338. if( j<0 ){
  110339. if( pTerm->truthProb<=0 ){
  110340. pLoop->nOut += pTerm->truthProb;
  110341. }else{
  110342. pLoop->nOut--;
  110343. if( pTerm->eOperator&WO_EQ ) nEq++;
  110344. }
  110345. }
  110346. }
  110347. /* TUNING: If there is at least one equality constraint in the WHERE
  110348. ** clause that does not have a likelihood() explicitly assigned to it
  110349. ** then do not let the estimated number of output rows exceed half
  110350. ** the number of rows in the table. */
  110351. if( nEq && pLoop->nOut>nRow-10 ){
  110352. pLoop->nOut = nRow - 10;
  110353. }
  110354. }
  110355. /*
  110356. ** Adjust the cost C by the costMult facter T. This only occurs if
  110357. ** compiled with -DSQLITE_ENABLE_COSTMULT
  110358. */
  110359. #ifdef SQLITE_ENABLE_COSTMULT
  110360. # define ApplyCostMultiplier(C,T) C += T
  110361. #else
  110362. # define ApplyCostMultiplier(C,T)
  110363. #endif
  110364. /*
  110365. ** We have so far matched pBuilder->pNew->u.btree.nEq terms of the
  110366. ** index pIndex. Try to match one more.
  110367. **
  110368. ** When this function is called, pBuilder->pNew->nOut contains the
  110369. ** number of rows expected to be visited by filtering using the nEq
  110370. ** terms only. If it is modified, this value is restored before this
  110371. ** function returns.
  110372. **
  110373. ** If pProbe->tnum==0, that means pIndex is a fake index used for the
  110374. ** INTEGER PRIMARY KEY.
  110375. */
  110376. static int whereLoopAddBtreeIndex(
  110377. WhereLoopBuilder *pBuilder, /* The WhereLoop factory */
  110378. struct SrcList_item *pSrc, /* FROM clause term being analyzed */
  110379. Index *pProbe, /* An index on pSrc */
  110380. LogEst nInMul /* log(Number of iterations due to IN) */
  110381. ){
  110382. WhereInfo *pWInfo = pBuilder->pWInfo; /* WHERE analyse context */
  110383. Parse *pParse = pWInfo->pParse; /* Parsing context */
  110384. sqlite3 *db = pParse->db; /* Database connection malloc context */
  110385. WhereLoop *pNew; /* Template WhereLoop under construction */
  110386. WhereTerm *pTerm; /* A WhereTerm under consideration */
  110387. int opMask; /* Valid operators for constraints */
  110388. WhereScan scan; /* Iterator for WHERE terms */
  110389. Bitmask saved_prereq; /* Original value of pNew->prereq */
  110390. u16 saved_nLTerm; /* Original value of pNew->nLTerm */
  110391. u16 saved_nEq; /* Original value of pNew->u.btree.nEq */
  110392. u16 saved_nSkip; /* Original value of pNew->u.btree.nSkip */
  110393. u32 saved_wsFlags; /* Original value of pNew->wsFlags */
  110394. LogEst saved_nOut; /* Original value of pNew->nOut */
  110395. int iCol; /* Index of the column in the table */
  110396. int rc = SQLITE_OK; /* Return code */
  110397. LogEst rSize; /* Number of rows in the table */
  110398. LogEst rLogSize; /* Logarithm of table size */
  110399. WhereTerm *pTop = 0, *pBtm = 0; /* Top and bottom range constraints */
  110400. pNew = pBuilder->pNew;
  110401. if( db->mallocFailed ) return SQLITE_NOMEM;
  110402. assert( (pNew->wsFlags & WHERE_VIRTUALTABLE)==0 );
  110403. assert( (pNew->wsFlags & WHERE_TOP_LIMIT)==0 );
  110404. if( pNew->wsFlags & WHERE_BTM_LIMIT ){
  110405. opMask = WO_LT|WO_LE;
  110406. }else if( pProbe->tnum<=0 || (pSrc->jointype & JT_LEFT)!=0 ){
  110407. opMask = WO_EQ|WO_IN|WO_GT|WO_GE|WO_LT|WO_LE;
  110408. }else{
  110409. opMask = WO_EQ|WO_IN|WO_ISNULL|WO_GT|WO_GE|WO_LT|WO_LE;
  110410. }
  110411. if( pProbe->bUnordered ) opMask &= ~(WO_GT|WO_GE|WO_LT|WO_LE);
  110412. assert( pNew->u.btree.nEq<pProbe->nColumn );
  110413. iCol = pProbe->aiColumn[pNew->u.btree.nEq];
  110414. pTerm = whereScanInit(&scan, pBuilder->pWC, pSrc->iCursor, iCol,
  110415. opMask, pProbe);
  110416. saved_nEq = pNew->u.btree.nEq;
  110417. saved_nSkip = pNew->u.btree.nSkip;
  110418. saved_nLTerm = pNew->nLTerm;
  110419. saved_wsFlags = pNew->wsFlags;
  110420. saved_prereq = pNew->prereq;
  110421. saved_nOut = pNew->nOut;
  110422. pNew->rSetup = 0;
  110423. rSize = pProbe->aiRowLogEst[0];
  110424. rLogSize = estLog(rSize);
  110425. /* Consider using a skip-scan if there are no WHERE clause constraints
  110426. ** available for the left-most terms of the index, and if the average
  110427. ** number of repeats in the left-most terms is at least 18.
  110428. **
  110429. ** The magic number 18 is selected on the basis that scanning 17 rows
  110430. ** is almost always quicker than an index seek (even though if the index
  110431. ** contains fewer than 2^17 rows we assume otherwise in other parts of
  110432. ** the code). And, even if it is not, it should not be too much slower.
  110433. ** On the other hand, the extra seeks could end up being significantly
  110434. ** more expensive. */
  110435. assert( 42==sqlite3LogEst(18) );
  110436. if( saved_nEq==saved_nSkip
  110437. && saved_nEq+1<pProbe->nKeyCol
  110438. && pProbe->aiRowLogEst[saved_nEq+1]>=42 /* TUNING: Minimum for skip-scan */
  110439. && (rc = whereLoopResize(db, pNew, pNew->nLTerm+1))==SQLITE_OK
  110440. ){
  110441. LogEst nIter;
  110442. pNew->u.btree.nEq++;
  110443. pNew->u.btree.nSkip++;
  110444. pNew->aLTerm[pNew->nLTerm++] = 0;
  110445. pNew->wsFlags |= WHERE_SKIPSCAN;
  110446. nIter = pProbe->aiRowLogEst[saved_nEq] - pProbe->aiRowLogEst[saved_nEq+1];
  110447. if( pTerm ){
  110448. /* TUNING: When estimating skip-scan for a term that is also indexable,
  110449. ** multiply the cost of the skip-scan by 2.0, to make it a little less
  110450. ** desirable than the regular index lookup. */
  110451. nIter += 10; assert( 10==sqlite3LogEst(2) );
  110452. }
  110453. pNew->nOut -= nIter;
  110454. /* TUNING: Because uncertainties in the estimates for skip-scan queries,
  110455. ** add a 1.375 fudge factor to make skip-scan slightly less likely. */
  110456. nIter += 5;
  110457. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nIter + nInMul);
  110458. pNew->nOut = saved_nOut;
  110459. pNew->u.btree.nEq = saved_nEq;
  110460. pNew->u.btree.nSkip = saved_nSkip;
  110461. }
  110462. for(; rc==SQLITE_OK && pTerm!=0; pTerm = whereScanNext(&scan)){
  110463. u16 eOp = pTerm->eOperator; /* Shorthand for pTerm->eOperator */
  110464. LogEst rCostIdx;
  110465. LogEst nOutUnadjusted; /* nOut before IN() and WHERE adjustments */
  110466. int nIn = 0;
  110467. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110468. int nRecValid = pBuilder->nRecValid;
  110469. #endif
  110470. if( (eOp==WO_ISNULL || (pTerm->wtFlags&TERM_VNULL)!=0)
  110471. && (iCol<0 || pSrc->pTab->aCol[iCol].notNull)
  110472. ){
  110473. continue; /* ignore IS [NOT] NULL constraints on NOT NULL columns */
  110474. }
  110475. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  110476. pNew->wsFlags = saved_wsFlags;
  110477. pNew->u.btree.nEq = saved_nEq;
  110478. pNew->nLTerm = saved_nLTerm;
  110479. if( whereLoopResize(db, pNew, pNew->nLTerm+1) ) break; /* OOM */
  110480. pNew->aLTerm[pNew->nLTerm++] = pTerm;
  110481. pNew->prereq = (saved_prereq | pTerm->prereqRight) & ~pNew->maskSelf;
  110482. assert( nInMul==0
  110483. || (pNew->wsFlags & WHERE_COLUMN_NULL)!=0
  110484. || (pNew->wsFlags & WHERE_COLUMN_IN)!=0
  110485. || (pNew->wsFlags & WHERE_SKIPSCAN)!=0
  110486. );
  110487. if( eOp & WO_IN ){
  110488. Expr *pExpr = pTerm->pExpr;
  110489. pNew->wsFlags |= WHERE_COLUMN_IN;
  110490. if( ExprHasProperty(pExpr, EP_xIsSelect) ){
  110491. /* "x IN (SELECT ...)": TUNING: the SELECT returns 25 rows */
  110492. nIn = 46; assert( 46==sqlite3LogEst(25) );
  110493. }else if( ALWAYS(pExpr->x.pList && pExpr->x.pList->nExpr) ){
  110494. /* "x IN (value, value, ...)" */
  110495. nIn = sqlite3LogEst(pExpr->x.pList->nExpr);
  110496. }
  110497. assert( nIn>0 ); /* RHS always has 2 or more terms... The parser
  110498. ** changes "x IN (?)" into "x=?". */
  110499. }else if( eOp & (WO_EQ) ){
  110500. pNew->wsFlags |= WHERE_COLUMN_EQ;
  110501. if( iCol<0 || (nInMul==0 && pNew->u.btree.nEq==pProbe->nKeyCol-1) ){
  110502. if( iCol>=0 && !IsUniqueIndex(pProbe) ){
  110503. pNew->wsFlags |= WHERE_UNQ_WANTED;
  110504. }else{
  110505. pNew->wsFlags |= WHERE_ONEROW;
  110506. }
  110507. }
  110508. }else if( eOp & WO_ISNULL ){
  110509. pNew->wsFlags |= WHERE_COLUMN_NULL;
  110510. }else if( eOp & (WO_GT|WO_GE) ){
  110511. testcase( eOp & WO_GT );
  110512. testcase( eOp & WO_GE );
  110513. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_BTM_LIMIT;
  110514. pBtm = pTerm;
  110515. pTop = 0;
  110516. }else{
  110517. assert( eOp & (WO_LT|WO_LE) );
  110518. testcase( eOp & WO_LT );
  110519. testcase( eOp & WO_LE );
  110520. pNew->wsFlags |= WHERE_COLUMN_RANGE|WHERE_TOP_LIMIT;
  110521. pTop = pTerm;
  110522. pBtm = (pNew->wsFlags & WHERE_BTM_LIMIT)!=0 ?
  110523. pNew->aLTerm[pNew->nLTerm-2] : 0;
  110524. }
  110525. /* At this point pNew->nOut is set to the number of rows expected to
  110526. ** be visited by the index scan before considering term pTerm, or the
  110527. ** values of nIn and nInMul. In other words, assuming that all
  110528. ** "x IN(...)" terms are replaced with "x = ?". This block updates
  110529. ** the value of pNew->nOut to account for pTerm (but not nIn/nInMul). */
  110530. assert( pNew->nOut==saved_nOut );
  110531. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  110532. /* Adjust nOut using stat3/stat4 data. Or, if there is no stat3/stat4
  110533. ** data, using some other estimate. */
  110534. whereRangeScanEst(pParse, pBuilder, pBtm, pTop, pNew);
  110535. }else{
  110536. int nEq = ++pNew->u.btree.nEq;
  110537. assert( eOp & (WO_ISNULL|WO_EQ|WO_IN) );
  110538. assert( pNew->nOut==saved_nOut );
  110539. if( pTerm->truthProb<=0 && iCol>=0 ){
  110540. assert( (eOp & WO_IN) || nIn==0 );
  110541. testcase( eOp & WO_IN );
  110542. pNew->nOut += pTerm->truthProb;
  110543. pNew->nOut -= nIn;
  110544. }else{
  110545. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110546. tRowcnt nOut = 0;
  110547. if( nInMul==0
  110548. && pProbe->nSample
  110549. && pNew->u.btree.nEq<=pProbe->nSampleCol
  110550. && OptimizationEnabled(db, SQLITE_Stat3)
  110551. && ((eOp & WO_IN)==0 || !ExprHasProperty(pTerm->pExpr, EP_xIsSelect))
  110552. ){
  110553. Expr *pExpr = pTerm->pExpr;
  110554. if( (eOp & (WO_EQ|WO_ISNULL))!=0 ){
  110555. testcase( eOp & WO_EQ );
  110556. testcase( eOp & WO_ISNULL );
  110557. rc = whereEqualScanEst(pParse, pBuilder, pExpr->pRight, &nOut);
  110558. }else{
  110559. rc = whereInScanEst(pParse, pBuilder, pExpr->x.pList, &nOut);
  110560. }
  110561. if( rc==SQLITE_NOTFOUND ) rc = SQLITE_OK;
  110562. if( rc!=SQLITE_OK ) break; /* Jump out of the pTerm loop */
  110563. if( nOut ){
  110564. pNew->nOut = sqlite3LogEst(nOut);
  110565. if( pNew->nOut>saved_nOut ) pNew->nOut = saved_nOut;
  110566. pNew->nOut -= nIn;
  110567. }
  110568. }
  110569. if( nOut==0 )
  110570. #endif
  110571. {
  110572. pNew->nOut += (pProbe->aiRowLogEst[nEq] - pProbe->aiRowLogEst[nEq-1]);
  110573. if( eOp & WO_ISNULL ){
  110574. /* TUNING: If there is no likelihood() value, assume that a
  110575. ** "col IS NULL" expression matches twice as many rows
  110576. ** as (col=?). */
  110577. pNew->nOut += 10;
  110578. }
  110579. }
  110580. }
  110581. }
  110582. /* Set rCostIdx to the cost of visiting selected rows in index. Add
  110583. ** it to pNew->rRun, which is currently set to the cost of the index
  110584. ** seek only. Then, if this is a non-covering index, add the cost of
  110585. ** visiting the rows in the main table. */
  110586. rCostIdx = pNew->nOut + 1 + (15*pProbe->szIdxRow)/pSrc->pTab->szTabRow;
  110587. pNew->rRun = sqlite3LogEstAdd(rLogSize, rCostIdx);
  110588. if( (pNew->wsFlags & (WHERE_IDX_ONLY|WHERE_IPK))==0 ){
  110589. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, pNew->nOut + 16);
  110590. }
  110591. ApplyCostMultiplier(pNew->rRun, pProbe->pTable->costMult);
  110592. nOutUnadjusted = pNew->nOut;
  110593. pNew->rRun += nInMul + nIn;
  110594. pNew->nOut += nInMul + nIn;
  110595. whereLoopOutputAdjust(pBuilder->pWC, pNew, rSize);
  110596. rc = whereLoopInsert(pBuilder, pNew);
  110597. if( pNew->wsFlags & WHERE_COLUMN_RANGE ){
  110598. pNew->nOut = saved_nOut;
  110599. }else{
  110600. pNew->nOut = nOutUnadjusted;
  110601. }
  110602. if( (pNew->wsFlags & WHERE_TOP_LIMIT)==0
  110603. && pNew->u.btree.nEq<pProbe->nColumn
  110604. ){
  110605. whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, nInMul+nIn);
  110606. }
  110607. pNew->nOut = saved_nOut;
  110608. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110609. pBuilder->nRecValid = nRecValid;
  110610. #endif
  110611. }
  110612. pNew->prereq = saved_prereq;
  110613. pNew->u.btree.nEq = saved_nEq;
  110614. pNew->u.btree.nSkip = saved_nSkip;
  110615. pNew->wsFlags = saved_wsFlags;
  110616. pNew->nOut = saved_nOut;
  110617. pNew->nLTerm = saved_nLTerm;
  110618. return rc;
  110619. }
  110620. /*
  110621. ** Return True if it is possible that pIndex might be useful in
  110622. ** implementing the ORDER BY clause in pBuilder.
  110623. **
  110624. ** Return False if pBuilder does not contain an ORDER BY clause or
  110625. ** if there is no way for pIndex to be useful in implementing that
  110626. ** ORDER BY clause.
  110627. */
  110628. static int indexMightHelpWithOrderBy(
  110629. WhereLoopBuilder *pBuilder,
  110630. Index *pIndex,
  110631. int iCursor
  110632. ){
  110633. ExprList *pOB;
  110634. int ii, jj;
  110635. if( pIndex->bUnordered ) return 0;
  110636. if( (pOB = pBuilder->pWInfo->pOrderBy)==0 ) return 0;
  110637. for(ii=0; ii<pOB->nExpr; ii++){
  110638. Expr *pExpr = sqlite3ExprSkipCollate(pOB->a[ii].pExpr);
  110639. if( pExpr->op!=TK_COLUMN ) return 0;
  110640. if( pExpr->iTable==iCursor ){
  110641. if( pExpr->iColumn<0 ) return 1;
  110642. for(jj=0; jj<pIndex->nKeyCol; jj++){
  110643. if( pExpr->iColumn==pIndex->aiColumn[jj] ) return 1;
  110644. }
  110645. }
  110646. }
  110647. return 0;
  110648. }
  110649. /*
  110650. ** Return a bitmask where 1s indicate that the corresponding column of
  110651. ** the table is used by an index. Only the first 63 columns are considered.
  110652. */
  110653. static Bitmask columnsInIndex(Index *pIdx){
  110654. Bitmask m = 0;
  110655. int j;
  110656. for(j=pIdx->nColumn-1; j>=0; j--){
  110657. int x = pIdx->aiColumn[j];
  110658. if( x>=0 ){
  110659. testcase( x==BMS-1 );
  110660. testcase( x==BMS-2 );
  110661. if( x<BMS-1 ) m |= MASKBIT(x);
  110662. }
  110663. }
  110664. return m;
  110665. }
  110666. /* Check to see if a partial index with pPartIndexWhere can be used
  110667. ** in the current query. Return true if it can be and false if not.
  110668. */
  110669. static int whereUsablePartialIndex(int iTab, WhereClause *pWC, Expr *pWhere){
  110670. int i;
  110671. WhereTerm *pTerm;
  110672. for(i=0, pTerm=pWC->a; i<pWC->nTerm; i++, pTerm++){
  110673. if( sqlite3ExprImpliesExpr(pTerm->pExpr, pWhere, iTab) ) return 1;
  110674. }
  110675. return 0;
  110676. }
  110677. /*
  110678. ** Add all WhereLoop objects for a single table of the join where the table
  110679. ** is idenfied by pBuilder->pNew->iTab. That table is guaranteed to be
  110680. ** a b-tree table, not a virtual table.
  110681. **
  110682. ** The costs (WhereLoop.rRun) of the b-tree loops added by this function
  110683. ** are calculated as follows:
  110684. **
  110685. ** For a full scan, assuming the table (or index) contains nRow rows:
  110686. **
  110687. ** cost = nRow * 3.0 // full-table scan
  110688. ** cost = nRow * K // scan of covering index
  110689. ** cost = nRow * (K+3.0) // scan of non-covering index
  110690. **
  110691. ** where K is a value between 1.1 and 3.0 set based on the relative
  110692. ** estimated average size of the index and table records.
  110693. **
  110694. ** For an index scan, where nVisit is the number of index rows visited
  110695. ** by the scan, and nSeek is the number of seek operations required on
  110696. ** the index b-tree:
  110697. **
  110698. ** cost = nSeek * (log(nRow) + K * nVisit) // covering index
  110699. ** cost = nSeek * (log(nRow) + (K+3.0) * nVisit) // non-covering index
  110700. **
  110701. ** Normally, nSeek is 1. nSeek values greater than 1 come about if the
  110702. ** WHERE clause includes "x IN (....)" terms used in place of "x=?". Or when
  110703. ** implicit "x IN (SELECT x FROM tbl)" terms are added for skip-scans.
  110704. **
  110705. ** The estimated values (nRow, nVisit, nSeek) often contain a large amount
  110706. ** of uncertainty. For this reason, scoring is designed to pick plans that
  110707. ** "do the least harm" if the estimates are inaccurate. For example, a
  110708. ** log(nRow) factor is omitted from a non-covering index scan in order to
  110709. ** bias the scoring in favor of using an index, since the worst-case
  110710. ** performance of using an index is far better than the worst-case performance
  110711. ** of a full table scan.
  110712. */
  110713. static int whereLoopAddBtree(
  110714. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  110715. Bitmask mExtra /* Extra prerequesites for using this table */
  110716. ){
  110717. WhereInfo *pWInfo; /* WHERE analysis context */
  110718. Index *pProbe; /* An index we are evaluating */
  110719. Index sPk; /* A fake index object for the primary key */
  110720. LogEst aiRowEstPk[2]; /* The aiRowLogEst[] value for the sPk index */
  110721. i16 aiColumnPk = -1; /* The aColumn[] value for the sPk index */
  110722. SrcList *pTabList; /* The FROM clause */
  110723. struct SrcList_item *pSrc; /* The FROM clause btree term to add */
  110724. WhereLoop *pNew; /* Template WhereLoop object */
  110725. int rc = SQLITE_OK; /* Return code */
  110726. int iSortIdx = 1; /* Index number */
  110727. int b; /* A boolean value */
  110728. LogEst rSize; /* number of rows in the table */
  110729. LogEst rLogSize; /* Logarithm of the number of rows in the table */
  110730. WhereClause *pWC; /* The parsed WHERE clause */
  110731. Table *pTab; /* Table being queried */
  110732. pNew = pBuilder->pNew;
  110733. pWInfo = pBuilder->pWInfo;
  110734. pTabList = pWInfo->pTabList;
  110735. pSrc = pTabList->a + pNew->iTab;
  110736. pTab = pSrc->pTab;
  110737. pWC = pBuilder->pWC;
  110738. assert( !IsVirtual(pSrc->pTab) );
  110739. if( pSrc->pIndex ){
  110740. /* An INDEXED BY clause specifies a particular index to use */
  110741. pProbe = pSrc->pIndex;
  110742. }else if( !HasRowid(pTab) ){
  110743. pProbe = pTab->pIndex;
  110744. }else{
  110745. /* There is no INDEXED BY clause. Create a fake Index object in local
  110746. ** variable sPk to represent the rowid primary key index. Make this
  110747. ** fake index the first in a chain of Index objects with all of the real
  110748. ** indices to follow */
  110749. Index *pFirst; /* First of real indices on the table */
  110750. memset(&sPk, 0, sizeof(Index));
  110751. sPk.nKeyCol = 1;
  110752. sPk.nColumn = 1;
  110753. sPk.aiColumn = &aiColumnPk;
  110754. sPk.aiRowLogEst = aiRowEstPk;
  110755. sPk.onError = OE_Replace;
  110756. sPk.pTable = pTab;
  110757. sPk.szIdxRow = pTab->szTabRow;
  110758. aiRowEstPk[0] = pTab->nRowLogEst;
  110759. aiRowEstPk[1] = 0;
  110760. pFirst = pSrc->pTab->pIndex;
  110761. if( pSrc->notIndexed==0 ){
  110762. /* The real indices of the table are only considered if the
  110763. ** NOT INDEXED qualifier is omitted from the FROM clause */
  110764. sPk.pNext = pFirst;
  110765. }
  110766. pProbe = &sPk;
  110767. }
  110768. rSize = pTab->nRowLogEst;
  110769. rLogSize = estLog(rSize);
  110770. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  110771. /* Automatic indexes */
  110772. if( !pBuilder->pOrSet
  110773. && (pWInfo->pParse->db->flags & SQLITE_AutoIndex)!=0
  110774. && pSrc->pIndex==0
  110775. && !pSrc->viaCoroutine
  110776. && !pSrc->notIndexed
  110777. && HasRowid(pTab)
  110778. && !pSrc->isCorrelated
  110779. && !pSrc->isRecursive
  110780. ){
  110781. /* Generate auto-index WhereLoops */
  110782. WhereTerm *pTerm;
  110783. WhereTerm *pWCEnd = pWC->a + pWC->nTerm;
  110784. for(pTerm=pWC->a; rc==SQLITE_OK && pTerm<pWCEnd; pTerm++){
  110785. if( pTerm->prereqRight & pNew->maskSelf ) continue;
  110786. if( termCanDriveIndex(pTerm, pSrc, 0) ){
  110787. pNew->u.btree.nEq = 1;
  110788. pNew->u.btree.nSkip = 0;
  110789. pNew->u.btree.pIndex = 0;
  110790. pNew->nLTerm = 1;
  110791. pNew->aLTerm[0] = pTerm;
  110792. /* TUNING: One-time cost for computing the automatic index is
  110793. ** estimated to be X*N*log2(N) where N is the number of rows in
  110794. ** the table being indexed and where X is 7 (LogEst=28) for normal
  110795. ** tables or 1.375 (LogEst=4) for views and subqueries. The value
  110796. ** of X is smaller for views and subqueries so that the query planner
  110797. ** will be more aggressive about generating automatic indexes for
  110798. ** those objects, since there is no opportunity to add schema
  110799. ** indexes on subqueries and views. */
  110800. pNew->rSetup = rLogSize + rSize + 4;
  110801. if( pTab->pSelect==0 && (pTab->tabFlags & TF_Ephemeral)==0 ){
  110802. pNew->rSetup += 24;
  110803. }
  110804. ApplyCostMultiplier(pNew->rSetup, pTab->costMult);
  110805. /* TUNING: Each index lookup yields 20 rows in the table. This
  110806. ** is more than the usual guess of 10 rows, since we have no way
  110807. ** of knowing how selective the index will ultimately be. It would
  110808. ** not be unreasonable to make this value much larger. */
  110809. pNew->nOut = 43; assert( 43==sqlite3LogEst(20) );
  110810. pNew->rRun = sqlite3LogEstAdd(rLogSize,pNew->nOut);
  110811. pNew->wsFlags = WHERE_AUTO_INDEX;
  110812. pNew->prereq = mExtra | pTerm->prereqRight;
  110813. rc = whereLoopInsert(pBuilder, pNew);
  110814. }
  110815. }
  110816. }
  110817. #endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
  110818. /* Loop over all indices
  110819. */
  110820. for(; rc==SQLITE_OK && pProbe; pProbe=pProbe->pNext, iSortIdx++){
  110821. if( pProbe->pPartIdxWhere!=0
  110822. && !whereUsablePartialIndex(pSrc->iCursor, pWC, pProbe->pPartIdxWhere) ){
  110823. testcase( pNew->iTab!=pSrc->iCursor ); /* See ticket [98d973b8f5] */
  110824. continue; /* Partial index inappropriate for this query */
  110825. }
  110826. rSize = pProbe->aiRowLogEst[0];
  110827. pNew->u.btree.nEq = 0;
  110828. pNew->u.btree.nSkip = 0;
  110829. pNew->nLTerm = 0;
  110830. pNew->iSortIdx = 0;
  110831. pNew->rSetup = 0;
  110832. pNew->prereq = mExtra;
  110833. pNew->nOut = rSize;
  110834. pNew->u.btree.pIndex = pProbe;
  110835. b = indexMightHelpWithOrderBy(pBuilder, pProbe, pSrc->iCursor);
  110836. /* The ONEPASS_DESIRED flags never occurs together with ORDER BY */
  110837. assert( (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || b==0 );
  110838. if( pProbe->tnum<=0 ){
  110839. /* Integer primary key index */
  110840. pNew->wsFlags = WHERE_IPK;
  110841. /* Full table scan */
  110842. pNew->iSortIdx = b ? iSortIdx : 0;
  110843. /* TUNING: Cost of full table scan is (N*3.0). */
  110844. pNew->rRun = rSize + 16;
  110845. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  110846. whereLoopOutputAdjust(pWC, pNew, rSize);
  110847. rc = whereLoopInsert(pBuilder, pNew);
  110848. pNew->nOut = rSize;
  110849. if( rc ) break;
  110850. }else{
  110851. Bitmask m;
  110852. if( pProbe->isCovering ){
  110853. pNew->wsFlags = WHERE_IDX_ONLY | WHERE_INDEXED;
  110854. m = 0;
  110855. }else{
  110856. m = pSrc->colUsed & ~columnsInIndex(pProbe);
  110857. pNew->wsFlags = (m==0) ? (WHERE_IDX_ONLY|WHERE_INDEXED) : WHERE_INDEXED;
  110858. }
  110859. /* Full scan via index */
  110860. if( b
  110861. || !HasRowid(pTab)
  110862. || ( m==0
  110863. && pProbe->bUnordered==0
  110864. && (pProbe->szIdxRow<pTab->szTabRow)
  110865. && (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0
  110866. && sqlite3GlobalConfig.bUseCis
  110867. && OptimizationEnabled(pWInfo->pParse->db, SQLITE_CoverIdxScan)
  110868. )
  110869. ){
  110870. pNew->iSortIdx = b ? iSortIdx : 0;
  110871. /* The cost of visiting the index rows is N*K, where K is
  110872. ** between 1.1 and 3.0, depending on the relative sizes of the
  110873. ** index and table rows. If this is a non-covering index scan,
  110874. ** also add the cost of visiting table rows (N*3.0). */
  110875. pNew->rRun = rSize + 1 + (15*pProbe->szIdxRow)/pTab->szTabRow;
  110876. if( m!=0 ){
  110877. pNew->rRun = sqlite3LogEstAdd(pNew->rRun, rSize+16);
  110878. }
  110879. ApplyCostMultiplier(pNew->rRun, pTab->costMult);
  110880. whereLoopOutputAdjust(pWC, pNew, rSize);
  110881. rc = whereLoopInsert(pBuilder, pNew);
  110882. pNew->nOut = rSize;
  110883. if( rc ) break;
  110884. }
  110885. }
  110886. rc = whereLoopAddBtreeIndex(pBuilder, pSrc, pProbe, 0);
  110887. #ifdef SQLITE_ENABLE_STAT3_OR_STAT4
  110888. sqlite3Stat4ProbeFree(pBuilder->pRec);
  110889. pBuilder->nRecValid = 0;
  110890. pBuilder->pRec = 0;
  110891. #endif
  110892. /* If there was an INDEXED BY clause, then only that one index is
  110893. ** considered. */
  110894. if( pSrc->pIndex ) break;
  110895. }
  110896. return rc;
  110897. }
  110898. #ifndef SQLITE_OMIT_VIRTUALTABLE
  110899. /*
  110900. ** Add all WhereLoop objects for a table of the join identified by
  110901. ** pBuilder->pNew->iTab. That table is guaranteed to be a virtual table.
  110902. */
  110903. static int whereLoopAddVirtual(
  110904. WhereLoopBuilder *pBuilder, /* WHERE clause information */
  110905. Bitmask mExtra
  110906. ){
  110907. WhereInfo *pWInfo; /* WHERE analysis context */
  110908. Parse *pParse; /* The parsing context */
  110909. WhereClause *pWC; /* The WHERE clause */
  110910. struct SrcList_item *pSrc; /* The FROM clause term to search */
  110911. Table *pTab;
  110912. sqlite3 *db;
  110913. sqlite3_index_info *pIdxInfo;
  110914. struct sqlite3_index_constraint *pIdxCons;
  110915. struct sqlite3_index_constraint_usage *pUsage;
  110916. WhereTerm *pTerm;
  110917. int i, j;
  110918. int iTerm, mxTerm;
  110919. int nConstraint;
  110920. int seenIn = 0; /* True if an IN operator is seen */
  110921. int seenVar = 0; /* True if a non-constant constraint is seen */
  110922. int iPhase; /* 0: const w/o IN, 1: const, 2: no IN, 2: IN */
  110923. WhereLoop *pNew;
  110924. int rc = SQLITE_OK;
  110925. pWInfo = pBuilder->pWInfo;
  110926. pParse = pWInfo->pParse;
  110927. db = pParse->db;
  110928. pWC = pBuilder->pWC;
  110929. pNew = pBuilder->pNew;
  110930. pSrc = &pWInfo->pTabList->a[pNew->iTab];
  110931. pTab = pSrc->pTab;
  110932. assert( IsVirtual(pTab) );
  110933. pIdxInfo = allocateIndexInfo(pParse, pWC, pSrc, pBuilder->pOrderBy);
  110934. if( pIdxInfo==0 ) return SQLITE_NOMEM;
  110935. pNew->prereq = 0;
  110936. pNew->rSetup = 0;
  110937. pNew->wsFlags = WHERE_VIRTUALTABLE;
  110938. pNew->nLTerm = 0;
  110939. pNew->u.vtab.needFree = 0;
  110940. pUsage = pIdxInfo->aConstraintUsage;
  110941. nConstraint = pIdxInfo->nConstraint;
  110942. if( whereLoopResize(db, pNew, nConstraint) ){
  110943. sqlite3DbFree(db, pIdxInfo);
  110944. return SQLITE_NOMEM;
  110945. }
  110946. for(iPhase=0; iPhase<=3; iPhase++){
  110947. if( !seenIn && (iPhase&1)!=0 ){
  110948. iPhase++;
  110949. if( iPhase>3 ) break;
  110950. }
  110951. if( !seenVar && iPhase>1 ) break;
  110952. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  110953. for(i=0; i<pIdxInfo->nConstraint; i++, pIdxCons++){
  110954. j = pIdxCons->iTermOffset;
  110955. pTerm = &pWC->a[j];
  110956. switch( iPhase ){
  110957. case 0: /* Constants without IN operator */
  110958. pIdxCons->usable = 0;
  110959. if( (pTerm->eOperator & WO_IN)!=0 ){
  110960. seenIn = 1;
  110961. }
  110962. if( pTerm->prereqRight!=0 ){
  110963. seenVar = 1;
  110964. }else if( (pTerm->eOperator & WO_IN)==0 ){
  110965. pIdxCons->usable = 1;
  110966. }
  110967. break;
  110968. case 1: /* Constants with IN operators */
  110969. assert( seenIn );
  110970. pIdxCons->usable = (pTerm->prereqRight==0);
  110971. break;
  110972. case 2: /* Variables without IN */
  110973. assert( seenVar );
  110974. pIdxCons->usable = (pTerm->eOperator & WO_IN)==0;
  110975. break;
  110976. default: /* Variables with IN */
  110977. assert( seenVar && seenIn );
  110978. pIdxCons->usable = 1;
  110979. break;
  110980. }
  110981. }
  110982. memset(pUsage, 0, sizeof(pUsage[0])*pIdxInfo->nConstraint);
  110983. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  110984. pIdxInfo->idxStr = 0;
  110985. pIdxInfo->idxNum = 0;
  110986. pIdxInfo->needToFreeIdxStr = 0;
  110987. pIdxInfo->orderByConsumed = 0;
  110988. pIdxInfo->estimatedCost = SQLITE_BIG_DBL / (double)2;
  110989. pIdxInfo->estimatedRows = 25;
  110990. rc = vtabBestIndex(pParse, pTab, pIdxInfo);
  110991. if( rc ) goto whereLoopAddVtab_exit;
  110992. pIdxCons = *(struct sqlite3_index_constraint**)&pIdxInfo->aConstraint;
  110993. pNew->prereq = mExtra;
  110994. mxTerm = -1;
  110995. assert( pNew->nLSlot>=nConstraint );
  110996. for(i=0; i<nConstraint; i++) pNew->aLTerm[i] = 0;
  110997. pNew->u.vtab.omitMask = 0;
  110998. for(i=0; i<nConstraint; i++, pIdxCons++){
  110999. if( (iTerm = pUsage[i].argvIndex - 1)>=0 ){
  111000. j = pIdxCons->iTermOffset;
  111001. if( iTerm>=nConstraint
  111002. || j<0
  111003. || j>=pWC->nTerm
  111004. || pNew->aLTerm[iTerm]!=0
  111005. ){
  111006. rc = SQLITE_ERROR;
  111007. sqlite3ErrorMsg(pParse, "%s.xBestIndex() malfunction", pTab->zName);
  111008. goto whereLoopAddVtab_exit;
  111009. }
  111010. testcase( iTerm==nConstraint-1 );
  111011. testcase( j==0 );
  111012. testcase( j==pWC->nTerm-1 );
  111013. pTerm = &pWC->a[j];
  111014. pNew->prereq |= pTerm->prereqRight;
  111015. assert( iTerm<pNew->nLSlot );
  111016. pNew->aLTerm[iTerm] = pTerm;
  111017. if( iTerm>mxTerm ) mxTerm = iTerm;
  111018. testcase( iTerm==15 );
  111019. testcase( iTerm==16 );
  111020. if( iTerm<16 && pUsage[i].omit ) pNew->u.vtab.omitMask |= 1<<iTerm;
  111021. if( (pTerm->eOperator & WO_IN)!=0 ){
  111022. if( pUsage[i].omit==0 ){
  111023. /* Do not attempt to use an IN constraint if the virtual table
  111024. ** says that the equivalent EQ constraint cannot be safely omitted.
  111025. ** If we do attempt to use such a constraint, some rows might be
  111026. ** repeated in the output. */
  111027. break;
  111028. }
  111029. /* A virtual table that is constrained by an IN clause may not
  111030. ** consume the ORDER BY clause because (1) the order of IN terms
  111031. ** is not necessarily related to the order of output terms and
  111032. ** (2) Multiple outputs from a single IN value will not merge
  111033. ** together. */
  111034. pIdxInfo->orderByConsumed = 0;
  111035. }
  111036. }
  111037. }
  111038. if( i>=nConstraint ){
  111039. pNew->nLTerm = mxTerm+1;
  111040. assert( pNew->nLTerm<=pNew->nLSlot );
  111041. pNew->u.vtab.idxNum = pIdxInfo->idxNum;
  111042. pNew->u.vtab.needFree = pIdxInfo->needToFreeIdxStr;
  111043. pIdxInfo->needToFreeIdxStr = 0;
  111044. pNew->u.vtab.idxStr = pIdxInfo->idxStr;
  111045. pNew->u.vtab.isOrdered = (i8)(pIdxInfo->orderByConsumed ?
  111046. pIdxInfo->nOrderBy : 0);
  111047. pNew->rSetup = 0;
  111048. pNew->rRun = sqlite3LogEstFromDouble(pIdxInfo->estimatedCost);
  111049. pNew->nOut = sqlite3LogEst(pIdxInfo->estimatedRows);
  111050. whereLoopInsert(pBuilder, pNew);
  111051. if( pNew->u.vtab.needFree ){
  111052. sqlite3_free(pNew->u.vtab.idxStr);
  111053. pNew->u.vtab.needFree = 0;
  111054. }
  111055. }
  111056. }
  111057. whereLoopAddVtab_exit:
  111058. if( pIdxInfo->needToFreeIdxStr ) sqlite3_free(pIdxInfo->idxStr);
  111059. sqlite3DbFree(db, pIdxInfo);
  111060. return rc;
  111061. }
  111062. #endif /* SQLITE_OMIT_VIRTUALTABLE */
  111063. /*
  111064. ** Add WhereLoop entries to handle OR terms. This works for either
  111065. ** btrees or virtual tables.
  111066. */
  111067. static int whereLoopAddOr(WhereLoopBuilder *pBuilder, Bitmask mExtra){
  111068. WhereInfo *pWInfo = pBuilder->pWInfo;
  111069. WhereClause *pWC;
  111070. WhereLoop *pNew;
  111071. WhereTerm *pTerm, *pWCEnd;
  111072. int rc = SQLITE_OK;
  111073. int iCur;
  111074. WhereClause tempWC;
  111075. WhereLoopBuilder sSubBuild;
  111076. WhereOrSet sSum, sCur;
  111077. struct SrcList_item *pItem;
  111078. pWC = pBuilder->pWC;
  111079. pWCEnd = pWC->a + pWC->nTerm;
  111080. pNew = pBuilder->pNew;
  111081. memset(&sSum, 0, sizeof(sSum));
  111082. pItem = pWInfo->pTabList->a + pNew->iTab;
  111083. iCur = pItem->iCursor;
  111084. for(pTerm=pWC->a; pTerm<pWCEnd && rc==SQLITE_OK; pTerm++){
  111085. if( (pTerm->eOperator & WO_OR)!=0
  111086. && (pTerm->u.pOrInfo->indexable & pNew->maskSelf)!=0
  111087. ){
  111088. WhereClause * const pOrWC = &pTerm->u.pOrInfo->wc;
  111089. WhereTerm * const pOrWCEnd = &pOrWC->a[pOrWC->nTerm];
  111090. WhereTerm *pOrTerm;
  111091. int once = 1;
  111092. int i, j;
  111093. sSubBuild = *pBuilder;
  111094. sSubBuild.pOrderBy = 0;
  111095. sSubBuild.pOrSet = &sCur;
  111096. WHERETRACE(0x200, ("Begin processing OR-clause %p\n", pTerm));
  111097. for(pOrTerm=pOrWC->a; pOrTerm<pOrWCEnd; pOrTerm++){
  111098. if( (pOrTerm->eOperator & WO_AND)!=0 ){
  111099. sSubBuild.pWC = &pOrTerm->u.pAndInfo->wc;
  111100. }else if( pOrTerm->leftCursor==iCur ){
  111101. tempWC.pWInfo = pWC->pWInfo;
  111102. tempWC.pOuter = pWC;
  111103. tempWC.op = TK_AND;
  111104. tempWC.nTerm = 1;
  111105. tempWC.a = pOrTerm;
  111106. sSubBuild.pWC = &tempWC;
  111107. }else{
  111108. continue;
  111109. }
  111110. sCur.n = 0;
  111111. #ifdef WHERETRACE_ENABLED
  111112. WHERETRACE(0x200, ("OR-term %d of %p has %d subterms:\n",
  111113. (int)(pOrTerm-pOrWC->a), pTerm, sSubBuild.pWC->nTerm));
  111114. if( sqlite3WhereTrace & 0x400 ){
  111115. for(i=0; i<sSubBuild.pWC->nTerm; i++){
  111116. whereTermPrint(&sSubBuild.pWC->a[i], i);
  111117. }
  111118. }
  111119. #endif
  111120. #ifndef SQLITE_OMIT_VIRTUALTABLE
  111121. if( IsVirtual(pItem->pTab) ){
  111122. rc = whereLoopAddVirtual(&sSubBuild, mExtra);
  111123. }else
  111124. #endif
  111125. {
  111126. rc = whereLoopAddBtree(&sSubBuild, mExtra);
  111127. }
  111128. if( rc==SQLITE_OK ){
  111129. rc = whereLoopAddOr(&sSubBuild, mExtra);
  111130. }
  111131. assert( rc==SQLITE_OK || sCur.n==0 );
  111132. if( sCur.n==0 ){
  111133. sSum.n = 0;
  111134. break;
  111135. }else if( once ){
  111136. whereOrMove(&sSum, &sCur);
  111137. once = 0;
  111138. }else{
  111139. WhereOrSet sPrev;
  111140. whereOrMove(&sPrev, &sSum);
  111141. sSum.n = 0;
  111142. for(i=0; i<sPrev.n; i++){
  111143. for(j=0; j<sCur.n; j++){
  111144. whereOrInsert(&sSum, sPrev.a[i].prereq | sCur.a[j].prereq,
  111145. sqlite3LogEstAdd(sPrev.a[i].rRun, sCur.a[j].rRun),
  111146. sqlite3LogEstAdd(sPrev.a[i].nOut, sCur.a[j].nOut));
  111147. }
  111148. }
  111149. }
  111150. }
  111151. pNew->nLTerm = 1;
  111152. pNew->aLTerm[0] = pTerm;
  111153. pNew->wsFlags = WHERE_MULTI_OR;
  111154. pNew->rSetup = 0;
  111155. pNew->iSortIdx = 0;
  111156. memset(&pNew->u, 0, sizeof(pNew->u));
  111157. for(i=0; rc==SQLITE_OK && i<sSum.n; i++){
  111158. /* TUNING: Currently sSum.a[i].rRun is set to the sum of the costs
  111159. ** of all sub-scans required by the OR-scan. However, due to rounding
  111160. ** errors, it may be that the cost of the OR-scan is equal to its
  111161. ** most expensive sub-scan. Add the smallest possible penalty
  111162. ** (equivalent to multiplying the cost by 1.07) to ensure that
  111163. ** this does not happen. Otherwise, for WHERE clauses such as the
  111164. ** following where there is an index on "y":
  111165. **
  111166. ** WHERE likelihood(x=?, 0.99) OR y=?
  111167. **
  111168. ** the planner may elect to "OR" together a full-table scan and an
  111169. ** index lookup. And other similarly odd results. */
  111170. pNew->rRun = sSum.a[i].rRun + 1;
  111171. pNew->nOut = sSum.a[i].nOut;
  111172. pNew->prereq = sSum.a[i].prereq;
  111173. rc = whereLoopInsert(pBuilder, pNew);
  111174. }
  111175. WHERETRACE(0x200, ("End processing OR-clause %p\n", pTerm));
  111176. }
  111177. }
  111178. return rc;
  111179. }
  111180. /*
  111181. ** Add all WhereLoop objects for all tables
  111182. */
  111183. static int whereLoopAddAll(WhereLoopBuilder *pBuilder){
  111184. WhereInfo *pWInfo = pBuilder->pWInfo;
  111185. Bitmask mExtra = 0;
  111186. Bitmask mPrior = 0;
  111187. int iTab;
  111188. SrcList *pTabList = pWInfo->pTabList;
  111189. struct SrcList_item *pItem;
  111190. sqlite3 *db = pWInfo->pParse->db;
  111191. int nTabList = pWInfo->nLevel;
  111192. int rc = SQLITE_OK;
  111193. u8 priorJoinType = 0;
  111194. WhereLoop *pNew;
  111195. /* Loop over the tables in the join, from left to right */
  111196. pNew = pBuilder->pNew;
  111197. whereLoopInit(pNew);
  111198. for(iTab=0, pItem=pTabList->a; iTab<nTabList; iTab++, pItem++){
  111199. pNew->iTab = iTab;
  111200. pNew->maskSelf = getMask(&pWInfo->sMaskSet, pItem->iCursor);
  111201. if( ((pItem->jointype|priorJoinType) & (JT_LEFT|JT_CROSS))!=0 ){
  111202. mExtra = mPrior;
  111203. }
  111204. priorJoinType = pItem->jointype;
  111205. if( IsVirtual(pItem->pTab) ){
  111206. rc = whereLoopAddVirtual(pBuilder, mExtra);
  111207. }else{
  111208. rc = whereLoopAddBtree(pBuilder, mExtra);
  111209. }
  111210. if( rc==SQLITE_OK ){
  111211. rc = whereLoopAddOr(pBuilder, mExtra);
  111212. }
  111213. mPrior |= pNew->maskSelf;
  111214. if( rc || db->mallocFailed ) break;
  111215. }
  111216. whereLoopClear(db, pNew);
  111217. return rc;
  111218. }
  111219. /*
  111220. ** Examine a WherePath (with the addition of the extra WhereLoop of the 5th
  111221. ** parameters) to see if it outputs rows in the requested ORDER BY
  111222. ** (or GROUP BY) without requiring a separate sort operation. Return N:
  111223. **
  111224. ** N>0: N terms of the ORDER BY clause are satisfied
  111225. ** N==0: No terms of the ORDER BY clause are satisfied
  111226. ** N<0: Unknown yet how many terms of ORDER BY might be satisfied.
  111227. **
  111228. ** Note that processing for WHERE_GROUPBY and WHERE_DISTINCTBY is not as
  111229. ** strict. With GROUP BY and DISTINCT the only requirement is that
  111230. ** equivalent rows appear immediately adjacent to one another. GROUP BY
  111231. ** and DISTINCT do not require rows to appear in any particular order as long
  111232. ** as equivalent rows are grouped together. Thus for GROUP BY and DISTINCT
  111233. ** the pOrderBy terms can be matched in any order. With ORDER BY, the
  111234. ** pOrderBy terms must be matched in strict left-to-right order.
  111235. */
  111236. static i8 wherePathSatisfiesOrderBy(
  111237. WhereInfo *pWInfo, /* The WHERE clause */
  111238. ExprList *pOrderBy, /* ORDER BY or GROUP BY or DISTINCT clause to check */
  111239. WherePath *pPath, /* The WherePath to check */
  111240. u16 wctrlFlags, /* Might contain WHERE_GROUPBY or WHERE_DISTINCTBY */
  111241. u16 nLoop, /* Number of entries in pPath->aLoop[] */
  111242. WhereLoop *pLast, /* Add this WhereLoop to the end of pPath->aLoop[] */
  111243. Bitmask *pRevMask /* OUT: Mask of WhereLoops to run in reverse order */
  111244. ){
  111245. u8 revSet; /* True if rev is known */
  111246. u8 rev; /* Composite sort order */
  111247. u8 revIdx; /* Index sort order */
  111248. u8 isOrderDistinct; /* All prior WhereLoops are order-distinct */
  111249. u8 distinctColumns; /* True if the loop has UNIQUE NOT NULL columns */
  111250. u8 isMatch; /* iColumn matches a term of the ORDER BY clause */
  111251. u16 nKeyCol; /* Number of key columns in pIndex */
  111252. u16 nColumn; /* Total number of ordered columns in the index */
  111253. u16 nOrderBy; /* Number terms in the ORDER BY clause */
  111254. int iLoop; /* Index of WhereLoop in pPath being processed */
  111255. int i, j; /* Loop counters */
  111256. int iCur; /* Cursor number for current WhereLoop */
  111257. int iColumn; /* A column number within table iCur */
  111258. WhereLoop *pLoop = 0; /* Current WhereLoop being processed. */
  111259. WhereTerm *pTerm; /* A single term of the WHERE clause */
  111260. Expr *pOBExpr; /* An expression from the ORDER BY clause */
  111261. CollSeq *pColl; /* COLLATE function from an ORDER BY clause term */
  111262. Index *pIndex; /* The index associated with pLoop */
  111263. sqlite3 *db = pWInfo->pParse->db; /* Database connection */
  111264. Bitmask obSat = 0; /* Mask of ORDER BY terms satisfied so far */
  111265. Bitmask obDone; /* Mask of all ORDER BY terms */
  111266. Bitmask orderDistinctMask; /* Mask of all well-ordered loops */
  111267. Bitmask ready; /* Mask of inner loops */
  111268. /*
  111269. ** We say the WhereLoop is "one-row" if it generates no more than one
  111270. ** row of output. A WhereLoop is one-row if all of the following are true:
  111271. ** (a) All index columns match with WHERE_COLUMN_EQ.
  111272. ** (b) The index is unique
  111273. ** Any WhereLoop with an WHERE_COLUMN_EQ constraint on the rowid is one-row.
  111274. ** Every one-row WhereLoop will have the WHERE_ONEROW bit set in wsFlags.
  111275. **
  111276. ** We say the WhereLoop is "order-distinct" if the set of columns from
  111277. ** that WhereLoop that are in the ORDER BY clause are different for every
  111278. ** row of the WhereLoop. Every one-row WhereLoop is automatically
  111279. ** order-distinct. A WhereLoop that has no columns in the ORDER BY clause
  111280. ** is not order-distinct. To be order-distinct is not quite the same as being
  111281. ** UNIQUE since a UNIQUE column or index can have multiple rows that
  111282. ** are NULL and NULL values are equivalent for the purpose of order-distinct.
  111283. ** To be order-distinct, the columns must be UNIQUE and NOT NULL.
  111284. **
  111285. ** The rowid for a table is always UNIQUE and NOT NULL so whenever the
  111286. ** rowid appears in the ORDER BY clause, the corresponding WhereLoop is
  111287. ** automatically order-distinct.
  111288. */
  111289. assert( pOrderBy!=0 );
  111290. if( nLoop && OptimizationDisabled(db, SQLITE_OrderByIdxJoin) ) return 0;
  111291. nOrderBy = pOrderBy->nExpr;
  111292. testcase( nOrderBy==BMS-1 );
  111293. if( nOrderBy>BMS-1 ) return 0; /* Cannot optimize overly large ORDER BYs */
  111294. isOrderDistinct = 1;
  111295. obDone = MASKBIT(nOrderBy)-1;
  111296. orderDistinctMask = 0;
  111297. ready = 0;
  111298. for(iLoop=0; isOrderDistinct && obSat<obDone && iLoop<=nLoop; iLoop++){
  111299. if( iLoop>0 ) ready |= pLoop->maskSelf;
  111300. pLoop = iLoop<nLoop ? pPath->aLoop[iLoop] : pLast;
  111301. if( pLoop->wsFlags & WHERE_VIRTUALTABLE ){
  111302. if( pLoop->u.vtab.isOrdered ) obSat = obDone;
  111303. break;
  111304. }
  111305. iCur = pWInfo->pTabList->a[pLoop->iTab].iCursor;
  111306. /* Mark off any ORDER BY term X that is a column in the table of
  111307. ** the current loop for which there is term in the WHERE
  111308. ** clause of the form X IS NULL or X=? that reference only outer
  111309. ** loops.
  111310. */
  111311. for(i=0; i<nOrderBy; i++){
  111312. if( MASKBIT(i) & obSat ) continue;
  111313. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  111314. if( pOBExpr->op!=TK_COLUMN ) continue;
  111315. if( pOBExpr->iTable!=iCur ) continue;
  111316. pTerm = findTerm(&pWInfo->sWC, iCur, pOBExpr->iColumn,
  111317. ~ready, WO_EQ|WO_ISNULL, 0);
  111318. if( pTerm==0 ) continue;
  111319. if( (pTerm->eOperator&WO_EQ)!=0 && pOBExpr->iColumn>=0 ){
  111320. const char *z1, *z2;
  111321. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  111322. if( !pColl ) pColl = db->pDfltColl;
  111323. z1 = pColl->zName;
  111324. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pTerm->pExpr);
  111325. if( !pColl ) pColl = db->pDfltColl;
  111326. z2 = pColl->zName;
  111327. if( sqlite3StrICmp(z1, z2)!=0 ) continue;
  111328. }
  111329. obSat |= MASKBIT(i);
  111330. }
  111331. if( (pLoop->wsFlags & WHERE_ONEROW)==0 ){
  111332. if( pLoop->wsFlags & WHERE_IPK ){
  111333. pIndex = 0;
  111334. nKeyCol = 0;
  111335. nColumn = 1;
  111336. }else if( (pIndex = pLoop->u.btree.pIndex)==0 || pIndex->bUnordered ){
  111337. return 0;
  111338. }else{
  111339. nKeyCol = pIndex->nKeyCol;
  111340. nColumn = pIndex->nColumn;
  111341. assert( nColumn==nKeyCol+1 || !HasRowid(pIndex->pTable) );
  111342. assert( pIndex->aiColumn[nColumn-1]==(-1) || !HasRowid(pIndex->pTable));
  111343. isOrderDistinct = IsUniqueIndex(pIndex);
  111344. }
  111345. /* Loop through all columns of the index and deal with the ones
  111346. ** that are not constrained by == or IN.
  111347. */
  111348. rev = revSet = 0;
  111349. distinctColumns = 0;
  111350. for(j=0; j<nColumn; j++){
  111351. u8 bOnce; /* True to run the ORDER BY search loop */
  111352. /* Skip over == and IS NULL terms */
  111353. if( j<pLoop->u.btree.nEq
  111354. && pLoop->u.btree.nSkip==0
  111355. && ((i = pLoop->aLTerm[j]->eOperator) & (WO_EQ|WO_ISNULL))!=0
  111356. ){
  111357. if( i & WO_ISNULL ){
  111358. testcase( isOrderDistinct );
  111359. isOrderDistinct = 0;
  111360. }
  111361. continue;
  111362. }
  111363. /* Get the column number in the table (iColumn) and sort order
  111364. ** (revIdx) for the j-th column of the index.
  111365. */
  111366. if( pIndex ){
  111367. iColumn = pIndex->aiColumn[j];
  111368. revIdx = pIndex->aSortOrder[j];
  111369. if( iColumn==pIndex->pTable->iPKey ) iColumn = -1;
  111370. }else{
  111371. iColumn = -1;
  111372. revIdx = 0;
  111373. }
  111374. /* An unconstrained column that might be NULL means that this
  111375. ** WhereLoop is not well-ordered
  111376. */
  111377. if( isOrderDistinct
  111378. && iColumn>=0
  111379. && j>=pLoop->u.btree.nEq
  111380. && pIndex->pTable->aCol[iColumn].notNull==0
  111381. ){
  111382. isOrderDistinct = 0;
  111383. }
  111384. /* Find the ORDER BY term that corresponds to the j-th column
  111385. ** of the index and mark that ORDER BY term off
  111386. */
  111387. bOnce = 1;
  111388. isMatch = 0;
  111389. for(i=0; bOnce && i<nOrderBy; i++){
  111390. if( MASKBIT(i) & obSat ) continue;
  111391. pOBExpr = sqlite3ExprSkipCollate(pOrderBy->a[i].pExpr);
  111392. testcase( wctrlFlags & WHERE_GROUPBY );
  111393. testcase( wctrlFlags & WHERE_DISTINCTBY );
  111394. if( (wctrlFlags & (WHERE_GROUPBY|WHERE_DISTINCTBY))==0 ) bOnce = 0;
  111395. if( pOBExpr->op!=TK_COLUMN ) continue;
  111396. if( pOBExpr->iTable!=iCur ) continue;
  111397. if( pOBExpr->iColumn!=iColumn ) continue;
  111398. if( iColumn>=0 ){
  111399. pColl = sqlite3ExprCollSeq(pWInfo->pParse, pOrderBy->a[i].pExpr);
  111400. if( !pColl ) pColl = db->pDfltColl;
  111401. if( sqlite3StrICmp(pColl->zName, pIndex->azColl[j])!=0 ) continue;
  111402. }
  111403. isMatch = 1;
  111404. break;
  111405. }
  111406. if( isMatch && (wctrlFlags & WHERE_GROUPBY)==0 ){
  111407. /* Make sure the sort order is compatible in an ORDER BY clause.
  111408. ** Sort order is irrelevant for a GROUP BY clause. */
  111409. if( revSet ){
  111410. if( (rev ^ revIdx)!=pOrderBy->a[i].sortOrder ) isMatch = 0;
  111411. }else{
  111412. rev = revIdx ^ pOrderBy->a[i].sortOrder;
  111413. if( rev ) *pRevMask |= MASKBIT(iLoop);
  111414. revSet = 1;
  111415. }
  111416. }
  111417. if( isMatch ){
  111418. if( iColumn<0 ){
  111419. testcase( distinctColumns==0 );
  111420. distinctColumns = 1;
  111421. }
  111422. obSat |= MASKBIT(i);
  111423. }else{
  111424. /* No match found */
  111425. if( j==0 || j<nKeyCol ){
  111426. testcase( isOrderDistinct!=0 );
  111427. isOrderDistinct = 0;
  111428. }
  111429. break;
  111430. }
  111431. } /* end Loop over all index columns */
  111432. if( distinctColumns ){
  111433. testcase( isOrderDistinct==0 );
  111434. isOrderDistinct = 1;
  111435. }
  111436. } /* end-if not one-row */
  111437. /* Mark off any other ORDER BY terms that reference pLoop */
  111438. if( isOrderDistinct ){
  111439. orderDistinctMask |= pLoop->maskSelf;
  111440. for(i=0; i<nOrderBy; i++){
  111441. Expr *p;
  111442. Bitmask mTerm;
  111443. if( MASKBIT(i) & obSat ) continue;
  111444. p = pOrderBy->a[i].pExpr;
  111445. mTerm = exprTableUsage(&pWInfo->sMaskSet,p);
  111446. if( mTerm==0 && !sqlite3ExprIsConstant(p) ) continue;
  111447. if( (mTerm&~orderDistinctMask)==0 ){
  111448. obSat |= MASKBIT(i);
  111449. }
  111450. }
  111451. }
  111452. } /* End the loop over all WhereLoops from outer-most down to inner-most */
  111453. if( obSat==obDone ) return (i8)nOrderBy;
  111454. if( !isOrderDistinct ){
  111455. for(i=nOrderBy-1; i>0; i--){
  111456. Bitmask m = MASKBIT(i) - 1;
  111457. if( (obSat&m)==m ) return i;
  111458. }
  111459. return 0;
  111460. }
  111461. return -1;
  111462. }
  111463. /*
  111464. ** If the WHERE_GROUPBY flag is set in the mask passed to sqlite3WhereBegin(),
  111465. ** the planner assumes that the specified pOrderBy list is actually a GROUP
  111466. ** BY clause - and so any order that groups rows as required satisfies the
  111467. ** request.
  111468. **
  111469. ** Normally, in this case it is not possible for the caller to determine
  111470. ** whether or not the rows are really being delivered in sorted order, or
  111471. ** just in some other order that provides the required grouping. However,
  111472. ** if the WHERE_SORTBYGROUP flag is also passed to sqlite3WhereBegin(), then
  111473. ** this function may be called on the returned WhereInfo object. It returns
  111474. ** true if the rows really will be sorted in the specified order, or false
  111475. ** otherwise.
  111476. **
  111477. ** For example, assuming:
  111478. **
  111479. ** CREATE INDEX i1 ON t1(x, Y);
  111480. **
  111481. ** then
  111482. **
  111483. ** SELECT * FROM t1 GROUP BY x,y ORDER BY x,y; -- IsSorted()==1
  111484. ** SELECT * FROM t1 GROUP BY y,x ORDER BY y,x; -- IsSorted()==0
  111485. */
  111486. SQLITE_PRIVATE int sqlite3WhereIsSorted(WhereInfo *pWInfo){
  111487. assert( pWInfo->wctrlFlags & WHERE_GROUPBY );
  111488. assert( pWInfo->wctrlFlags & WHERE_SORTBYGROUP );
  111489. return pWInfo->sorted;
  111490. }
  111491. #ifdef WHERETRACE_ENABLED
  111492. /* For debugging use only: */
  111493. static const char *wherePathName(WherePath *pPath, int nLoop, WhereLoop *pLast){
  111494. static char zName[65];
  111495. int i;
  111496. for(i=0; i<nLoop; i++){ zName[i] = pPath->aLoop[i]->cId; }
  111497. if( pLast ) zName[i++] = pLast->cId;
  111498. zName[i] = 0;
  111499. return zName;
  111500. }
  111501. #endif
  111502. /*
  111503. ** Return the cost of sorting nRow rows, assuming that the keys have
  111504. ** nOrderby columns and that the first nSorted columns are already in
  111505. ** order.
  111506. */
  111507. static LogEst whereSortingCost(
  111508. WhereInfo *pWInfo,
  111509. LogEst nRow,
  111510. int nOrderBy,
  111511. int nSorted
  111512. ){
  111513. /* TUNING: Estimated cost of a full external sort, where N is
  111514. ** the number of rows to sort is:
  111515. **
  111516. ** cost = (3.0 * N * log(N)).
  111517. **
  111518. ** Or, if the order-by clause has X terms but only the last Y
  111519. ** terms are out of order, then block-sorting will reduce the
  111520. ** sorting cost to:
  111521. **
  111522. ** cost = (3.0 * N * log(N)) * (Y/X)
  111523. **
  111524. ** The (Y/X) term is implemented using stack variable rScale
  111525. ** below. */
  111526. LogEst rScale, rSortCost;
  111527. assert( nOrderBy>0 && 66==sqlite3LogEst(100) );
  111528. rScale = sqlite3LogEst((nOrderBy-nSorted)*100/nOrderBy) - 66;
  111529. rSortCost = nRow + estLog(nRow) + rScale + 16;
  111530. /* TUNING: The cost of implementing DISTINCT using a B-TREE is
  111531. ** similar but with a larger constant of proportionality.
  111532. ** Multiply by an additional factor of 3.0. */
  111533. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  111534. rSortCost += 16;
  111535. }
  111536. return rSortCost;
  111537. }
  111538. /*
  111539. ** Given the list of WhereLoop objects at pWInfo->pLoops, this routine
  111540. ** attempts to find the lowest cost path that visits each WhereLoop
  111541. ** once. This path is then loaded into the pWInfo->a[].pWLoop fields.
  111542. **
  111543. ** Assume that the total number of output rows that will need to be sorted
  111544. ** will be nRowEst (in the 10*log2 representation). Or, ignore sorting
  111545. ** costs if nRowEst==0.
  111546. **
  111547. ** Return SQLITE_OK on success or SQLITE_NOMEM of a memory allocation
  111548. ** error occurs.
  111549. */
  111550. static int wherePathSolver(WhereInfo *pWInfo, LogEst nRowEst){
  111551. int mxChoice; /* Maximum number of simultaneous paths tracked */
  111552. int nLoop; /* Number of terms in the join */
  111553. Parse *pParse; /* Parsing context */
  111554. sqlite3 *db; /* The database connection */
  111555. int iLoop; /* Loop counter over the terms of the join */
  111556. int ii, jj; /* Loop counters */
  111557. int mxI = 0; /* Index of next entry to replace */
  111558. int nOrderBy; /* Number of ORDER BY clause terms */
  111559. LogEst mxCost = 0; /* Maximum cost of a set of paths */
  111560. LogEst mxUnsorted = 0; /* Maximum unsorted cost of a set of path */
  111561. int nTo, nFrom; /* Number of valid entries in aTo[] and aFrom[] */
  111562. WherePath *aFrom; /* All nFrom paths at the previous level */
  111563. WherePath *aTo; /* The nTo best paths at the current level */
  111564. WherePath *pFrom; /* An element of aFrom[] that we are working on */
  111565. WherePath *pTo; /* An element of aTo[] that we are working on */
  111566. WhereLoop *pWLoop; /* One of the WhereLoop objects */
  111567. WhereLoop **pX; /* Used to divy up the pSpace memory */
  111568. LogEst *aSortCost = 0; /* Sorting and partial sorting costs */
  111569. char *pSpace; /* Temporary memory used by this routine */
  111570. int nSpace; /* Bytes of space allocated at pSpace */
  111571. pParse = pWInfo->pParse;
  111572. db = pParse->db;
  111573. nLoop = pWInfo->nLevel;
  111574. /* TUNING: For simple queries, only the best path is tracked.
  111575. ** For 2-way joins, the 5 best paths are followed.
  111576. ** For joins of 3 or more tables, track the 10 best paths */
  111577. mxChoice = (nLoop<=1) ? 1 : (nLoop==2 ? 5 : 10);
  111578. assert( nLoop<=pWInfo->pTabList->nSrc );
  111579. WHERETRACE(0x002, ("---- begin solver. (nRowEst=%d)\n", nRowEst));
  111580. /* If nRowEst is zero and there is an ORDER BY clause, ignore it. In this
  111581. ** case the purpose of this call is to estimate the number of rows returned
  111582. ** by the overall query. Once this estimate has been obtained, the caller
  111583. ** will invoke this function a second time, passing the estimate as the
  111584. ** nRowEst parameter. */
  111585. if( pWInfo->pOrderBy==0 || nRowEst==0 ){
  111586. nOrderBy = 0;
  111587. }else{
  111588. nOrderBy = pWInfo->pOrderBy->nExpr;
  111589. }
  111590. /* Allocate and initialize space for aTo, aFrom and aSortCost[] */
  111591. nSpace = (sizeof(WherePath)+sizeof(WhereLoop*)*nLoop)*mxChoice*2;
  111592. nSpace += sizeof(LogEst) * nOrderBy;
  111593. pSpace = sqlite3DbMallocRaw(db, nSpace);
  111594. if( pSpace==0 ) return SQLITE_NOMEM;
  111595. aTo = (WherePath*)pSpace;
  111596. aFrom = aTo+mxChoice;
  111597. memset(aFrom, 0, sizeof(aFrom[0]));
  111598. pX = (WhereLoop**)(aFrom+mxChoice);
  111599. for(ii=mxChoice*2, pFrom=aTo; ii>0; ii--, pFrom++, pX += nLoop){
  111600. pFrom->aLoop = pX;
  111601. }
  111602. if( nOrderBy ){
  111603. /* If there is an ORDER BY clause and it is not being ignored, set up
  111604. ** space for the aSortCost[] array. Each element of the aSortCost array
  111605. ** is either zero - meaning it has not yet been initialized - or the
  111606. ** cost of sorting nRowEst rows of data where the first X terms of
  111607. ** the ORDER BY clause are already in order, where X is the array
  111608. ** index. */
  111609. aSortCost = (LogEst*)pX;
  111610. memset(aSortCost, 0, sizeof(LogEst) * nOrderBy);
  111611. }
  111612. assert( aSortCost==0 || &pSpace[nSpace]==(char*)&aSortCost[nOrderBy] );
  111613. assert( aSortCost!=0 || &pSpace[nSpace]==(char*)pX );
  111614. /* Seed the search with a single WherePath containing zero WhereLoops.
  111615. **
  111616. ** TUNING: Do not let the number of iterations go above 25. If the cost
  111617. ** of computing an automatic index is not paid back within the first 25
  111618. ** rows, then do not use the automatic index. */
  111619. aFrom[0].nRow = MIN(pParse->nQueryLoop, 46); assert( 46==sqlite3LogEst(25) );
  111620. nFrom = 1;
  111621. assert( aFrom[0].isOrdered==0 );
  111622. if( nOrderBy ){
  111623. /* If nLoop is zero, then there are no FROM terms in the query. Since
  111624. ** in this case the query may return a maximum of one row, the results
  111625. ** are already in the requested order. Set isOrdered to nOrderBy to
  111626. ** indicate this. Or, if nLoop is greater than zero, set isOrdered to
  111627. ** -1, indicating that the result set may or may not be ordered,
  111628. ** depending on the loops added to the current plan. */
  111629. aFrom[0].isOrdered = nLoop>0 ? -1 : nOrderBy;
  111630. }
  111631. /* Compute successively longer WherePaths using the previous generation
  111632. ** of WherePaths as the basis for the next. Keep track of the mxChoice
  111633. ** best paths at each generation */
  111634. for(iLoop=0; iLoop<nLoop; iLoop++){
  111635. nTo = 0;
  111636. for(ii=0, pFrom=aFrom; ii<nFrom; ii++, pFrom++){
  111637. for(pWLoop=pWInfo->pLoops; pWLoop; pWLoop=pWLoop->pNextLoop){
  111638. LogEst nOut; /* Rows visited by (pFrom+pWLoop) */
  111639. LogEst rCost; /* Cost of path (pFrom+pWLoop) */
  111640. LogEst rUnsorted; /* Unsorted cost of (pFrom+pWLoop) */
  111641. i8 isOrdered = pFrom->isOrdered; /* isOrdered for (pFrom+pWLoop) */
  111642. Bitmask maskNew; /* Mask of src visited by (..) */
  111643. Bitmask revMask = 0; /* Mask of rev-order loops for (..) */
  111644. if( (pWLoop->prereq & ~pFrom->maskLoop)!=0 ) continue;
  111645. if( (pWLoop->maskSelf & pFrom->maskLoop)!=0 ) continue;
  111646. /* At this point, pWLoop is a candidate to be the next loop.
  111647. ** Compute its cost */
  111648. rUnsorted = sqlite3LogEstAdd(pWLoop->rSetup,pWLoop->rRun + pFrom->nRow);
  111649. rUnsorted = sqlite3LogEstAdd(rUnsorted, pFrom->rUnsorted);
  111650. nOut = pFrom->nRow + pWLoop->nOut;
  111651. maskNew = pFrom->maskLoop | pWLoop->maskSelf;
  111652. if( isOrdered<0 ){
  111653. isOrdered = wherePathSatisfiesOrderBy(pWInfo,
  111654. pWInfo->pOrderBy, pFrom, pWInfo->wctrlFlags,
  111655. iLoop, pWLoop, &revMask);
  111656. }else{
  111657. revMask = pFrom->revLoop;
  111658. }
  111659. if( isOrdered>=0 && isOrdered<nOrderBy ){
  111660. if( aSortCost[isOrdered]==0 ){
  111661. aSortCost[isOrdered] = whereSortingCost(
  111662. pWInfo, nRowEst, nOrderBy, isOrdered
  111663. );
  111664. }
  111665. rCost = sqlite3LogEstAdd(rUnsorted, aSortCost[isOrdered]);
  111666. WHERETRACE(0x002,
  111667. ("---- sort cost=%-3d (%d/%d) increases cost %3d to %-3d\n",
  111668. aSortCost[isOrdered], (nOrderBy-isOrdered), nOrderBy,
  111669. rUnsorted, rCost));
  111670. }else{
  111671. rCost = rUnsorted;
  111672. }
  111673. /* Check to see if pWLoop should be added to the set of
  111674. ** mxChoice best-so-far paths.
  111675. **
  111676. ** First look for an existing path among best-so-far paths
  111677. ** that covers the same set of loops and has the same isOrdered
  111678. ** setting as the current path candidate.
  111679. **
  111680. ** The term "((pTo->isOrdered^isOrdered)&0x80)==0" is equivalent
  111681. ** to (pTo->isOrdered==(-1))==(isOrdered==(-1))" for the range
  111682. ** of legal values for isOrdered, -1..64.
  111683. */
  111684. for(jj=0, pTo=aTo; jj<nTo; jj++, pTo++){
  111685. if( pTo->maskLoop==maskNew
  111686. && ((pTo->isOrdered^isOrdered)&0x80)==0
  111687. ){
  111688. testcase( jj==nTo-1 );
  111689. break;
  111690. }
  111691. }
  111692. if( jj>=nTo ){
  111693. /* None of the existing best-so-far paths match the candidate. */
  111694. if( nTo>=mxChoice
  111695. && (rCost>mxCost || (rCost==mxCost && rUnsorted>=mxUnsorted))
  111696. ){
  111697. /* The current candidate is no better than any of the mxChoice
  111698. ** paths currently in the best-so-far buffer. So discard
  111699. ** this candidate as not viable. */
  111700. #ifdef WHERETRACE_ENABLED /* 0x4 */
  111701. if( sqlite3WhereTrace&0x4 ){
  111702. sqlite3DebugPrintf("Skip %s cost=%-3d,%3d order=%c\n",
  111703. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  111704. isOrdered>=0 ? isOrdered+'0' : '?');
  111705. }
  111706. #endif
  111707. continue;
  111708. }
  111709. /* If we reach this points it means that the new candidate path
  111710. ** needs to be added to the set of best-so-far paths. */
  111711. if( nTo<mxChoice ){
  111712. /* Increase the size of the aTo set by one */
  111713. jj = nTo++;
  111714. }else{
  111715. /* New path replaces the prior worst to keep count below mxChoice */
  111716. jj = mxI;
  111717. }
  111718. pTo = &aTo[jj];
  111719. #ifdef WHERETRACE_ENABLED /* 0x4 */
  111720. if( sqlite3WhereTrace&0x4 ){
  111721. sqlite3DebugPrintf("New %s cost=%-3d,%3d order=%c\n",
  111722. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  111723. isOrdered>=0 ? isOrdered+'0' : '?');
  111724. }
  111725. #endif
  111726. }else{
  111727. /* Control reaches here if best-so-far path pTo=aTo[jj] covers the
  111728. ** same set of loops and has the sam isOrdered setting as the
  111729. ** candidate path. Check to see if the candidate should replace
  111730. ** pTo or if the candidate should be skipped */
  111731. if( pTo->rCost<rCost || (pTo->rCost==rCost && pTo->nRow<=nOut) ){
  111732. #ifdef WHERETRACE_ENABLED /* 0x4 */
  111733. if( sqlite3WhereTrace&0x4 ){
  111734. sqlite3DebugPrintf(
  111735. "Skip %s cost=%-3d,%3d order=%c",
  111736. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  111737. isOrdered>=0 ? isOrdered+'0' : '?');
  111738. sqlite3DebugPrintf(" vs %s cost=%-3d,%d order=%c\n",
  111739. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  111740. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  111741. }
  111742. #endif
  111743. /* Discard the candidate path from further consideration */
  111744. testcase( pTo->rCost==rCost );
  111745. continue;
  111746. }
  111747. testcase( pTo->rCost==rCost+1 );
  111748. /* Control reaches here if the candidate path is better than the
  111749. ** pTo path. Replace pTo with the candidate. */
  111750. #ifdef WHERETRACE_ENABLED /* 0x4 */
  111751. if( sqlite3WhereTrace&0x4 ){
  111752. sqlite3DebugPrintf(
  111753. "Update %s cost=%-3d,%3d order=%c",
  111754. wherePathName(pFrom, iLoop, pWLoop), rCost, nOut,
  111755. isOrdered>=0 ? isOrdered+'0' : '?');
  111756. sqlite3DebugPrintf(" was %s cost=%-3d,%3d order=%c\n",
  111757. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  111758. pTo->isOrdered>=0 ? pTo->isOrdered+'0' : '?');
  111759. }
  111760. #endif
  111761. }
  111762. /* pWLoop is a winner. Add it to the set of best so far */
  111763. pTo->maskLoop = pFrom->maskLoop | pWLoop->maskSelf;
  111764. pTo->revLoop = revMask;
  111765. pTo->nRow = nOut;
  111766. pTo->rCost = rCost;
  111767. pTo->rUnsorted = rUnsorted;
  111768. pTo->isOrdered = isOrdered;
  111769. memcpy(pTo->aLoop, pFrom->aLoop, sizeof(WhereLoop*)*iLoop);
  111770. pTo->aLoop[iLoop] = pWLoop;
  111771. if( nTo>=mxChoice ){
  111772. mxI = 0;
  111773. mxCost = aTo[0].rCost;
  111774. mxUnsorted = aTo[0].nRow;
  111775. for(jj=1, pTo=&aTo[1]; jj<mxChoice; jj++, pTo++){
  111776. if( pTo->rCost>mxCost
  111777. || (pTo->rCost==mxCost && pTo->rUnsorted>mxUnsorted)
  111778. ){
  111779. mxCost = pTo->rCost;
  111780. mxUnsorted = pTo->rUnsorted;
  111781. mxI = jj;
  111782. }
  111783. }
  111784. }
  111785. }
  111786. }
  111787. #ifdef WHERETRACE_ENABLED /* >=2 */
  111788. if( sqlite3WhereTrace>=2 ){
  111789. sqlite3DebugPrintf("---- after round %d ----\n", iLoop);
  111790. for(ii=0, pTo=aTo; ii<nTo; ii++, pTo++){
  111791. sqlite3DebugPrintf(" %s cost=%-3d nrow=%-3d order=%c",
  111792. wherePathName(pTo, iLoop+1, 0), pTo->rCost, pTo->nRow,
  111793. pTo->isOrdered>=0 ? (pTo->isOrdered+'0') : '?');
  111794. if( pTo->isOrdered>0 ){
  111795. sqlite3DebugPrintf(" rev=0x%llx\n", pTo->revLoop);
  111796. }else{
  111797. sqlite3DebugPrintf("\n");
  111798. }
  111799. }
  111800. }
  111801. #endif
  111802. /* Swap the roles of aFrom and aTo for the next generation */
  111803. pFrom = aTo;
  111804. aTo = aFrom;
  111805. aFrom = pFrom;
  111806. nFrom = nTo;
  111807. }
  111808. if( nFrom==0 ){
  111809. sqlite3ErrorMsg(pParse, "no query solution");
  111810. sqlite3DbFree(db, pSpace);
  111811. return SQLITE_ERROR;
  111812. }
  111813. /* Find the lowest cost path. pFrom will be left pointing to that path */
  111814. pFrom = aFrom;
  111815. for(ii=1; ii<nFrom; ii++){
  111816. if( pFrom->rCost>aFrom[ii].rCost ) pFrom = &aFrom[ii];
  111817. }
  111818. assert( pWInfo->nLevel==nLoop );
  111819. /* Load the lowest cost path into pWInfo */
  111820. for(iLoop=0; iLoop<nLoop; iLoop++){
  111821. WhereLevel *pLevel = pWInfo->a + iLoop;
  111822. pLevel->pWLoop = pWLoop = pFrom->aLoop[iLoop];
  111823. pLevel->iFrom = pWLoop->iTab;
  111824. pLevel->iTabCur = pWInfo->pTabList->a[pLevel->iFrom].iCursor;
  111825. }
  111826. if( (pWInfo->wctrlFlags & WHERE_WANT_DISTINCT)!=0
  111827. && (pWInfo->wctrlFlags & WHERE_DISTINCTBY)==0
  111828. && pWInfo->eDistinct==WHERE_DISTINCT_NOOP
  111829. && nRowEst
  111830. ){
  111831. Bitmask notUsed;
  111832. int rc = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pResultSet, pFrom,
  111833. WHERE_DISTINCTBY, nLoop-1, pFrom->aLoop[nLoop-1], &notUsed);
  111834. if( rc==pWInfo->pResultSet->nExpr ){
  111835. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  111836. }
  111837. }
  111838. if( pWInfo->pOrderBy ){
  111839. if( pWInfo->wctrlFlags & WHERE_DISTINCTBY ){
  111840. if( pFrom->isOrdered==pWInfo->pOrderBy->nExpr ){
  111841. pWInfo->eDistinct = WHERE_DISTINCT_ORDERED;
  111842. }
  111843. }else{
  111844. pWInfo->nOBSat = pFrom->isOrdered;
  111845. if( pWInfo->nOBSat<0 ) pWInfo->nOBSat = 0;
  111846. pWInfo->revMask = pFrom->revLoop;
  111847. }
  111848. if( (pWInfo->wctrlFlags & WHERE_SORTBYGROUP)
  111849. && pWInfo->nOBSat==pWInfo->pOrderBy->nExpr
  111850. ){
  111851. Bitmask revMask = 0;
  111852. int nOrder = wherePathSatisfiesOrderBy(pWInfo, pWInfo->pOrderBy,
  111853. pFrom, 0, nLoop-1, pFrom->aLoop[nLoop-1], &revMask
  111854. );
  111855. assert( pWInfo->sorted==0 );
  111856. if( nOrder==pWInfo->pOrderBy->nExpr ){
  111857. pWInfo->sorted = 1;
  111858. pWInfo->revMask = revMask;
  111859. }
  111860. }
  111861. }
  111862. pWInfo->nRowOut = pFrom->nRow;
  111863. /* Free temporary memory and return success */
  111864. sqlite3DbFree(db, pSpace);
  111865. return SQLITE_OK;
  111866. }
  111867. /*
  111868. ** Most queries use only a single table (they are not joins) and have
  111869. ** simple == constraints against indexed fields. This routine attempts
  111870. ** to plan those simple cases using much less ceremony than the
  111871. ** general-purpose query planner, and thereby yield faster sqlite3_prepare()
  111872. ** times for the common case.
  111873. **
  111874. ** Return non-zero on success, if this query can be handled by this
  111875. ** no-frills query planner. Return zero if this query needs the
  111876. ** general-purpose query planner.
  111877. */
  111878. static int whereShortCut(WhereLoopBuilder *pBuilder){
  111879. WhereInfo *pWInfo;
  111880. struct SrcList_item *pItem;
  111881. WhereClause *pWC;
  111882. WhereTerm *pTerm;
  111883. WhereLoop *pLoop;
  111884. int iCur;
  111885. int j;
  111886. Table *pTab;
  111887. Index *pIdx;
  111888. pWInfo = pBuilder->pWInfo;
  111889. if( pWInfo->wctrlFlags & WHERE_FORCE_TABLE ) return 0;
  111890. assert( pWInfo->pTabList->nSrc>=1 );
  111891. pItem = pWInfo->pTabList->a;
  111892. pTab = pItem->pTab;
  111893. if( IsVirtual(pTab) ) return 0;
  111894. if( pItem->zIndex ) return 0;
  111895. iCur = pItem->iCursor;
  111896. pWC = &pWInfo->sWC;
  111897. pLoop = pBuilder->pNew;
  111898. pLoop->wsFlags = 0;
  111899. pLoop->u.btree.nSkip = 0;
  111900. pTerm = findTerm(pWC, iCur, -1, 0, WO_EQ, 0);
  111901. if( pTerm ){
  111902. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_IPK|WHERE_ONEROW;
  111903. pLoop->aLTerm[0] = pTerm;
  111904. pLoop->nLTerm = 1;
  111905. pLoop->u.btree.nEq = 1;
  111906. /* TUNING: Cost of a rowid lookup is 10 */
  111907. pLoop->rRun = 33; /* 33==sqlite3LogEst(10) */
  111908. }else{
  111909. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  111910. assert( pLoop->aLTermSpace==pLoop->aLTerm );
  111911. assert( ArraySize(pLoop->aLTermSpace)==4 );
  111912. if( !IsUniqueIndex(pIdx)
  111913. || pIdx->pPartIdxWhere!=0
  111914. || pIdx->nKeyCol>ArraySize(pLoop->aLTermSpace)
  111915. ) continue;
  111916. for(j=0; j<pIdx->nKeyCol; j++){
  111917. pTerm = findTerm(pWC, iCur, pIdx->aiColumn[j], 0, WO_EQ, pIdx);
  111918. if( pTerm==0 ) break;
  111919. pLoop->aLTerm[j] = pTerm;
  111920. }
  111921. if( j!=pIdx->nKeyCol ) continue;
  111922. pLoop->wsFlags = WHERE_COLUMN_EQ|WHERE_ONEROW|WHERE_INDEXED;
  111923. if( pIdx->isCovering || (pItem->colUsed & ~columnsInIndex(pIdx))==0 ){
  111924. pLoop->wsFlags |= WHERE_IDX_ONLY;
  111925. }
  111926. pLoop->nLTerm = j;
  111927. pLoop->u.btree.nEq = j;
  111928. pLoop->u.btree.pIndex = pIdx;
  111929. /* TUNING: Cost of a unique index lookup is 15 */
  111930. pLoop->rRun = 39; /* 39==sqlite3LogEst(15) */
  111931. break;
  111932. }
  111933. }
  111934. if( pLoop->wsFlags ){
  111935. pLoop->nOut = (LogEst)1;
  111936. pWInfo->a[0].pWLoop = pLoop;
  111937. pLoop->maskSelf = getMask(&pWInfo->sMaskSet, iCur);
  111938. pWInfo->a[0].iTabCur = iCur;
  111939. pWInfo->nRowOut = 1;
  111940. if( pWInfo->pOrderBy ) pWInfo->nOBSat = pWInfo->pOrderBy->nExpr;
  111941. if( pWInfo->wctrlFlags & WHERE_WANT_DISTINCT ){
  111942. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  111943. }
  111944. #ifdef SQLITE_DEBUG
  111945. pLoop->cId = '0';
  111946. #endif
  111947. return 1;
  111948. }
  111949. return 0;
  111950. }
  111951. /*
  111952. ** Generate the beginning of the loop used for WHERE clause processing.
  111953. ** The return value is a pointer to an opaque structure that contains
  111954. ** information needed to terminate the loop. Later, the calling routine
  111955. ** should invoke sqlite3WhereEnd() with the return value of this function
  111956. ** in order to complete the WHERE clause processing.
  111957. **
  111958. ** If an error occurs, this routine returns NULL.
  111959. **
  111960. ** The basic idea is to do a nested loop, one loop for each table in
  111961. ** the FROM clause of a select. (INSERT and UPDATE statements are the
  111962. ** same as a SELECT with only a single table in the FROM clause.) For
  111963. ** example, if the SQL is this:
  111964. **
  111965. ** SELECT * FROM t1, t2, t3 WHERE ...;
  111966. **
  111967. ** Then the code generated is conceptually like the following:
  111968. **
  111969. ** foreach row1 in t1 do \ Code generated
  111970. ** foreach row2 in t2 do |-- by sqlite3WhereBegin()
  111971. ** foreach row3 in t3 do /
  111972. ** ...
  111973. ** end \ Code generated
  111974. ** end |-- by sqlite3WhereEnd()
  111975. ** end /
  111976. **
  111977. ** Note that the loops might not be nested in the order in which they
  111978. ** appear in the FROM clause if a different order is better able to make
  111979. ** use of indices. Note also that when the IN operator appears in
  111980. ** the WHERE clause, it might result in additional nested loops for
  111981. ** scanning through all values on the right-hand side of the IN.
  111982. **
  111983. ** There are Btree cursors associated with each table. t1 uses cursor
  111984. ** number pTabList->a[0].iCursor. t2 uses the cursor pTabList->a[1].iCursor.
  111985. ** And so forth. This routine generates code to open those VDBE cursors
  111986. ** and sqlite3WhereEnd() generates the code to close them.
  111987. **
  111988. ** The code that sqlite3WhereBegin() generates leaves the cursors named
  111989. ** in pTabList pointing at their appropriate entries. The [...] code
  111990. ** can use OP_Column and OP_Rowid opcodes on these cursors to extract
  111991. ** data from the various tables of the loop.
  111992. **
  111993. ** If the WHERE clause is empty, the foreach loops must each scan their
  111994. ** entire tables. Thus a three-way join is an O(N^3) operation. But if
  111995. ** the tables have indices and there are terms in the WHERE clause that
  111996. ** refer to those indices, a complete table scan can be avoided and the
  111997. ** code will run much faster. Most of the work of this routine is checking
  111998. ** to see if there are indices that can be used to speed up the loop.
  111999. **
  112000. ** Terms of the WHERE clause are also used to limit which rows actually
  112001. ** make it to the "..." in the middle of the loop. After each "foreach",
  112002. ** terms of the WHERE clause that use only terms in that loop and outer
  112003. ** loops are evaluated and if false a jump is made around all subsequent
  112004. ** inner loops (or around the "..." if the test occurs within the inner-
  112005. ** most loop)
  112006. **
  112007. ** OUTER JOINS
  112008. **
  112009. ** An outer join of tables t1 and t2 is conceptally coded as follows:
  112010. **
  112011. ** foreach row1 in t1 do
  112012. ** flag = 0
  112013. ** foreach row2 in t2 do
  112014. ** start:
  112015. ** ...
  112016. ** flag = 1
  112017. ** end
  112018. ** if flag==0 then
  112019. ** move the row2 cursor to a null row
  112020. ** goto start
  112021. ** fi
  112022. ** end
  112023. **
  112024. ** ORDER BY CLAUSE PROCESSING
  112025. **
  112026. ** pOrderBy is a pointer to the ORDER BY clause (or the GROUP BY clause
  112027. ** if the WHERE_GROUPBY flag is set in wctrlFlags) of a SELECT statement
  112028. ** if there is one. If there is no ORDER BY clause or if this routine
  112029. ** is called from an UPDATE or DELETE statement, then pOrderBy is NULL.
  112030. **
  112031. ** The iIdxCur parameter is the cursor number of an index. If
  112032. ** WHERE_ONETABLE_ONLY is set, iIdxCur is the cursor number of an index
  112033. ** to use for OR clause processing. The WHERE clause should use this
  112034. ** specific cursor. If WHERE_ONEPASS_DESIRED is set, then iIdxCur is
  112035. ** the first cursor in an array of cursors for all indices. iIdxCur should
  112036. ** be used to compute the appropriate cursor depending on which index is
  112037. ** used.
  112038. */
  112039. SQLITE_PRIVATE WhereInfo *sqlite3WhereBegin(
  112040. Parse *pParse, /* The parser context */
  112041. SrcList *pTabList, /* FROM clause: A list of all tables to be scanned */
  112042. Expr *pWhere, /* The WHERE clause */
  112043. ExprList *pOrderBy, /* An ORDER BY (or GROUP BY) clause, or NULL */
  112044. ExprList *pResultSet, /* Result set of the query */
  112045. u16 wctrlFlags, /* One of the WHERE_* flags defined in sqliteInt.h */
  112046. int iIdxCur /* If WHERE_ONETABLE_ONLY is set, index cursor number */
  112047. ){
  112048. int nByteWInfo; /* Num. bytes allocated for WhereInfo struct */
  112049. int nTabList; /* Number of elements in pTabList */
  112050. WhereInfo *pWInfo; /* Will become the return value of this function */
  112051. Vdbe *v = pParse->pVdbe; /* The virtual database engine */
  112052. Bitmask notReady; /* Cursors that are not yet positioned */
  112053. WhereLoopBuilder sWLB; /* The WhereLoop builder */
  112054. WhereMaskSet *pMaskSet; /* The expression mask set */
  112055. WhereLevel *pLevel; /* A single level in pWInfo->a[] */
  112056. WhereLoop *pLoop; /* Pointer to a single WhereLoop object */
  112057. int ii; /* Loop counter */
  112058. sqlite3 *db; /* Database connection */
  112059. int rc; /* Return code */
  112060. /* Variable initialization */
  112061. db = pParse->db;
  112062. memset(&sWLB, 0, sizeof(sWLB));
  112063. /* An ORDER/GROUP BY clause of more than 63 terms cannot be optimized */
  112064. testcase( pOrderBy && pOrderBy->nExpr==BMS-1 );
  112065. if( pOrderBy && pOrderBy->nExpr>=BMS ) pOrderBy = 0;
  112066. sWLB.pOrderBy = pOrderBy;
  112067. /* Disable the DISTINCT optimization if SQLITE_DistinctOpt is set via
  112068. ** sqlite3_test_ctrl(SQLITE_TESTCTRL_OPTIMIZATIONS,...) */
  112069. if( OptimizationDisabled(db, SQLITE_DistinctOpt) ){
  112070. wctrlFlags &= ~WHERE_WANT_DISTINCT;
  112071. }
  112072. /* The number of tables in the FROM clause is limited by the number of
  112073. ** bits in a Bitmask
  112074. */
  112075. testcase( pTabList->nSrc==BMS );
  112076. if( pTabList->nSrc>BMS ){
  112077. sqlite3ErrorMsg(pParse, "at most %d tables in a join", BMS);
  112078. return 0;
  112079. }
  112080. /* This function normally generates a nested loop for all tables in
  112081. ** pTabList. But if the WHERE_ONETABLE_ONLY flag is set, then we should
  112082. ** only generate code for the first table in pTabList and assume that
  112083. ** any cursors associated with subsequent tables are uninitialized.
  112084. */
  112085. nTabList = (wctrlFlags & WHERE_ONETABLE_ONLY) ? 1 : pTabList->nSrc;
  112086. /* Allocate and initialize the WhereInfo structure that will become the
  112087. ** return value. A single allocation is used to store the WhereInfo
  112088. ** struct, the contents of WhereInfo.a[], the WhereClause structure
  112089. ** and the WhereMaskSet structure. Since WhereClause contains an 8-byte
  112090. ** field (type Bitmask) it must be aligned on an 8-byte boundary on
  112091. ** some architectures. Hence the ROUND8() below.
  112092. */
  112093. nByteWInfo = ROUND8(sizeof(WhereInfo)+(nTabList-1)*sizeof(WhereLevel));
  112094. pWInfo = sqlite3DbMallocZero(db, nByteWInfo + sizeof(WhereLoop));
  112095. if( db->mallocFailed ){
  112096. sqlite3DbFree(db, pWInfo);
  112097. pWInfo = 0;
  112098. goto whereBeginError;
  112099. }
  112100. pWInfo->aiCurOnePass[0] = pWInfo->aiCurOnePass[1] = -1;
  112101. pWInfo->nLevel = nTabList;
  112102. pWInfo->pParse = pParse;
  112103. pWInfo->pTabList = pTabList;
  112104. pWInfo->pOrderBy = pOrderBy;
  112105. pWInfo->pResultSet = pResultSet;
  112106. pWInfo->iBreak = pWInfo->iContinue = sqlite3VdbeMakeLabel(v);
  112107. pWInfo->wctrlFlags = wctrlFlags;
  112108. pWInfo->savedNQueryLoop = pParse->nQueryLoop;
  112109. pMaskSet = &pWInfo->sMaskSet;
  112110. sWLB.pWInfo = pWInfo;
  112111. sWLB.pWC = &pWInfo->sWC;
  112112. sWLB.pNew = (WhereLoop*)(((char*)pWInfo)+nByteWInfo);
  112113. assert( EIGHT_BYTE_ALIGNMENT(sWLB.pNew) );
  112114. whereLoopInit(sWLB.pNew);
  112115. #ifdef SQLITE_DEBUG
  112116. sWLB.pNew->cId = '*';
  112117. #endif
  112118. /* Split the WHERE clause into separate subexpressions where each
  112119. ** subexpression is separated by an AND operator.
  112120. */
  112121. initMaskSet(pMaskSet);
  112122. whereClauseInit(&pWInfo->sWC, pWInfo);
  112123. whereSplit(&pWInfo->sWC, pWhere, TK_AND);
  112124. /* Special case: a WHERE clause that is constant. Evaluate the
  112125. ** expression and either jump over all of the code or fall thru.
  112126. */
  112127. for(ii=0; ii<sWLB.pWC->nTerm; ii++){
  112128. if( nTabList==0 || sqlite3ExprIsConstantNotJoin(sWLB.pWC->a[ii].pExpr) ){
  112129. sqlite3ExprIfFalse(pParse, sWLB.pWC->a[ii].pExpr, pWInfo->iBreak,
  112130. SQLITE_JUMPIFNULL);
  112131. sWLB.pWC->a[ii].wtFlags |= TERM_CODED;
  112132. }
  112133. }
  112134. /* Special case: No FROM clause
  112135. */
  112136. if( nTabList==0 ){
  112137. if( pOrderBy ) pWInfo->nOBSat = pOrderBy->nExpr;
  112138. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  112139. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  112140. }
  112141. }
  112142. /* Assign a bit from the bitmask to every term in the FROM clause.
  112143. **
  112144. ** When assigning bitmask values to FROM clause cursors, it must be
  112145. ** the case that if X is the bitmask for the N-th FROM clause term then
  112146. ** the bitmask for all FROM clause terms to the left of the N-th term
  112147. ** is (X-1). An expression from the ON clause of a LEFT JOIN can use
  112148. ** its Expr.iRightJoinTable value to find the bitmask of the right table
  112149. ** of the join. Subtracting one from the right table bitmask gives a
  112150. ** bitmask for all tables to the left of the join. Knowing the bitmask
  112151. ** for all tables to the left of a left join is important. Ticket #3015.
  112152. **
  112153. ** Note that bitmasks are created for all pTabList->nSrc tables in
  112154. ** pTabList, not just the first nTabList tables. nTabList is normally
  112155. ** equal to pTabList->nSrc but might be shortened to 1 if the
  112156. ** WHERE_ONETABLE_ONLY flag is set.
  112157. */
  112158. for(ii=0; ii<pTabList->nSrc; ii++){
  112159. createMask(pMaskSet, pTabList->a[ii].iCursor);
  112160. }
  112161. #ifndef NDEBUG
  112162. {
  112163. Bitmask toTheLeft = 0;
  112164. for(ii=0; ii<pTabList->nSrc; ii++){
  112165. Bitmask m = getMask(pMaskSet, pTabList->a[ii].iCursor);
  112166. assert( (m-1)==toTheLeft );
  112167. toTheLeft |= m;
  112168. }
  112169. }
  112170. #endif
  112171. /* Analyze all of the subexpressions. Note that exprAnalyze() might
  112172. ** add new virtual terms onto the end of the WHERE clause. We do not
  112173. ** want to analyze these virtual terms, so start analyzing at the end
  112174. ** and work forward so that the added virtual terms are never processed.
  112175. */
  112176. exprAnalyzeAll(pTabList, &pWInfo->sWC);
  112177. if( db->mallocFailed ){
  112178. goto whereBeginError;
  112179. }
  112180. if( wctrlFlags & WHERE_WANT_DISTINCT ){
  112181. if( isDistinctRedundant(pParse, pTabList, &pWInfo->sWC, pResultSet) ){
  112182. /* The DISTINCT marking is pointless. Ignore it. */
  112183. pWInfo->eDistinct = WHERE_DISTINCT_UNIQUE;
  112184. }else if( pOrderBy==0 ){
  112185. /* Try to ORDER BY the result set to make distinct processing easier */
  112186. pWInfo->wctrlFlags |= WHERE_DISTINCTBY;
  112187. pWInfo->pOrderBy = pResultSet;
  112188. }
  112189. }
  112190. /* Construct the WhereLoop objects */
  112191. WHERETRACE(0xffff,("*** Optimizer Start ***\n"));
  112192. #if defined(WHERETRACE_ENABLED)
  112193. /* Display all terms of the WHERE clause */
  112194. if( sqlite3WhereTrace & 0x100 ){
  112195. int i;
  112196. for(i=0; i<sWLB.pWC->nTerm; i++){
  112197. whereTermPrint(&sWLB.pWC->a[i], i);
  112198. }
  112199. }
  112200. #endif
  112201. if( nTabList!=1 || whereShortCut(&sWLB)==0 ){
  112202. rc = whereLoopAddAll(&sWLB);
  112203. if( rc ) goto whereBeginError;
  112204. /* Display all of the WhereLoop objects if wheretrace is enabled */
  112205. #ifdef WHERETRACE_ENABLED /* !=0 */
  112206. if( sqlite3WhereTrace ){
  112207. WhereLoop *p;
  112208. int i;
  112209. static char zLabel[] = "0123456789abcdefghijklmnopqrstuvwyxz"
  112210. "ABCDEFGHIJKLMNOPQRSTUVWYXZ";
  112211. for(p=pWInfo->pLoops, i=0; p; p=p->pNextLoop, i++){
  112212. p->cId = zLabel[i%sizeof(zLabel)];
  112213. whereLoopPrint(p, sWLB.pWC);
  112214. }
  112215. }
  112216. #endif
  112217. wherePathSolver(pWInfo, 0);
  112218. if( db->mallocFailed ) goto whereBeginError;
  112219. if( pWInfo->pOrderBy ){
  112220. wherePathSolver(pWInfo, pWInfo->nRowOut+1);
  112221. if( db->mallocFailed ) goto whereBeginError;
  112222. }
  112223. }
  112224. if( pWInfo->pOrderBy==0 && (db->flags & SQLITE_ReverseOrder)!=0 ){
  112225. pWInfo->revMask = (Bitmask)(-1);
  112226. }
  112227. if( pParse->nErr || NEVER(db->mallocFailed) ){
  112228. goto whereBeginError;
  112229. }
  112230. #ifdef WHERETRACE_ENABLED /* !=0 */
  112231. if( sqlite3WhereTrace ){
  112232. int ii;
  112233. sqlite3DebugPrintf("---- Solution nRow=%d", pWInfo->nRowOut);
  112234. if( pWInfo->nOBSat>0 ){
  112235. sqlite3DebugPrintf(" ORDERBY=%d,0x%llx", pWInfo->nOBSat, pWInfo->revMask);
  112236. }
  112237. switch( pWInfo->eDistinct ){
  112238. case WHERE_DISTINCT_UNIQUE: {
  112239. sqlite3DebugPrintf(" DISTINCT=unique");
  112240. break;
  112241. }
  112242. case WHERE_DISTINCT_ORDERED: {
  112243. sqlite3DebugPrintf(" DISTINCT=ordered");
  112244. break;
  112245. }
  112246. case WHERE_DISTINCT_UNORDERED: {
  112247. sqlite3DebugPrintf(" DISTINCT=unordered");
  112248. break;
  112249. }
  112250. }
  112251. sqlite3DebugPrintf("\n");
  112252. for(ii=0; ii<pWInfo->nLevel; ii++){
  112253. whereLoopPrint(pWInfo->a[ii].pWLoop, sWLB.pWC);
  112254. }
  112255. }
  112256. #endif
  112257. /* Attempt to omit tables from the join that do not effect the result */
  112258. if( pWInfo->nLevel>=2
  112259. && pResultSet!=0
  112260. && OptimizationEnabled(db, SQLITE_OmitNoopJoin)
  112261. ){
  112262. Bitmask tabUsed = exprListTableUsage(pMaskSet, pResultSet);
  112263. if( sWLB.pOrderBy ) tabUsed |= exprListTableUsage(pMaskSet, sWLB.pOrderBy);
  112264. while( pWInfo->nLevel>=2 ){
  112265. WhereTerm *pTerm, *pEnd;
  112266. pLoop = pWInfo->a[pWInfo->nLevel-1].pWLoop;
  112267. if( (pWInfo->pTabList->a[pLoop->iTab].jointype & JT_LEFT)==0 ) break;
  112268. if( (wctrlFlags & WHERE_WANT_DISTINCT)==0
  112269. && (pLoop->wsFlags & WHERE_ONEROW)==0
  112270. ){
  112271. break;
  112272. }
  112273. if( (tabUsed & pLoop->maskSelf)!=0 ) break;
  112274. pEnd = sWLB.pWC->a + sWLB.pWC->nTerm;
  112275. for(pTerm=sWLB.pWC->a; pTerm<pEnd; pTerm++){
  112276. if( (pTerm->prereqAll & pLoop->maskSelf)!=0
  112277. && !ExprHasProperty(pTerm->pExpr, EP_FromJoin)
  112278. ){
  112279. break;
  112280. }
  112281. }
  112282. if( pTerm<pEnd ) break;
  112283. WHERETRACE(0xffff, ("-> drop loop %c not used\n", pLoop->cId));
  112284. pWInfo->nLevel--;
  112285. nTabList--;
  112286. }
  112287. }
  112288. WHERETRACE(0xffff,("*** Optimizer Finished ***\n"));
  112289. pWInfo->pParse->nQueryLoop += pWInfo->nRowOut;
  112290. /* If the caller is an UPDATE or DELETE statement that is requesting
  112291. ** to use a one-pass algorithm, determine if this is appropriate.
  112292. ** The one-pass algorithm only works if the WHERE clause constrains
  112293. ** the statement to update a single row.
  112294. */
  112295. assert( (wctrlFlags & WHERE_ONEPASS_DESIRED)==0 || pWInfo->nLevel==1 );
  112296. if( (wctrlFlags & WHERE_ONEPASS_DESIRED)!=0
  112297. && (pWInfo->a[0].pWLoop->wsFlags & WHERE_ONEROW)!=0 ){
  112298. pWInfo->okOnePass = 1;
  112299. if( HasRowid(pTabList->a[0].pTab) ){
  112300. pWInfo->a[0].pWLoop->wsFlags &= ~WHERE_IDX_ONLY;
  112301. }
  112302. }
  112303. /* Open all tables in the pTabList and any indices selected for
  112304. ** searching those tables.
  112305. */
  112306. notReady = ~(Bitmask)0;
  112307. for(ii=0, pLevel=pWInfo->a; ii<nTabList; ii++, pLevel++){
  112308. Table *pTab; /* Table to open */
  112309. int iDb; /* Index of database containing table/index */
  112310. struct SrcList_item *pTabItem;
  112311. pTabItem = &pTabList->a[pLevel->iFrom];
  112312. pTab = pTabItem->pTab;
  112313. iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
  112314. pLoop = pLevel->pWLoop;
  112315. if( (pTab->tabFlags & TF_Ephemeral)!=0 || pTab->pSelect ){
  112316. /* Do nothing */
  112317. }else
  112318. #ifndef SQLITE_OMIT_VIRTUALTABLE
  112319. if( (pLoop->wsFlags & WHERE_VIRTUALTABLE)!=0 ){
  112320. const char *pVTab = (const char *)sqlite3GetVTable(db, pTab);
  112321. int iCur = pTabItem->iCursor;
  112322. sqlite3VdbeAddOp4(v, OP_VOpen, iCur, 0, 0, pVTab, P4_VTAB);
  112323. }else if( IsVirtual(pTab) ){
  112324. /* noop */
  112325. }else
  112326. #endif
  112327. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  112328. && (wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0 ){
  112329. int op = OP_OpenRead;
  112330. if( pWInfo->okOnePass ){
  112331. op = OP_OpenWrite;
  112332. pWInfo->aiCurOnePass[0] = pTabItem->iCursor;
  112333. };
  112334. sqlite3OpenTable(pParse, pTabItem->iCursor, iDb, pTab, op);
  112335. assert( pTabItem->iCursor==pLevel->iTabCur );
  112336. testcase( !pWInfo->okOnePass && pTab->nCol==BMS-1 );
  112337. testcase( !pWInfo->okOnePass && pTab->nCol==BMS );
  112338. if( !pWInfo->okOnePass && pTab->nCol<BMS && HasRowid(pTab) ){
  112339. Bitmask b = pTabItem->colUsed;
  112340. int n = 0;
  112341. for(; b; b=b>>1, n++){}
  112342. sqlite3VdbeChangeP4(v, sqlite3VdbeCurrentAddr(v)-1,
  112343. SQLITE_INT_TO_PTR(n), P4_INT32);
  112344. assert( n<=pTab->nCol );
  112345. }
  112346. }else{
  112347. sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
  112348. }
  112349. if( pLoop->wsFlags & WHERE_INDEXED ){
  112350. Index *pIx = pLoop->u.btree.pIndex;
  112351. int iIndexCur;
  112352. int op = OP_OpenRead;
  112353. /* iIdxCur is always set if to a positive value if ONEPASS is possible */
  112354. assert( iIdxCur!=0 || (pWInfo->wctrlFlags & WHERE_ONEPASS_DESIRED)==0 );
  112355. if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIx)
  112356. && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0
  112357. ){
  112358. /* This is one term of an OR-optimization using the PRIMARY KEY of a
  112359. ** WITHOUT ROWID table. No need for a separate index */
  112360. iIndexCur = pLevel->iTabCur;
  112361. op = 0;
  112362. }else if( pWInfo->okOnePass ){
  112363. Index *pJ = pTabItem->pTab->pIndex;
  112364. iIndexCur = iIdxCur;
  112365. assert( wctrlFlags & WHERE_ONEPASS_DESIRED );
  112366. while( ALWAYS(pJ) && pJ!=pIx ){
  112367. iIndexCur++;
  112368. pJ = pJ->pNext;
  112369. }
  112370. op = OP_OpenWrite;
  112371. pWInfo->aiCurOnePass[1] = iIndexCur;
  112372. }else if( iIdxCur && (wctrlFlags & WHERE_ONETABLE_ONLY)!=0 ){
  112373. iIndexCur = iIdxCur;
  112374. if( wctrlFlags & WHERE_REOPEN_IDX ) op = OP_ReopenIdx;
  112375. }else{
  112376. iIndexCur = pParse->nTab++;
  112377. }
  112378. pLevel->iIdxCur = iIndexCur;
  112379. assert( pIx->pSchema==pTab->pSchema );
  112380. assert( iIndexCur>=0 );
  112381. if( op ){
  112382. sqlite3VdbeAddOp3(v, op, iIndexCur, pIx->tnum, iDb);
  112383. sqlite3VdbeSetP4KeyInfo(pParse, pIx);
  112384. VdbeComment((v, "%s", pIx->zName));
  112385. }
  112386. }
  112387. if( iDb>=0 ) sqlite3CodeVerifySchema(pParse, iDb);
  112388. notReady &= ~getMask(&pWInfo->sMaskSet, pTabItem->iCursor);
  112389. }
  112390. pWInfo->iTop = sqlite3VdbeCurrentAddr(v);
  112391. if( db->mallocFailed ) goto whereBeginError;
  112392. /* Generate the code to do the search. Each iteration of the for
  112393. ** loop below generates code for a single nested loop of the VM
  112394. ** program.
  112395. */
  112396. notReady = ~(Bitmask)0;
  112397. for(ii=0; ii<nTabList; ii++){
  112398. pLevel = &pWInfo->a[ii];
  112399. #ifndef SQLITE_OMIT_AUTOMATIC_INDEX
  112400. if( (pLevel->pWLoop->wsFlags & WHERE_AUTO_INDEX)!=0 ){
  112401. constructAutomaticIndex(pParse, &pWInfo->sWC,
  112402. &pTabList->a[pLevel->iFrom], notReady, pLevel);
  112403. if( db->mallocFailed ) goto whereBeginError;
  112404. }
  112405. #endif
  112406. explainOneScan(pParse, pTabList, pLevel, ii, pLevel->iFrom, wctrlFlags);
  112407. pLevel->addrBody = sqlite3VdbeCurrentAddr(v);
  112408. notReady = codeOneLoopStart(pWInfo, ii, notReady);
  112409. pWInfo->iContinue = pLevel->addrCont;
  112410. }
  112411. /* Done. */
  112412. VdbeModuleComment((v, "Begin WHERE-core"));
  112413. return pWInfo;
  112414. /* Jump here if malloc fails */
  112415. whereBeginError:
  112416. if( pWInfo ){
  112417. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  112418. whereInfoFree(db, pWInfo);
  112419. }
  112420. return 0;
  112421. }
  112422. /*
  112423. ** Generate the end of the WHERE loop. See comments on
  112424. ** sqlite3WhereBegin() for additional information.
  112425. */
  112426. SQLITE_PRIVATE void sqlite3WhereEnd(WhereInfo *pWInfo){
  112427. Parse *pParse = pWInfo->pParse;
  112428. Vdbe *v = pParse->pVdbe;
  112429. int i;
  112430. WhereLevel *pLevel;
  112431. WhereLoop *pLoop;
  112432. SrcList *pTabList = pWInfo->pTabList;
  112433. sqlite3 *db = pParse->db;
  112434. /* Generate loop termination code.
  112435. */
  112436. VdbeModuleComment((v, "End WHERE-core"));
  112437. sqlite3ExprCacheClear(pParse);
  112438. for(i=pWInfo->nLevel-1; i>=0; i--){
  112439. int addr;
  112440. pLevel = &pWInfo->a[i];
  112441. pLoop = pLevel->pWLoop;
  112442. sqlite3VdbeResolveLabel(v, pLevel->addrCont);
  112443. if( pLevel->op!=OP_Noop ){
  112444. sqlite3VdbeAddOp3(v, pLevel->op, pLevel->p1, pLevel->p2, pLevel->p3);
  112445. sqlite3VdbeChangeP5(v, pLevel->p5);
  112446. VdbeCoverage(v);
  112447. VdbeCoverageIf(v, pLevel->op==OP_Next);
  112448. VdbeCoverageIf(v, pLevel->op==OP_Prev);
  112449. VdbeCoverageIf(v, pLevel->op==OP_VNext);
  112450. }
  112451. if( pLoop->wsFlags & WHERE_IN_ABLE && pLevel->u.in.nIn>0 ){
  112452. struct InLoop *pIn;
  112453. int j;
  112454. sqlite3VdbeResolveLabel(v, pLevel->addrNxt);
  112455. for(j=pLevel->u.in.nIn, pIn=&pLevel->u.in.aInLoop[j-1]; j>0; j--, pIn--){
  112456. sqlite3VdbeJumpHere(v, pIn->addrInTop+1);
  112457. sqlite3VdbeAddOp2(v, pIn->eEndLoopOp, pIn->iCur, pIn->addrInTop);
  112458. VdbeCoverage(v);
  112459. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_PrevIfOpen);
  112460. VdbeCoverageIf(v, pIn->eEndLoopOp==OP_NextIfOpen);
  112461. sqlite3VdbeJumpHere(v, pIn->addrInTop-1);
  112462. }
  112463. sqlite3DbFree(db, pLevel->u.in.aInLoop);
  112464. }
  112465. sqlite3VdbeResolveLabel(v, pLevel->addrBrk);
  112466. if( pLevel->addrSkip ){
  112467. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrSkip);
  112468. VdbeComment((v, "next skip-scan on %s", pLoop->u.btree.pIndex->zName));
  112469. sqlite3VdbeJumpHere(v, pLevel->addrSkip);
  112470. sqlite3VdbeJumpHere(v, pLevel->addrSkip-2);
  112471. }
  112472. if( pLevel->iLeftJoin ){
  112473. addr = sqlite3VdbeAddOp1(v, OP_IfPos, pLevel->iLeftJoin); VdbeCoverage(v);
  112474. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0
  112475. || (pLoop->wsFlags & WHERE_INDEXED)!=0 );
  112476. if( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 ){
  112477. sqlite3VdbeAddOp1(v, OP_NullRow, pTabList->a[i].iCursor);
  112478. }
  112479. if( pLoop->wsFlags & WHERE_INDEXED ){
  112480. sqlite3VdbeAddOp1(v, OP_NullRow, pLevel->iIdxCur);
  112481. }
  112482. if( pLevel->op==OP_Return ){
  112483. sqlite3VdbeAddOp2(v, OP_Gosub, pLevel->p1, pLevel->addrFirst);
  112484. }else{
  112485. sqlite3VdbeAddOp2(v, OP_Goto, 0, pLevel->addrFirst);
  112486. }
  112487. sqlite3VdbeJumpHere(v, addr);
  112488. }
  112489. VdbeModuleComment((v, "End WHERE-loop%d: %s", i,
  112490. pWInfo->pTabList->a[pLevel->iFrom].pTab->zName));
  112491. }
  112492. /* The "break" point is here, just past the end of the outer loop.
  112493. ** Set it.
  112494. */
  112495. sqlite3VdbeResolveLabel(v, pWInfo->iBreak);
  112496. assert( pWInfo->nLevel<=pTabList->nSrc );
  112497. for(i=0, pLevel=pWInfo->a; i<pWInfo->nLevel; i++, pLevel++){
  112498. int k, last;
  112499. VdbeOp *pOp;
  112500. Index *pIdx = 0;
  112501. struct SrcList_item *pTabItem = &pTabList->a[pLevel->iFrom];
  112502. Table *pTab = pTabItem->pTab;
  112503. assert( pTab!=0 );
  112504. pLoop = pLevel->pWLoop;
  112505. /* For a co-routine, change all OP_Column references to the table of
  112506. ** the co-routine into OP_SCopy of result contained in a register.
  112507. ** OP_Rowid becomes OP_Null.
  112508. */
  112509. if( pTabItem->viaCoroutine && !db->mallocFailed ){
  112510. last = sqlite3VdbeCurrentAddr(v);
  112511. k = pLevel->addrBody;
  112512. pOp = sqlite3VdbeGetOp(v, k);
  112513. for(; k<last; k++, pOp++){
  112514. if( pOp->p1!=pLevel->iTabCur ) continue;
  112515. if( pOp->opcode==OP_Column ){
  112516. pOp->opcode = OP_Copy;
  112517. pOp->p1 = pOp->p2 + pTabItem->regResult;
  112518. pOp->p2 = pOp->p3;
  112519. pOp->p3 = 0;
  112520. }else if( pOp->opcode==OP_Rowid ){
  112521. pOp->opcode = OP_Null;
  112522. pOp->p1 = 0;
  112523. pOp->p3 = 0;
  112524. }
  112525. }
  112526. continue;
  112527. }
  112528. /* Close all of the cursors that were opened by sqlite3WhereBegin.
  112529. ** Except, do not close cursors that will be reused by the OR optimization
  112530. ** (WHERE_OMIT_OPEN_CLOSE). And do not close the OP_OpenWrite cursors
  112531. ** created for the ONEPASS optimization.
  112532. */
  112533. if( (pTab->tabFlags & TF_Ephemeral)==0
  112534. && pTab->pSelect==0
  112535. && (pWInfo->wctrlFlags & WHERE_OMIT_OPEN_CLOSE)==0
  112536. ){
  112537. int ws = pLoop->wsFlags;
  112538. if( !pWInfo->okOnePass && (ws & WHERE_IDX_ONLY)==0 ){
  112539. sqlite3VdbeAddOp1(v, OP_Close, pTabItem->iCursor);
  112540. }
  112541. if( (ws & WHERE_INDEXED)!=0
  112542. && (ws & (WHERE_IPK|WHERE_AUTO_INDEX))==0
  112543. && pLevel->iIdxCur!=pWInfo->aiCurOnePass[1]
  112544. ){
  112545. sqlite3VdbeAddOp1(v, OP_Close, pLevel->iIdxCur);
  112546. }
  112547. }
  112548. /* If this scan uses an index, make VDBE code substitutions to read data
  112549. ** from the index instead of from the table where possible. In some cases
  112550. ** this optimization prevents the table from ever being read, which can
  112551. ** yield a significant performance boost.
  112552. **
  112553. ** Calls to the code generator in between sqlite3WhereBegin and
  112554. ** sqlite3WhereEnd will have created code that references the table
  112555. ** directly. This loop scans all that code looking for opcodes
  112556. ** that reference the table and converts them into opcodes that
  112557. ** reference the index.
  112558. */
  112559. if( pLoop->wsFlags & (WHERE_INDEXED|WHERE_IDX_ONLY) ){
  112560. pIdx = pLoop->u.btree.pIndex;
  112561. }else if( pLoop->wsFlags & WHERE_MULTI_OR ){
  112562. pIdx = pLevel->u.pCovidx;
  112563. }
  112564. if( pIdx && !db->mallocFailed ){
  112565. last = sqlite3VdbeCurrentAddr(v);
  112566. k = pLevel->addrBody;
  112567. pOp = sqlite3VdbeGetOp(v, k);
  112568. for(; k<last; k++, pOp++){
  112569. if( pOp->p1!=pLevel->iTabCur ) continue;
  112570. if( pOp->opcode==OP_Column ){
  112571. int x = pOp->p2;
  112572. assert( pIdx->pTable==pTab );
  112573. if( !HasRowid(pTab) ){
  112574. Index *pPk = sqlite3PrimaryKeyIndex(pTab);
  112575. x = pPk->aiColumn[x];
  112576. }
  112577. x = sqlite3ColumnOfIndex(pIdx, x);
  112578. if( x>=0 ){
  112579. pOp->p2 = x;
  112580. pOp->p1 = pLevel->iIdxCur;
  112581. }
  112582. assert( (pLoop->wsFlags & WHERE_IDX_ONLY)==0 || x>=0 );
  112583. }else if( pOp->opcode==OP_Rowid ){
  112584. pOp->p1 = pLevel->iIdxCur;
  112585. pOp->opcode = OP_IdxRowid;
  112586. }
  112587. }
  112588. }
  112589. }
  112590. /* Final cleanup
  112591. */
  112592. pParse->nQueryLoop = pWInfo->savedNQueryLoop;
  112593. whereInfoFree(db, pWInfo);
  112594. return;
  112595. }
  112596. /************** End of where.c ***********************************************/
  112597. /************** Begin file parse.c *******************************************/
  112598. /* Driver template for the LEMON parser generator.
  112599. ** The author disclaims copyright to this source code.
  112600. **
  112601. ** This version of "lempar.c" is modified, slightly, for use by SQLite.
  112602. ** The only modifications are the addition of a couple of NEVER()
  112603. ** macros to disable tests that are needed in the case of a general
  112604. ** LALR(1) grammar but which are always false in the
  112605. ** specific grammar used by SQLite.
  112606. */
  112607. /* First off, code is included that follows the "include" declaration
  112608. ** in the input grammar file. */
  112609. /* #include <stdio.h> */
  112610. /*
  112611. ** Disable all error recovery processing in the parser push-down
  112612. ** automaton.
  112613. */
  112614. #define YYNOERRORRECOVERY 1
  112615. /*
  112616. ** Make yytestcase() the same as testcase()
  112617. */
  112618. #define yytestcase(X) testcase(X)
  112619. /*
  112620. ** An instance of this structure holds information about the
  112621. ** LIMIT clause of a SELECT statement.
  112622. */
  112623. struct LimitVal {
  112624. Expr *pLimit; /* The LIMIT expression. NULL if there is no limit */
  112625. Expr *pOffset; /* The OFFSET expression. NULL if there is none */
  112626. };
  112627. /*
  112628. ** An instance of this structure is used to store the LIKE,
  112629. ** GLOB, NOT LIKE, and NOT GLOB operators.
  112630. */
  112631. struct LikeOp {
  112632. Token eOperator; /* "like" or "glob" or "regexp" */
  112633. int bNot; /* True if the NOT keyword is present */
  112634. };
  112635. /*
  112636. ** An instance of the following structure describes the event of a
  112637. ** TRIGGER. "a" is the event type, one of TK_UPDATE, TK_INSERT,
  112638. ** TK_DELETE, or TK_INSTEAD. If the event is of the form
  112639. **
  112640. ** UPDATE ON (a,b,c)
  112641. **
  112642. ** Then the "b" IdList records the list "a,b,c".
  112643. */
  112644. struct TrigEvent { int a; IdList * b; };
  112645. /*
  112646. ** An instance of this structure holds the ATTACH key and the key type.
  112647. */
  112648. struct AttachKey { int type; Token key; };
  112649. /* This is a utility routine used to set the ExprSpan.zStart and
  112650. ** ExprSpan.zEnd values of pOut so that the span covers the complete
  112651. ** range of text beginning with pStart and going to the end of pEnd.
  112652. */
  112653. static void spanSet(ExprSpan *pOut, Token *pStart, Token *pEnd){
  112654. pOut->zStart = pStart->z;
  112655. pOut->zEnd = &pEnd->z[pEnd->n];
  112656. }
  112657. /* Construct a new Expr object from a single identifier. Use the
  112658. ** new Expr to populate pOut. Set the span of pOut to be the identifier
  112659. ** that created the expression.
  112660. */
  112661. static void spanExpr(ExprSpan *pOut, Parse *pParse, int op, Token *pValue){
  112662. pOut->pExpr = sqlite3PExpr(pParse, op, 0, 0, pValue);
  112663. pOut->zStart = pValue->z;
  112664. pOut->zEnd = &pValue->z[pValue->n];
  112665. }
  112666. /* This routine constructs a binary expression node out of two ExprSpan
  112667. ** objects and uses the result to populate a new ExprSpan object.
  112668. */
  112669. static void spanBinaryExpr(
  112670. ExprSpan *pOut, /* Write the result here */
  112671. Parse *pParse, /* The parsing context. Errors accumulate here */
  112672. int op, /* The binary operation */
  112673. ExprSpan *pLeft, /* The left operand */
  112674. ExprSpan *pRight /* The right operand */
  112675. ){
  112676. pOut->pExpr = sqlite3PExpr(pParse, op, pLeft->pExpr, pRight->pExpr, 0);
  112677. pOut->zStart = pLeft->zStart;
  112678. pOut->zEnd = pRight->zEnd;
  112679. }
  112680. /* Construct an expression node for a unary postfix operator
  112681. */
  112682. static void spanUnaryPostfix(
  112683. ExprSpan *pOut, /* Write the new expression node here */
  112684. Parse *pParse, /* Parsing context to record errors */
  112685. int op, /* The operator */
  112686. ExprSpan *pOperand, /* The operand */
  112687. Token *pPostOp /* The operand token for setting the span */
  112688. ){
  112689. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  112690. pOut->zStart = pOperand->zStart;
  112691. pOut->zEnd = &pPostOp->z[pPostOp->n];
  112692. }
  112693. /* A routine to convert a binary TK_IS or TK_ISNOT expression into a
  112694. ** unary TK_ISNULL or TK_NOTNULL expression. */
  112695. static void binaryToUnaryIfNull(Parse *pParse, Expr *pY, Expr *pA, int op){
  112696. sqlite3 *db = pParse->db;
  112697. if( pY && pA && pY->op==TK_NULL ){
  112698. pA->op = (u8)op;
  112699. sqlite3ExprDelete(db, pA->pRight);
  112700. pA->pRight = 0;
  112701. }
  112702. }
  112703. /* Construct an expression node for a unary prefix operator
  112704. */
  112705. static void spanUnaryPrefix(
  112706. ExprSpan *pOut, /* Write the new expression node here */
  112707. Parse *pParse, /* Parsing context to record errors */
  112708. int op, /* The operator */
  112709. ExprSpan *pOperand, /* The operand */
  112710. Token *pPreOp /* The operand token for setting the span */
  112711. ){
  112712. pOut->pExpr = sqlite3PExpr(pParse, op, pOperand->pExpr, 0, 0);
  112713. pOut->zStart = pPreOp->z;
  112714. pOut->zEnd = pOperand->zEnd;
  112715. }
  112716. /* Next is all token values, in a form suitable for use by makeheaders.
  112717. ** This section will be null unless lemon is run with the -m switch.
  112718. */
  112719. /*
  112720. ** These constants (all generated automatically by the parser generator)
  112721. ** specify the various kinds of tokens (terminals) that the parser
  112722. ** understands.
  112723. **
  112724. ** Each symbol here is a terminal symbol in the grammar.
  112725. */
  112726. /* Make sure the INTERFACE macro is defined.
  112727. */
  112728. #ifndef INTERFACE
  112729. # define INTERFACE 1
  112730. #endif
  112731. /* The next thing included is series of defines which control
  112732. ** various aspects of the generated parser.
  112733. ** YYCODETYPE is the data type used for storing terminal
  112734. ** and nonterminal numbers. "unsigned char" is
  112735. ** used if there are fewer than 250 terminals
  112736. ** and nonterminals. "int" is used otherwise.
  112737. ** YYNOCODE is a number of type YYCODETYPE which corresponds
  112738. ** to no legal terminal or nonterminal number. This
  112739. ** number is used to fill in empty slots of the hash
  112740. ** table.
  112741. ** YYFALLBACK If defined, this indicates that one or more tokens
  112742. ** have fall-back values which should be used if the
  112743. ** original value of the token will not parse.
  112744. ** YYACTIONTYPE is the data type used for storing terminal
  112745. ** and nonterminal numbers. "unsigned char" is
  112746. ** used if there are fewer than 250 rules and
  112747. ** states combined. "int" is used otherwise.
  112748. ** sqlite3ParserTOKENTYPE is the data type used for minor tokens given
  112749. ** directly to the parser from the tokenizer.
  112750. ** YYMINORTYPE is the data type used for all minor tokens.
  112751. ** This is typically a union of many types, one of
  112752. ** which is sqlite3ParserTOKENTYPE. The entry in the union
  112753. ** for base tokens is called "yy0".
  112754. ** YYSTACKDEPTH is the maximum depth of the parser's stack. If
  112755. ** zero the stack is dynamically sized using realloc()
  112756. ** sqlite3ParserARG_SDECL A static variable declaration for the %extra_argument
  112757. ** sqlite3ParserARG_PDECL A parameter declaration for the %extra_argument
  112758. ** sqlite3ParserARG_STORE Code to store %extra_argument into yypParser
  112759. ** sqlite3ParserARG_FETCH Code to extract %extra_argument from yypParser
  112760. ** YYNSTATE the combined number of states.
  112761. ** YYNRULE the number of rules in the grammar
  112762. ** YYERRORSYMBOL is the code number of the error symbol. If not
  112763. ** defined, then do no error processing.
  112764. */
  112765. #define YYCODETYPE unsigned char
  112766. #define YYNOCODE 254
  112767. #define YYACTIONTYPE unsigned short int
  112768. #define YYWILDCARD 70
  112769. #define sqlite3ParserTOKENTYPE Token
  112770. typedef union {
  112771. int yyinit;
  112772. sqlite3ParserTOKENTYPE yy0;
  112773. Select* yy3;
  112774. ExprList* yy14;
  112775. With* yy59;
  112776. SrcList* yy65;
  112777. struct LikeOp yy96;
  112778. Expr* yy132;
  112779. u8 yy186;
  112780. int yy328;
  112781. ExprSpan yy346;
  112782. struct TrigEvent yy378;
  112783. u16 yy381;
  112784. IdList* yy408;
  112785. struct {int value; int mask;} yy429;
  112786. TriggerStep* yy473;
  112787. struct LimitVal yy476;
  112788. } YYMINORTYPE;
  112789. #ifndef YYSTACKDEPTH
  112790. #define YYSTACKDEPTH 100
  112791. #endif
  112792. #define sqlite3ParserARG_SDECL Parse *pParse;
  112793. #define sqlite3ParserARG_PDECL ,Parse *pParse
  112794. #define sqlite3ParserARG_FETCH Parse *pParse = yypParser->pParse
  112795. #define sqlite3ParserARG_STORE yypParser->pParse = pParse
  112796. #define YYNSTATE 642
  112797. #define YYNRULE 327
  112798. #define YYFALLBACK 1
  112799. #define YY_NO_ACTION (YYNSTATE+YYNRULE+2)
  112800. #define YY_ACCEPT_ACTION (YYNSTATE+YYNRULE+1)
  112801. #define YY_ERROR_ACTION (YYNSTATE+YYNRULE)
  112802. /* The yyzerominor constant is used to initialize instances of
  112803. ** YYMINORTYPE objects to zero. */
  112804. static const YYMINORTYPE yyzerominor = { 0 };
  112805. /* Define the yytestcase() macro to be a no-op if is not already defined
  112806. ** otherwise.
  112807. **
  112808. ** Applications can choose to define yytestcase() in the %include section
  112809. ** to a macro that can assist in verifying code coverage. For production
  112810. ** code the yytestcase() macro should be turned off. But it is useful
  112811. ** for testing.
  112812. */
  112813. #ifndef yytestcase
  112814. # define yytestcase(X)
  112815. #endif
  112816. /* Next are the tables used to determine what action to take based on the
  112817. ** current state and lookahead token. These tables are used to implement
  112818. ** functions that take a state number and lookahead value and return an
  112819. ** action integer.
  112820. **
  112821. ** Suppose the action integer is N. Then the action is determined as
  112822. ** follows
  112823. **
  112824. ** 0 <= N < YYNSTATE Shift N. That is, push the lookahead
  112825. ** token onto the stack and goto state N.
  112826. **
  112827. ** YYNSTATE <= N < YYNSTATE+YYNRULE Reduce by rule N-YYNSTATE.
  112828. **
  112829. ** N == YYNSTATE+YYNRULE A syntax error has occurred.
  112830. **
  112831. ** N == YYNSTATE+YYNRULE+1 The parser accepts its input.
  112832. **
  112833. ** N == YYNSTATE+YYNRULE+2 No such action. Denotes unused
  112834. ** slots in the yy_action[] table.
  112835. **
  112836. ** The action table is constructed as a single large table named yy_action[].
  112837. ** Given state S and lookahead X, the action is computed as
  112838. **
  112839. ** yy_action[ yy_shift_ofst[S] + X ]
  112840. **
  112841. ** If the index value yy_shift_ofst[S]+X is out of range or if the value
  112842. ** yy_lookahead[yy_shift_ofst[S]+X] is not equal to X or if yy_shift_ofst[S]
  112843. ** is equal to YY_SHIFT_USE_DFLT, it means that the action is not in the table
  112844. ** and that yy_default[S] should be used instead.
  112845. **
  112846. ** The formula above is for computing the action when the lookahead is
  112847. ** a terminal symbol. If the lookahead is a non-terminal (as occurs after
  112848. ** a reduce action) then the yy_reduce_ofst[] array is used in place of
  112849. ** the yy_shift_ofst[] array and YY_REDUCE_USE_DFLT is used in place of
  112850. ** YY_SHIFT_USE_DFLT.
  112851. **
  112852. ** The following are the tables generated in this section:
  112853. **
  112854. ** yy_action[] A single table containing all actions.
  112855. ** yy_lookahead[] A table containing the lookahead for each entry in
  112856. ** yy_action. Used to detect hash collisions.
  112857. ** yy_shift_ofst[] For each state, the offset into yy_action for
  112858. ** shifting terminals.
  112859. ** yy_reduce_ofst[] For each state, the offset into yy_action for
  112860. ** shifting non-terminals after a reduce.
  112861. ** yy_default[] Default action for each state.
  112862. */
  112863. #define YY_ACTTAB_COUNT (1497)
  112864. static const YYACTIONTYPE yy_action[] = {
  112865. /* 0 */ 306, 212, 432, 955, 639, 191, 955, 295, 559, 88,
  112866. /* 10 */ 88, 88, 88, 81, 86, 86, 86, 86, 85, 85,
  112867. /* 20 */ 84, 84, 84, 83, 330, 185, 184, 183, 635, 635,
  112868. /* 30 */ 292, 606, 606, 88, 88, 88, 88, 683, 86, 86,
  112869. /* 40 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 16,
  112870. /* 50 */ 436, 597, 89, 90, 80, 600, 599, 601, 601, 87,
  112871. /* 60 */ 87, 88, 88, 88, 88, 684, 86, 86, 86, 86,
  112872. /* 70 */ 85, 85, 84, 84, 84, 83, 330, 306, 559, 84,
  112873. /* 80 */ 84, 84, 83, 330, 65, 86, 86, 86, 86, 85,
  112874. /* 90 */ 85, 84, 84, 84, 83, 330, 635, 635, 634, 633,
  112875. /* 100 */ 182, 682, 550, 379, 376, 375, 17, 322, 606, 606,
  112876. /* 110 */ 371, 198, 479, 91, 374, 82, 79, 165, 85, 85,
  112877. /* 120 */ 84, 84, 84, 83, 330, 598, 635, 635, 107, 89,
  112878. /* 130 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  112879. /* 140 */ 88, 88, 186, 86, 86, 86, 86, 85, 85, 84,
  112880. /* 150 */ 84, 84, 83, 330, 306, 594, 594, 142, 328, 327,
  112881. /* 160 */ 484, 249, 344, 238, 635, 635, 634, 633, 585, 448,
  112882. /* 170 */ 526, 525, 229, 388, 1, 394, 450, 584, 449, 635,
  112883. /* 180 */ 635, 635, 635, 319, 395, 606, 606, 199, 157, 273,
  112884. /* 190 */ 382, 268, 381, 187, 635, 635, 634, 633, 311, 555,
  112885. /* 200 */ 266, 593, 593, 266, 347, 588, 89, 90, 80, 600,
  112886. /* 210 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 478,
  112887. /* 220 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
  112888. /* 230 */ 330, 306, 272, 536, 634, 633, 146, 610, 197, 310,
  112889. /* 240 */ 575, 182, 482, 271, 379, 376, 375, 506, 21, 634,
  112890. /* 250 */ 633, 634, 633, 635, 635, 374, 611, 574, 548, 440,
  112891. /* 260 */ 111, 563, 606, 606, 634, 633, 324, 479, 608, 608,
  112892. /* 270 */ 608, 300, 435, 573, 119, 407, 210, 162, 562, 883,
  112893. /* 280 */ 592, 592, 306, 89, 90, 80, 600, 599, 601, 601,
  112894. /* 290 */ 87, 87, 88, 88, 88, 88, 506, 86, 86, 86,
  112895. /* 300 */ 86, 85, 85, 84, 84, 84, 83, 330, 620, 111,
  112896. /* 310 */ 635, 635, 361, 606, 606, 358, 249, 349, 248, 433,
  112897. /* 320 */ 243, 479, 586, 634, 633, 195, 611, 93, 119, 221,
  112898. /* 330 */ 575, 497, 534, 534, 89, 90, 80, 600, 599, 601,
  112899. /* 340 */ 601, 87, 87, 88, 88, 88, 88, 574, 86, 86,
  112900. /* 350 */ 86, 86, 85, 85, 84, 84, 84, 83, 330, 306,
  112901. /* 360 */ 77, 429, 638, 573, 589, 530, 240, 230, 242, 105,
  112902. /* 370 */ 249, 349, 248, 515, 588, 208, 460, 529, 564, 173,
  112903. /* 380 */ 634, 633, 970, 144, 430, 2, 424, 228, 380, 557,
  112904. /* 390 */ 606, 606, 190, 153, 159, 158, 514, 51, 632, 631,
  112905. /* 400 */ 630, 71, 536, 432, 954, 196, 610, 954, 614, 45,
  112906. /* 410 */ 18, 89, 90, 80, 600, 599, 601, 601, 87, 87,
  112907. /* 420 */ 88, 88, 88, 88, 261, 86, 86, 86, 86, 85,
  112908. /* 430 */ 85, 84, 84, 84, 83, 330, 306, 608, 608, 608,
  112909. /* 440 */ 542, 424, 402, 385, 241, 506, 451, 320, 211, 543,
  112910. /* 450 */ 164, 436, 386, 293, 451, 587, 108, 496, 111, 334,
  112911. /* 460 */ 391, 591, 424, 614, 27, 452, 453, 606, 606, 72,
  112912. /* 470 */ 257, 70, 259, 452, 339, 342, 564, 582, 68, 415,
  112913. /* 480 */ 469, 328, 327, 62, 614, 45, 110, 393, 89, 90,
  112914. /* 490 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
  112915. /* 500 */ 88, 152, 86, 86, 86, 86, 85, 85, 84, 84,
  112916. /* 510 */ 84, 83, 330, 306, 110, 499, 520, 538, 402, 389,
  112917. /* 520 */ 424, 110, 566, 500, 593, 593, 454, 82, 79, 165,
  112918. /* 530 */ 424, 591, 384, 564, 340, 615, 188, 162, 424, 350,
  112919. /* 540 */ 616, 424, 614, 44, 606, 606, 445, 582, 300, 434,
  112920. /* 550 */ 151, 19, 614, 9, 568, 580, 348, 615, 469, 567,
  112921. /* 560 */ 614, 26, 616, 614, 45, 89, 90, 80, 600, 599,
  112922. /* 570 */ 601, 601, 87, 87, 88, 88, 88, 88, 411, 86,
  112923. /* 580 */ 86, 86, 86, 85, 85, 84, 84, 84, 83, 330,
  112924. /* 590 */ 306, 579, 110, 578, 521, 282, 433, 398, 400, 255,
  112925. /* 600 */ 486, 82, 79, 165, 487, 164, 82, 79, 165, 488,
  112926. /* 610 */ 488, 364, 387, 424, 544, 544, 509, 350, 362, 155,
  112927. /* 620 */ 191, 606, 606, 559, 642, 640, 333, 82, 79, 165,
  112928. /* 630 */ 305, 564, 507, 312, 357, 614, 45, 329, 596, 595,
  112929. /* 640 */ 194, 337, 89, 90, 80, 600, 599, 601, 601, 87,
  112930. /* 650 */ 87, 88, 88, 88, 88, 424, 86, 86, 86, 86,
  112931. /* 660 */ 85, 85, 84, 84, 84, 83, 330, 306, 20, 323,
  112932. /* 670 */ 150, 263, 211, 543, 421, 596, 595, 614, 22, 424,
  112933. /* 680 */ 193, 424, 284, 424, 391, 424, 509, 424, 577, 424,
  112934. /* 690 */ 186, 335, 424, 559, 424, 313, 120, 546, 606, 606,
  112935. /* 700 */ 67, 614, 47, 614, 50, 614, 48, 614, 100, 614,
  112936. /* 710 */ 99, 614, 101, 576, 614, 102, 614, 109, 326, 89,
  112937. /* 720 */ 90, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  112938. /* 730 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
  112939. /* 740 */ 84, 84, 83, 330, 306, 424, 311, 424, 585, 54,
  112940. /* 750 */ 424, 516, 517, 590, 614, 112, 424, 584, 424, 572,
  112941. /* 760 */ 424, 195, 424, 571, 424, 67, 424, 614, 94, 614,
  112942. /* 770 */ 98, 424, 614, 97, 264, 606, 606, 195, 614, 46,
  112943. /* 780 */ 614, 96, 614, 30, 614, 49, 614, 115, 614, 114,
  112944. /* 790 */ 418, 229, 388, 614, 113, 306, 89, 90, 80, 600,
  112945. /* 800 */ 599, 601, 601, 87, 87, 88, 88, 88, 88, 424,
  112946. /* 810 */ 86, 86, 86, 86, 85, 85, 84, 84, 84, 83,
  112947. /* 820 */ 330, 119, 424, 590, 110, 372, 606, 606, 195, 53,
  112948. /* 830 */ 250, 614, 29, 195, 472, 438, 729, 190, 302, 498,
  112949. /* 840 */ 14, 523, 641, 2, 614, 43, 306, 89, 90, 80,
  112950. /* 850 */ 600, 599, 601, 601, 87, 87, 88, 88, 88, 88,
  112951. /* 860 */ 424, 86, 86, 86, 86, 85, 85, 84, 84, 84,
  112952. /* 870 */ 83, 330, 424, 613, 964, 964, 354, 606, 606, 420,
  112953. /* 880 */ 312, 64, 614, 42, 391, 355, 283, 437, 301, 255,
  112954. /* 890 */ 414, 410, 495, 492, 614, 28, 471, 306, 89, 90,
  112955. /* 900 */ 80, 600, 599, 601, 601, 87, 87, 88, 88, 88,
  112956. /* 910 */ 88, 424, 86, 86, 86, 86, 85, 85, 84, 84,
  112957. /* 920 */ 84, 83, 330, 424, 110, 110, 110, 110, 606, 606,
  112958. /* 930 */ 110, 254, 13, 614, 41, 532, 531, 283, 481, 531,
  112959. /* 940 */ 457, 284, 119, 561, 356, 614, 40, 284, 306, 89,
  112960. /* 950 */ 78, 80, 600, 599, 601, 601, 87, 87, 88, 88,
  112961. /* 960 */ 88, 88, 424, 86, 86, 86, 86, 85, 85, 84,
  112962. /* 970 */ 84, 84, 83, 330, 110, 424, 341, 220, 555, 606,
  112963. /* 980 */ 606, 351, 555, 318, 614, 95, 413, 255, 83, 330,
  112964. /* 990 */ 284, 284, 255, 640, 333, 356, 255, 614, 39, 306,
  112965. /* 1000 */ 356, 90, 80, 600, 599, 601, 601, 87, 87, 88,
  112966. /* 1010 */ 88, 88, 88, 424, 86, 86, 86, 86, 85, 85,
  112967. /* 1020 */ 84, 84, 84, 83, 330, 424, 317, 316, 141, 465,
  112968. /* 1030 */ 606, 606, 219, 619, 463, 614, 10, 417, 462, 255,
  112969. /* 1040 */ 189, 510, 553, 351, 207, 363, 161, 614, 38, 315,
  112970. /* 1050 */ 218, 255, 255, 80, 600, 599, 601, 601, 87, 87,
  112971. /* 1060 */ 88, 88, 88, 88, 424, 86, 86, 86, 86, 85,
  112972. /* 1070 */ 85, 84, 84, 84, 83, 330, 76, 419, 255, 3,
  112973. /* 1080 */ 878, 461, 424, 247, 331, 331, 614, 37, 217, 76,
  112974. /* 1090 */ 419, 390, 3, 216, 215, 422, 4, 331, 331, 424,
  112975. /* 1100 */ 547, 12, 424, 545, 614, 36, 424, 541, 422, 424,
  112976. /* 1110 */ 540, 424, 214, 424, 408, 424, 539, 403, 605, 605,
  112977. /* 1120 */ 237, 614, 25, 119, 614, 24, 588, 408, 614, 45,
  112978. /* 1130 */ 118, 614, 35, 614, 34, 614, 33, 614, 23, 588,
  112979. /* 1140 */ 60, 223, 603, 602, 513, 378, 73, 74, 140, 139,
  112980. /* 1150 */ 424, 110, 265, 75, 426, 425, 59, 424, 610, 73,
  112981. /* 1160 */ 74, 549, 402, 404, 424, 373, 75, 426, 425, 604,
  112982. /* 1170 */ 138, 610, 614, 11, 392, 76, 419, 181, 3, 614,
  112983. /* 1180 */ 32, 271, 369, 331, 331, 493, 614, 31, 149, 608,
  112984. /* 1190 */ 608, 608, 607, 15, 422, 365, 614, 8, 137, 489,
  112985. /* 1200 */ 136, 190, 608, 608, 608, 607, 15, 485, 176, 135,
  112986. /* 1210 */ 7, 252, 477, 408, 174, 133, 175, 474, 57, 56,
  112987. /* 1220 */ 132, 130, 119, 76, 419, 588, 3, 468, 245, 464,
  112988. /* 1230 */ 171, 331, 331, 125, 123, 456, 447, 122, 446, 104,
  112989. /* 1240 */ 336, 231, 422, 166, 154, 73, 74, 332, 116, 431,
  112990. /* 1250 */ 121, 309, 75, 426, 425, 222, 106, 610, 308, 637,
  112991. /* 1260 */ 204, 408, 629, 627, 628, 6, 200, 428, 427, 290,
  112992. /* 1270 */ 203, 622, 201, 588, 62, 63, 289, 66, 419, 399,
  112993. /* 1280 */ 3, 401, 288, 92, 143, 331, 331, 287, 608, 608,
  112994. /* 1290 */ 608, 607, 15, 73, 74, 227, 422, 325, 69, 416,
  112995. /* 1300 */ 75, 426, 425, 612, 412, 610, 192, 61, 569, 209,
  112996. /* 1310 */ 396, 226, 278, 225, 383, 408, 527, 558, 276, 533,
  112997. /* 1320 */ 552, 528, 321, 523, 370, 508, 180, 588, 494, 179,
  112998. /* 1330 */ 366, 117, 253, 269, 522, 503, 608, 608, 608, 607,
  112999. /* 1340 */ 15, 551, 502, 58, 274, 524, 178, 73, 74, 304,
  113000. /* 1350 */ 501, 368, 303, 206, 75, 426, 425, 491, 360, 610,
  113001. /* 1360 */ 213, 177, 483, 131, 345, 298, 297, 296, 202, 294,
  113002. /* 1370 */ 480, 490, 466, 134, 172, 129, 444, 346, 470, 128,
  113003. /* 1380 */ 314, 459, 103, 127, 126, 148, 124, 167, 443, 235,
  113004. /* 1390 */ 608, 608, 608, 607, 15, 442, 439, 623, 234, 299,
  113005. /* 1400 */ 145, 583, 291, 377, 581, 160, 119, 156, 270, 636,
  113006. /* 1410 */ 971, 169, 279, 626, 520, 625, 473, 624, 170, 621,
  113007. /* 1420 */ 618, 119, 168, 55, 409, 423, 537, 609, 286, 285,
  113008. /* 1430 */ 405, 570, 560, 556, 5, 52, 458, 554, 147, 267,
  113009. /* 1440 */ 519, 504, 518, 406, 262, 239, 260, 512, 343, 511,
  113010. /* 1450 */ 258, 353, 565, 256, 224, 251, 359, 277, 275, 476,
  113011. /* 1460 */ 475, 246, 352, 244, 467, 455, 236, 233, 232, 307,
  113012. /* 1470 */ 441, 281, 205, 163, 397, 280, 535, 505, 330, 617,
  113013. /* 1480 */ 971, 971, 971, 971, 367, 971, 971, 971, 971, 971,
  113014. /* 1490 */ 971, 971, 971, 971, 971, 971, 338,
  113015. };
  113016. static const YYCODETYPE yy_lookahead[] = {
  113017. /* 0 */ 19, 22, 22, 23, 1, 24, 26, 15, 27, 80,
  113018. /* 10 */ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90,
  113019. /* 20 */ 91, 92, 93, 94, 95, 108, 109, 110, 27, 28,
  113020. /* 30 */ 23, 50, 51, 80, 81, 82, 83, 122, 85, 86,
  113021. /* 40 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 22,
  113022. /* 50 */ 70, 23, 71, 72, 73, 74, 75, 76, 77, 78,
  113023. /* 60 */ 79, 80, 81, 82, 83, 122, 85, 86, 87, 88,
  113024. /* 70 */ 89, 90, 91, 92, 93, 94, 95, 19, 97, 91,
  113025. /* 80 */ 92, 93, 94, 95, 26, 85, 86, 87, 88, 89,
  113026. /* 90 */ 90, 91, 92, 93, 94, 95, 27, 28, 97, 98,
  113027. /* 100 */ 99, 122, 211, 102, 103, 104, 79, 19, 50, 51,
  113028. /* 110 */ 19, 122, 59, 55, 113, 224, 225, 226, 89, 90,
  113029. /* 120 */ 91, 92, 93, 94, 95, 23, 27, 28, 26, 71,
  113030. /* 130 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  113031. /* 140 */ 82, 83, 51, 85, 86, 87, 88, 89, 90, 91,
  113032. /* 150 */ 92, 93, 94, 95, 19, 132, 133, 58, 89, 90,
  113033. /* 160 */ 21, 108, 109, 110, 27, 28, 97, 98, 33, 100,
  113034. /* 170 */ 7, 8, 119, 120, 22, 19, 107, 42, 109, 27,
  113035. /* 180 */ 28, 27, 28, 95, 28, 50, 51, 99, 100, 101,
  113036. /* 190 */ 102, 103, 104, 105, 27, 28, 97, 98, 107, 152,
  113037. /* 200 */ 112, 132, 133, 112, 65, 69, 71, 72, 73, 74,
  113038. /* 210 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 11,
  113039. /* 220 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  113040. /* 230 */ 95, 19, 101, 97, 97, 98, 24, 101, 122, 157,
  113041. /* 240 */ 12, 99, 103, 112, 102, 103, 104, 152, 22, 97,
  113042. /* 250 */ 98, 97, 98, 27, 28, 113, 27, 29, 91, 164,
  113043. /* 260 */ 165, 124, 50, 51, 97, 98, 219, 59, 132, 133,
  113044. /* 270 */ 134, 22, 23, 45, 66, 47, 212, 213, 124, 140,
  113045. /* 280 */ 132, 133, 19, 71, 72, 73, 74, 75, 76, 77,
  113046. /* 290 */ 78, 79, 80, 81, 82, 83, 152, 85, 86, 87,
  113047. /* 300 */ 88, 89, 90, 91, 92, 93, 94, 95, 164, 165,
  113048. /* 310 */ 27, 28, 230, 50, 51, 233, 108, 109, 110, 70,
  113049. /* 320 */ 16, 59, 23, 97, 98, 26, 97, 22, 66, 185,
  113050. /* 330 */ 12, 187, 27, 28, 71, 72, 73, 74, 75, 76,
  113051. /* 340 */ 77, 78, 79, 80, 81, 82, 83, 29, 85, 86,
  113052. /* 350 */ 87, 88, 89, 90, 91, 92, 93, 94, 95, 19,
  113053. /* 360 */ 22, 148, 149, 45, 23, 47, 62, 154, 64, 156,
  113054. /* 370 */ 108, 109, 110, 37, 69, 23, 163, 59, 26, 26,
  113055. /* 380 */ 97, 98, 144, 145, 146, 147, 152, 200, 52, 23,
  113056. /* 390 */ 50, 51, 26, 22, 89, 90, 60, 210, 7, 8,
  113057. /* 400 */ 9, 138, 97, 22, 23, 26, 101, 26, 174, 175,
  113058. /* 410 */ 197, 71, 72, 73, 74, 75, 76, 77, 78, 79,
  113059. /* 420 */ 80, 81, 82, 83, 16, 85, 86, 87, 88, 89,
  113060. /* 430 */ 90, 91, 92, 93, 94, 95, 19, 132, 133, 134,
  113061. /* 440 */ 23, 152, 208, 209, 140, 152, 152, 111, 195, 196,
  113062. /* 450 */ 98, 70, 163, 160, 152, 23, 22, 164, 165, 246,
  113063. /* 460 */ 207, 27, 152, 174, 175, 171, 172, 50, 51, 137,
  113064. /* 470 */ 62, 139, 64, 171, 172, 222, 124, 27, 138, 24,
  113065. /* 480 */ 163, 89, 90, 130, 174, 175, 197, 163, 71, 72,
  113066. /* 490 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  113067. /* 500 */ 83, 22, 85, 86, 87, 88, 89, 90, 91, 92,
  113068. /* 510 */ 93, 94, 95, 19, 197, 181, 182, 23, 208, 209,
  113069. /* 520 */ 152, 197, 26, 189, 132, 133, 232, 224, 225, 226,
  113070. /* 530 */ 152, 97, 91, 26, 232, 116, 212, 213, 152, 222,
  113071. /* 540 */ 121, 152, 174, 175, 50, 51, 243, 97, 22, 23,
  113072. /* 550 */ 22, 234, 174, 175, 177, 23, 239, 116, 163, 177,
  113073. /* 560 */ 174, 175, 121, 174, 175, 71, 72, 73, 74, 75,
  113074. /* 570 */ 76, 77, 78, 79, 80, 81, 82, 83, 24, 85,
  113075. /* 580 */ 86, 87, 88, 89, 90, 91, 92, 93, 94, 95,
  113076. /* 590 */ 19, 23, 197, 11, 23, 227, 70, 208, 220, 152,
  113077. /* 600 */ 31, 224, 225, 226, 35, 98, 224, 225, 226, 108,
  113078. /* 610 */ 109, 110, 115, 152, 117, 118, 27, 222, 49, 123,
  113079. /* 620 */ 24, 50, 51, 27, 0, 1, 2, 224, 225, 226,
  113080. /* 630 */ 166, 124, 168, 169, 239, 174, 175, 170, 171, 172,
  113081. /* 640 */ 22, 194, 71, 72, 73, 74, 75, 76, 77, 78,
  113082. /* 650 */ 79, 80, 81, 82, 83, 152, 85, 86, 87, 88,
  113083. /* 660 */ 89, 90, 91, 92, 93, 94, 95, 19, 22, 208,
  113084. /* 670 */ 24, 23, 195, 196, 170, 171, 172, 174, 175, 152,
  113085. /* 680 */ 26, 152, 152, 152, 207, 152, 97, 152, 23, 152,
  113086. /* 690 */ 51, 244, 152, 97, 152, 247, 248, 23, 50, 51,
  113087. /* 700 */ 26, 174, 175, 174, 175, 174, 175, 174, 175, 174,
  113088. /* 710 */ 175, 174, 175, 23, 174, 175, 174, 175, 188, 71,
  113089. /* 720 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  113090. /* 730 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  113091. /* 740 */ 92, 93, 94, 95, 19, 152, 107, 152, 33, 24,
  113092. /* 750 */ 152, 100, 101, 27, 174, 175, 152, 42, 152, 23,
  113093. /* 760 */ 152, 26, 152, 23, 152, 26, 152, 174, 175, 174,
  113094. /* 770 */ 175, 152, 174, 175, 23, 50, 51, 26, 174, 175,
  113095. /* 780 */ 174, 175, 174, 175, 174, 175, 174, 175, 174, 175,
  113096. /* 790 */ 163, 119, 120, 174, 175, 19, 71, 72, 73, 74,
  113097. /* 800 */ 75, 76, 77, 78, 79, 80, 81, 82, 83, 152,
  113098. /* 810 */ 85, 86, 87, 88, 89, 90, 91, 92, 93, 94,
  113099. /* 820 */ 95, 66, 152, 97, 197, 23, 50, 51, 26, 53,
  113100. /* 830 */ 23, 174, 175, 26, 23, 23, 23, 26, 26, 26,
  113101. /* 840 */ 36, 106, 146, 147, 174, 175, 19, 71, 72, 73,
  113102. /* 850 */ 74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
  113103. /* 860 */ 152, 85, 86, 87, 88, 89, 90, 91, 92, 93,
  113104. /* 870 */ 94, 95, 152, 196, 119, 120, 19, 50, 51, 168,
  113105. /* 880 */ 169, 26, 174, 175, 207, 28, 152, 249, 250, 152,
  113106. /* 890 */ 163, 163, 163, 163, 174, 175, 163, 19, 71, 72,
  113107. /* 900 */ 73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
  113108. /* 910 */ 83, 152, 85, 86, 87, 88, 89, 90, 91, 92,
  113109. /* 920 */ 93, 94, 95, 152, 197, 197, 197, 197, 50, 51,
  113110. /* 930 */ 197, 194, 36, 174, 175, 191, 192, 152, 191, 192,
  113111. /* 940 */ 163, 152, 66, 124, 152, 174, 175, 152, 19, 71,
  113112. /* 950 */ 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
  113113. /* 960 */ 82, 83, 152, 85, 86, 87, 88, 89, 90, 91,
  113114. /* 970 */ 92, 93, 94, 95, 197, 152, 100, 188, 152, 50,
  113115. /* 980 */ 51, 152, 152, 188, 174, 175, 252, 152, 94, 95,
  113116. /* 990 */ 152, 152, 152, 1, 2, 152, 152, 174, 175, 19,
  113117. /* 1000 */ 152, 72, 73, 74, 75, 76, 77, 78, 79, 80,
  113118. /* 1010 */ 81, 82, 83, 152, 85, 86, 87, 88, 89, 90,
  113119. /* 1020 */ 91, 92, 93, 94, 95, 152, 188, 188, 22, 194,
  113120. /* 1030 */ 50, 51, 240, 173, 194, 174, 175, 252, 194, 152,
  113121. /* 1040 */ 36, 181, 28, 152, 23, 219, 122, 174, 175, 219,
  113122. /* 1050 */ 221, 152, 152, 73, 74, 75, 76, 77, 78, 79,
  113123. /* 1060 */ 80, 81, 82, 83, 152, 85, 86, 87, 88, 89,
  113124. /* 1070 */ 90, 91, 92, 93, 94, 95, 19, 20, 152, 22,
  113125. /* 1080 */ 23, 194, 152, 240, 27, 28, 174, 175, 240, 19,
  113126. /* 1090 */ 20, 26, 22, 194, 194, 38, 22, 27, 28, 152,
  113127. /* 1100 */ 23, 22, 152, 116, 174, 175, 152, 23, 38, 152,
  113128. /* 1110 */ 23, 152, 221, 152, 57, 152, 23, 163, 50, 51,
  113129. /* 1120 */ 194, 174, 175, 66, 174, 175, 69, 57, 174, 175,
  113130. /* 1130 */ 40, 174, 175, 174, 175, 174, 175, 174, 175, 69,
  113131. /* 1140 */ 22, 53, 74, 75, 30, 53, 89, 90, 22, 22,
  113132. /* 1150 */ 152, 197, 23, 96, 97, 98, 22, 152, 101, 89,
  113133. /* 1160 */ 90, 91, 208, 209, 152, 53, 96, 97, 98, 101,
  113134. /* 1170 */ 22, 101, 174, 175, 152, 19, 20, 105, 22, 174,
  113135. /* 1180 */ 175, 112, 19, 27, 28, 20, 174, 175, 24, 132,
  113136. /* 1190 */ 133, 134, 135, 136, 38, 44, 174, 175, 107, 61,
  113137. /* 1200 */ 54, 26, 132, 133, 134, 135, 136, 54, 107, 22,
  113138. /* 1210 */ 5, 140, 1, 57, 36, 111, 122, 28, 79, 79,
  113139. /* 1220 */ 131, 123, 66, 19, 20, 69, 22, 1, 16, 20,
  113140. /* 1230 */ 125, 27, 28, 123, 111, 120, 23, 131, 23, 16,
  113141. /* 1240 */ 68, 142, 38, 15, 22, 89, 90, 3, 167, 4,
  113142. /* 1250 */ 248, 251, 96, 97, 98, 180, 180, 101, 251, 151,
  113143. /* 1260 */ 6, 57, 151, 13, 151, 26, 25, 151, 161, 202,
  113144. /* 1270 */ 153, 162, 153, 69, 130, 128, 203, 19, 20, 127,
  113145. /* 1280 */ 22, 126, 204, 129, 22, 27, 28, 205, 132, 133,
  113146. /* 1290 */ 134, 135, 136, 89, 90, 231, 38, 95, 137, 179,
  113147. /* 1300 */ 96, 97, 98, 206, 179, 101, 122, 107, 159, 159,
  113148. /* 1310 */ 125, 231, 216, 228, 107, 57, 184, 217, 216, 176,
  113149. /* 1320 */ 217, 176, 48, 106, 18, 184, 158, 69, 159, 158,
  113150. /* 1330 */ 46, 71, 237, 176, 176, 176, 132, 133, 134, 135,
  113151. /* 1340 */ 136, 217, 176, 137, 216, 178, 158, 89, 90, 179,
  113152. /* 1350 */ 176, 159, 179, 159, 96, 97, 98, 159, 159, 101,
  113153. /* 1360 */ 5, 158, 202, 22, 18, 10, 11, 12, 13, 14,
  113154. /* 1370 */ 190, 238, 17, 190, 158, 193, 41, 159, 202, 193,
  113155. /* 1380 */ 159, 202, 245, 193, 193, 223, 190, 32, 159, 34,
  113156. /* 1390 */ 132, 133, 134, 135, 136, 159, 39, 155, 43, 150,
  113157. /* 1400 */ 223, 177, 201, 178, 177, 186, 66, 199, 177, 152,
  113158. /* 1410 */ 253, 56, 215, 152, 182, 152, 202, 152, 63, 152,
  113159. /* 1420 */ 152, 66, 67, 242, 229, 152, 174, 152, 152, 152,
  113160. /* 1430 */ 152, 152, 152, 152, 199, 242, 202, 152, 198, 152,
  113161. /* 1440 */ 152, 152, 183, 192, 152, 215, 152, 183, 215, 183,
  113162. /* 1450 */ 152, 241, 214, 152, 211, 152, 152, 211, 211, 152,
  113163. /* 1460 */ 152, 241, 152, 152, 152, 152, 152, 152, 152, 114,
  113164. /* 1470 */ 152, 152, 235, 152, 152, 152, 174, 187, 95, 174,
  113165. /* 1480 */ 253, 253, 253, 253, 236, 253, 253, 253, 253, 253,
  113166. /* 1490 */ 253, 253, 253, 253, 253, 253, 141,
  113167. };
  113168. #define YY_SHIFT_USE_DFLT (-86)
  113169. #define YY_SHIFT_COUNT (429)
  113170. #define YY_SHIFT_MIN (-85)
  113171. #define YY_SHIFT_MAX (1383)
  113172. static const short yy_shift_ofst[] = {
  113173. /* 0 */ 992, 1057, 1355, 1156, 1204, 1204, 1, 262, -19, 135,
  113174. /* 10 */ 135, 776, 1204, 1204, 1204, 1204, 69, 69, 53, 208,
  113175. /* 20 */ 283, 755, 58, 725, 648, 571, 494, 417, 340, 263,
  113176. /* 30 */ 212, 827, 827, 827, 827, 827, 827, 827, 827, 827,
  113177. /* 40 */ 827, 827, 827, 827, 827, 827, 878, 827, 929, 980,
  113178. /* 50 */ 980, 1070, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  113179. /* 60 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  113180. /* 70 */ 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  113181. /* 80 */ 1258, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204, 1204,
  113182. /* 90 */ 1204, 1204, 1204, 1204, -71, -47, -47, -47, -47, -47,
  113183. /* 100 */ 0, 29, -12, 283, 283, 139, 91, 392, 392, 894,
  113184. /* 110 */ 672, 726, 1383, -86, -86, -86, 88, 318, 318, 99,
  113185. /* 120 */ 381, -20, 283, 283, 283, 283, 283, 283, 283, 283,
  113186. /* 130 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  113187. /* 140 */ 283, 283, 283, 283, 624, 876, 726, 672, 1340, 1340,
  113188. /* 150 */ 1340, 1340, 1340, 1340, -86, -86, -86, 305, 136, 136,
  113189. /* 160 */ 142, 167, 226, 154, 137, 152, 283, 283, 283, 283,
  113190. /* 170 */ 283, 283, 283, 283, 283, 283, 283, 283, 283, 283,
  113191. /* 180 */ 283, 283, 283, 336, 336, 336, 283, 283, 352, 283,
  113192. /* 190 */ 283, 283, 283, 283, 228, 283, 283, 283, 283, 283,
  113193. /* 200 */ 283, 283, 283, 283, 283, 501, 569, 596, 596, 596,
  113194. /* 210 */ 507, 497, 441, 391, 353, 156, 156, 857, 353, 857,
  113195. /* 220 */ 735, 813, 639, 715, 156, 332, 715, 715, 496, 419,
  113196. /* 230 */ 646, 1357, 1184, 1184, 1335, 1335, 1184, 1341, 1260, 1144,
  113197. /* 240 */ 1346, 1346, 1346, 1346, 1184, 1306, 1144, 1341, 1260, 1260,
  113198. /* 250 */ 1144, 1184, 1306, 1206, 1284, 1184, 1184, 1306, 1184, 1306,
  113199. /* 260 */ 1184, 1306, 1262, 1207, 1207, 1207, 1274, 1262, 1207, 1217,
  113200. /* 270 */ 1207, 1274, 1207, 1207, 1185, 1200, 1185, 1200, 1185, 1200,
  113201. /* 280 */ 1184, 1184, 1161, 1262, 1202, 1202, 1262, 1154, 1155, 1147,
  113202. /* 290 */ 1152, 1144, 1241, 1239, 1250, 1250, 1254, 1254, 1254, 1254,
  113203. /* 300 */ -86, -86, -86, -86, -86, -86, 1068, 304, 526, 249,
  113204. /* 310 */ 408, -83, 434, 812, 27, 811, 807, 802, 751, 589,
  113205. /* 320 */ 651, 163, 131, 674, 366, 450, 299, 148, 23, 102,
  113206. /* 330 */ 229, -21, 1245, 1244, 1222, 1099, 1228, 1172, 1223, 1215,
  113207. /* 340 */ 1213, 1115, 1106, 1123, 1110, 1209, 1105, 1212, 1226, 1098,
  113208. /* 350 */ 1089, 1140, 1139, 1104, 1189, 1178, 1094, 1211, 1205, 1187,
  113209. /* 360 */ 1101, 1071, 1153, 1175, 1146, 1138, 1151, 1091, 1164, 1165,
  113210. /* 370 */ 1163, 1069, 1072, 1148, 1112, 1134, 1127, 1129, 1126, 1092,
  113211. /* 380 */ 1114, 1118, 1088, 1090, 1093, 1087, 1084, 987, 1079, 1077,
  113212. /* 390 */ 1074, 1065, 924, 1021, 1014, 1004, 1006, 819, 739, 896,
  113213. /* 400 */ 855, 804, 739, 740, 736, 690, 654, 665, 618, 582,
  113214. /* 410 */ 568, 528, 554, 379, 532, 479, 455, 379, 432, 371,
  113215. /* 420 */ 341, 28, 338, 116, -11, -57, -85, 7, -8, 3,
  113216. };
  113217. #define YY_REDUCE_USE_DFLT (-110)
  113218. #define YY_REDUCE_COUNT (305)
  113219. #define YY_REDUCE_MIN (-109)
  113220. #define YY_REDUCE_MAX (1323)
  113221. static const short yy_reduce_ofst[] = {
  113222. /* 0 */ 238, 954, 213, 289, 310, 234, 144, 317, -109, 382,
  113223. /* 10 */ 377, 303, 461, 389, 378, 368, 302, 294, 253, 395,
  113224. /* 20 */ 293, 324, 403, 403, 403, 403, 403, 403, 403, 403,
  113225. /* 30 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
  113226. /* 40 */ 403, 403, 403, 403, 403, 403, 403, 403, 403, 403,
  113227. /* 50 */ 403, 1022, 1012, 1005, 998, 963, 961, 959, 957, 950,
  113228. /* 60 */ 947, 930, 912, 873, 861, 823, 810, 771, 759, 720,
  113229. /* 70 */ 708, 670, 657, 619, 614, 612, 610, 608, 606, 604,
  113230. /* 80 */ 598, 595, 593, 580, 542, 540, 537, 535, 533, 531,
  113231. /* 90 */ 529, 527, 503, 386, 403, 403, 403, 403, 403, 403,
  113232. /* 100 */ 403, 403, 403, 95, 447, 82, 334, 504, 467, 403,
  113233. /* 110 */ 477, 464, 403, 403, 403, 403, 860, 747, 744, 785,
  113234. /* 120 */ 638, 638, 926, 891, 900, 899, 887, 844, 840, 835,
  113235. /* 130 */ 848, 830, 843, 829, 792, 839, 826, 737, 838, 795,
  113236. /* 140 */ 789, 47, 734, 530, 696, 777, 711, 677, 733, 730,
  113237. /* 150 */ 729, 728, 727, 627, 448, 64, 187, 1305, 1302, 1252,
  113238. /* 160 */ 1290, 1273, 1323, 1322, 1321, 1319, 1318, 1316, 1315, 1314,
  113239. /* 170 */ 1313, 1312, 1311, 1310, 1308, 1307, 1304, 1303, 1301, 1298,
  113240. /* 180 */ 1294, 1292, 1289, 1266, 1264, 1259, 1288, 1287, 1238, 1285,
  113241. /* 190 */ 1281, 1280, 1279, 1278, 1251, 1277, 1276, 1275, 1273, 1268,
  113242. /* 200 */ 1267, 1265, 1263, 1261, 1257, 1248, 1237, 1247, 1246, 1243,
  113243. /* 210 */ 1238, 1240, 1235, 1249, 1234, 1233, 1230, 1220, 1214, 1210,
  113244. /* 220 */ 1225, 1219, 1232, 1231, 1197, 1195, 1227, 1224, 1201, 1208,
  113245. /* 230 */ 1242, 1137, 1236, 1229, 1193, 1181, 1221, 1177, 1196, 1179,
  113246. /* 240 */ 1191, 1190, 1186, 1182, 1218, 1216, 1176, 1162, 1183, 1180,
  113247. /* 250 */ 1160, 1199, 1203, 1133, 1095, 1198, 1194, 1188, 1192, 1171,
  113248. /* 260 */ 1169, 1168, 1173, 1174, 1166, 1159, 1141, 1170, 1158, 1167,
  113249. /* 270 */ 1157, 1132, 1145, 1143, 1124, 1128, 1103, 1102, 1100, 1096,
  113250. /* 280 */ 1150, 1149, 1085, 1125, 1080, 1064, 1120, 1097, 1082, 1078,
  113251. /* 290 */ 1073, 1067, 1109, 1107, 1119, 1117, 1116, 1113, 1111, 1108,
  113252. /* 300 */ 1007, 1000, 1002, 1076, 1075, 1081,
  113253. };
  113254. static const YYACTIONTYPE yy_default[] = {
  113255. /* 0 */ 647, 964, 964, 964, 878, 878, 969, 964, 774, 802,
  113256. /* 10 */ 802, 938, 969, 969, 969, 876, 969, 969, 969, 964,
  113257. /* 20 */ 969, 778, 808, 969, 969, 969, 969, 969, 969, 969,
  113258. /* 30 */ 969, 937, 939, 816, 815, 918, 789, 813, 806, 810,
  113259. /* 40 */ 879, 872, 873, 871, 875, 880, 969, 809, 841, 856,
  113260. /* 50 */ 840, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113261. /* 60 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113262. /* 70 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113263. /* 80 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113264. /* 90 */ 969, 969, 969, 969, 850, 855, 862, 854, 851, 843,
  113265. /* 100 */ 842, 844, 845, 969, 969, 673, 739, 969, 969, 846,
  113266. /* 110 */ 969, 685, 847, 859, 858, 857, 680, 969, 969, 969,
  113267. /* 120 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113268. /* 130 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113269. /* 140 */ 969, 969, 969, 969, 647, 964, 969, 969, 964, 964,
  113270. /* 150 */ 964, 964, 964, 964, 956, 778, 768, 969, 969, 969,
  113271. /* 160 */ 969, 969, 969, 969, 969, 969, 969, 944, 942, 969,
  113272. /* 170 */ 891, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113273. /* 180 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113274. /* 190 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113275. /* 200 */ 969, 969, 969, 969, 653, 969, 911, 774, 774, 774,
  113276. /* 210 */ 776, 754, 766, 655, 812, 791, 791, 923, 812, 923,
  113277. /* 220 */ 710, 733, 707, 802, 791, 874, 802, 802, 775, 766,
  113278. /* 230 */ 969, 949, 782, 782, 941, 941, 782, 821, 743, 812,
  113279. /* 240 */ 750, 750, 750, 750, 782, 670, 812, 821, 743, 743,
  113280. /* 250 */ 812, 782, 670, 917, 915, 782, 782, 670, 782, 670,
  113281. /* 260 */ 782, 670, 884, 741, 741, 741, 725, 884, 741, 710,
  113282. /* 270 */ 741, 725, 741, 741, 795, 790, 795, 790, 795, 790,
  113283. /* 280 */ 782, 782, 969, 884, 888, 888, 884, 807, 796, 805,
  113284. /* 290 */ 803, 812, 676, 728, 663, 663, 652, 652, 652, 652,
  113285. /* 300 */ 961, 961, 956, 712, 712, 695, 969, 969, 969, 969,
  113286. /* 310 */ 969, 969, 687, 969, 893, 969, 969, 969, 969, 969,
  113287. /* 320 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113288. /* 330 */ 969, 828, 969, 648, 951, 969, 969, 948, 969, 969,
  113289. /* 340 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113290. /* 350 */ 969, 969, 969, 969, 969, 969, 921, 969, 969, 969,
  113291. /* 360 */ 969, 969, 969, 914, 913, 969, 969, 969, 969, 969,
  113292. /* 370 */ 969, 969, 969, 969, 969, 969, 969, 969, 969, 969,
  113293. /* 380 */ 969, 969, 969, 969, 969, 969, 969, 757, 969, 969,
  113294. /* 390 */ 969, 761, 969, 969, 969, 969, 969, 969, 804, 969,
  113295. /* 400 */ 797, 969, 877, 969, 969, 969, 969, 969, 969, 969,
  113296. /* 410 */ 969, 969, 969, 966, 969, 969, 969, 965, 969, 969,
  113297. /* 420 */ 969, 969, 969, 830, 969, 829, 833, 969, 661, 969,
  113298. /* 430 */ 644, 649, 960, 963, 962, 959, 958, 957, 952, 950,
  113299. /* 440 */ 947, 946, 945, 943, 940, 936, 897, 895, 902, 901,
  113300. /* 450 */ 900, 899, 898, 896, 894, 892, 818, 817, 814, 811,
  113301. /* 460 */ 753, 935, 890, 752, 749, 748, 669, 953, 920, 929,
  113302. /* 470 */ 928, 927, 822, 926, 925, 924, 922, 919, 906, 820,
  113303. /* 480 */ 819, 744, 882, 881, 672, 910, 909, 908, 912, 916,
  113304. /* 490 */ 907, 784, 751, 671, 668, 675, 679, 731, 732, 740,
  113305. /* 500 */ 738, 737, 736, 735, 734, 730, 681, 686, 724, 709,
  113306. /* 510 */ 708, 717, 716, 722, 721, 720, 719, 718, 715, 714,
  113307. /* 520 */ 713, 706, 705, 711, 704, 727, 726, 723, 703, 747,
  113308. /* 530 */ 746, 745, 742, 702, 701, 700, 833, 699, 698, 838,
  113309. /* 540 */ 837, 866, 826, 755, 759, 758, 762, 763, 771, 770,
  113310. /* 550 */ 769, 780, 781, 793, 792, 824, 823, 794, 779, 773,
  113311. /* 560 */ 772, 788, 787, 786, 785, 777, 767, 799, 798, 868,
  113312. /* 570 */ 783, 867, 865, 934, 933, 932, 931, 930, 870, 967,
  113313. /* 580 */ 968, 887, 889, 886, 801, 800, 885, 869, 839, 836,
  113314. /* 590 */ 690, 691, 905, 904, 903, 693, 692, 689, 688, 863,
  113315. /* 600 */ 860, 852, 864, 861, 853, 849, 848, 834, 832, 831,
  113316. /* 610 */ 827, 835, 760, 756, 825, 765, 764, 697, 696, 694,
  113317. /* 620 */ 678, 677, 674, 667, 665, 664, 666, 662, 660, 659,
  113318. /* 630 */ 658, 657, 656, 684, 683, 682, 654, 651, 650, 646,
  113319. /* 640 */ 645, 643,
  113320. };
  113321. /* The next table maps tokens into fallback tokens. If a construct
  113322. ** like the following:
  113323. **
  113324. ** %fallback ID X Y Z.
  113325. **
  113326. ** appears in the grammar, then ID becomes a fallback token for X, Y,
  113327. ** and Z. Whenever one of the tokens X, Y, or Z is input to the parser
  113328. ** but it does not parse, the type of the token is changed to ID and
  113329. ** the parse is retried before an error is thrown.
  113330. */
  113331. #ifdef YYFALLBACK
  113332. static const YYCODETYPE yyFallback[] = {
  113333. 0, /* $ => nothing */
  113334. 0, /* SEMI => nothing */
  113335. 27, /* EXPLAIN => ID */
  113336. 27, /* QUERY => ID */
  113337. 27, /* PLAN => ID */
  113338. 27, /* BEGIN => ID */
  113339. 0, /* TRANSACTION => nothing */
  113340. 27, /* DEFERRED => ID */
  113341. 27, /* IMMEDIATE => ID */
  113342. 27, /* EXCLUSIVE => ID */
  113343. 0, /* COMMIT => nothing */
  113344. 27, /* END => ID */
  113345. 27, /* ROLLBACK => ID */
  113346. 27, /* SAVEPOINT => ID */
  113347. 27, /* RELEASE => ID */
  113348. 0, /* TO => nothing */
  113349. 0, /* TABLE => nothing */
  113350. 0, /* CREATE => nothing */
  113351. 27, /* IF => ID */
  113352. 0, /* NOT => nothing */
  113353. 0, /* EXISTS => nothing */
  113354. 27, /* TEMP => ID */
  113355. 0, /* LP => nothing */
  113356. 0, /* RP => nothing */
  113357. 0, /* AS => nothing */
  113358. 27, /* WITHOUT => ID */
  113359. 0, /* COMMA => nothing */
  113360. 0, /* ID => nothing */
  113361. 0, /* INDEXED => nothing */
  113362. 27, /* ABORT => ID */
  113363. 27, /* ACTION => ID */
  113364. 27, /* AFTER => ID */
  113365. 27, /* ANALYZE => ID */
  113366. 27, /* ASC => ID */
  113367. 27, /* ATTACH => ID */
  113368. 27, /* BEFORE => ID */
  113369. 27, /* BY => ID */
  113370. 27, /* CASCADE => ID */
  113371. 27, /* CAST => ID */
  113372. 27, /* COLUMNKW => ID */
  113373. 27, /* CONFLICT => ID */
  113374. 27, /* DATABASE => ID */
  113375. 27, /* DESC => ID */
  113376. 27, /* DETACH => ID */
  113377. 27, /* EACH => ID */
  113378. 27, /* FAIL => ID */
  113379. 27, /* FOR => ID */
  113380. 27, /* IGNORE => ID */
  113381. 27, /* INITIALLY => ID */
  113382. 27, /* INSTEAD => ID */
  113383. 27, /* LIKE_KW => ID */
  113384. 27, /* MATCH => ID */
  113385. 27, /* NO => ID */
  113386. 27, /* KEY => ID */
  113387. 27, /* OF => ID */
  113388. 27, /* OFFSET => ID */
  113389. 27, /* PRAGMA => ID */
  113390. 27, /* RAISE => ID */
  113391. 27, /* RECURSIVE => ID */
  113392. 27, /* REPLACE => ID */
  113393. 27, /* RESTRICT => ID */
  113394. 27, /* ROW => ID */
  113395. 27, /* TRIGGER => ID */
  113396. 27, /* VACUUM => ID */
  113397. 27, /* VIEW => ID */
  113398. 27, /* VIRTUAL => ID */
  113399. 27, /* WITH => ID */
  113400. 27, /* REINDEX => ID */
  113401. 27, /* RENAME => ID */
  113402. 27, /* CTIME_KW => ID */
  113403. };
  113404. #endif /* YYFALLBACK */
  113405. /* The following structure represents a single element of the
  113406. ** parser's stack. Information stored includes:
  113407. **
  113408. ** + The state number for the parser at this level of the stack.
  113409. **
  113410. ** + The value of the token stored at this level of the stack.
  113411. ** (In other words, the "major" token.)
  113412. **
  113413. ** + The semantic value stored at this level of the stack. This is
  113414. ** the information used by the action routines in the grammar.
  113415. ** It is sometimes called the "minor" token.
  113416. */
  113417. struct yyStackEntry {
  113418. YYACTIONTYPE stateno; /* The state-number */
  113419. YYCODETYPE major; /* The major token value. This is the code
  113420. ** number for the token at this stack level */
  113421. YYMINORTYPE minor; /* The user-supplied minor token value. This
  113422. ** is the value of the token */
  113423. };
  113424. typedef struct yyStackEntry yyStackEntry;
  113425. /* The state of the parser is completely contained in an instance of
  113426. ** the following structure */
  113427. struct yyParser {
  113428. int yyidx; /* Index of top element in stack */
  113429. #ifdef YYTRACKMAXSTACKDEPTH
  113430. int yyidxMax; /* Maximum value of yyidx */
  113431. #endif
  113432. int yyerrcnt; /* Shifts left before out of the error */
  113433. sqlite3ParserARG_SDECL /* A place to hold %extra_argument */
  113434. #if YYSTACKDEPTH<=0
  113435. int yystksz; /* Current side of the stack */
  113436. yyStackEntry *yystack; /* The parser's stack */
  113437. #else
  113438. yyStackEntry yystack[YYSTACKDEPTH]; /* The parser's stack */
  113439. #endif
  113440. };
  113441. typedef struct yyParser yyParser;
  113442. #ifndef NDEBUG
  113443. /* #include <stdio.h> */
  113444. static FILE *yyTraceFILE = 0;
  113445. static char *yyTracePrompt = 0;
  113446. #endif /* NDEBUG */
  113447. #ifndef NDEBUG
  113448. /*
  113449. ** Turn parser tracing on by giving a stream to which to write the trace
  113450. ** and a prompt to preface each trace message. Tracing is turned off
  113451. ** by making either argument NULL
  113452. **
  113453. ** Inputs:
  113454. ** <ul>
  113455. ** <li> A FILE* to which trace output should be written.
  113456. ** If NULL, then tracing is turned off.
  113457. ** <li> A prefix string written at the beginning of every
  113458. ** line of trace output. If NULL, then tracing is
  113459. ** turned off.
  113460. ** </ul>
  113461. **
  113462. ** Outputs:
  113463. ** None.
  113464. */
  113465. SQLITE_PRIVATE void sqlite3ParserTrace(FILE *TraceFILE, char *zTracePrompt){
  113466. yyTraceFILE = TraceFILE;
  113467. yyTracePrompt = zTracePrompt;
  113468. if( yyTraceFILE==0 ) yyTracePrompt = 0;
  113469. else if( yyTracePrompt==0 ) yyTraceFILE = 0;
  113470. }
  113471. #endif /* NDEBUG */
  113472. #ifndef NDEBUG
  113473. /* For tracing shifts, the names of all terminals and nonterminals
  113474. ** are required. The following table supplies these names */
  113475. static const char *const yyTokenName[] = {
  113476. "$", "SEMI", "EXPLAIN", "QUERY",
  113477. "PLAN", "BEGIN", "TRANSACTION", "DEFERRED",
  113478. "IMMEDIATE", "EXCLUSIVE", "COMMIT", "END",
  113479. "ROLLBACK", "SAVEPOINT", "RELEASE", "TO",
  113480. "TABLE", "CREATE", "IF", "NOT",
  113481. "EXISTS", "TEMP", "LP", "RP",
  113482. "AS", "WITHOUT", "COMMA", "ID",
  113483. "INDEXED", "ABORT", "ACTION", "AFTER",
  113484. "ANALYZE", "ASC", "ATTACH", "BEFORE",
  113485. "BY", "CASCADE", "CAST", "COLUMNKW",
  113486. "CONFLICT", "DATABASE", "DESC", "DETACH",
  113487. "EACH", "FAIL", "FOR", "IGNORE",
  113488. "INITIALLY", "INSTEAD", "LIKE_KW", "MATCH",
  113489. "NO", "KEY", "OF", "OFFSET",
  113490. "PRAGMA", "RAISE", "RECURSIVE", "REPLACE",
  113491. "RESTRICT", "ROW", "TRIGGER", "VACUUM",
  113492. "VIEW", "VIRTUAL", "WITH", "REINDEX",
  113493. "RENAME", "CTIME_KW", "ANY", "OR",
  113494. "AND", "IS", "BETWEEN", "IN",
  113495. "ISNULL", "NOTNULL", "NE", "EQ",
  113496. "GT", "LE", "LT", "GE",
  113497. "ESCAPE", "BITAND", "BITOR", "LSHIFT",
  113498. "RSHIFT", "PLUS", "MINUS", "STAR",
  113499. "SLASH", "REM", "CONCAT", "COLLATE",
  113500. "BITNOT", "STRING", "JOIN_KW", "CONSTRAINT",
  113501. "DEFAULT", "NULL", "PRIMARY", "UNIQUE",
  113502. "CHECK", "REFERENCES", "AUTOINCR", "ON",
  113503. "INSERT", "DELETE", "UPDATE", "SET",
  113504. "DEFERRABLE", "FOREIGN", "DROP", "UNION",
  113505. "ALL", "EXCEPT", "INTERSECT", "SELECT",
  113506. "VALUES", "DISTINCT", "DOT", "FROM",
  113507. "JOIN", "USING", "ORDER", "GROUP",
  113508. "HAVING", "LIMIT", "WHERE", "INTO",
  113509. "INTEGER", "FLOAT", "BLOB", "VARIABLE",
  113510. "CASE", "WHEN", "THEN", "ELSE",
  113511. "INDEX", "ALTER", "ADD", "error",
  113512. "input", "cmdlist", "ecmd", "explain",
  113513. "cmdx", "cmd", "transtype", "trans_opt",
  113514. "nm", "savepoint_opt", "create_table", "create_table_args",
  113515. "createkw", "temp", "ifnotexists", "dbnm",
  113516. "columnlist", "conslist_opt", "table_options", "select",
  113517. "column", "columnid", "type", "carglist",
  113518. "typetoken", "typename", "signed", "plus_num",
  113519. "minus_num", "ccons", "term", "expr",
  113520. "onconf", "sortorder", "autoinc", "idxlist_opt",
  113521. "refargs", "defer_subclause", "refarg", "refact",
  113522. "init_deferred_pred_opt", "conslist", "tconscomma", "tcons",
  113523. "idxlist", "defer_subclause_opt", "orconf", "resolvetype",
  113524. "raisetype", "ifexists", "fullname", "selectnowith",
  113525. "oneselect", "with", "multiselect_op", "distinct",
  113526. "selcollist", "from", "where_opt", "groupby_opt",
  113527. "having_opt", "orderby_opt", "limit_opt", "values",
  113528. "nexprlist", "exprlist", "sclp", "as",
  113529. "seltablist", "stl_prefix", "joinop", "indexed_opt",
  113530. "on_opt", "using_opt", "joinop2", "idlist",
  113531. "sortlist", "setlist", "insert_cmd", "inscollist_opt",
  113532. "likeop", "between_op", "in_op", "case_operand",
  113533. "case_exprlist", "case_else", "uniqueflag", "collate",
  113534. "nmnum", "trigger_decl", "trigger_cmd_list", "trigger_time",
  113535. "trigger_event", "foreach_clause", "when_clause", "trigger_cmd",
  113536. "trnm", "tridxby", "database_kw_opt", "key_opt",
  113537. "add_column_fullname", "kwcolumn_opt", "create_vtab", "vtabarglist",
  113538. "vtabarg", "vtabargtoken", "lp", "anylist",
  113539. "wqlist",
  113540. };
  113541. #endif /* NDEBUG */
  113542. #ifndef NDEBUG
  113543. /* For tracing reduce actions, the names of all rules are required.
  113544. */
  113545. static const char *const yyRuleName[] = {
  113546. /* 0 */ "input ::= cmdlist",
  113547. /* 1 */ "cmdlist ::= cmdlist ecmd",
  113548. /* 2 */ "cmdlist ::= ecmd",
  113549. /* 3 */ "ecmd ::= SEMI",
  113550. /* 4 */ "ecmd ::= explain cmdx SEMI",
  113551. /* 5 */ "explain ::=",
  113552. /* 6 */ "explain ::= EXPLAIN",
  113553. /* 7 */ "explain ::= EXPLAIN QUERY PLAN",
  113554. /* 8 */ "cmdx ::= cmd",
  113555. /* 9 */ "cmd ::= BEGIN transtype trans_opt",
  113556. /* 10 */ "trans_opt ::=",
  113557. /* 11 */ "trans_opt ::= TRANSACTION",
  113558. /* 12 */ "trans_opt ::= TRANSACTION nm",
  113559. /* 13 */ "transtype ::=",
  113560. /* 14 */ "transtype ::= DEFERRED",
  113561. /* 15 */ "transtype ::= IMMEDIATE",
  113562. /* 16 */ "transtype ::= EXCLUSIVE",
  113563. /* 17 */ "cmd ::= COMMIT trans_opt",
  113564. /* 18 */ "cmd ::= END trans_opt",
  113565. /* 19 */ "cmd ::= ROLLBACK trans_opt",
  113566. /* 20 */ "savepoint_opt ::= SAVEPOINT",
  113567. /* 21 */ "savepoint_opt ::=",
  113568. /* 22 */ "cmd ::= SAVEPOINT nm",
  113569. /* 23 */ "cmd ::= RELEASE savepoint_opt nm",
  113570. /* 24 */ "cmd ::= ROLLBACK trans_opt TO savepoint_opt nm",
  113571. /* 25 */ "cmd ::= create_table create_table_args",
  113572. /* 26 */ "create_table ::= createkw temp TABLE ifnotexists nm dbnm",
  113573. /* 27 */ "createkw ::= CREATE",
  113574. /* 28 */ "ifnotexists ::=",
  113575. /* 29 */ "ifnotexists ::= IF NOT EXISTS",
  113576. /* 30 */ "temp ::= TEMP",
  113577. /* 31 */ "temp ::=",
  113578. /* 32 */ "create_table_args ::= LP columnlist conslist_opt RP table_options",
  113579. /* 33 */ "create_table_args ::= AS select",
  113580. /* 34 */ "table_options ::=",
  113581. /* 35 */ "table_options ::= WITHOUT nm",
  113582. /* 36 */ "columnlist ::= columnlist COMMA column",
  113583. /* 37 */ "columnlist ::= column",
  113584. /* 38 */ "column ::= columnid type carglist",
  113585. /* 39 */ "columnid ::= nm",
  113586. /* 40 */ "nm ::= ID|INDEXED",
  113587. /* 41 */ "nm ::= STRING",
  113588. /* 42 */ "nm ::= JOIN_KW",
  113589. /* 43 */ "type ::=",
  113590. /* 44 */ "type ::= typetoken",
  113591. /* 45 */ "typetoken ::= typename",
  113592. /* 46 */ "typetoken ::= typename LP signed RP",
  113593. /* 47 */ "typetoken ::= typename LP signed COMMA signed RP",
  113594. /* 48 */ "typename ::= ID|STRING",
  113595. /* 49 */ "typename ::= typename ID|STRING",
  113596. /* 50 */ "signed ::= plus_num",
  113597. /* 51 */ "signed ::= minus_num",
  113598. /* 52 */ "carglist ::= carglist ccons",
  113599. /* 53 */ "carglist ::=",
  113600. /* 54 */ "ccons ::= CONSTRAINT nm",
  113601. /* 55 */ "ccons ::= DEFAULT term",
  113602. /* 56 */ "ccons ::= DEFAULT LP expr RP",
  113603. /* 57 */ "ccons ::= DEFAULT PLUS term",
  113604. /* 58 */ "ccons ::= DEFAULT MINUS term",
  113605. /* 59 */ "ccons ::= DEFAULT ID|INDEXED",
  113606. /* 60 */ "ccons ::= NULL onconf",
  113607. /* 61 */ "ccons ::= NOT NULL onconf",
  113608. /* 62 */ "ccons ::= PRIMARY KEY sortorder onconf autoinc",
  113609. /* 63 */ "ccons ::= UNIQUE onconf",
  113610. /* 64 */ "ccons ::= CHECK LP expr RP",
  113611. /* 65 */ "ccons ::= REFERENCES nm idxlist_opt refargs",
  113612. /* 66 */ "ccons ::= defer_subclause",
  113613. /* 67 */ "ccons ::= COLLATE ID|STRING",
  113614. /* 68 */ "autoinc ::=",
  113615. /* 69 */ "autoinc ::= AUTOINCR",
  113616. /* 70 */ "refargs ::=",
  113617. /* 71 */ "refargs ::= refargs refarg",
  113618. /* 72 */ "refarg ::= MATCH nm",
  113619. /* 73 */ "refarg ::= ON INSERT refact",
  113620. /* 74 */ "refarg ::= ON DELETE refact",
  113621. /* 75 */ "refarg ::= ON UPDATE refact",
  113622. /* 76 */ "refact ::= SET NULL",
  113623. /* 77 */ "refact ::= SET DEFAULT",
  113624. /* 78 */ "refact ::= CASCADE",
  113625. /* 79 */ "refact ::= RESTRICT",
  113626. /* 80 */ "refact ::= NO ACTION",
  113627. /* 81 */ "defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt",
  113628. /* 82 */ "defer_subclause ::= DEFERRABLE init_deferred_pred_opt",
  113629. /* 83 */ "init_deferred_pred_opt ::=",
  113630. /* 84 */ "init_deferred_pred_opt ::= INITIALLY DEFERRED",
  113631. /* 85 */ "init_deferred_pred_opt ::= INITIALLY IMMEDIATE",
  113632. /* 86 */ "conslist_opt ::=",
  113633. /* 87 */ "conslist_opt ::= COMMA conslist",
  113634. /* 88 */ "conslist ::= conslist tconscomma tcons",
  113635. /* 89 */ "conslist ::= tcons",
  113636. /* 90 */ "tconscomma ::= COMMA",
  113637. /* 91 */ "tconscomma ::=",
  113638. /* 92 */ "tcons ::= CONSTRAINT nm",
  113639. /* 93 */ "tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf",
  113640. /* 94 */ "tcons ::= UNIQUE LP idxlist RP onconf",
  113641. /* 95 */ "tcons ::= CHECK LP expr RP onconf",
  113642. /* 96 */ "tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt",
  113643. /* 97 */ "defer_subclause_opt ::=",
  113644. /* 98 */ "defer_subclause_opt ::= defer_subclause",
  113645. /* 99 */ "onconf ::=",
  113646. /* 100 */ "onconf ::= ON CONFLICT resolvetype",
  113647. /* 101 */ "orconf ::=",
  113648. /* 102 */ "orconf ::= OR resolvetype",
  113649. /* 103 */ "resolvetype ::= raisetype",
  113650. /* 104 */ "resolvetype ::= IGNORE",
  113651. /* 105 */ "resolvetype ::= REPLACE",
  113652. /* 106 */ "cmd ::= DROP TABLE ifexists fullname",
  113653. /* 107 */ "ifexists ::= IF EXISTS",
  113654. /* 108 */ "ifexists ::=",
  113655. /* 109 */ "cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select",
  113656. /* 110 */ "cmd ::= DROP VIEW ifexists fullname",
  113657. /* 111 */ "cmd ::= select",
  113658. /* 112 */ "select ::= with selectnowith",
  113659. /* 113 */ "selectnowith ::= oneselect",
  113660. /* 114 */ "selectnowith ::= selectnowith multiselect_op oneselect",
  113661. /* 115 */ "multiselect_op ::= UNION",
  113662. /* 116 */ "multiselect_op ::= UNION ALL",
  113663. /* 117 */ "multiselect_op ::= EXCEPT|INTERSECT",
  113664. /* 118 */ "oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt",
  113665. /* 119 */ "oneselect ::= values",
  113666. /* 120 */ "values ::= VALUES LP nexprlist RP",
  113667. /* 121 */ "values ::= values COMMA LP exprlist RP",
  113668. /* 122 */ "distinct ::= DISTINCT",
  113669. /* 123 */ "distinct ::= ALL",
  113670. /* 124 */ "distinct ::=",
  113671. /* 125 */ "sclp ::= selcollist COMMA",
  113672. /* 126 */ "sclp ::=",
  113673. /* 127 */ "selcollist ::= sclp expr as",
  113674. /* 128 */ "selcollist ::= sclp STAR",
  113675. /* 129 */ "selcollist ::= sclp nm DOT STAR",
  113676. /* 130 */ "as ::= AS nm",
  113677. /* 131 */ "as ::= ID|STRING",
  113678. /* 132 */ "as ::=",
  113679. /* 133 */ "from ::=",
  113680. /* 134 */ "from ::= FROM seltablist",
  113681. /* 135 */ "stl_prefix ::= seltablist joinop",
  113682. /* 136 */ "stl_prefix ::=",
  113683. /* 137 */ "seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt",
  113684. /* 138 */ "seltablist ::= stl_prefix LP select RP as on_opt using_opt",
  113685. /* 139 */ "seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt",
  113686. /* 140 */ "dbnm ::=",
  113687. /* 141 */ "dbnm ::= DOT nm",
  113688. /* 142 */ "fullname ::= nm dbnm",
  113689. /* 143 */ "joinop ::= COMMA|JOIN",
  113690. /* 144 */ "joinop ::= JOIN_KW JOIN",
  113691. /* 145 */ "joinop ::= JOIN_KW nm JOIN",
  113692. /* 146 */ "joinop ::= JOIN_KW nm nm JOIN",
  113693. /* 147 */ "on_opt ::= ON expr",
  113694. /* 148 */ "on_opt ::=",
  113695. /* 149 */ "indexed_opt ::=",
  113696. /* 150 */ "indexed_opt ::= INDEXED BY nm",
  113697. /* 151 */ "indexed_opt ::= NOT INDEXED",
  113698. /* 152 */ "using_opt ::= USING LP idlist RP",
  113699. /* 153 */ "using_opt ::=",
  113700. /* 154 */ "orderby_opt ::=",
  113701. /* 155 */ "orderby_opt ::= ORDER BY sortlist",
  113702. /* 156 */ "sortlist ::= sortlist COMMA expr sortorder",
  113703. /* 157 */ "sortlist ::= expr sortorder",
  113704. /* 158 */ "sortorder ::= ASC",
  113705. /* 159 */ "sortorder ::= DESC",
  113706. /* 160 */ "sortorder ::=",
  113707. /* 161 */ "groupby_opt ::=",
  113708. /* 162 */ "groupby_opt ::= GROUP BY nexprlist",
  113709. /* 163 */ "having_opt ::=",
  113710. /* 164 */ "having_opt ::= HAVING expr",
  113711. /* 165 */ "limit_opt ::=",
  113712. /* 166 */ "limit_opt ::= LIMIT expr",
  113713. /* 167 */ "limit_opt ::= LIMIT expr OFFSET expr",
  113714. /* 168 */ "limit_opt ::= LIMIT expr COMMA expr",
  113715. /* 169 */ "cmd ::= with DELETE FROM fullname indexed_opt where_opt",
  113716. /* 170 */ "where_opt ::=",
  113717. /* 171 */ "where_opt ::= WHERE expr",
  113718. /* 172 */ "cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt",
  113719. /* 173 */ "setlist ::= setlist COMMA nm EQ expr",
  113720. /* 174 */ "setlist ::= nm EQ expr",
  113721. /* 175 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt select",
  113722. /* 176 */ "cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES",
  113723. /* 177 */ "insert_cmd ::= INSERT orconf",
  113724. /* 178 */ "insert_cmd ::= REPLACE",
  113725. /* 179 */ "inscollist_opt ::=",
  113726. /* 180 */ "inscollist_opt ::= LP idlist RP",
  113727. /* 181 */ "idlist ::= idlist COMMA nm",
  113728. /* 182 */ "idlist ::= nm",
  113729. /* 183 */ "expr ::= term",
  113730. /* 184 */ "expr ::= LP expr RP",
  113731. /* 185 */ "term ::= NULL",
  113732. /* 186 */ "expr ::= ID|INDEXED",
  113733. /* 187 */ "expr ::= JOIN_KW",
  113734. /* 188 */ "expr ::= nm DOT nm",
  113735. /* 189 */ "expr ::= nm DOT nm DOT nm",
  113736. /* 190 */ "term ::= INTEGER|FLOAT|BLOB",
  113737. /* 191 */ "term ::= STRING",
  113738. /* 192 */ "expr ::= VARIABLE",
  113739. /* 193 */ "expr ::= expr COLLATE ID|STRING",
  113740. /* 194 */ "expr ::= CAST LP expr AS typetoken RP",
  113741. /* 195 */ "expr ::= ID|INDEXED LP distinct exprlist RP",
  113742. /* 196 */ "expr ::= ID|INDEXED LP STAR RP",
  113743. /* 197 */ "term ::= CTIME_KW",
  113744. /* 198 */ "expr ::= expr AND expr",
  113745. /* 199 */ "expr ::= expr OR expr",
  113746. /* 200 */ "expr ::= expr LT|GT|GE|LE expr",
  113747. /* 201 */ "expr ::= expr EQ|NE expr",
  113748. /* 202 */ "expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr",
  113749. /* 203 */ "expr ::= expr PLUS|MINUS expr",
  113750. /* 204 */ "expr ::= expr STAR|SLASH|REM expr",
  113751. /* 205 */ "expr ::= expr CONCAT expr",
  113752. /* 206 */ "likeop ::= LIKE_KW|MATCH",
  113753. /* 207 */ "likeop ::= NOT LIKE_KW|MATCH",
  113754. /* 208 */ "expr ::= expr likeop expr",
  113755. /* 209 */ "expr ::= expr likeop expr ESCAPE expr",
  113756. /* 210 */ "expr ::= expr ISNULL|NOTNULL",
  113757. /* 211 */ "expr ::= expr NOT NULL",
  113758. /* 212 */ "expr ::= expr IS expr",
  113759. /* 213 */ "expr ::= expr IS NOT expr",
  113760. /* 214 */ "expr ::= NOT expr",
  113761. /* 215 */ "expr ::= BITNOT expr",
  113762. /* 216 */ "expr ::= MINUS expr",
  113763. /* 217 */ "expr ::= PLUS expr",
  113764. /* 218 */ "between_op ::= BETWEEN",
  113765. /* 219 */ "between_op ::= NOT BETWEEN",
  113766. /* 220 */ "expr ::= expr between_op expr AND expr",
  113767. /* 221 */ "in_op ::= IN",
  113768. /* 222 */ "in_op ::= NOT IN",
  113769. /* 223 */ "expr ::= expr in_op LP exprlist RP",
  113770. /* 224 */ "expr ::= LP select RP",
  113771. /* 225 */ "expr ::= expr in_op LP select RP",
  113772. /* 226 */ "expr ::= expr in_op nm dbnm",
  113773. /* 227 */ "expr ::= EXISTS LP select RP",
  113774. /* 228 */ "expr ::= CASE case_operand case_exprlist case_else END",
  113775. /* 229 */ "case_exprlist ::= case_exprlist WHEN expr THEN expr",
  113776. /* 230 */ "case_exprlist ::= WHEN expr THEN expr",
  113777. /* 231 */ "case_else ::= ELSE expr",
  113778. /* 232 */ "case_else ::=",
  113779. /* 233 */ "case_operand ::= expr",
  113780. /* 234 */ "case_operand ::=",
  113781. /* 235 */ "exprlist ::= nexprlist",
  113782. /* 236 */ "exprlist ::=",
  113783. /* 237 */ "nexprlist ::= nexprlist COMMA expr",
  113784. /* 238 */ "nexprlist ::= expr",
  113785. /* 239 */ "cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt",
  113786. /* 240 */ "uniqueflag ::= UNIQUE",
  113787. /* 241 */ "uniqueflag ::=",
  113788. /* 242 */ "idxlist_opt ::=",
  113789. /* 243 */ "idxlist_opt ::= LP idxlist RP",
  113790. /* 244 */ "idxlist ::= idxlist COMMA nm collate sortorder",
  113791. /* 245 */ "idxlist ::= nm collate sortorder",
  113792. /* 246 */ "collate ::=",
  113793. /* 247 */ "collate ::= COLLATE ID|STRING",
  113794. /* 248 */ "cmd ::= DROP INDEX ifexists fullname",
  113795. /* 249 */ "cmd ::= VACUUM",
  113796. /* 250 */ "cmd ::= VACUUM nm",
  113797. /* 251 */ "cmd ::= PRAGMA nm dbnm",
  113798. /* 252 */ "cmd ::= PRAGMA nm dbnm EQ nmnum",
  113799. /* 253 */ "cmd ::= PRAGMA nm dbnm LP nmnum RP",
  113800. /* 254 */ "cmd ::= PRAGMA nm dbnm EQ minus_num",
  113801. /* 255 */ "cmd ::= PRAGMA nm dbnm LP minus_num RP",
  113802. /* 256 */ "nmnum ::= plus_num",
  113803. /* 257 */ "nmnum ::= nm",
  113804. /* 258 */ "nmnum ::= ON",
  113805. /* 259 */ "nmnum ::= DELETE",
  113806. /* 260 */ "nmnum ::= DEFAULT",
  113807. /* 261 */ "plus_num ::= PLUS INTEGER|FLOAT",
  113808. /* 262 */ "plus_num ::= INTEGER|FLOAT",
  113809. /* 263 */ "minus_num ::= MINUS INTEGER|FLOAT",
  113810. /* 264 */ "cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END",
  113811. /* 265 */ "trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause",
  113812. /* 266 */ "trigger_time ::= BEFORE",
  113813. /* 267 */ "trigger_time ::= AFTER",
  113814. /* 268 */ "trigger_time ::= INSTEAD OF",
  113815. /* 269 */ "trigger_time ::=",
  113816. /* 270 */ "trigger_event ::= DELETE|INSERT",
  113817. /* 271 */ "trigger_event ::= UPDATE",
  113818. /* 272 */ "trigger_event ::= UPDATE OF idlist",
  113819. /* 273 */ "foreach_clause ::=",
  113820. /* 274 */ "foreach_clause ::= FOR EACH ROW",
  113821. /* 275 */ "when_clause ::=",
  113822. /* 276 */ "when_clause ::= WHEN expr",
  113823. /* 277 */ "trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI",
  113824. /* 278 */ "trigger_cmd_list ::= trigger_cmd SEMI",
  113825. /* 279 */ "trnm ::= nm",
  113826. /* 280 */ "trnm ::= nm DOT nm",
  113827. /* 281 */ "tridxby ::=",
  113828. /* 282 */ "tridxby ::= INDEXED BY nm",
  113829. /* 283 */ "tridxby ::= NOT INDEXED",
  113830. /* 284 */ "trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt",
  113831. /* 285 */ "trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select",
  113832. /* 286 */ "trigger_cmd ::= DELETE FROM trnm tridxby where_opt",
  113833. /* 287 */ "trigger_cmd ::= select",
  113834. /* 288 */ "expr ::= RAISE LP IGNORE RP",
  113835. /* 289 */ "expr ::= RAISE LP raisetype COMMA nm RP",
  113836. /* 290 */ "raisetype ::= ROLLBACK",
  113837. /* 291 */ "raisetype ::= ABORT",
  113838. /* 292 */ "raisetype ::= FAIL",
  113839. /* 293 */ "cmd ::= DROP TRIGGER ifexists fullname",
  113840. /* 294 */ "cmd ::= ATTACH database_kw_opt expr AS expr key_opt",
  113841. /* 295 */ "cmd ::= DETACH database_kw_opt expr",
  113842. /* 296 */ "key_opt ::=",
  113843. /* 297 */ "key_opt ::= KEY expr",
  113844. /* 298 */ "database_kw_opt ::= DATABASE",
  113845. /* 299 */ "database_kw_opt ::=",
  113846. /* 300 */ "cmd ::= REINDEX",
  113847. /* 301 */ "cmd ::= REINDEX nm dbnm",
  113848. /* 302 */ "cmd ::= ANALYZE",
  113849. /* 303 */ "cmd ::= ANALYZE nm dbnm",
  113850. /* 304 */ "cmd ::= ALTER TABLE fullname RENAME TO nm",
  113851. /* 305 */ "cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column",
  113852. /* 306 */ "add_column_fullname ::= fullname",
  113853. /* 307 */ "kwcolumn_opt ::=",
  113854. /* 308 */ "kwcolumn_opt ::= COLUMNKW",
  113855. /* 309 */ "cmd ::= create_vtab",
  113856. /* 310 */ "cmd ::= create_vtab LP vtabarglist RP",
  113857. /* 311 */ "create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm",
  113858. /* 312 */ "vtabarglist ::= vtabarg",
  113859. /* 313 */ "vtabarglist ::= vtabarglist COMMA vtabarg",
  113860. /* 314 */ "vtabarg ::=",
  113861. /* 315 */ "vtabarg ::= vtabarg vtabargtoken",
  113862. /* 316 */ "vtabargtoken ::= ANY",
  113863. /* 317 */ "vtabargtoken ::= lp anylist RP",
  113864. /* 318 */ "lp ::= LP",
  113865. /* 319 */ "anylist ::=",
  113866. /* 320 */ "anylist ::= anylist LP anylist RP",
  113867. /* 321 */ "anylist ::= anylist ANY",
  113868. /* 322 */ "with ::=",
  113869. /* 323 */ "with ::= WITH wqlist",
  113870. /* 324 */ "with ::= WITH RECURSIVE wqlist",
  113871. /* 325 */ "wqlist ::= nm idxlist_opt AS LP select RP",
  113872. /* 326 */ "wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP",
  113873. };
  113874. #endif /* NDEBUG */
  113875. #if YYSTACKDEPTH<=0
  113876. /*
  113877. ** Try to increase the size of the parser stack.
  113878. */
  113879. static void yyGrowStack(yyParser *p){
  113880. int newSize;
  113881. yyStackEntry *pNew;
  113882. newSize = p->yystksz*2 + 100;
  113883. pNew = realloc(p->yystack, newSize*sizeof(pNew[0]));
  113884. if( pNew ){
  113885. p->yystack = pNew;
  113886. p->yystksz = newSize;
  113887. #ifndef NDEBUG
  113888. if( yyTraceFILE ){
  113889. fprintf(yyTraceFILE,"%sStack grows to %d entries!\n",
  113890. yyTracePrompt, p->yystksz);
  113891. }
  113892. #endif
  113893. }
  113894. }
  113895. #endif
  113896. /*
  113897. ** This function allocates a new parser.
  113898. ** The only argument is a pointer to a function which works like
  113899. ** malloc.
  113900. **
  113901. ** Inputs:
  113902. ** A pointer to the function used to allocate memory.
  113903. **
  113904. ** Outputs:
  113905. ** A pointer to a parser. This pointer is used in subsequent calls
  113906. ** to sqlite3Parser and sqlite3ParserFree.
  113907. */
  113908. SQLITE_PRIVATE void *sqlite3ParserAlloc(void *(*mallocProc)(u64)){
  113909. yyParser *pParser;
  113910. pParser = (yyParser*)(*mallocProc)( (u64)sizeof(yyParser) );
  113911. if( pParser ){
  113912. pParser->yyidx = -1;
  113913. #ifdef YYTRACKMAXSTACKDEPTH
  113914. pParser->yyidxMax = 0;
  113915. #endif
  113916. #if YYSTACKDEPTH<=0
  113917. pParser->yystack = NULL;
  113918. pParser->yystksz = 0;
  113919. yyGrowStack(pParser);
  113920. #endif
  113921. }
  113922. return pParser;
  113923. }
  113924. /* The following function deletes the value associated with a
  113925. ** symbol. The symbol can be either a terminal or nonterminal.
  113926. ** "yymajor" is the symbol code, and "yypminor" is a pointer to
  113927. ** the value.
  113928. */
  113929. static void yy_destructor(
  113930. yyParser *yypParser, /* The parser */
  113931. YYCODETYPE yymajor, /* Type code for object to destroy */
  113932. YYMINORTYPE *yypminor /* The object to be destroyed */
  113933. ){
  113934. sqlite3ParserARG_FETCH;
  113935. switch( yymajor ){
  113936. /* Here is inserted the actions which take place when a
  113937. ** terminal or non-terminal is destroyed. This can happen
  113938. ** when the symbol is popped from the stack during a
  113939. ** reduce or during error processing or when a parser is
  113940. ** being destroyed before it is finished parsing.
  113941. **
  113942. ** Note: during a reduce, the only symbols destroyed are those
  113943. ** which appear on the RHS of the rule, but which are not used
  113944. ** inside the C code.
  113945. */
  113946. case 163: /* select */
  113947. case 195: /* selectnowith */
  113948. case 196: /* oneselect */
  113949. case 207: /* values */
  113950. {
  113951. sqlite3SelectDelete(pParse->db, (yypminor->yy3));
  113952. }
  113953. break;
  113954. case 174: /* term */
  113955. case 175: /* expr */
  113956. {
  113957. sqlite3ExprDelete(pParse->db, (yypminor->yy346).pExpr);
  113958. }
  113959. break;
  113960. case 179: /* idxlist_opt */
  113961. case 188: /* idxlist */
  113962. case 200: /* selcollist */
  113963. case 203: /* groupby_opt */
  113964. case 205: /* orderby_opt */
  113965. case 208: /* nexprlist */
  113966. case 209: /* exprlist */
  113967. case 210: /* sclp */
  113968. case 220: /* sortlist */
  113969. case 221: /* setlist */
  113970. case 228: /* case_exprlist */
  113971. {
  113972. sqlite3ExprListDelete(pParse->db, (yypminor->yy14));
  113973. }
  113974. break;
  113975. case 194: /* fullname */
  113976. case 201: /* from */
  113977. case 212: /* seltablist */
  113978. case 213: /* stl_prefix */
  113979. {
  113980. sqlite3SrcListDelete(pParse->db, (yypminor->yy65));
  113981. }
  113982. break;
  113983. case 197: /* with */
  113984. case 252: /* wqlist */
  113985. {
  113986. sqlite3WithDelete(pParse->db, (yypminor->yy59));
  113987. }
  113988. break;
  113989. case 202: /* where_opt */
  113990. case 204: /* having_opt */
  113991. case 216: /* on_opt */
  113992. case 227: /* case_operand */
  113993. case 229: /* case_else */
  113994. case 238: /* when_clause */
  113995. case 243: /* key_opt */
  113996. {
  113997. sqlite3ExprDelete(pParse->db, (yypminor->yy132));
  113998. }
  113999. break;
  114000. case 217: /* using_opt */
  114001. case 219: /* idlist */
  114002. case 223: /* inscollist_opt */
  114003. {
  114004. sqlite3IdListDelete(pParse->db, (yypminor->yy408));
  114005. }
  114006. break;
  114007. case 234: /* trigger_cmd_list */
  114008. case 239: /* trigger_cmd */
  114009. {
  114010. sqlite3DeleteTriggerStep(pParse->db, (yypminor->yy473));
  114011. }
  114012. break;
  114013. case 236: /* trigger_event */
  114014. {
  114015. sqlite3IdListDelete(pParse->db, (yypminor->yy378).b);
  114016. }
  114017. break;
  114018. default: break; /* If no destructor action specified: do nothing */
  114019. }
  114020. }
  114021. /*
  114022. ** Pop the parser's stack once.
  114023. **
  114024. ** If there is a destructor routine associated with the token which
  114025. ** is popped from the stack, then call it.
  114026. **
  114027. ** Return the major token number for the symbol popped.
  114028. */
  114029. static int yy_pop_parser_stack(yyParser *pParser){
  114030. YYCODETYPE yymajor;
  114031. yyStackEntry *yytos = &pParser->yystack[pParser->yyidx];
  114032. /* There is no mechanism by which the parser stack can be popped below
  114033. ** empty in SQLite. */
  114034. if( NEVER(pParser->yyidx<0) ) return 0;
  114035. #ifndef NDEBUG
  114036. if( yyTraceFILE && pParser->yyidx>=0 ){
  114037. fprintf(yyTraceFILE,"%sPopping %s\n",
  114038. yyTracePrompt,
  114039. yyTokenName[yytos->major]);
  114040. }
  114041. #endif
  114042. yymajor = yytos->major;
  114043. yy_destructor(pParser, yymajor, &yytos->minor);
  114044. pParser->yyidx--;
  114045. return yymajor;
  114046. }
  114047. /*
  114048. ** Deallocate and destroy a parser. Destructors are all called for
  114049. ** all stack elements before shutting the parser down.
  114050. **
  114051. ** Inputs:
  114052. ** <ul>
  114053. ** <li> A pointer to the parser. This should be a pointer
  114054. ** obtained from sqlite3ParserAlloc.
  114055. ** <li> A pointer to a function used to reclaim memory obtained
  114056. ** from malloc.
  114057. ** </ul>
  114058. */
  114059. SQLITE_PRIVATE void sqlite3ParserFree(
  114060. void *p, /* The parser to be deleted */
  114061. void (*freeProc)(void*) /* Function used to reclaim memory */
  114062. ){
  114063. yyParser *pParser = (yyParser*)p;
  114064. /* In SQLite, we never try to destroy a parser that was not successfully
  114065. ** created in the first place. */
  114066. if( NEVER(pParser==0) ) return;
  114067. while( pParser->yyidx>=0 ) yy_pop_parser_stack(pParser);
  114068. #if YYSTACKDEPTH<=0
  114069. free(pParser->yystack);
  114070. #endif
  114071. (*freeProc)((void*)pParser);
  114072. }
  114073. /*
  114074. ** Return the peak depth of the stack for a parser.
  114075. */
  114076. #ifdef YYTRACKMAXSTACKDEPTH
  114077. SQLITE_PRIVATE int sqlite3ParserStackPeak(void *p){
  114078. yyParser *pParser = (yyParser*)p;
  114079. return pParser->yyidxMax;
  114080. }
  114081. #endif
  114082. /*
  114083. ** Find the appropriate action for a parser given the terminal
  114084. ** look-ahead token iLookAhead.
  114085. **
  114086. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  114087. ** independent of the look-ahead. If it is, return the action, otherwise
  114088. ** return YY_NO_ACTION.
  114089. */
  114090. static int yy_find_shift_action(
  114091. yyParser *pParser, /* The parser */
  114092. YYCODETYPE iLookAhead /* The look-ahead token */
  114093. ){
  114094. int i;
  114095. int stateno = pParser->yystack[pParser->yyidx].stateno;
  114096. if( stateno>YY_SHIFT_COUNT
  114097. || (i = yy_shift_ofst[stateno])==YY_SHIFT_USE_DFLT ){
  114098. return yy_default[stateno];
  114099. }
  114100. assert( iLookAhead!=YYNOCODE );
  114101. i += iLookAhead;
  114102. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  114103. if( iLookAhead>0 ){
  114104. #ifdef YYFALLBACK
  114105. YYCODETYPE iFallback; /* Fallback token */
  114106. if( iLookAhead<sizeof(yyFallback)/sizeof(yyFallback[0])
  114107. && (iFallback = yyFallback[iLookAhead])!=0 ){
  114108. #ifndef NDEBUG
  114109. if( yyTraceFILE ){
  114110. fprintf(yyTraceFILE, "%sFALLBACK %s => %s\n",
  114111. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[iFallback]);
  114112. }
  114113. #endif
  114114. return yy_find_shift_action(pParser, iFallback);
  114115. }
  114116. #endif
  114117. #ifdef YYWILDCARD
  114118. {
  114119. int j = i - iLookAhead + YYWILDCARD;
  114120. if(
  114121. #if YY_SHIFT_MIN+YYWILDCARD<0
  114122. j>=0 &&
  114123. #endif
  114124. #if YY_SHIFT_MAX+YYWILDCARD>=YY_ACTTAB_COUNT
  114125. j<YY_ACTTAB_COUNT &&
  114126. #endif
  114127. yy_lookahead[j]==YYWILDCARD
  114128. ){
  114129. #ifndef NDEBUG
  114130. if( yyTraceFILE ){
  114131. fprintf(yyTraceFILE, "%sWILDCARD %s => %s\n",
  114132. yyTracePrompt, yyTokenName[iLookAhead], yyTokenName[YYWILDCARD]);
  114133. }
  114134. #endif /* NDEBUG */
  114135. return yy_action[j];
  114136. }
  114137. }
  114138. #endif /* YYWILDCARD */
  114139. }
  114140. return yy_default[stateno];
  114141. }else{
  114142. return yy_action[i];
  114143. }
  114144. }
  114145. /*
  114146. ** Find the appropriate action for a parser given the non-terminal
  114147. ** look-ahead token iLookAhead.
  114148. **
  114149. ** If the look-ahead token is YYNOCODE, then check to see if the action is
  114150. ** independent of the look-ahead. If it is, return the action, otherwise
  114151. ** return YY_NO_ACTION.
  114152. */
  114153. static int yy_find_reduce_action(
  114154. int stateno, /* Current state number */
  114155. YYCODETYPE iLookAhead /* The look-ahead token */
  114156. ){
  114157. int i;
  114158. #ifdef YYERRORSYMBOL
  114159. if( stateno>YY_REDUCE_COUNT ){
  114160. return yy_default[stateno];
  114161. }
  114162. #else
  114163. assert( stateno<=YY_REDUCE_COUNT );
  114164. #endif
  114165. i = yy_reduce_ofst[stateno];
  114166. assert( i!=YY_REDUCE_USE_DFLT );
  114167. assert( iLookAhead!=YYNOCODE );
  114168. i += iLookAhead;
  114169. #ifdef YYERRORSYMBOL
  114170. if( i<0 || i>=YY_ACTTAB_COUNT || yy_lookahead[i]!=iLookAhead ){
  114171. return yy_default[stateno];
  114172. }
  114173. #else
  114174. assert( i>=0 && i<YY_ACTTAB_COUNT );
  114175. assert( yy_lookahead[i]==iLookAhead );
  114176. #endif
  114177. return yy_action[i];
  114178. }
  114179. /*
  114180. ** The following routine is called if the stack overflows.
  114181. */
  114182. static void yyStackOverflow(yyParser *yypParser, YYMINORTYPE *yypMinor){
  114183. sqlite3ParserARG_FETCH;
  114184. yypParser->yyidx--;
  114185. #ifndef NDEBUG
  114186. if( yyTraceFILE ){
  114187. fprintf(yyTraceFILE,"%sStack Overflow!\n",yyTracePrompt);
  114188. }
  114189. #endif
  114190. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  114191. /* Here code is inserted which will execute if the parser
  114192. ** stack every overflows */
  114193. UNUSED_PARAMETER(yypMinor); /* Silence some compiler warnings */
  114194. sqlite3ErrorMsg(pParse, "parser stack overflow");
  114195. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument var */
  114196. }
  114197. /*
  114198. ** Perform a shift action.
  114199. */
  114200. static void yy_shift(
  114201. yyParser *yypParser, /* The parser to be shifted */
  114202. int yyNewState, /* The new state to shift in */
  114203. int yyMajor, /* The major token to shift in */
  114204. YYMINORTYPE *yypMinor /* Pointer to the minor token to shift in */
  114205. ){
  114206. yyStackEntry *yytos;
  114207. yypParser->yyidx++;
  114208. #ifdef YYTRACKMAXSTACKDEPTH
  114209. if( yypParser->yyidx>yypParser->yyidxMax ){
  114210. yypParser->yyidxMax = yypParser->yyidx;
  114211. }
  114212. #endif
  114213. #if YYSTACKDEPTH>0
  114214. if( yypParser->yyidx>=YYSTACKDEPTH ){
  114215. yyStackOverflow(yypParser, yypMinor);
  114216. return;
  114217. }
  114218. #else
  114219. if( yypParser->yyidx>=yypParser->yystksz ){
  114220. yyGrowStack(yypParser);
  114221. if( yypParser->yyidx>=yypParser->yystksz ){
  114222. yyStackOverflow(yypParser, yypMinor);
  114223. return;
  114224. }
  114225. }
  114226. #endif
  114227. yytos = &yypParser->yystack[yypParser->yyidx];
  114228. yytos->stateno = (YYACTIONTYPE)yyNewState;
  114229. yytos->major = (YYCODETYPE)yyMajor;
  114230. yytos->minor = *yypMinor;
  114231. #ifndef NDEBUG
  114232. if( yyTraceFILE && yypParser->yyidx>0 ){
  114233. int i;
  114234. fprintf(yyTraceFILE,"%sShift %d\n",yyTracePrompt,yyNewState);
  114235. fprintf(yyTraceFILE,"%sStack:",yyTracePrompt);
  114236. for(i=1; i<=yypParser->yyidx; i++)
  114237. fprintf(yyTraceFILE," %s",yyTokenName[yypParser->yystack[i].major]);
  114238. fprintf(yyTraceFILE,"\n");
  114239. }
  114240. #endif
  114241. }
  114242. /* The following table contains information about every rule that
  114243. ** is used during the reduce.
  114244. */
  114245. static const struct {
  114246. YYCODETYPE lhs; /* Symbol on the left-hand side of the rule */
  114247. unsigned char nrhs; /* Number of right-hand side symbols in the rule */
  114248. } yyRuleInfo[] = {
  114249. { 144, 1 },
  114250. { 145, 2 },
  114251. { 145, 1 },
  114252. { 146, 1 },
  114253. { 146, 3 },
  114254. { 147, 0 },
  114255. { 147, 1 },
  114256. { 147, 3 },
  114257. { 148, 1 },
  114258. { 149, 3 },
  114259. { 151, 0 },
  114260. { 151, 1 },
  114261. { 151, 2 },
  114262. { 150, 0 },
  114263. { 150, 1 },
  114264. { 150, 1 },
  114265. { 150, 1 },
  114266. { 149, 2 },
  114267. { 149, 2 },
  114268. { 149, 2 },
  114269. { 153, 1 },
  114270. { 153, 0 },
  114271. { 149, 2 },
  114272. { 149, 3 },
  114273. { 149, 5 },
  114274. { 149, 2 },
  114275. { 154, 6 },
  114276. { 156, 1 },
  114277. { 158, 0 },
  114278. { 158, 3 },
  114279. { 157, 1 },
  114280. { 157, 0 },
  114281. { 155, 5 },
  114282. { 155, 2 },
  114283. { 162, 0 },
  114284. { 162, 2 },
  114285. { 160, 3 },
  114286. { 160, 1 },
  114287. { 164, 3 },
  114288. { 165, 1 },
  114289. { 152, 1 },
  114290. { 152, 1 },
  114291. { 152, 1 },
  114292. { 166, 0 },
  114293. { 166, 1 },
  114294. { 168, 1 },
  114295. { 168, 4 },
  114296. { 168, 6 },
  114297. { 169, 1 },
  114298. { 169, 2 },
  114299. { 170, 1 },
  114300. { 170, 1 },
  114301. { 167, 2 },
  114302. { 167, 0 },
  114303. { 173, 2 },
  114304. { 173, 2 },
  114305. { 173, 4 },
  114306. { 173, 3 },
  114307. { 173, 3 },
  114308. { 173, 2 },
  114309. { 173, 2 },
  114310. { 173, 3 },
  114311. { 173, 5 },
  114312. { 173, 2 },
  114313. { 173, 4 },
  114314. { 173, 4 },
  114315. { 173, 1 },
  114316. { 173, 2 },
  114317. { 178, 0 },
  114318. { 178, 1 },
  114319. { 180, 0 },
  114320. { 180, 2 },
  114321. { 182, 2 },
  114322. { 182, 3 },
  114323. { 182, 3 },
  114324. { 182, 3 },
  114325. { 183, 2 },
  114326. { 183, 2 },
  114327. { 183, 1 },
  114328. { 183, 1 },
  114329. { 183, 2 },
  114330. { 181, 3 },
  114331. { 181, 2 },
  114332. { 184, 0 },
  114333. { 184, 2 },
  114334. { 184, 2 },
  114335. { 161, 0 },
  114336. { 161, 2 },
  114337. { 185, 3 },
  114338. { 185, 1 },
  114339. { 186, 1 },
  114340. { 186, 0 },
  114341. { 187, 2 },
  114342. { 187, 7 },
  114343. { 187, 5 },
  114344. { 187, 5 },
  114345. { 187, 10 },
  114346. { 189, 0 },
  114347. { 189, 1 },
  114348. { 176, 0 },
  114349. { 176, 3 },
  114350. { 190, 0 },
  114351. { 190, 2 },
  114352. { 191, 1 },
  114353. { 191, 1 },
  114354. { 191, 1 },
  114355. { 149, 4 },
  114356. { 193, 2 },
  114357. { 193, 0 },
  114358. { 149, 8 },
  114359. { 149, 4 },
  114360. { 149, 1 },
  114361. { 163, 2 },
  114362. { 195, 1 },
  114363. { 195, 3 },
  114364. { 198, 1 },
  114365. { 198, 2 },
  114366. { 198, 1 },
  114367. { 196, 9 },
  114368. { 196, 1 },
  114369. { 207, 4 },
  114370. { 207, 5 },
  114371. { 199, 1 },
  114372. { 199, 1 },
  114373. { 199, 0 },
  114374. { 210, 2 },
  114375. { 210, 0 },
  114376. { 200, 3 },
  114377. { 200, 2 },
  114378. { 200, 4 },
  114379. { 211, 2 },
  114380. { 211, 1 },
  114381. { 211, 0 },
  114382. { 201, 0 },
  114383. { 201, 2 },
  114384. { 213, 2 },
  114385. { 213, 0 },
  114386. { 212, 7 },
  114387. { 212, 7 },
  114388. { 212, 7 },
  114389. { 159, 0 },
  114390. { 159, 2 },
  114391. { 194, 2 },
  114392. { 214, 1 },
  114393. { 214, 2 },
  114394. { 214, 3 },
  114395. { 214, 4 },
  114396. { 216, 2 },
  114397. { 216, 0 },
  114398. { 215, 0 },
  114399. { 215, 3 },
  114400. { 215, 2 },
  114401. { 217, 4 },
  114402. { 217, 0 },
  114403. { 205, 0 },
  114404. { 205, 3 },
  114405. { 220, 4 },
  114406. { 220, 2 },
  114407. { 177, 1 },
  114408. { 177, 1 },
  114409. { 177, 0 },
  114410. { 203, 0 },
  114411. { 203, 3 },
  114412. { 204, 0 },
  114413. { 204, 2 },
  114414. { 206, 0 },
  114415. { 206, 2 },
  114416. { 206, 4 },
  114417. { 206, 4 },
  114418. { 149, 6 },
  114419. { 202, 0 },
  114420. { 202, 2 },
  114421. { 149, 8 },
  114422. { 221, 5 },
  114423. { 221, 3 },
  114424. { 149, 6 },
  114425. { 149, 7 },
  114426. { 222, 2 },
  114427. { 222, 1 },
  114428. { 223, 0 },
  114429. { 223, 3 },
  114430. { 219, 3 },
  114431. { 219, 1 },
  114432. { 175, 1 },
  114433. { 175, 3 },
  114434. { 174, 1 },
  114435. { 175, 1 },
  114436. { 175, 1 },
  114437. { 175, 3 },
  114438. { 175, 5 },
  114439. { 174, 1 },
  114440. { 174, 1 },
  114441. { 175, 1 },
  114442. { 175, 3 },
  114443. { 175, 6 },
  114444. { 175, 5 },
  114445. { 175, 4 },
  114446. { 174, 1 },
  114447. { 175, 3 },
  114448. { 175, 3 },
  114449. { 175, 3 },
  114450. { 175, 3 },
  114451. { 175, 3 },
  114452. { 175, 3 },
  114453. { 175, 3 },
  114454. { 175, 3 },
  114455. { 224, 1 },
  114456. { 224, 2 },
  114457. { 175, 3 },
  114458. { 175, 5 },
  114459. { 175, 2 },
  114460. { 175, 3 },
  114461. { 175, 3 },
  114462. { 175, 4 },
  114463. { 175, 2 },
  114464. { 175, 2 },
  114465. { 175, 2 },
  114466. { 175, 2 },
  114467. { 225, 1 },
  114468. { 225, 2 },
  114469. { 175, 5 },
  114470. { 226, 1 },
  114471. { 226, 2 },
  114472. { 175, 5 },
  114473. { 175, 3 },
  114474. { 175, 5 },
  114475. { 175, 4 },
  114476. { 175, 4 },
  114477. { 175, 5 },
  114478. { 228, 5 },
  114479. { 228, 4 },
  114480. { 229, 2 },
  114481. { 229, 0 },
  114482. { 227, 1 },
  114483. { 227, 0 },
  114484. { 209, 1 },
  114485. { 209, 0 },
  114486. { 208, 3 },
  114487. { 208, 1 },
  114488. { 149, 12 },
  114489. { 230, 1 },
  114490. { 230, 0 },
  114491. { 179, 0 },
  114492. { 179, 3 },
  114493. { 188, 5 },
  114494. { 188, 3 },
  114495. { 231, 0 },
  114496. { 231, 2 },
  114497. { 149, 4 },
  114498. { 149, 1 },
  114499. { 149, 2 },
  114500. { 149, 3 },
  114501. { 149, 5 },
  114502. { 149, 6 },
  114503. { 149, 5 },
  114504. { 149, 6 },
  114505. { 232, 1 },
  114506. { 232, 1 },
  114507. { 232, 1 },
  114508. { 232, 1 },
  114509. { 232, 1 },
  114510. { 171, 2 },
  114511. { 171, 1 },
  114512. { 172, 2 },
  114513. { 149, 5 },
  114514. { 233, 11 },
  114515. { 235, 1 },
  114516. { 235, 1 },
  114517. { 235, 2 },
  114518. { 235, 0 },
  114519. { 236, 1 },
  114520. { 236, 1 },
  114521. { 236, 3 },
  114522. { 237, 0 },
  114523. { 237, 3 },
  114524. { 238, 0 },
  114525. { 238, 2 },
  114526. { 234, 3 },
  114527. { 234, 2 },
  114528. { 240, 1 },
  114529. { 240, 3 },
  114530. { 241, 0 },
  114531. { 241, 3 },
  114532. { 241, 2 },
  114533. { 239, 7 },
  114534. { 239, 5 },
  114535. { 239, 5 },
  114536. { 239, 1 },
  114537. { 175, 4 },
  114538. { 175, 6 },
  114539. { 192, 1 },
  114540. { 192, 1 },
  114541. { 192, 1 },
  114542. { 149, 4 },
  114543. { 149, 6 },
  114544. { 149, 3 },
  114545. { 243, 0 },
  114546. { 243, 2 },
  114547. { 242, 1 },
  114548. { 242, 0 },
  114549. { 149, 1 },
  114550. { 149, 3 },
  114551. { 149, 1 },
  114552. { 149, 3 },
  114553. { 149, 6 },
  114554. { 149, 6 },
  114555. { 244, 1 },
  114556. { 245, 0 },
  114557. { 245, 1 },
  114558. { 149, 1 },
  114559. { 149, 4 },
  114560. { 246, 8 },
  114561. { 247, 1 },
  114562. { 247, 3 },
  114563. { 248, 0 },
  114564. { 248, 2 },
  114565. { 249, 1 },
  114566. { 249, 3 },
  114567. { 250, 1 },
  114568. { 251, 0 },
  114569. { 251, 4 },
  114570. { 251, 2 },
  114571. { 197, 0 },
  114572. { 197, 2 },
  114573. { 197, 3 },
  114574. { 252, 6 },
  114575. { 252, 8 },
  114576. };
  114577. static void yy_accept(yyParser*); /* Forward Declaration */
  114578. /*
  114579. ** Perform a reduce action and the shift that must immediately
  114580. ** follow the reduce.
  114581. */
  114582. static void yy_reduce(
  114583. yyParser *yypParser, /* The parser */
  114584. int yyruleno /* Number of the rule by which to reduce */
  114585. ){
  114586. int yygoto; /* The next state */
  114587. int yyact; /* The next action */
  114588. YYMINORTYPE yygotominor; /* The LHS of the rule reduced */
  114589. yyStackEntry *yymsp; /* The top of the parser's stack */
  114590. int yysize; /* Amount to pop the stack */
  114591. sqlite3ParserARG_FETCH;
  114592. yymsp = &yypParser->yystack[yypParser->yyidx];
  114593. #ifndef NDEBUG
  114594. if( yyTraceFILE && yyruleno>=0
  114595. && yyruleno<(int)(sizeof(yyRuleName)/sizeof(yyRuleName[0])) ){
  114596. fprintf(yyTraceFILE, "%sReduce [%s].\n", yyTracePrompt,
  114597. yyRuleName[yyruleno]);
  114598. }
  114599. #endif /* NDEBUG */
  114600. /* Silence complaints from purify about yygotominor being uninitialized
  114601. ** in some cases when it is copied into the stack after the following
  114602. ** switch. yygotominor is uninitialized when a rule reduces that does
  114603. ** not set the value of its left-hand side nonterminal. Leaving the
  114604. ** value of the nonterminal uninitialized is utterly harmless as long
  114605. ** as the value is never used. So really the only thing this code
  114606. ** accomplishes is to quieten purify.
  114607. **
  114608. ** 2007-01-16: The wireshark project (www.wireshark.org) reports that
  114609. ** without this code, their parser segfaults. I'm not sure what there
  114610. ** parser is doing to make this happen. This is the second bug report
  114611. ** from wireshark this week. Clearly they are stressing Lemon in ways
  114612. ** that it has not been previously stressed... (SQLite ticket #2172)
  114613. */
  114614. /*memset(&yygotominor, 0, sizeof(yygotominor));*/
  114615. yygotominor = yyzerominor;
  114616. switch( yyruleno ){
  114617. /* Beginning here are the reduction cases. A typical example
  114618. ** follows:
  114619. ** case 0:
  114620. ** #line <lineno> <grammarfile>
  114621. ** { ... } // User supplied code
  114622. ** #line <lineno> <thisfile>
  114623. ** break;
  114624. */
  114625. case 5: /* explain ::= */
  114626. { sqlite3BeginParse(pParse, 0); }
  114627. break;
  114628. case 6: /* explain ::= EXPLAIN */
  114629. { sqlite3BeginParse(pParse, 1); }
  114630. break;
  114631. case 7: /* explain ::= EXPLAIN QUERY PLAN */
  114632. { sqlite3BeginParse(pParse, 2); }
  114633. break;
  114634. case 8: /* cmdx ::= cmd */
  114635. { sqlite3FinishCoding(pParse); }
  114636. break;
  114637. case 9: /* cmd ::= BEGIN transtype trans_opt */
  114638. {sqlite3BeginTransaction(pParse, yymsp[-1].minor.yy328);}
  114639. break;
  114640. case 13: /* transtype ::= */
  114641. {yygotominor.yy328 = TK_DEFERRED;}
  114642. break;
  114643. case 14: /* transtype ::= DEFERRED */
  114644. case 15: /* transtype ::= IMMEDIATE */ yytestcase(yyruleno==15);
  114645. case 16: /* transtype ::= EXCLUSIVE */ yytestcase(yyruleno==16);
  114646. case 115: /* multiselect_op ::= UNION */ yytestcase(yyruleno==115);
  114647. case 117: /* multiselect_op ::= EXCEPT|INTERSECT */ yytestcase(yyruleno==117);
  114648. {yygotominor.yy328 = yymsp[0].major;}
  114649. break;
  114650. case 17: /* cmd ::= COMMIT trans_opt */
  114651. case 18: /* cmd ::= END trans_opt */ yytestcase(yyruleno==18);
  114652. {sqlite3CommitTransaction(pParse);}
  114653. break;
  114654. case 19: /* cmd ::= ROLLBACK trans_opt */
  114655. {sqlite3RollbackTransaction(pParse);}
  114656. break;
  114657. case 22: /* cmd ::= SAVEPOINT nm */
  114658. {
  114659. sqlite3Savepoint(pParse, SAVEPOINT_BEGIN, &yymsp[0].minor.yy0);
  114660. }
  114661. break;
  114662. case 23: /* cmd ::= RELEASE savepoint_opt nm */
  114663. {
  114664. sqlite3Savepoint(pParse, SAVEPOINT_RELEASE, &yymsp[0].minor.yy0);
  114665. }
  114666. break;
  114667. case 24: /* cmd ::= ROLLBACK trans_opt TO savepoint_opt nm */
  114668. {
  114669. sqlite3Savepoint(pParse, SAVEPOINT_ROLLBACK, &yymsp[0].minor.yy0);
  114670. }
  114671. break;
  114672. case 26: /* create_table ::= createkw temp TABLE ifnotexists nm dbnm */
  114673. {
  114674. sqlite3StartTable(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,yymsp[-4].minor.yy328,0,0,yymsp[-2].minor.yy328);
  114675. }
  114676. break;
  114677. case 27: /* createkw ::= CREATE */
  114678. {
  114679. pParse->db->lookaside.bEnabled = 0;
  114680. yygotominor.yy0 = yymsp[0].minor.yy0;
  114681. }
  114682. break;
  114683. case 28: /* ifnotexists ::= */
  114684. case 31: /* temp ::= */ yytestcase(yyruleno==31);
  114685. case 68: /* autoinc ::= */ yytestcase(yyruleno==68);
  114686. case 81: /* defer_subclause ::= NOT DEFERRABLE init_deferred_pred_opt */ yytestcase(yyruleno==81);
  114687. case 83: /* init_deferred_pred_opt ::= */ yytestcase(yyruleno==83);
  114688. case 85: /* init_deferred_pred_opt ::= INITIALLY IMMEDIATE */ yytestcase(yyruleno==85);
  114689. case 97: /* defer_subclause_opt ::= */ yytestcase(yyruleno==97);
  114690. case 108: /* ifexists ::= */ yytestcase(yyruleno==108);
  114691. case 218: /* between_op ::= BETWEEN */ yytestcase(yyruleno==218);
  114692. case 221: /* in_op ::= IN */ yytestcase(yyruleno==221);
  114693. {yygotominor.yy328 = 0;}
  114694. break;
  114695. case 29: /* ifnotexists ::= IF NOT EXISTS */
  114696. case 30: /* temp ::= TEMP */ yytestcase(yyruleno==30);
  114697. case 69: /* autoinc ::= AUTOINCR */ yytestcase(yyruleno==69);
  114698. case 84: /* init_deferred_pred_opt ::= INITIALLY DEFERRED */ yytestcase(yyruleno==84);
  114699. case 107: /* ifexists ::= IF EXISTS */ yytestcase(yyruleno==107);
  114700. case 219: /* between_op ::= NOT BETWEEN */ yytestcase(yyruleno==219);
  114701. case 222: /* in_op ::= NOT IN */ yytestcase(yyruleno==222);
  114702. {yygotominor.yy328 = 1;}
  114703. break;
  114704. case 32: /* create_table_args ::= LP columnlist conslist_opt RP table_options */
  114705. {
  114706. sqlite3EndTable(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,yymsp[0].minor.yy186,0);
  114707. }
  114708. break;
  114709. case 33: /* create_table_args ::= AS select */
  114710. {
  114711. sqlite3EndTable(pParse,0,0,0,yymsp[0].minor.yy3);
  114712. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  114713. }
  114714. break;
  114715. case 34: /* table_options ::= */
  114716. {yygotominor.yy186 = 0;}
  114717. break;
  114718. case 35: /* table_options ::= WITHOUT nm */
  114719. {
  114720. if( yymsp[0].minor.yy0.n==5 && sqlite3_strnicmp(yymsp[0].minor.yy0.z,"rowid",5)==0 ){
  114721. yygotominor.yy186 = TF_WithoutRowid;
  114722. }else{
  114723. yygotominor.yy186 = 0;
  114724. sqlite3ErrorMsg(pParse, "unknown table option: %.*s", yymsp[0].minor.yy0.n, yymsp[0].minor.yy0.z);
  114725. }
  114726. }
  114727. break;
  114728. case 38: /* column ::= columnid type carglist */
  114729. {
  114730. yygotominor.yy0.z = yymsp[-2].minor.yy0.z;
  114731. yygotominor.yy0.n = (int)(pParse->sLastToken.z-yymsp[-2].minor.yy0.z) + pParse->sLastToken.n;
  114732. }
  114733. break;
  114734. case 39: /* columnid ::= nm */
  114735. {
  114736. sqlite3AddColumn(pParse,&yymsp[0].minor.yy0);
  114737. yygotominor.yy0 = yymsp[0].minor.yy0;
  114738. pParse->constraintName.n = 0;
  114739. }
  114740. break;
  114741. case 40: /* nm ::= ID|INDEXED */
  114742. case 41: /* nm ::= STRING */ yytestcase(yyruleno==41);
  114743. case 42: /* nm ::= JOIN_KW */ yytestcase(yyruleno==42);
  114744. case 45: /* typetoken ::= typename */ yytestcase(yyruleno==45);
  114745. case 48: /* typename ::= ID|STRING */ yytestcase(yyruleno==48);
  114746. case 130: /* as ::= AS nm */ yytestcase(yyruleno==130);
  114747. case 131: /* as ::= ID|STRING */ yytestcase(yyruleno==131);
  114748. case 141: /* dbnm ::= DOT nm */ yytestcase(yyruleno==141);
  114749. case 150: /* indexed_opt ::= INDEXED BY nm */ yytestcase(yyruleno==150);
  114750. case 247: /* collate ::= COLLATE ID|STRING */ yytestcase(yyruleno==247);
  114751. case 256: /* nmnum ::= plus_num */ yytestcase(yyruleno==256);
  114752. case 257: /* nmnum ::= nm */ yytestcase(yyruleno==257);
  114753. case 258: /* nmnum ::= ON */ yytestcase(yyruleno==258);
  114754. case 259: /* nmnum ::= DELETE */ yytestcase(yyruleno==259);
  114755. case 260: /* nmnum ::= DEFAULT */ yytestcase(yyruleno==260);
  114756. case 261: /* plus_num ::= PLUS INTEGER|FLOAT */ yytestcase(yyruleno==261);
  114757. case 262: /* plus_num ::= INTEGER|FLOAT */ yytestcase(yyruleno==262);
  114758. case 263: /* minus_num ::= MINUS INTEGER|FLOAT */ yytestcase(yyruleno==263);
  114759. case 279: /* trnm ::= nm */ yytestcase(yyruleno==279);
  114760. {yygotominor.yy0 = yymsp[0].minor.yy0;}
  114761. break;
  114762. case 44: /* type ::= typetoken */
  114763. {sqlite3AddColumnType(pParse,&yymsp[0].minor.yy0);}
  114764. break;
  114765. case 46: /* typetoken ::= typename LP signed RP */
  114766. {
  114767. yygotominor.yy0.z = yymsp[-3].minor.yy0.z;
  114768. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-3].minor.yy0.z);
  114769. }
  114770. break;
  114771. case 47: /* typetoken ::= typename LP signed COMMA signed RP */
  114772. {
  114773. yygotominor.yy0.z = yymsp[-5].minor.yy0.z;
  114774. yygotominor.yy0.n = (int)(&yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n] - yymsp[-5].minor.yy0.z);
  114775. }
  114776. break;
  114777. case 49: /* typename ::= typename ID|STRING */
  114778. {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);}
  114779. break;
  114780. case 54: /* ccons ::= CONSTRAINT nm */
  114781. case 92: /* tcons ::= CONSTRAINT nm */ yytestcase(yyruleno==92);
  114782. {pParse->constraintName = yymsp[0].minor.yy0;}
  114783. break;
  114784. case 55: /* ccons ::= DEFAULT term */
  114785. case 57: /* ccons ::= DEFAULT PLUS term */ yytestcase(yyruleno==57);
  114786. {sqlite3AddDefaultValue(pParse,&yymsp[0].minor.yy346);}
  114787. break;
  114788. case 56: /* ccons ::= DEFAULT LP expr RP */
  114789. {sqlite3AddDefaultValue(pParse,&yymsp[-1].minor.yy346);}
  114790. break;
  114791. case 58: /* ccons ::= DEFAULT MINUS term */
  114792. {
  114793. ExprSpan v;
  114794. v.pExpr = sqlite3PExpr(pParse, TK_UMINUS, yymsp[0].minor.yy346.pExpr, 0, 0);
  114795. v.zStart = yymsp[-1].minor.yy0.z;
  114796. v.zEnd = yymsp[0].minor.yy346.zEnd;
  114797. sqlite3AddDefaultValue(pParse,&v);
  114798. }
  114799. break;
  114800. case 59: /* ccons ::= DEFAULT ID|INDEXED */
  114801. {
  114802. ExprSpan v;
  114803. spanExpr(&v, pParse, TK_STRING, &yymsp[0].minor.yy0);
  114804. sqlite3AddDefaultValue(pParse,&v);
  114805. }
  114806. break;
  114807. case 61: /* ccons ::= NOT NULL onconf */
  114808. {sqlite3AddNotNull(pParse, yymsp[0].minor.yy328);}
  114809. break;
  114810. case 62: /* ccons ::= PRIMARY KEY sortorder onconf autoinc */
  114811. {sqlite3AddPrimaryKey(pParse,0,yymsp[-1].minor.yy328,yymsp[0].minor.yy328,yymsp[-2].minor.yy328);}
  114812. break;
  114813. case 63: /* ccons ::= UNIQUE onconf */
  114814. {sqlite3CreateIndex(pParse,0,0,0,0,yymsp[0].minor.yy328,0,0,0,0);}
  114815. break;
  114816. case 64: /* ccons ::= CHECK LP expr RP */
  114817. {sqlite3AddCheckConstraint(pParse,yymsp[-1].minor.yy346.pExpr);}
  114818. break;
  114819. case 65: /* ccons ::= REFERENCES nm idxlist_opt refargs */
  114820. {sqlite3CreateForeignKey(pParse,0,&yymsp[-2].minor.yy0,yymsp[-1].minor.yy14,yymsp[0].minor.yy328);}
  114821. break;
  114822. case 66: /* ccons ::= defer_subclause */
  114823. {sqlite3DeferForeignKey(pParse,yymsp[0].minor.yy328);}
  114824. break;
  114825. case 67: /* ccons ::= COLLATE ID|STRING */
  114826. {sqlite3AddCollateType(pParse, &yymsp[0].minor.yy0);}
  114827. break;
  114828. case 70: /* refargs ::= */
  114829. { yygotominor.yy328 = OE_None*0x0101; /* EV: R-19803-45884 */}
  114830. break;
  114831. case 71: /* refargs ::= refargs refarg */
  114832. { yygotominor.yy328 = (yymsp[-1].minor.yy328 & ~yymsp[0].minor.yy429.mask) | yymsp[0].minor.yy429.value; }
  114833. break;
  114834. case 72: /* refarg ::= MATCH nm */
  114835. case 73: /* refarg ::= ON INSERT refact */ yytestcase(yyruleno==73);
  114836. { yygotominor.yy429.value = 0; yygotominor.yy429.mask = 0x000000; }
  114837. break;
  114838. case 74: /* refarg ::= ON DELETE refact */
  114839. { yygotominor.yy429.value = yymsp[0].minor.yy328; yygotominor.yy429.mask = 0x0000ff; }
  114840. break;
  114841. case 75: /* refarg ::= ON UPDATE refact */
  114842. { yygotominor.yy429.value = yymsp[0].minor.yy328<<8; yygotominor.yy429.mask = 0x00ff00; }
  114843. break;
  114844. case 76: /* refact ::= SET NULL */
  114845. { yygotominor.yy328 = OE_SetNull; /* EV: R-33326-45252 */}
  114846. break;
  114847. case 77: /* refact ::= SET DEFAULT */
  114848. { yygotominor.yy328 = OE_SetDflt; /* EV: R-33326-45252 */}
  114849. break;
  114850. case 78: /* refact ::= CASCADE */
  114851. { yygotominor.yy328 = OE_Cascade; /* EV: R-33326-45252 */}
  114852. break;
  114853. case 79: /* refact ::= RESTRICT */
  114854. { yygotominor.yy328 = OE_Restrict; /* EV: R-33326-45252 */}
  114855. break;
  114856. case 80: /* refact ::= NO ACTION */
  114857. { yygotominor.yy328 = OE_None; /* EV: R-33326-45252 */}
  114858. break;
  114859. case 82: /* defer_subclause ::= DEFERRABLE init_deferred_pred_opt */
  114860. case 98: /* defer_subclause_opt ::= defer_subclause */ yytestcase(yyruleno==98);
  114861. case 100: /* onconf ::= ON CONFLICT resolvetype */ yytestcase(yyruleno==100);
  114862. case 103: /* resolvetype ::= raisetype */ yytestcase(yyruleno==103);
  114863. {yygotominor.yy328 = yymsp[0].minor.yy328;}
  114864. break;
  114865. case 86: /* conslist_opt ::= */
  114866. {yygotominor.yy0.n = 0; yygotominor.yy0.z = 0;}
  114867. break;
  114868. case 87: /* conslist_opt ::= COMMA conslist */
  114869. {yygotominor.yy0 = yymsp[-1].minor.yy0;}
  114870. break;
  114871. case 90: /* tconscomma ::= COMMA */
  114872. {pParse->constraintName.n = 0;}
  114873. break;
  114874. case 93: /* tcons ::= PRIMARY KEY LP idxlist autoinc RP onconf */
  114875. {sqlite3AddPrimaryKey(pParse,yymsp[-3].minor.yy14,yymsp[0].minor.yy328,yymsp[-2].minor.yy328,0);}
  114876. break;
  114877. case 94: /* tcons ::= UNIQUE LP idxlist RP onconf */
  114878. {sqlite3CreateIndex(pParse,0,0,0,yymsp[-2].minor.yy14,yymsp[0].minor.yy328,0,0,0,0);}
  114879. break;
  114880. case 95: /* tcons ::= CHECK LP expr RP onconf */
  114881. {sqlite3AddCheckConstraint(pParse,yymsp[-2].minor.yy346.pExpr);}
  114882. break;
  114883. case 96: /* tcons ::= FOREIGN KEY LP idxlist RP REFERENCES nm idxlist_opt refargs defer_subclause_opt */
  114884. {
  114885. sqlite3CreateForeignKey(pParse, yymsp[-6].minor.yy14, &yymsp[-3].minor.yy0, yymsp[-2].minor.yy14, yymsp[-1].minor.yy328);
  114886. sqlite3DeferForeignKey(pParse, yymsp[0].minor.yy328);
  114887. }
  114888. break;
  114889. case 99: /* onconf ::= */
  114890. {yygotominor.yy328 = OE_Default;}
  114891. break;
  114892. case 101: /* orconf ::= */
  114893. {yygotominor.yy186 = OE_Default;}
  114894. break;
  114895. case 102: /* orconf ::= OR resolvetype */
  114896. {yygotominor.yy186 = (u8)yymsp[0].minor.yy328;}
  114897. break;
  114898. case 104: /* resolvetype ::= IGNORE */
  114899. {yygotominor.yy328 = OE_Ignore;}
  114900. break;
  114901. case 105: /* resolvetype ::= REPLACE */
  114902. {yygotominor.yy328 = OE_Replace;}
  114903. break;
  114904. case 106: /* cmd ::= DROP TABLE ifexists fullname */
  114905. {
  114906. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 0, yymsp[-1].minor.yy328);
  114907. }
  114908. break;
  114909. case 109: /* cmd ::= createkw temp VIEW ifnotexists nm dbnm AS select */
  114910. {
  114911. sqlite3CreateView(pParse, &yymsp[-7].minor.yy0, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, yymsp[0].minor.yy3, yymsp[-6].minor.yy328, yymsp[-4].minor.yy328);
  114912. }
  114913. break;
  114914. case 110: /* cmd ::= DROP VIEW ifexists fullname */
  114915. {
  114916. sqlite3DropTable(pParse, yymsp[0].minor.yy65, 1, yymsp[-1].minor.yy328);
  114917. }
  114918. break;
  114919. case 111: /* cmd ::= select */
  114920. {
  114921. SelectDest dest = {SRT_Output, 0, 0, 0, 0, 0};
  114922. sqlite3Select(pParse, yymsp[0].minor.yy3, &dest);
  114923. sqlite3SelectDelete(pParse->db, yymsp[0].minor.yy3);
  114924. }
  114925. break;
  114926. case 112: /* select ::= with selectnowith */
  114927. {
  114928. Select *p = yymsp[0].minor.yy3, *pNext, *pLoop;
  114929. if( p ){
  114930. int cnt = 0, mxSelect;
  114931. p->pWith = yymsp[-1].minor.yy59;
  114932. if( p->pPrior ){
  114933. pNext = 0;
  114934. for(pLoop=p; pLoop; pNext=pLoop, pLoop=pLoop->pPrior, cnt++){
  114935. pLoop->pNext = pNext;
  114936. pLoop->selFlags |= SF_Compound;
  114937. }
  114938. mxSelect = pParse->db->aLimit[SQLITE_LIMIT_COMPOUND_SELECT];
  114939. if( mxSelect && cnt>mxSelect ){
  114940. sqlite3ErrorMsg(pParse, "too many terms in compound SELECT");
  114941. }
  114942. }
  114943. }else{
  114944. sqlite3WithDelete(pParse->db, yymsp[-1].minor.yy59);
  114945. }
  114946. yygotominor.yy3 = p;
  114947. }
  114948. break;
  114949. case 113: /* selectnowith ::= oneselect */
  114950. case 119: /* oneselect ::= values */ yytestcase(yyruleno==119);
  114951. {yygotominor.yy3 = yymsp[0].minor.yy3;}
  114952. break;
  114953. case 114: /* selectnowith ::= selectnowith multiselect_op oneselect */
  114954. {
  114955. Select *pRhs = yymsp[0].minor.yy3;
  114956. if( pRhs && pRhs->pPrior ){
  114957. SrcList *pFrom;
  114958. Token x;
  114959. x.n = 0;
  114960. pFrom = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&x,pRhs,0,0);
  114961. pRhs = sqlite3SelectNew(pParse,0,pFrom,0,0,0,0,0,0,0);
  114962. }
  114963. if( pRhs ){
  114964. pRhs->op = (u8)yymsp[-1].minor.yy328;
  114965. pRhs->pPrior = yymsp[-2].minor.yy3;
  114966. if( yymsp[-1].minor.yy328!=TK_ALL ) pParse->hasCompound = 1;
  114967. }else{
  114968. sqlite3SelectDelete(pParse->db, yymsp[-2].minor.yy3);
  114969. }
  114970. yygotominor.yy3 = pRhs;
  114971. }
  114972. break;
  114973. case 116: /* multiselect_op ::= UNION ALL */
  114974. {yygotominor.yy328 = TK_ALL;}
  114975. break;
  114976. case 118: /* oneselect ::= SELECT distinct selcollist from where_opt groupby_opt having_opt orderby_opt limit_opt */
  114977. {
  114978. yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-6].minor.yy14,yymsp[-5].minor.yy65,yymsp[-4].minor.yy132,yymsp[-3].minor.yy14,yymsp[-2].minor.yy132,yymsp[-1].minor.yy14,yymsp[-7].minor.yy381,yymsp[0].minor.yy476.pLimit,yymsp[0].minor.yy476.pOffset);
  114979. #if SELECTTRACE_ENABLED
  114980. /* Populate the Select.zSelName[] string that is used to help with
  114981. ** query planner debugging, to differentiate between multiple Select
  114982. ** objects in a complex query.
  114983. **
  114984. ** If the SELECT keyword is immediately followed by a C-style comment
  114985. ** then extract the first few alphanumeric characters from within that
  114986. ** comment to be the zSelName value. Otherwise, the label is #N where
  114987. ** is an integer that is incremented with each SELECT statement seen.
  114988. */
  114989. if( yygotominor.yy3!=0 ){
  114990. const char *z = yymsp[-8].minor.yy0.z+6;
  114991. int i;
  114992. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "#%d",
  114993. ++pParse->nSelect);
  114994. while( z[0]==' ' ) z++;
  114995. if( z[0]=='/' && z[1]=='*' ){
  114996. z += 2;
  114997. while( z[0]==' ' ) z++;
  114998. for(i=0; sqlite3Isalnum(z[i]); i++){}
  114999. sqlite3_snprintf(sizeof(yygotominor.yy3->zSelName), yygotominor.yy3->zSelName, "%.*s", i, z);
  115000. }
  115001. }
  115002. #endif /* SELECTRACE_ENABLED */
  115003. }
  115004. break;
  115005. case 120: /* values ::= VALUES LP nexprlist RP */
  115006. {
  115007. yygotominor.yy3 = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
  115008. }
  115009. break;
  115010. case 121: /* values ::= values COMMA LP exprlist RP */
  115011. {
  115012. Select *pRight = sqlite3SelectNew(pParse,yymsp[-1].minor.yy14,0,0,0,0,0,SF_Values,0,0);
  115013. if( pRight ){
  115014. pRight->op = TK_ALL;
  115015. pRight->pPrior = yymsp[-4].minor.yy3;
  115016. yygotominor.yy3 = pRight;
  115017. }else{
  115018. yygotominor.yy3 = yymsp[-4].minor.yy3;
  115019. }
  115020. }
  115021. break;
  115022. case 122: /* distinct ::= DISTINCT */
  115023. {yygotominor.yy381 = SF_Distinct;}
  115024. break;
  115025. case 123: /* distinct ::= ALL */
  115026. case 124: /* distinct ::= */ yytestcase(yyruleno==124);
  115027. {yygotominor.yy381 = 0;}
  115028. break;
  115029. case 125: /* sclp ::= selcollist COMMA */
  115030. case 243: /* idxlist_opt ::= LP idxlist RP */ yytestcase(yyruleno==243);
  115031. {yygotominor.yy14 = yymsp[-1].minor.yy14;}
  115032. break;
  115033. case 126: /* sclp ::= */
  115034. case 154: /* orderby_opt ::= */ yytestcase(yyruleno==154);
  115035. case 161: /* groupby_opt ::= */ yytestcase(yyruleno==161);
  115036. case 236: /* exprlist ::= */ yytestcase(yyruleno==236);
  115037. case 242: /* idxlist_opt ::= */ yytestcase(yyruleno==242);
  115038. {yygotominor.yy14 = 0;}
  115039. break;
  115040. case 127: /* selcollist ::= sclp expr as */
  115041. {
  115042. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-2].minor.yy14, yymsp[-1].minor.yy346.pExpr);
  115043. if( yymsp[0].minor.yy0.n>0 ) sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[0].minor.yy0, 1);
  115044. sqlite3ExprListSetSpan(pParse,yygotominor.yy14,&yymsp[-1].minor.yy346);
  115045. }
  115046. break;
  115047. case 128: /* selcollist ::= sclp STAR */
  115048. {
  115049. Expr *p = sqlite3Expr(pParse->db, TK_ALL, 0);
  115050. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-1].minor.yy14, p);
  115051. }
  115052. break;
  115053. case 129: /* selcollist ::= sclp nm DOT STAR */
  115054. {
  115055. Expr *pRight = sqlite3PExpr(pParse, TK_ALL, 0, 0, &yymsp[0].minor.yy0);
  115056. Expr *pLeft = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  115057. Expr *pDot = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight, 0);
  115058. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14, pDot);
  115059. }
  115060. break;
  115061. case 132: /* as ::= */
  115062. {yygotominor.yy0.n = 0;}
  115063. break;
  115064. case 133: /* from ::= */
  115065. {yygotominor.yy65 = sqlite3DbMallocZero(pParse->db, sizeof(*yygotominor.yy65));}
  115066. break;
  115067. case 134: /* from ::= FROM seltablist */
  115068. {
  115069. yygotominor.yy65 = yymsp[0].minor.yy65;
  115070. sqlite3SrcListShiftJoinType(yygotominor.yy65);
  115071. }
  115072. break;
  115073. case 135: /* stl_prefix ::= seltablist joinop */
  115074. {
  115075. yygotominor.yy65 = yymsp[-1].minor.yy65;
  115076. if( ALWAYS(yygotominor.yy65 && yygotominor.yy65->nSrc>0) ) yygotominor.yy65->a[yygotominor.yy65->nSrc-1].jointype = (u8)yymsp[0].minor.yy328;
  115077. }
  115078. break;
  115079. case 136: /* stl_prefix ::= */
  115080. {yygotominor.yy65 = 0;}
  115081. break;
  115082. case 137: /* seltablist ::= stl_prefix nm dbnm as indexed_opt on_opt using_opt */
  115083. {
  115084. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,&yymsp[-5].minor.yy0,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  115085. sqlite3SrcListIndexedBy(pParse, yygotominor.yy65, &yymsp[-2].minor.yy0);
  115086. }
  115087. break;
  115088. case 138: /* seltablist ::= stl_prefix LP select RP as on_opt using_opt */
  115089. {
  115090. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,yymsp[-4].minor.yy3,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  115091. }
  115092. break;
  115093. case 139: /* seltablist ::= stl_prefix LP seltablist RP as on_opt using_opt */
  115094. {
  115095. if( yymsp[-6].minor.yy65==0 && yymsp[-2].minor.yy0.n==0 && yymsp[-1].minor.yy132==0 && yymsp[0].minor.yy408==0 ){
  115096. yygotominor.yy65 = yymsp[-4].minor.yy65;
  115097. }else if( yymsp[-4].minor.yy65->nSrc==1 ){
  115098. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,0,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  115099. if( yygotominor.yy65 ){
  115100. struct SrcList_item *pNew = &yygotominor.yy65->a[yygotominor.yy65->nSrc-1];
  115101. struct SrcList_item *pOld = yymsp[-4].minor.yy65->a;
  115102. pNew->zName = pOld->zName;
  115103. pNew->zDatabase = pOld->zDatabase;
  115104. pNew->pSelect = pOld->pSelect;
  115105. pOld->zName = pOld->zDatabase = 0;
  115106. pOld->pSelect = 0;
  115107. }
  115108. sqlite3SrcListDelete(pParse->db, yymsp[-4].minor.yy65);
  115109. }else{
  115110. Select *pSubquery;
  115111. sqlite3SrcListShiftJoinType(yymsp[-4].minor.yy65);
  115112. pSubquery = sqlite3SelectNew(pParse,0,yymsp[-4].minor.yy65,0,0,0,0,SF_NestedFrom,0,0);
  115113. yygotominor.yy65 = sqlite3SrcListAppendFromTerm(pParse,yymsp[-6].minor.yy65,0,0,&yymsp[-2].minor.yy0,pSubquery,yymsp[-1].minor.yy132,yymsp[0].minor.yy408);
  115114. }
  115115. }
  115116. break;
  115117. case 140: /* dbnm ::= */
  115118. case 149: /* indexed_opt ::= */ yytestcase(yyruleno==149);
  115119. {yygotominor.yy0.z=0; yygotominor.yy0.n=0;}
  115120. break;
  115121. case 142: /* fullname ::= nm dbnm */
  115122. {yygotominor.yy65 = sqlite3SrcListAppend(pParse->db,0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);}
  115123. break;
  115124. case 143: /* joinop ::= COMMA|JOIN */
  115125. { yygotominor.yy328 = JT_INNER; }
  115126. break;
  115127. case 144: /* joinop ::= JOIN_KW JOIN */
  115128. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-1].minor.yy0,0,0); }
  115129. break;
  115130. case 145: /* joinop ::= JOIN_KW nm JOIN */
  115131. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0,0); }
  115132. break;
  115133. case 146: /* joinop ::= JOIN_KW nm nm JOIN */
  115134. { yygotominor.yy328 = sqlite3JoinType(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[-1].minor.yy0); }
  115135. break;
  115136. case 147: /* on_opt ::= ON expr */
  115137. case 164: /* having_opt ::= HAVING expr */ yytestcase(yyruleno==164);
  115138. case 171: /* where_opt ::= WHERE expr */ yytestcase(yyruleno==171);
  115139. case 231: /* case_else ::= ELSE expr */ yytestcase(yyruleno==231);
  115140. case 233: /* case_operand ::= expr */ yytestcase(yyruleno==233);
  115141. {yygotominor.yy132 = yymsp[0].minor.yy346.pExpr;}
  115142. break;
  115143. case 148: /* on_opt ::= */
  115144. case 163: /* having_opt ::= */ yytestcase(yyruleno==163);
  115145. case 170: /* where_opt ::= */ yytestcase(yyruleno==170);
  115146. case 232: /* case_else ::= */ yytestcase(yyruleno==232);
  115147. case 234: /* case_operand ::= */ yytestcase(yyruleno==234);
  115148. {yygotominor.yy132 = 0;}
  115149. break;
  115150. case 151: /* indexed_opt ::= NOT INDEXED */
  115151. {yygotominor.yy0.z=0; yygotominor.yy0.n=1;}
  115152. break;
  115153. case 152: /* using_opt ::= USING LP idlist RP */
  115154. case 180: /* inscollist_opt ::= LP idlist RP */ yytestcase(yyruleno==180);
  115155. {yygotominor.yy408 = yymsp[-1].minor.yy408;}
  115156. break;
  115157. case 153: /* using_opt ::= */
  115158. case 179: /* inscollist_opt ::= */ yytestcase(yyruleno==179);
  115159. {yygotominor.yy408 = 0;}
  115160. break;
  115161. case 155: /* orderby_opt ::= ORDER BY sortlist */
  115162. case 162: /* groupby_opt ::= GROUP BY nexprlist */ yytestcase(yyruleno==162);
  115163. case 235: /* exprlist ::= nexprlist */ yytestcase(yyruleno==235);
  115164. {yygotominor.yy14 = yymsp[0].minor.yy14;}
  115165. break;
  115166. case 156: /* sortlist ::= sortlist COMMA expr sortorder */
  115167. {
  115168. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-3].minor.yy14,yymsp[-1].minor.yy346.pExpr);
  115169. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  115170. }
  115171. break;
  115172. case 157: /* sortlist ::= expr sortorder */
  115173. {
  115174. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[-1].minor.yy346.pExpr);
  115175. if( yygotominor.yy14 && ALWAYS(yygotominor.yy14->a) ) yygotominor.yy14->a[0].sortOrder = (u8)yymsp[0].minor.yy328;
  115176. }
  115177. break;
  115178. case 158: /* sortorder ::= ASC */
  115179. case 160: /* sortorder ::= */ yytestcase(yyruleno==160);
  115180. {yygotominor.yy328 = SQLITE_SO_ASC;}
  115181. break;
  115182. case 159: /* sortorder ::= DESC */
  115183. {yygotominor.yy328 = SQLITE_SO_DESC;}
  115184. break;
  115185. case 165: /* limit_opt ::= */
  115186. {yygotominor.yy476.pLimit = 0; yygotominor.yy476.pOffset = 0;}
  115187. break;
  115188. case 166: /* limit_opt ::= LIMIT expr */
  115189. {yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr; yygotominor.yy476.pOffset = 0;}
  115190. break;
  115191. case 167: /* limit_opt ::= LIMIT expr OFFSET expr */
  115192. {yygotominor.yy476.pLimit = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pOffset = yymsp[0].minor.yy346.pExpr;}
  115193. break;
  115194. case 168: /* limit_opt ::= LIMIT expr COMMA expr */
  115195. {yygotominor.yy476.pOffset = yymsp[-2].minor.yy346.pExpr; yygotominor.yy476.pLimit = yymsp[0].minor.yy346.pExpr;}
  115196. break;
  115197. case 169: /* cmd ::= with DELETE FROM fullname indexed_opt where_opt */
  115198. {
  115199. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  115200. sqlite3SrcListIndexedBy(pParse, yymsp[-2].minor.yy65, &yymsp[-1].minor.yy0);
  115201. sqlite3DeleteFrom(pParse,yymsp[-2].minor.yy65,yymsp[0].minor.yy132);
  115202. }
  115203. break;
  115204. case 172: /* cmd ::= with UPDATE orconf fullname indexed_opt SET setlist where_opt */
  115205. {
  115206. sqlite3WithPush(pParse, yymsp[-7].minor.yy59, 1);
  115207. sqlite3SrcListIndexedBy(pParse, yymsp[-4].minor.yy65, &yymsp[-3].minor.yy0);
  115208. sqlite3ExprListCheckLength(pParse,yymsp[-1].minor.yy14,"set list");
  115209. sqlite3Update(pParse,yymsp[-4].minor.yy65,yymsp[-1].minor.yy14,yymsp[0].minor.yy132,yymsp[-5].minor.yy186);
  115210. }
  115211. break;
  115212. case 173: /* setlist ::= setlist COMMA nm EQ expr */
  115213. {
  115214. yygotominor.yy14 = sqlite3ExprListAppend(pParse, yymsp[-4].minor.yy14, yymsp[0].minor.yy346.pExpr);
  115215. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  115216. }
  115217. break;
  115218. case 174: /* setlist ::= nm EQ expr */
  115219. {
  115220. yygotominor.yy14 = sqlite3ExprListAppend(pParse, 0, yymsp[0].minor.yy346.pExpr);
  115221. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  115222. }
  115223. break;
  115224. case 175: /* cmd ::= with insert_cmd INTO fullname inscollist_opt select */
  115225. {
  115226. sqlite3WithPush(pParse, yymsp[-5].minor.yy59, 1);
  115227. sqlite3Insert(pParse, yymsp[-2].minor.yy65, yymsp[0].minor.yy3, yymsp[-1].minor.yy408, yymsp[-4].minor.yy186);
  115228. }
  115229. break;
  115230. case 176: /* cmd ::= with insert_cmd INTO fullname inscollist_opt DEFAULT VALUES */
  115231. {
  115232. sqlite3WithPush(pParse, yymsp[-6].minor.yy59, 1);
  115233. sqlite3Insert(pParse, yymsp[-3].minor.yy65, 0, yymsp[-2].minor.yy408, yymsp[-5].minor.yy186);
  115234. }
  115235. break;
  115236. case 177: /* insert_cmd ::= INSERT orconf */
  115237. {yygotominor.yy186 = yymsp[0].minor.yy186;}
  115238. break;
  115239. case 178: /* insert_cmd ::= REPLACE */
  115240. {yygotominor.yy186 = OE_Replace;}
  115241. break;
  115242. case 181: /* idlist ::= idlist COMMA nm */
  115243. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,yymsp[-2].minor.yy408,&yymsp[0].minor.yy0);}
  115244. break;
  115245. case 182: /* idlist ::= nm */
  115246. {yygotominor.yy408 = sqlite3IdListAppend(pParse->db,0,&yymsp[0].minor.yy0);}
  115247. break;
  115248. case 183: /* expr ::= term */
  115249. {yygotominor.yy346 = yymsp[0].minor.yy346;}
  115250. break;
  115251. case 184: /* expr ::= LP expr RP */
  115252. {yygotominor.yy346.pExpr = yymsp[-1].minor.yy346.pExpr; spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);}
  115253. break;
  115254. case 185: /* term ::= NULL */
  115255. case 190: /* term ::= INTEGER|FLOAT|BLOB */ yytestcase(yyruleno==190);
  115256. case 191: /* term ::= STRING */ yytestcase(yyruleno==191);
  115257. {spanExpr(&yygotominor.yy346, pParse, yymsp[0].major, &yymsp[0].minor.yy0);}
  115258. break;
  115259. case 186: /* expr ::= ID|INDEXED */
  115260. case 187: /* expr ::= JOIN_KW */ yytestcase(yyruleno==187);
  115261. {spanExpr(&yygotominor.yy346, pParse, TK_ID, &yymsp[0].minor.yy0);}
  115262. break;
  115263. case 188: /* expr ::= nm DOT nm */
  115264. {
  115265. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  115266. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  115267. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp2, 0);
  115268. spanSet(&yygotominor.yy346,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0);
  115269. }
  115270. break;
  115271. case 189: /* expr ::= nm DOT nm DOT nm */
  115272. {
  115273. Expr *temp1 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-4].minor.yy0);
  115274. Expr *temp2 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[-2].minor.yy0);
  115275. Expr *temp3 = sqlite3PExpr(pParse, TK_ID, 0, 0, &yymsp[0].minor.yy0);
  115276. Expr *temp4 = sqlite3PExpr(pParse, TK_DOT, temp2, temp3, 0);
  115277. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_DOT, temp1, temp4, 0);
  115278. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  115279. }
  115280. break;
  115281. case 192: /* expr ::= VARIABLE */
  115282. {
  115283. if( yymsp[0].minor.yy0.n>=2 && yymsp[0].minor.yy0.z[0]=='#' && sqlite3Isdigit(yymsp[0].minor.yy0.z[1]) ){
  115284. /* When doing a nested parse, one can include terms in an expression
  115285. ** that look like this: #1 #2 ... These terms refer to registers
  115286. ** in the virtual machine. #N is the N-th register. */
  115287. if( pParse->nested==0 ){
  115288. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &yymsp[0].minor.yy0);
  115289. yygotominor.yy346.pExpr = 0;
  115290. }else{
  115291. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, &yymsp[0].minor.yy0);
  115292. if( yygotominor.yy346.pExpr ) sqlite3GetInt32(&yymsp[0].minor.yy0.z[1], &yygotominor.yy346.pExpr->iTable);
  115293. }
  115294. }else{
  115295. spanExpr(&yygotominor.yy346, pParse, TK_VARIABLE, &yymsp[0].minor.yy0);
  115296. sqlite3ExprAssignVarNumber(pParse, yygotominor.yy346.pExpr);
  115297. }
  115298. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  115299. }
  115300. break;
  115301. case 193: /* expr ::= expr COLLATE ID|STRING */
  115302. {
  115303. yygotominor.yy346.pExpr = sqlite3ExprAddCollateToken(pParse, yymsp[-2].minor.yy346.pExpr, &yymsp[0].minor.yy0);
  115304. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  115305. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115306. }
  115307. break;
  115308. case 194: /* expr ::= CAST LP expr AS typetoken RP */
  115309. {
  115310. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CAST, yymsp[-3].minor.yy346.pExpr, 0, &yymsp[-1].minor.yy0);
  115311. spanSet(&yygotominor.yy346,&yymsp[-5].minor.yy0,&yymsp[0].minor.yy0);
  115312. }
  115313. break;
  115314. case 195: /* expr ::= ID|INDEXED LP distinct exprlist RP */
  115315. {
  115316. if( yymsp[-1].minor.yy14 && yymsp[-1].minor.yy14->nExpr>pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
  115317. sqlite3ErrorMsg(pParse, "too many arguments on function %T", &yymsp[-4].minor.yy0);
  115318. }
  115319. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, yymsp[-1].minor.yy14, &yymsp[-4].minor.yy0);
  115320. spanSet(&yygotominor.yy346,&yymsp[-4].minor.yy0,&yymsp[0].minor.yy0);
  115321. if( yymsp[-2].minor.yy381 && yygotominor.yy346.pExpr ){
  115322. yygotominor.yy346.pExpr->flags |= EP_Distinct;
  115323. }
  115324. }
  115325. break;
  115326. case 196: /* expr ::= ID|INDEXED LP STAR RP */
  115327. {
  115328. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[-3].minor.yy0);
  115329. spanSet(&yygotominor.yy346,&yymsp[-3].minor.yy0,&yymsp[0].minor.yy0);
  115330. }
  115331. break;
  115332. case 197: /* term ::= CTIME_KW */
  115333. {
  115334. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, 0, &yymsp[0].minor.yy0);
  115335. spanSet(&yygotominor.yy346, &yymsp[0].minor.yy0, &yymsp[0].minor.yy0);
  115336. }
  115337. break;
  115338. case 198: /* expr ::= expr AND expr */
  115339. case 199: /* expr ::= expr OR expr */ yytestcase(yyruleno==199);
  115340. case 200: /* expr ::= expr LT|GT|GE|LE expr */ yytestcase(yyruleno==200);
  115341. case 201: /* expr ::= expr EQ|NE expr */ yytestcase(yyruleno==201);
  115342. case 202: /* expr ::= expr BITAND|BITOR|LSHIFT|RSHIFT expr */ yytestcase(yyruleno==202);
  115343. case 203: /* expr ::= expr PLUS|MINUS expr */ yytestcase(yyruleno==203);
  115344. case 204: /* expr ::= expr STAR|SLASH|REM expr */ yytestcase(yyruleno==204);
  115345. case 205: /* expr ::= expr CONCAT expr */ yytestcase(yyruleno==205);
  115346. {spanBinaryExpr(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);}
  115347. break;
  115348. case 206: /* likeop ::= LIKE_KW|MATCH */
  115349. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 0;}
  115350. break;
  115351. case 207: /* likeop ::= NOT LIKE_KW|MATCH */
  115352. {yygotominor.yy96.eOperator = yymsp[0].minor.yy0; yygotominor.yy96.bNot = 1;}
  115353. break;
  115354. case 208: /* expr ::= expr likeop expr */
  115355. {
  115356. ExprList *pList;
  115357. pList = sqlite3ExprListAppend(pParse,0, yymsp[0].minor.yy346.pExpr);
  115358. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-2].minor.yy346.pExpr);
  115359. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-1].minor.yy96.eOperator);
  115360. if( yymsp[-1].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115361. yygotominor.yy346.zStart = yymsp[-2].minor.yy346.zStart;
  115362. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  115363. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  115364. }
  115365. break;
  115366. case 209: /* expr ::= expr likeop expr ESCAPE expr */
  115367. {
  115368. ExprList *pList;
  115369. pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  115370. pList = sqlite3ExprListAppend(pParse,pList, yymsp[-4].minor.yy346.pExpr);
  115371. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  115372. yygotominor.yy346.pExpr = sqlite3ExprFunction(pParse, pList, &yymsp[-3].minor.yy96.eOperator);
  115373. if( yymsp[-3].minor.yy96.bNot ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115374. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  115375. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  115376. if( yygotominor.yy346.pExpr ) yygotominor.yy346.pExpr->flags |= EP_InfixFunc;
  115377. }
  115378. break;
  115379. case 210: /* expr ::= expr ISNULL|NOTNULL */
  115380. {spanUnaryPostfix(&yygotominor.yy346,pParse,yymsp[0].major,&yymsp[-1].minor.yy346,&yymsp[0].minor.yy0);}
  115381. break;
  115382. case 211: /* expr ::= expr NOT NULL */
  115383. {spanUnaryPostfix(&yygotominor.yy346,pParse,TK_NOTNULL,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy0);}
  115384. break;
  115385. case 212: /* expr ::= expr IS expr */
  115386. {
  115387. spanBinaryExpr(&yygotominor.yy346,pParse,TK_IS,&yymsp[-2].minor.yy346,&yymsp[0].minor.yy346);
  115388. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_ISNULL);
  115389. }
  115390. break;
  115391. case 213: /* expr ::= expr IS NOT expr */
  115392. {
  115393. spanBinaryExpr(&yygotominor.yy346,pParse,TK_ISNOT,&yymsp[-3].minor.yy346,&yymsp[0].minor.yy346);
  115394. binaryToUnaryIfNull(pParse, yymsp[0].minor.yy346.pExpr, yygotominor.yy346.pExpr, TK_NOTNULL);
  115395. }
  115396. break;
  115397. case 214: /* expr ::= NOT expr */
  115398. case 215: /* expr ::= BITNOT expr */ yytestcase(yyruleno==215);
  115399. {spanUnaryPrefix(&yygotominor.yy346,pParse,yymsp[-1].major,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  115400. break;
  115401. case 216: /* expr ::= MINUS expr */
  115402. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UMINUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  115403. break;
  115404. case 217: /* expr ::= PLUS expr */
  115405. {spanUnaryPrefix(&yygotominor.yy346,pParse,TK_UPLUS,&yymsp[0].minor.yy346,&yymsp[-1].minor.yy0);}
  115406. break;
  115407. case 220: /* expr ::= expr between_op expr AND expr */
  115408. {
  115409. ExprList *pList = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  115410. pList = sqlite3ExprListAppend(pParse,pList, yymsp[0].minor.yy346.pExpr);
  115411. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_BETWEEN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  115412. if( yygotominor.yy346.pExpr ){
  115413. yygotominor.yy346.pExpr->x.pList = pList;
  115414. }else{
  115415. sqlite3ExprListDelete(pParse->db, pList);
  115416. }
  115417. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115418. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  115419. yygotominor.yy346.zEnd = yymsp[0].minor.yy346.zEnd;
  115420. }
  115421. break;
  115422. case 223: /* expr ::= expr in_op LP exprlist RP */
  115423. {
  115424. if( yymsp[-1].minor.yy14==0 ){
  115425. /* Expressions of the form
  115426. **
  115427. ** expr1 IN ()
  115428. ** expr1 NOT IN ()
  115429. **
  115430. ** simplify to constants 0 (false) and 1 (true), respectively,
  115431. ** regardless of the value of expr1.
  115432. */
  115433. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &sqlite3IntTokens[yymsp[-3].minor.yy328]);
  115434. sqlite3ExprDelete(pParse->db, yymsp[-4].minor.yy346.pExpr);
  115435. }else if( yymsp[-1].minor.yy14->nExpr==1 ){
  115436. /* Expressions of the form:
  115437. **
  115438. ** expr1 IN (?1)
  115439. ** expr1 NOT IN (?2)
  115440. **
  115441. ** with exactly one value on the RHS can be simplified to something
  115442. ** like this:
  115443. **
  115444. ** expr1 == ?1
  115445. ** expr1 <> ?2
  115446. **
  115447. ** But, the RHS of the == or <> is marked with the EP_Generic flag
  115448. ** so that it may not contribute to the computation of comparison
  115449. ** affinity or the collating sequence to use for comparison. Otherwise,
  115450. ** the semantics would be subtly different from IN or NOT IN.
  115451. */
  115452. Expr *pRHS = yymsp[-1].minor.yy14->a[0].pExpr;
  115453. yymsp[-1].minor.yy14->a[0].pExpr = 0;
  115454. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  115455. /* pRHS cannot be NULL because a malloc error would have been detected
  115456. ** before now and control would have never reached this point */
  115457. if( ALWAYS(pRHS) ){
  115458. pRHS->flags &= ~EP_Collate;
  115459. pRHS->flags |= EP_Generic;
  115460. }
  115461. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, yymsp[-3].minor.yy328 ? TK_NE : TK_EQ, yymsp[-4].minor.yy346.pExpr, pRHS, 0);
  115462. }else{
  115463. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  115464. if( yygotominor.yy346.pExpr ){
  115465. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy14;
  115466. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115467. }else{
  115468. sqlite3ExprListDelete(pParse->db, yymsp[-1].minor.yy14);
  115469. }
  115470. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115471. }
  115472. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  115473. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115474. }
  115475. break;
  115476. case 224: /* expr ::= LP select RP */
  115477. {
  115478. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_SELECT, 0, 0, 0);
  115479. if( yygotominor.yy346.pExpr ){
  115480. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  115481. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
  115482. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115483. }else{
  115484. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  115485. }
  115486. yygotominor.yy346.zStart = yymsp[-2].minor.yy0.z;
  115487. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115488. }
  115489. break;
  115490. case 225: /* expr ::= expr in_op LP select RP */
  115491. {
  115492. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-4].minor.yy346.pExpr, 0, 0);
  115493. if( yygotominor.yy346.pExpr ){
  115494. yygotominor.yy346.pExpr->x.pSelect = yymsp[-1].minor.yy3;
  115495. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
  115496. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115497. }else{
  115498. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  115499. }
  115500. if( yymsp[-3].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115501. yygotominor.yy346.zStart = yymsp[-4].minor.yy346.zStart;
  115502. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115503. }
  115504. break;
  115505. case 226: /* expr ::= expr in_op nm dbnm */
  115506. {
  115507. SrcList *pSrc = sqlite3SrcListAppend(pParse->db, 0,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0);
  115508. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_IN, yymsp[-3].minor.yy346.pExpr, 0, 0);
  115509. if( yygotominor.yy346.pExpr ){
  115510. yygotominor.yy346.pExpr->x.pSelect = sqlite3SelectNew(pParse, 0,pSrc,0,0,0,0,0,0,0);
  115511. ExprSetProperty(yygotominor.yy346.pExpr, EP_xIsSelect);
  115512. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115513. }else{
  115514. sqlite3SrcListDelete(pParse->db, pSrc);
  115515. }
  115516. if( yymsp[-2].minor.yy328 ) yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_NOT, yygotominor.yy346.pExpr, 0, 0);
  115517. yygotominor.yy346.zStart = yymsp[-3].minor.yy346.zStart;
  115518. yygotominor.yy346.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];
  115519. }
  115520. break;
  115521. case 227: /* expr ::= EXISTS LP select RP */
  115522. {
  115523. Expr *p = yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_EXISTS, 0, 0, 0);
  115524. if( p ){
  115525. p->x.pSelect = yymsp[-1].minor.yy3;
  115526. ExprSetProperty(p, EP_xIsSelect);
  115527. sqlite3ExprSetHeight(pParse, p);
  115528. }else{
  115529. sqlite3SelectDelete(pParse->db, yymsp[-1].minor.yy3);
  115530. }
  115531. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  115532. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115533. }
  115534. break;
  115535. case 228: /* expr ::= CASE case_operand case_exprlist case_else END */
  115536. {
  115537. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_CASE, yymsp[-3].minor.yy132, 0, 0);
  115538. if( yygotominor.yy346.pExpr ){
  115539. yygotominor.yy346.pExpr->x.pList = yymsp[-1].minor.yy132 ? sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[-1].minor.yy132) : yymsp[-2].minor.yy14;
  115540. sqlite3ExprSetHeight(pParse, yygotominor.yy346.pExpr);
  115541. }else{
  115542. sqlite3ExprListDelete(pParse->db, yymsp[-2].minor.yy14);
  115543. sqlite3ExprDelete(pParse->db, yymsp[-1].minor.yy132);
  115544. }
  115545. yygotominor.yy346.zStart = yymsp[-4].minor.yy0.z;
  115546. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115547. }
  115548. break;
  115549. case 229: /* case_exprlist ::= case_exprlist WHEN expr THEN expr */
  115550. {
  115551. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, yymsp[-2].minor.yy346.pExpr);
  115552. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  115553. }
  115554. break;
  115555. case 230: /* case_exprlist ::= WHEN expr THEN expr */
  115556. {
  115557. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, yymsp[-2].minor.yy346.pExpr);
  115558. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yygotominor.yy14, yymsp[0].minor.yy346.pExpr);
  115559. }
  115560. break;
  115561. case 237: /* nexprlist ::= nexprlist COMMA expr */
  115562. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-2].minor.yy14,yymsp[0].minor.yy346.pExpr);}
  115563. break;
  115564. case 238: /* nexprlist ::= expr */
  115565. {yygotominor.yy14 = sqlite3ExprListAppend(pParse,0,yymsp[0].minor.yy346.pExpr);}
  115566. break;
  115567. case 239: /* cmd ::= createkw uniqueflag INDEX ifnotexists nm dbnm ON nm LP idxlist RP where_opt */
  115568. {
  115569. sqlite3CreateIndex(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0,
  115570. sqlite3SrcListAppend(pParse->db,0,&yymsp[-4].minor.yy0,0), yymsp[-2].minor.yy14, yymsp[-10].minor.yy328,
  115571. &yymsp[-11].minor.yy0, yymsp[0].minor.yy132, SQLITE_SO_ASC, yymsp[-8].minor.yy328);
  115572. }
  115573. break;
  115574. case 240: /* uniqueflag ::= UNIQUE */
  115575. case 291: /* raisetype ::= ABORT */ yytestcase(yyruleno==291);
  115576. {yygotominor.yy328 = OE_Abort;}
  115577. break;
  115578. case 241: /* uniqueflag ::= */
  115579. {yygotominor.yy328 = OE_None;}
  115580. break;
  115581. case 244: /* idxlist ::= idxlist COMMA nm collate sortorder */
  115582. {
  115583. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  115584. yygotominor.yy14 = sqlite3ExprListAppend(pParse,yymsp[-4].minor.yy14, p);
  115585. sqlite3ExprListSetName(pParse,yygotominor.yy14,&yymsp[-2].minor.yy0,1);
  115586. sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
  115587. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  115588. }
  115589. break;
  115590. case 245: /* idxlist ::= nm collate sortorder */
  115591. {
  115592. Expr *p = sqlite3ExprAddCollateToken(pParse, 0, &yymsp[-1].minor.yy0);
  115593. yygotominor.yy14 = sqlite3ExprListAppend(pParse,0, p);
  115594. sqlite3ExprListSetName(pParse, yygotominor.yy14, &yymsp[-2].minor.yy0, 1);
  115595. sqlite3ExprListCheckLength(pParse, yygotominor.yy14, "index");
  115596. if( yygotominor.yy14 ) yygotominor.yy14->a[yygotominor.yy14->nExpr-1].sortOrder = (u8)yymsp[0].minor.yy328;
  115597. }
  115598. break;
  115599. case 246: /* collate ::= */
  115600. {yygotominor.yy0.z = 0; yygotominor.yy0.n = 0;}
  115601. break;
  115602. case 248: /* cmd ::= DROP INDEX ifexists fullname */
  115603. {sqlite3DropIndex(pParse, yymsp[0].minor.yy65, yymsp[-1].minor.yy328);}
  115604. break;
  115605. case 249: /* cmd ::= VACUUM */
  115606. case 250: /* cmd ::= VACUUM nm */ yytestcase(yyruleno==250);
  115607. {sqlite3Vacuum(pParse);}
  115608. break;
  115609. case 251: /* cmd ::= PRAGMA nm dbnm */
  115610. {sqlite3Pragma(pParse,&yymsp[-1].minor.yy0,&yymsp[0].minor.yy0,0,0);}
  115611. break;
  115612. case 252: /* cmd ::= PRAGMA nm dbnm EQ nmnum */
  115613. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,0);}
  115614. break;
  115615. case 253: /* cmd ::= PRAGMA nm dbnm LP nmnum RP */
  115616. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,0);}
  115617. break;
  115618. case 254: /* cmd ::= PRAGMA nm dbnm EQ minus_num */
  115619. {sqlite3Pragma(pParse,&yymsp[-3].minor.yy0,&yymsp[-2].minor.yy0,&yymsp[0].minor.yy0,1);}
  115620. break;
  115621. case 255: /* cmd ::= PRAGMA nm dbnm LP minus_num RP */
  115622. {sqlite3Pragma(pParse,&yymsp[-4].minor.yy0,&yymsp[-3].minor.yy0,&yymsp[-1].minor.yy0,1);}
  115623. break;
  115624. case 264: /* cmd ::= createkw trigger_decl BEGIN trigger_cmd_list END */
  115625. {
  115626. Token all;
  115627. all.z = yymsp[-3].minor.yy0.z;
  115628. all.n = (int)(yymsp[0].minor.yy0.z - yymsp[-3].minor.yy0.z) + yymsp[0].minor.yy0.n;
  115629. sqlite3FinishTrigger(pParse, yymsp[-1].minor.yy473, &all);
  115630. }
  115631. break;
  115632. case 265: /* trigger_decl ::= temp TRIGGER ifnotexists nm dbnm trigger_time trigger_event ON fullname foreach_clause when_clause */
  115633. {
  115634. sqlite3BeginTrigger(pParse, &yymsp[-7].minor.yy0, &yymsp[-6].minor.yy0, yymsp[-5].minor.yy328, yymsp[-4].minor.yy378.a, yymsp[-4].minor.yy378.b, yymsp[-2].minor.yy65, yymsp[0].minor.yy132, yymsp[-10].minor.yy328, yymsp[-8].minor.yy328);
  115635. yygotominor.yy0 = (yymsp[-6].minor.yy0.n==0?yymsp[-7].minor.yy0:yymsp[-6].minor.yy0);
  115636. }
  115637. break;
  115638. case 266: /* trigger_time ::= BEFORE */
  115639. case 269: /* trigger_time ::= */ yytestcase(yyruleno==269);
  115640. { yygotominor.yy328 = TK_BEFORE; }
  115641. break;
  115642. case 267: /* trigger_time ::= AFTER */
  115643. { yygotominor.yy328 = TK_AFTER; }
  115644. break;
  115645. case 268: /* trigger_time ::= INSTEAD OF */
  115646. { yygotominor.yy328 = TK_INSTEAD;}
  115647. break;
  115648. case 270: /* trigger_event ::= DELETE|INSERT */
  115649. case 271: /* trigger_event ::= UPDATE */ yytestcase(yyruleno==271);
  115650. {yygotominor.yy378.a = yymsp[0].major; yygotominor.yy378.b = 0;}
  115651. break;
  115652. case 272: /* trigger_event ::= UPDATE OF idlist */
  115653. {yygotominor.yy378.a = TK_UPDATE; yygotominor.yy378.b = yymsp[0].minor.yy408;}
  115654. break;
  115655. case 275: /* when_clause ::= */
  115656. case 296: /* key_opt ::= */ yytestcase(yyruleno==296);
  115657. { yygotominor.yy132 = 0; }
  115658. break;
  115659. case 276: /* when_clause ::= WHEN expr */
  115660. case 297: /* key_opt ::= KEY expr */ yytestcase(yyruleno==297);
  115661. { yygotominor.yy132 = yymsp[0].minor.yy346.pExpr; }
  115662. break;
  115663. case 277: /* trigger_cmd_list ::= trigger_cmd_list trigger_cmd SEMI */
  115664. {
  115665. assert( yymsp[-2].minor.yy473!=0 );
  115666. yymsp[-2].minor.yy473->pLast->pNext = yymsp[-1].minor.yy473;
  115667. yymsp[-2].minor.yy473->pLast = yymsp[-1].minor.yy473;
  115668. yygotominor.yy473 = yymsp[-2].minor.yy473;
  115669. }
  115670. break;
  115671. case 278: /* trigger_cmd_list ::= trigger_cmd SEMI */
  115672. {
  115673. assert( yymsp[-1].minor.yy473!=0 );
  115674. yymsp[-1].minor.yy473->pLast = yymsp[-1].minor.yy473;
  115675. yygotominor.yy473 = yymsp[-1].minor.yy473;
  115676. }
  115677. break;
  115678. case 280: /* trnm ::= nm DOT nm */
  115679. {
  115680. yygotominor.yy0 = yymsp[0].minor.yy0;
  115681. sqlite3ErrorMsg(pParse,
  115682. "qualified table names are not allowed on INSERT, UPDATE, and DELETE "
  115683. "statements within triggers");
  115684. }
  115685. break;
  115686. case 282: /* tridxby ::= INDEXED BY nm */
  115687. {
  115688. sqlite3ErrorMsg(pParse,
  115689. "the INDEXED BY clause is not allowed on UPDATE or DELETE statements "
  115690. "within triggers");
  115691. }
  115692. break;
  115693. case 283: /* tridxby ::= NOT INDEXED */
  115694. {
  115695. sqlite3ErrorMsg(pParse,
  115696. "the NOT INDEXED clause is not allowed on UPDATE or DELETE statements "
  115697. "within triggers");
  115698. }
  115699. break;
  115700. case 284: /* trigger_cmd ::= UPDATE orconf trnm tridxby SET setlist where_opt */
  115701. { yygotominor.yy473 = sqlite3TriggerUpdateStep(pParse->db, &yymsp[-4].minor.yy0, yymsp[-1].minor.yy14, yymsp[0].minor.yy132, yymsp[-5].minor.yy186); }
  115702. break;
  115703. case 285: /* trigger_cmd ::= insert_cmd INTO trnm inscollist_opt select */
  115704. {yygotominor.yy473 = sqlite3TriggerInsertStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[-1].minor.yy408, yymsp[0].minor.yy3, yymsp[-4].minor.yy186);}
  115705. break;
  115706. case 286: /* trigger_cmd ::= DELETE FROM trnm tridxby where_opt */
  115707. {yygotominor.yy473 = sqlite3TriggerDeleteStep(pParse->db, &yymsp[-2].minor.yy0, yymsp[0].minor.yy132);}
  115708. break;
  115709. case 287: /* trigger_cmd ::= select */
  115710. {yygotominor.yy473 = sqlite3TriggerSelectStep(pParse->db, yymsp[0].minor.yy3); }
  115711. break;
  115712. case 288: /* expr ::= RAISE LP IGNORE RP */
  115713. {
  115714. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, 0);
  115715. if( yygotominor.yy346.pExpr ){
  115716. yygotominor.yy346.pExpr->affinity = OE_Ignore;
  115717. }
  115718. yygotominor.yy346.zStart = yymsp[-3].minor.yy0.z;
  115719. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115720. }
  115721. break;
  115722. case 289: /* expr ::= RAISE LP raisetype COMMA nm RP */
  115723. {
  115724. yygotominor.yy346.pExpr = sqlite3PExpr(pParse, TK_RAISE, 0, 0, &yymsp[-1].minor.yy0);
  115725. if( yygotominor.yy346.pExpr ) {
  115726. yygotominor.yy346.pExpr->affinity = (char)yymsp[-3].minor.yy328;
  115727. }
  115728. yygotominor.yy346.zStart = yymsp[-5].minor.yy0.z;
  115729. yygotominor.yy346.zEnd = &yymsp[0].minor.yy0.z[yymsp[0].minor.yy0.n];
  115730. }
  115731. break;
  115732. case 290: /* raisetype ::= ROLLBACK */
  115733. {yygotominor.yy328 = OE_Rollback;}
  115734. break;
  115735. case 292: /* raisetype ::= FAIL */
  115736. {yygotominor.yy328 = OE_Fail;}
  115737. break;
  115738. case 293: /* cmd ::= DROP TRIGGER ifexists fullname */
  115739. {
  115740. sqlite3DropTrigger(pParse,yymsp[0].minor.yy65,yymsp[-1].minor.yy328);
  115741. }
  115742. break;
  115743. case 294: /* cmd ::= ATTACH database_kw_opt expr AS expr key_opt */
  115744. {
  115745. sqlite3Attach(pParse, yymsp[-3].minor.yy346.pExpr, yymsp[-1].minor.yy346.pExpr, yymsp[0].minor.yy132);
  115746. }
  115747. break;
  115748. case 295: /* cmd ::= DETACH database_kw_opt expr */
  115749. {
  115750. sqlite3Detach(pParse, yymsp[0].minor.yy346.pExpr);
  115751. }
  115752. break;
  115753. case 300: /* cmd ::= REINDEX */
  115754. {sqlite3Reindex(pParse, 0, 0);}
  115755. break;
  115756. case 301: /* cmd ::= REINDEX nm dbnm */
  115757. {sqlite3Reindex(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  115758. break;
  115759. case 302: /* cmd ::= ANALYZE */
  115760. {sqlite3Analyze(pParse, 0, 0);}
  115761. break;
  115762. case 303: /* cmd ::= ANALYZE nm dbnm */
  115763. {sqlite3Analyze(pParse, &yymsp[-1].minor.yy0, &yymsp[0].minor.yy0);}
  115764. break;
  115765. case 304: /* cmd ::= ALTER TABLE fullname RENAME TO nm */
  115766. {
  115767. sqlite3AlterRenameTable(pParse,yymsp[-3].minor.yy65,&yymsp[0].minor.yy0);
  115768. }
  115769. break;
  115770. case 305: /* cmd ::= ALTER TABLE add_column_fullname ADD kwcolumn_opt column */
  115771. {
  115772. sqlite3AlterFinishAddColumn(pParse, &yymsp[0].minor.yy0);
  115773. }
  115774. break;
  115775. case 306: /* add_column_fullname ::= fullname */
  115776. {
  115777. pParse->db->lookaside.bEnabled = 0;
  115778. sqlite3AlterBeginAddColumn(pParse, yymsp[0].minor.yy65);
  115779. }
  115780. break;
  115781. case 309: /* cmd ::= create_vtab */
  115782. {sqlite3VtabFinishParse(pParse,0);}
  115783. break;
  115784. case 310: /* cmd ::= create_vtab LP vtabarglist RP */
  115785. {sqlite3VtabFinishParse(pParse,&yymsp[0].minor.yy0);}
  115786. break;
  115787. case 311: /* create_vtab ::= createkw VIRTUAL TABLE ifnotexists nm dbnm USING nm */
  115788. {
  115789. sqlite3VtabBeginParse(pParse, &yymsp[-3].minor.yy0, &yymsp[-2].minor.yy0, &yymsp[0].minor.yy0, yymsp[-4].minor.yy328);
  115790. }
  115791. break;
  115792. case 314: /* vtabarg ::= */
  115793. {sqlite3VtabArgInit(pParse);}
  115794. break;
  115795. case 316: /* vtabargtoken ::= ANY */
  115796. case 317: /* vtabargtoken ::= lp anylist RP */ yytestcase(yyruleno==317);
  115797. case 318: /* lp ::= LP */ yytestcase(yyruleno==318);
  115798. {sqlite3VtabArgExtend(pParse,&yymsp[0].minor.yy0);}
  115799. break;
  115800. case 322: /* with ::= */
  115801. {yygotominor.yy59 = 0;}
  115802. break;
  115803. case 323: /* with ::= WITH wqlist */
  115804. case 324: /* with ::= WITH RECURSIVE wqlist */ yytestcase(yyruleno==324);
  115805. { yygotominor.yy59 = yymsp[0].minor.yy59; }
  115806. break;
  115807. case 325: /* wqlist ::= nm idxlist_opt AS LP select RP */
  115808. {
  115809. yygotominor.yy59 = sqlite3WithAdd(pParse, 0, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  115810. }
  115811. break;
  115812. case 326: /* wqlist ::= wqlist COMMA nm idxlist_opt AS LP select RP */
  115813. {
  115814. yygotominor.yy59 = sqlite3WithAdd(pParse, yymsp[-7].minor.yy59, &yymsp[-5].minor.yy0, yymsp[-4].minor.yy14, yymsp[-1].minor.yy3);
  115815. }
  115816. break;
  115817. default:
  115818. /* (0) input ::= cmdlist */ yytestcase(yyruleno==0);
  115819. /* (1) cmdlist ::= cmdlist ecmd */ yytestcase(yyruleno==1);
  115820. /* (2) cmdlist ::= ecmd */ yytestcase(yyruleno==2);
  115821. /* (3) ecmd ::= SEMI */ yytestcase(yyruleno==3);
  115822. /* (4) ecmd ::= explain cmdx SEMI */ yytestcase(yyruleno==4);
  115823. /* (10) trans_opt ::= */ yytestcase(yyruleno==10);
  115824. /* (11) trans_opt ::= TRANSACTION */ yytestcase(yyruleno==11);
  115825. /* (12) trans_opt ::= TRANSACTION nm */ yytestcase(yyruleno==12);
  115826. /* (20) savepoint_opt ::= SAVEPOINT */ yytestcase(yyruleno==20);
  115827. /* (21) savepoint_opt ::= */ yytestcase(yyruleno==21);
  115828. /* (25) cmd ::= create_table create_table_args */ yytestcase(yyruleno==25);
  115829. /* (36) columnlist ::= columnlist COMMA column */ yytestcase(yyruleno==36);
  115830. /* (37) columnlist ::= column */ yytestcase(yyruleno==37);
  115831. /* (43) type ::= */ yytestcase(yyruleno==43);
  115832. /* (50) signed ::= plus_num */ yytestcase(yyruleno==50);
  115833. /* (51) signed ::= minus_num */ yytestcase(yyruleno==51);
  115834. /* (52) carglist ::= carglist ccons */ yytestcase(yyruleno==52);
  115835. /* (53) carglist ::= */ yytestcase(yyruleno==53);
  115836. /* (60) ccons ::= NULL onconf */ yytestcase(yyruleno==60);
  115837. /* (88) conslist ::= conslist tconscomma tcons */ yytestcase(yyruleno==88);
  115838. /* (89) conslist ::= tcons */ yytestcase(yyruleno==89);
  115839. /* (91) tconscomma ::= */ yytestcase(yyruleno==91);
  115840. /* (273) foreach_clause ::= */ yytestcase(yyruleno==273);
  115841. /* (274) foreach_clause ::= FOR EACH ROW */ yytestcase(yyruleno==274);
  115842. /* (281) tridxby ::= */ yytestcase(yyruleno==281);
  115843. /* (298) database_kw_opt ::= DATABASE */ yytestcase(yyruleno==298);
  115844. /* (299) database_kw_opt ::= */ yytestcase(yyruleno==299);
  115845. /* (307) kwcolumn_opt ::= */ yytestcase(yyruleno==307);
  115846. /* (308) kwcolumn_opt ::= COLUMNKW */ yytestcase(yyruleno==308);
  115847. /* (312) vtabarglist ::= vtabarg */ yytestcase(yyruleno==312);
  115848. /* (313) vtabarglist ::= vtabarglist COMMA vtabarg */ yytestcase(yyruleno==313);
  115849. /* (315) vtabarg ::= vtabarg vtabargtoken */ yytestcase(yyruleno==315);
  115850. /* (319) anylist ::= */ yytestcase(yyruleno==319);
  115851. /* (320) anylist ::= anylist LP anylist RP */ yytestcase(yyruleno==320);
  115852. /* (321) anylist ::= anylist ANY */ yytestcase(yyruleno==321);
  115853. break;
  115854. };
  115855. assert( yyruleno>=0 && yyruleno<sizeof(yyRuleInfo)/sizeof(yyRuleInfo[0]) );
  115856. yygoto = yyRuleInfo[yyruleno].lhs;
  115857. yysize = yyRuleInfo[yyruleno].nrhs;
  115858. yypParser->yyidx -= yysize;
  115859. yyact = yy_find_reduce_action(yymsp[-yysize].stateno,(YYCODETYPE)yygoto);
  115860. if( yyact < YYNSTATE ){
  115861. #ifdef NDEBUG
  115862. /* If we are not debugging and the reduce action popped at least
  115863. ** one element off the stack, then we can push the new element back
  115864. ** onto the stack here, and skip the stack overflow test in yy_shift().
  115865. ** That gives a significant speed improvement. */
  115866. if( yysize ){
  115867. yypParser->yyidx++;
  115868. yymsp -= yysize-1;
  115869. yymsp->stateno = (YYACTIONTYPE)yyact;
  115870. yymsp->major = (YYCODETYPE)yygoto;
  115871. yymsp->minor = yygotominor;
  115872. }else
  115873. #endif
  115874. {
  115875. yy_shift(yypParser,yyact,yygoto,&yygotominor);
  115876. }
  115877. }else{
  115878. assert( yyact == YYNSTATE + YYNRULE + 1 );
  115879. yy_accept(yypParser);
  115880. }
  115881. }
  115882. /*
  115883. ** The following code executes when the parse fails
  115884. */
  115885. #ifndef YYNOERRORRECOVERY
  115886. static void yy_parse_failed(
  115887. yyParser *yypParser /* The parser */
  115888. ){
  115889. sqlite3ParserARG_FETCH;
  115890. #ifndef NDEBUG
  115891. if( yyTraceFILE ){
  115892. fprintf(yyTraceFILE,"%sFail!\n",yyTracePrompt);
  115893. }
  115894. #endif
  115895. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  115896. /* Here code is inserted which will be executed whenever the
  115897. ** parser fails */
  115898. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  115899. }
  115900. #endif /* YYNOERRORRECOVERY */
  115901. /*
  115902. ** The following code executes when a syntax error first occurs.
  115903. */
  115904. static void yy_syntax_error(
  115905. yyParser *yypParser, /* The parser */
  115906. int yymajor, /* The major type of the error token */
  115907. YYMINORTYPE yyminor /* The minor type of the error token */
  115908. ){
  115909. sqlite3ParserARG_FETCH;
  115910. #define TOKEN (yyminor.yy0)
  115911. UNUSED_PARAMETER(yymajor); /* Silence some compiler warnings */
  115912. assert( TOKEN.z[0] ); /* The tokenizer always gives us a token */
  115913. sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", &TOKEN);
  115914. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  115915. }
  115916. /*
  115917. ** The following is executed when the parser accepts
  115918. */
  115919. static void yy_accept(
  115920. yyParser *yypParser /* The parser */
  115921. ){
  115922. sqlite3ParserARG_FETCH;
  115923. #ifndef NDEBUG
  115924. if( yyTraceFILE ){
  115925. fprintf(yyTraceFILE,"%sAccept!\n",yyTracePrompt);
  115926. }
  115927. #endif
  115928. while( yypParser->yyidx>=0 ) yy_pop_parser_stack(yypParser);
  115929. /* Here code is inserted which will be executed whenever the
  115930. ** parser accepts */
  115931. sqlite3ParserARG_STORE; /* Suppress warning about unused %extra_argument variable */
  115932. }
  115933. /* The main parser program.
  115934. ** The first argument is a pointer to a structure obtained from
  115935. ** "sqlite3ParserAlloc" which describes the current state of the parser.
  115936. ** The second argument is the major token number. The third is
  115937. ** the minor token. The fourth optional argument is whatever the
  115938. ** user wants (and specified in the grammar) and is available for
  115939. ** use by the action routines.
  115940. **
  115941. ** Inputs:
  115942. ** <ul>
  115943. ** <li> A pointer to the parser (an opaque structure.)
  115944. ** <li> The major token number.
  115945. ** <li> The minor token number.
  115946. ** <li> An option argument of a grammar-specified type.
  115947. ** </ul>
  115948. **
  115949. ** Outputs:
  115950. ** None.
  115951. */
  115952. SQLITE_PRIVATE void sqlite3Parser(
  115953. void *yyp, /* The parser */
  115954. int yymajor, /* The major token code number */
  115955. sqlite3ParserTOKENTYPE yyminor /* The value for the token */
  115956. sqlite3ParserARG_PDECL /* Optional %extra_argument parameter */
  115957. ){
  115958. YYMINORTYPE yyminorunion;
  115959. int yyact; /* The parser action. */
  115960. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  115961. int yyendofinput; /* True if we are at the end of input */
  115962. #endif
  115963. #ifdef YYERRORSYMBOL
  115964. int yyerrorhit = 0; /* True if yymajor has invoked an error */
  115965. #endif
  115966. yyParser *yypParser; /* The parser */
  115967. /* (re)initialize the parser, if necessary */
  115968. yypParser = (yyParser*)yyp;
  115969. if( yypParser->yyidx<0 ){
  115970. #if YYSTACKDEPTH<=0
  115971. if( yypParser->yystksz <=0 ){
  115972. /*memset(&yyminorunion, 0, sizeof(yyminorunion));*/
  115973. yyminorunion = yyzerominor;
  115974. yyStackOverflow(yypParser, &yyminorunion);
  115975. return;
  115976. }
  115977. #endif
  115978. yypParser->yyidx = 0;
  115979. yypParser->yyerrcnt = -1;
  115980. yypParser->yystack[0].stateno = 0;
  115981. yypParser->yystack[0].major = 0;
  115982. }
  115983. yyminorunion.yy0 = yyminor;
  115984. #if !defined(YYERRORSYMBOL) && !defined(YYNOERRORRECOVERY)
  115985. yyendofinput = (yymajor==0);
  115986. #endif
  115987. sqlite3ParserARG_STORE;
  115988. #ifndef NDEBUG
  115989. if( yyTraceFILE ){
  115990. fprintf(yyTraceFILE,"%sInput %s\n",yyTracePrompt,yyTokenName[yymajor]);
  115991. }
  115992. #endif
  115993. do{
  115994. yyact = yy_find_shift_action(yypParser,(YYCODETYPE)yymajor);
  115995. if( yyact<YYNSTATE ){
  115996. yy_shift(yypParser,yyact,yymajor,&yyminorunion);
  115997. yypParser->yyerrcnt--;
  115998. yymajor = YYNOCODE;
  115999. }else if( yyact < YYNSTATE + YYNRULE ){
  116000. yy_reduce(yypParser,yyact-YYNSTATE);
  116001. }else{
  116002. assert( yyact == YY_ERROR_ACTION );
  116003. #ifdef YYERRORSYMBOL
  116004. int yymx;
  116005. #endif
  116006. #ifndef NDEBUG
  116007. if( yyTraceFILE ){
  116008. fprintf(yyTraceFILE,"%sSyntax Error!\n",yyTracePrompt);
  116009. }
  116010. #endif
  116011. #ifdef YYERRORSYMBOL
  116012. /* A syntax error has occurred.
  116013. ** The response to an error depends upon whether or not the
  116014. ** grammar defines an error token "ERROR".
  116015. **
  116016. ** This is what we do if the grammar does define ERROR:
  116017. **
  116018. ** * Call the %syntax_error function.
  116019. **
  116020. ** * Begin popping the stack until we enter a state where
  116021. ** it is legal to shift the error symbol, then shift
  116022. ** the error symbol.
  116023. **
  116024. ** * Set the error count to three.
  116025. **
  116026. ** * Begin accepting and shifting new tokens. No new error
  116027. ** processing will occur until three tokens have been
  116028. ** shifted successfully.
  116029. **
  116030. */
  116031. if( yypParser->yyerrcnt<0 ){
  116032. yy_syntax_error(yypParser,yymajor,yyminorunion);
  116033. }
  116034. yymx = yypParser->yystack[yypParser->yyidx].major;
  116035. if( yymx==YYERRORSYMBOL || yyerrorhit ){
  116036. #ifndef NDEBUG
  116037. if( yyTraceFILE ){
  116038. fprintf(yyTraceFILE,"%sDiscard input token %s\n",
  116039. yyTracePrompt,yyTokenName[yymajor]);
  116040. }
  116041. #endif
  116042. yy_destructor(yypParser, (YYCODETYPE)yymajor,&yyminorunion);
  116043. yymajor = YYNOCODE;
  116044. }else{
  116045. while(
  116046. yypParser->yyidx >= 0 &&
  116047. yymx != YYERRORSYMBOL &&
  116048. (yyact = yy_find_reduce_action(
  116049. yypParser->yystack[yypParser->yyidx].stateno,
  116050. YYERRORSYMBOL)) >= YYNSTATE
  116051. ){
  116052. yy_pop_parser_stack(yypParser);
  116053. }
  116054. if( yypParser->yyidx < 0 || yymajor==0 ){
  116055. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  116056. yy_parse_failed(yypParser);
  116057. yymajor = YYNOCODE;
  116058. }else if( yymx!=YYERRORSYMBOL ){
  116059. YYMINORTYPE u2;
  116060. u2.YYERRSYMDT = 0;
  116061. yy_shift(yypParser,yyact,YYERRORSYMBOL,&u2);
  116062. }
  116063. }
  116064. yypParser->yyerrcnt = 3;
  116065. yyerrorhit = 1;
  116066. #elif defined(YYNOERRORRECOVERY)
  116067. /* If the YYNOERRORRECOVERY macro is defined, then do not attempt to
  116068. ** do any kind of error recovery. Instead, simply invoke the syntax
  116069. ** error routine and continue going as if nothing had happened.
  116070. **
  116071. ** Applications can set this macro (for example inside %include) if
  116072. ** they intend to abandon the parse upon the first syntax error seen.
  116073. */
  116074. yy_syntax_error(yypParser,yymajor,yyminorunion);
  116075. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  116076. yymajor = YYNOCODE;
  116077. #else /* YYERRORSYMBOL is not defined */
  116078. /* This is what we do if the grammar does not define ERROR:
  116079. **
  116080. ** * Report an error message, and throw away the input token.
  116081. **
  116082. ** * If the input token is $, then fail the parse.
  116083. **
  116084. ** As before, subsequent error messages are suppressed until
  116085. ** three input tokens have been successfully shifted.
  116086. */
  116087. if( yypParser->yyerrcnt<=0 ){
  116088. yy_syntax_error(yypParser,yymajor,yyminorunion);
  116089. }
  116090. yypParser->yyerrcnt = 3;
  116091. yy_destructor(yypParser,(YYCODETYPE)yymajor,&yyminorunion);
  116092. if( yyendofinput ){
  116093. yy_parse_failed(yypParser);
  116094. }
  116095. yymajor = YYNOCODE;
  116096. #endif
  116097. }
  116098. }while( yymajor!=YYNOCODE && yypParser->yyidx>=0 );
  116099. return;
  116100. }
  116101. /************** End of parse.c ***********************************************/
  116102. /************** Begin file tokenize.c ****************************************/
  116103. /*
  116104. ** 2001 September 15
  116105. **
  116106. ** The author disclaims copyright to this source code. In place of
  116107. ** a legal notice, here is a blessing:
  116108. **
  116109. ** May you do good and not evil.
  116110. ** May you find forgiveness for yourself and forgive others.
  116111. ** May you share freely, never taking more than you give.
  116112. **
  116113. *************************************************************************
  116114. ** An tokenizer for SQL
  116115. **
  116116. ** This file contains C code that splits an SQL input string up into
  116117. ** individual tokens and sends those tokens one-by-one over to the
  116118. ** parser for analysis.
  116119. */
  116120. /* #include <stdlib.h> */
  116121. /*
  116122. ** The charMap() macro maps alphabetic characters into their
  116123. ** lower-case ASCII equivalent. On ASCII machines, this is just
  116124. ** an upper-to-lower case map. On EBCDIC machines we also need
  116125. ** to adjust the encoding. Only alphabetic characters and underscores
  116126. ** need to be translated.
  116127. */
  116128. #ifdef SQLITE_ASCII
  116129. # define charMap(X) sqlite3UpperToLower[(unsigned char)X]
  116130. #endif
  116131. #ifdef SQLITE_EBCDIC
  116132. # define charMap(X) ebcdicToAscii[(unsigned char)X]
  116133. const unsigned char ebcdicToAscii[] = {
  116134. /* 0 1 2 3 4 5 6 7 8 9 A B C D E F */
  116135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  116136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  116137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  116138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 3x */
  116139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 4x */
  116140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 5x */
  116141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 95, 0, 0, /* 6x */
  116142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  116143. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* 8x */
  116144. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* 9x */
  116145. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ax */
  116146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  116147. 0, 97, 98, 99,100,101,102,103,104,105, 0, 0, 0, 0, 0, 0, /* Cx */
  116148. 0,106,107,108,109,110,111,112,113,114, 0, 0, 0, 0, 0, 0, /* Dx */
  116149. 0, 0,115,116,117,118,119,120,121,122, 0, 0, 0, 0, 0, 0, /* Ex */
  116150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Fx */
  116151. };
  116152. #endif
  116153. /*
  116154. ** The sqlite3KeywordCode function looks up an identifier to determine if
  116155. ** it is a keyword. If it is a keyword, the token code of that keyword is
  116156. ** returned. If the input is not a keyword, TK_ID is returned.
  116157. **
  116158. ** The implementation of this routine was generated by a program,
  116159. ** mkkeywordhash.h, located in the tool subdirectory of the distribution.
  116160. ** The output of the mkkeywordhash.c program is written into a file
  116161. ** named keywordhash.h and then included into this source file by
  116162. ** the #include below.
  116163. */
  116164. /************** Include keywordhash.h in the middle of tokenize.c ************/
  116165. /************** Begin file keywordhash.h *************************************/
  116166. /***** This file contains automatically generated code ******
  116167. **
  116168. ** The code in this file has been automatically generated by
  116169. **
  116170. ** sqlite/tool/mkkeywordhash.c
  116171. **
  116172. ** The code in this file implements a function that determines whether
  116173. ** or not a given identifier is really an SQL keyword. The same thing
  116174. ** might be implemented more directly using a hand-written hash table.
  116175. ** But by using this automatically generated code, the size of the code
  116176. ** is substantially reduced. This is important for embedded applications
  116177. ** on platforms with limited memory.
  116178. */
  116179. /* Hash score: 182 */
  116180. static int keywordCode(const char *z, int n){
  116181. /* zText[] encodes 834 bytes of keywords in 554 bytes */
  116182. /* REINDEXEDESCAPEACHECKEYBEFOREIGNOREGEXPLAINSTEADDATABASELECT */
  116183. /* ABLEFTHENDEFERRABLELSEXCEPTRANSACTIONATURALTERAISEXCLUSIVE */
  116184. /* XISTSAVEPOINTERSECTRIGGEREFERENCESCONSTRAINTOFFSETEMPORARY */
  116185. /* UNIQUERYWITHOUTERELEASEATTACHAVINGROUPDATEBEGINNERECURSIVE */
  116186. /* BETWEENOTNULLIKECASCADELETECASECOLLATECREATECURRENT_DATEDETACH */
  116187. /* IMMEDIATEJOINSERTMATCHPLANALYZEPRAGMABORTVALUESVIRTUALIMITWHEN */
  116188. /* WHERENAMEAFTEREPLACEANDEFAULTAUTOINCREMENTCASTCOLUMNCOMMIT */
  116189. /* CONFLICTCROSSCURRENT_TIMESTAMPRIMARYDEFERREDISTINCTDROPFAIL */
  116190. /* FROMFULLGLOBYIFISNULLORDERESTRICTRIGHTROLLBACKROWUNIONUSING */
  116191. /* VACUUMVIEWINITIALLY */
  116192. static const char zText[553] = {
  116193. 'R','E','I','N','D','E','X','E','D','E','S','C','A','P','E','A','C','H',
  116194. 'E','C','K','E','Y','B','E','F','O','R','E','I','G','N','O','R','E','G',
  116195. 'E','X','P','L','A','I','N','S','T','E','A','D','D','A','T','A','B','A',
  116196. 'S','E','L','E','C','T','A','B','L','E','F','T','H','E','N','D','E','F',
  116197. 'E','R','R','A','B','L','E','L','S','E','X','C','E','P','T','R','A','N',
  116198. 'S','A','C','T','I','O','N','A','T','U','R','A','L','T','E','R','A','I',
  116199. 'S','E','X','C','L','U','S','I','V','E','X','I','S','T','S','A','V','E',
  116200. 'P','O','I','N','T','E','R','S','E','C','T','R','I','G','G','E','R','E',
  116201. 'F','E','R','E','N','C','E','S','C','O','N','S','T','R','A','I','N','T',
  116202. 'O','F','F','S','E','T','E','M','P','O','R','A','R','Y','U','N','I','Q',
  116203. 'U','E','R','Y','W','I','T','H','O','U','T','E','R','E','L','E','A','S',
  116204. 'E','A','T','T','A','C','H','A','V','I','N','G','R','O','U','P','D','A',
  116205. 'T','E','B','E','G','I','N','N','E','R','E','C','U','R','S','I','V','E',
  116206. 'B','E','T','W','E','E','N','O','T','N','U','L','L','I','K','E','C','A',
  116207. 'S','C','A','D','E','L','E','T','E','C','A','S','E','C','O','L','L','A',
  116208. 'T','E','C','R','E','A','T','E','C','U','R','R','E','N','T','_','D','A',
  116209. 'T','E','D','E','T','A','C','H','I','M','M','E','D','I','A','T','E','J',
  116210. 'O','I','N','S','E','R','T','M','A','T','C','H','P','L','A','N','A','L',
  116211. 'Y','Z','E','P','R','A','G','M','A','B','O','R','T','V','A','L','U','E',
  116212. 'S','V','I','R','T','U','A','L','I','M','I','T','W','H','E','N','W','H',
  116213. 'E','R','E','N','A','M','E','A','F','T','E','R','E','P','L','A','C','E',
  116214. 'A','N','D','E','F','A','U','L','T','A','U','T','O','I','N','C','R','E',
  116215. 'M','E','N','T','C','A','S','T','C','O','L','U','M','N','C','O','M','M',
  116216. 'I','T','C','O','N','F','L','I','C','T','C','R','O','S','S','C','U','R',
  116217. 'R','E','N','T','_','T','I','M','E','S','T','A','M','P','R','I','M','A',
  116218. 'R','Y','D','E','F','E','R','R','E','D','I','S','T','I','N','C','T','D',
  116219. 'R','O','P','F','A','I','L','F','R','O','M','F','U','L','L','G','L','O',
  116220. 'B','Y','I','F','I','S','N','U','L','L','O','R','D','E','R','E','S','T',
  116221. 'R','I','C','T','R','I','G','H','T','R','O','L','L','B','A','C','K','R',
  116222. 'O','W','U','N','I','O','N','U','S','I','N','G','V','A','C','U','U','M',
  116223. 'V','I','E','W','I','N','I','T','I','A','L','L','Y',
  116224. };
  116225. static const unsigned char aHash[127] = {
  116226. 76, 105, 117, 74, 0, 45, 0, 0, 82, 0, 77, 0, 0,
  116227. 42, 12, 78, 15, 0, 116, 85, 54, 112, 0, 19, 0, 0,
  116228. 121, 0, 119, 115, 0, 22, 93, 0, 9, 0, 0, 70, 71,
  116229. 0, 69, 6, 0, 48, 90, 102, 0, 118, 101, 0, 0, 44,
  116230. 0, 103, 24, 0, 17, 0, 122, 53, 23, 0, 5, 110, 25,
  116231. 96, 0, 0, 124, 106, 60, 123, 57, 28, 55, 0, 91, 0,
  116232. 100, 26, 0, 99, 0, 0, 0, 95, 92, 97, 88, 109, 14,
  116233. 39, 108, 0, 81, 0, 18, 89, 111, 32, 0, 120, 80, 113,
  116234. 62, 46, 84, 0, 0, 94, 40, 59, 114, 0, 36, 0, 0,
  116235. 29, 0, 86, 63, 64, 0, 20, 61, 0, 56,
  116236. };
  116237. static const unsigned char aNext[124] = {
  116238. 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0,
  116239. 0, 2, 0, 0, 0, 0, 0, 0, 13, 0, 0, 0, 0,
  116240. 0, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  116241. 0, 0, 0, 0, 33, 0, 21, 0, 0, 0, 0, 0, 50,
  116242. 0, 43, 3, 47, 0, 0, 0, 0, 30, 0, 58, 0, 38,
  116243. 0, 0, 0, 1, 66, 0, 0, 67, 0, 41, 0, 0, 0,
  116244. 0, 0, 0, 49, 65, 0, 0, 0, 0, 31, 52, 16, 34,
  116245. 10, 0, 0, 0, 0, 0, 0, 0, 11, 72, 79, 0, 8,
  116246. 0, 104, 98, 0, 107, 0, 87, 0, 75, 51, 0, 27, 37,
  116247. 73, 83, 0, 35, 68, 0, 0,
  116248. };
  116249. static const unsigned char aLen[124] = {
  116250. 7, 7, 5, 4, 6, 4, 5, 3, 6, 7, 3, 6, 6,
  116251. 7, 7, 3, 8, 2, 6, 5, 4, 4, 3, 10, 4, 6,
  116252. 11, 6, 2, 7, 5, 5, 9, 6, 9, 9, 7, 10, 10,
  116253. 4, 6, 2, 3, 9, 4, 2, 6, 5, 7, 4, 5, 7,
  116254. 6, 6, 5, 6, 5, 5, 9, 7, 7, 3, 2, 4, 4,
  116255. 7, 3, 6, 4, 7, 6, 12, 6, 9, 4, 6, 5, 4,
  116256. 7, 6, 5, 6, 7, 5, 4, 5, 6, 5, 7, 3, 7,
  116257. 13, 2, 2, 4, 6, 6, 8, 5, 17, 12, 7, 8, 8,
  116258. 2, 4, 4, 4, 4, 4, 2, 2, 6, 5, 8, 5, 8,
  116259. 3, 5, 5, 6, 4, 9, 3,
  116260. };
  116261. static const unsigned short int aOffset[124] = {
  116262. 0, 2, 2, 8, 9, 14, 16, 20, 23, 25, 25, 29, 33,
  116263. 36, 41, 46, 48, 53, 54, 59, 62, 65, 67, 69, 78, 81,
  116264. 86, 91, 95, 96, 101, 105, 109, 117, 122, 128, 136, 142, 152,
  116265. 159, 162, 162, 165, 167, 167, 171, 176, 179, 184, 184, 188, 192,
  116266. 199, 204, 209, 212, 218, 221, 225, 234, 240, 240, 240, 243, 246,
  116267. 250, 251, 255, 261, 265, 272, 278, 290, 296, 305, 307, 313, 318,
  116268. 320, 327, 332, 337, 343, 349, 354, 358, 361, 367, 371, 378, 380,
  116269. 387, 389, 391, 400, 404, 410, 416, 424, 429, 429, 445, 452, 459,
  116270. 460, 467, 471, 475, 479, 483, 486, 488, 490, 496, 500, 508, 513,
  116271. 521, 524, 529, 534, 540, 544, 549,
  116272. };
  116273. static const unsigned char aCode[124] = {
  116274. TK_REINDEX, TK_INDEXED, TK_INDEX, TK_DESC, TK_ESCAPE,
  116275. TK_EACH, TK_CHECK, TK_KEY, TK_BEFORE, TK_FOREIGN,
  116276. TK_FOR, TK_IGNORE, TK_LIKE_KW, TK_EXPLAIN, TK_INSTEAD,
  116277. TK_ADD, TK_DATABASE, TK_AS, TK_SELECT, TK_TABLE,
  116278. TK_JOIN_KW, TK_THEN, TK_END, TK_DEFERRABLE, TK_ELSE,
  116279. TK_EXCEPT, TK_TRANSACTION,TK_ACTION, TK_ON, TK_JOIN_KW,
  116280. TK_ALTER, TK_RAISE, TK_EXCLUSIVE, TK_EXISTS, TK_SAVEPOINT,
  116281. TK_INTERSECT, TK_TRIGGER, TK_REFERENCES, TK_CONSTRAINT, TK_INTO,
  116282. TK_OFFSET, TK_OF, TK_SET, TK_TEMP, TK_TEMP,
  116283. TK_OR, TK_UNIQUE, TK_QUERY, TK_WITHOUT, TK_WITH,
  116284. TK_JOIN_KW, TK_RELEASE, TK_ATTACH, TK_HAVING, TK_GROUP,
  116285. TK_UPDATE, TK_BEGIN, TK_JOIN_KW, TK_RECURSIVE, TK_BETWEEN,
  116286. TK_NOTNULL, TK_NOT, TK_NO, TK_NULL, TK_LIKE_KW,
  116287. TK_CASCADE, TK_ASC, TK_DELETE, TK_CASE, TK_COLLATE,
  116288. TK_CREATE, TK_CTIME_KW, TK_DETACH, TK_IMMEDIATE, TK_JOIN,
  116289. TK_INSERT, TK_MATCH, TK_PLAN, TK_ANALYZE, TK_PRAGMA,
  116290. TK_ABORT, TK_VALUES, TK_VIRTUAL, TK_LIMIT, TK_WHEN,
  116291. TK_WHERE, TK_RENAME, TK_AFTER, TK_REPLACE, TK_AND,
  116292. TK_DEFAULT, TK_AUTOINCR, TK_TO, TK_IN, TK_CAST,
  116293. TK_COLUMNKW, TK_COMMIT, TK_CONFLICT, TK_JOIN_KW, TK_CTIME_KW,
  116294. TK_CTIME_KW, TK_PRIMARY, TK_DEFERRED, TK_DISTINCT, TK_IS,
  116295. TK_DROP, TK_FAIL, TK_FROM, TK_JOIN_KW, TK_LIKE_KW,
  116296. TK_BY, TK_IF, TK_ISNULL, TK_ORDER, TK_RESTRICT,
  116297. TK_JOIN_KW, TK_ROLLBACK, TK_ROW, TK_UNION, TK_USING,
  116298. TK_VACUUM, TK_VIEW, TK_INITIALLY, TK_ALL,
  116299. };
  116300. int h, i;
  116301. if( n<2 ) return TK_ID;
  116302. h = ((charMap(z[0])*4) ^
  116303. (charMap(z[n-1])*3) ^
  116304. n) % 127;
  116305. for(i=((int)aHash[h])-1; i>=0; i=((int)aNext[i])-1){
  116306. if( aLen[i]==n && sqlite3StrNICmp(&zText[aOffset[i]],z,n)==0 ){
  116307. testcase( i==0 ); /* REINDEX */
  116308. testcase( i==1 ); /* INDEXED */
  116309. testcase( i==2 ); /* INDEX */
  116310. testcase( i==3 ); /* DESC */
  116311. testcase( i==4 ); /* ESCAPE */
  116312. testcase( i==5 ); /* EACH */
  116313. testcase( i==6 ); /* CHECK */
  116314. testcase( i==7 ); /* KEY */
  116315. testcase( i==8 ); /* BEFORE */
  116316. testcase( i==9 ); /* FOREIGN */
  116317. testcase( i==10 ); /* FOR */
  116318. testcase( i==11 ); /* IGNORE */
  116319. testcase( i==12 ); /* REGEXP */
  116320. testcase( i==13 ); /* EXPLAIN */
  116321. testcase( i==14 ); /* INSTEAD */
  116322. testcase( i==15 ); /* ADD */
  116323. testcase( i==16 ); /* DATABASE */
  116324. testcase( i==17 ); /* AS */
  116325. testcase( i==18 ); /* SELECT */
  116326. testcase( i==19 ); /* TABLE */
  116327. testcase( i==20 ); /* LEFT */
  116328. testcase( i==21 ); /* THEN */
  116329. testcase( i==22 ); /* END */
  116330. testcase( i==23 ); /* DEFERRABLE */
  116331. testcase( i==24 ); /* ELSE */
  116332. testcase( i==25 ); /* EXCEPT */
  116333. testcase( i==26 ); /* TRANSACTION */
  116334. testcase( i==27 ); /* ACTION */
  116335. testcase( i==28 ); /* ON */
  116336. testcase( i==29 ); /* NATURAL */
  116337. testcase( i==30 ); /* ALTER */
  116338. testcase( i==31 ); /* RAISE */
  116339. testcase( i==32 ); /* EXCLUSIVE */
  116340. testcase( i==33 ); /* EXISTS */
  116341. testcase( i==34 ); /* SAVEPOINT */
  116342. testcase( i==35 ); /* INTERSECT */
  116343. testcase( i==36 ); /* TRIGGER */
  116344. testcase( i==37 ); /* REFERENCES */
  116345. testcase( i==38 ); /* CONSTRAINT */
  116346. testcase( i==39 ); /* INTO */
  116347. testcase( i==40 ); /* OFFSET */
  116348. testcase( i==41 ); /* OF */
  116349. testcase( i==42 ); /* SET */
  116350. testcase( i==43 ); /* TEMPORARY */
  116351. testcase( i==44 ); /* TEMP */
  116352. testcase( i==45 ); /* OR */
  116353. testcase( i==46 ); /* UNIQUE */
  116354. testcase( i==47 ); /* QUERY */
  116355. testcase( i==48 ); /* WITHOUT */
  116356. testcase( i==49 ); /* WITH */
  116357. testcase( i==50 ); /* OUTER */
  116358. testcase( i==51 ); /* RELEASE */
  116359. testcase( i==52 ); /* ATTACH */
  116360. testcase( i==53 ); /* HAVING */
  116361. testcase( i==54 ); /* GROUP */
  116362. testcase( i==55 ); /* UPDATE */
  116363. testcase( i==56 ); /* BEGIN */
  116364. testcase( i==57 ); /* INNER */
  116365. testcase( i==58 ); /* RECURSIVE */
  116366. testcase( i==59 ); /* BETWEEN */
  116367. testcase( i==60 ); /* NOTNULL */
  116368. testcase( i==61 ); /* NOT */
  116369. testcase( i==62 ); /* NO */
  116370. testcase( i==63 ); /* NULL */
  116371. testcase( i==64 ); /* LIKE */
  116372. testcase( i==65 ); /* CASCADE */
  116373. testcase( i==66 ); /* ASC */
  116374. testcase( i==67 ); /* DELETE */
  116375. testcase( i==68 ); /* CASE */
  116376. testcase( i==69 ); /* COLLATE */
  116377. testcase( i==70 ); /* CREATE */
  116378. testcase( i==71 ); /* CURRENT_DATE */
  116379. testcase( i==72 ); /* DETACH */
  116380. testcase( i==73 ); /* IMMEDIATE */
  116381. testcase( i==74 ); /* JOIN */
  116382. testcase( i==75 ); /* INSERT */
  116383. testcase( i==76 ); /* MATCH */
  116384. testcase( i==77 ); /* PLAN */
  116385. testcase( i==78 ); /* ANALYZE */
  116386. testcase( i==79 ); /* PRAGMA */
  116387. testcase( i==80 ); /* ABORT */
  116388. testcase( i==81 ); /* VALUES */
  116389. testcase( i==82 ); /* VIRTUAL */
  116390. testcase( i==83 ); /* LIMIT */
  116391. testcase( i==84 ); /* WHEN */
  116392. testcase( i==85 ); /* WHERE */
  116393. testcase( i==86 ); /* RENAME */
  116394. testcase( i==87 ); /* AFTER */
  116395. testcase( i==88 ); /* REPLACE */
  116396. testcase( i==89 ); /* AND */
  116397. testcase( i==90 ); /* DEFAULT */
  116398. testcase( i==91 ); /* AUTOINCREMENT */
  116399. testcase( i==92 ); /* TO */
  116400. testcase( i==93 ); /* IN */
  116401. testcase( i==94 ); /* CAST */
  116402. testcase( i==95 ); /* COLUMN */
  116403. testcase( i==96 ); /* COMMIT */
  116404. testcase( i==97 ); /* CONFLICT */
  116405. testcase( i==98 ); /* CROSS */
  116406. testcase( i==99 ); /* CURRENT_TIMESTAMP */
  116407. testcase( i==100 ); /* CURRENT_TIME */
  116408. testcase( i==101 ); /* PRIMARY */
  116409. testcase( i==102 ); /* DEFERRED */
  116410. testcase( i==103 ); /* DISTINCT */
  116411. testcase( i==104 ); /* IS */
  116412. testcase( i==105 ); /* DROP */
  116413. testcase( i==106 ); /* FAIL */
  116414. testcase( i==107 ); /* FROM */
  116415. testcase( i==108 ); /* FULL */
  116416. testcase( i==109 ); /* GLOB */
  116417. testcase( i==110 ); /* BY */
  116418. testcase( i==111 ); /* IF */
  116419. testcase( i==112 ); /* ISNULL */
  116420. testcase( i==113 ); /* ORDER */
  116421. testcase( i==114 ); /* RESTRICT */
  116422. testcase( i==115 ); /* RIGHT */
  116423. testcase( i==116 ); /* ROLLBACK */
  116424. testcase( i==117 ); /* ROW */
  116425. testcase( i==118 ); /* UNION */
  116426. testcase( i==119 ); /* USING */
  116427. testcase( i==120 ); /* VACUUM */
  116428. testcase( i==121 ); /* VIEW */
  116429. testcase( i==122 ); /* INITIALLY */
  116430. testcase( i==123 ); /* ALL */
  116431. return aCode[i];
  116432. }
  116433. }
  116434. return TK_ID;
  116435. }
  116436. SQLITE_PRIVATE int sqlite3KeywordCode(const unsigned char *z, int n){
  116437. return keywordCode((char*)z, n);
  116438. }
  116439. #define SQLITE_N_KEYWORD 124
  116440. /************** End of keywordhash.h *****************************************/
  116441. /************** Continuing where we left off in tokenize.c *******************/
  116442. /*
  116443. ** If X is a character that can be used in an identifier then
  116444. ** IdChar(X) will be true. Otherwise it is false.
  116445. **
  116446. ** For ASCII, any character with the high-order bit set is
  116447. ** allowed in an identifier. For 7-bit characters,
  116448. ** sqlite3IsIdChar[X] must be 1.
  116449. **
  116450. ** For EBCDIC, the rules are more complex but have the same
  116451. ** end result.
  116452. **
  116453. ** Ticket #1066. the SQL standard does not allow '$' in the
  116454. ** middle of identifiers. But many SQL implementations do.
  116455. ** SQLite will allow '$' in identifiers for compatibility.
  116456. ** But the feature is undocumented.
  116457. */
  116458. #ifdef SQLITE_ASCII
  116459. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  116460. #endif
  116461. #ifdef SQLITE_EBCDIC
  116462. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[] = {
  116463. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  116464. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 4x */
  116465. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 0, 0, 0, /* 5x */
  116466. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 0, 0, /* 6x */
  116467. 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, /* 7x */
  116468. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 1, 1, 0, /* 8x */
  116469. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 1, 0, 1, 0, /* 9x */
  116470. 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, /* Ax */
  116471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* Bx */
  116472. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Cx */
  116473. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Dx */
  116474. 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, /* Ex */
  116475. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, /* Fx */
  116476. };
  116477. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  116478. #endif
  116479. SQLITE_PRIVATE int sqlite3IsIdChar(u8 c){ return IdChar(c); }
  116480. /*
  116481. ** Return the length of the token that begins at z[0].
  116482. ** Store the token type in *tokenType before returning.
  116483. */
  116484. SQLITE_PRIVATE int sqlite3GetToken(const unsigned char *z, int *tokenType){
  116485. int i, c;
  116486. switch( *z ){
  116487. case ' ': case '\t': case '\n': case '\f': case '\r': {
  116488. testcase( z[0]==' ' );
  116489. testcase( z[0]=='\t' );
  116490. testcase( z[0]=='\n' );
  116491. testcase( z[0]=='\f' );
  116492. testcase( z[0]=='\r' );
  116493. for(i=1; sqlite3Isspace(z[i]); i++){}
  116494. *tokenType = TK_SPACE;
  116495. return i;
  116496. }
  116497. case '-': {
  116498. if( z[1]=='-' ){
  116499. for(i=2; (c=z[i])!=0 && c!='\n'; i++){}
  116500. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  116501. return i;
  116502. }
  116503. *tokenType = TK_MINUS;
  116504. return 1;
  116505. }
  116506. case '(': {
  116507. *tokenType = TK_LP;
  116508. return 1;
  116509. }
  116510. case ')': {
  116511. *tokenType = TK_RP;
  116512. return 1;
  116513. }
  116514. case ';': {
  116515. *tokenType = TK_SEMI;
  116516. return 1;
  116517. }
  116518. case '+': {
  116519. *tokenType = TK_PLUS;
  116520. return 1;
  116521. }
  116522. case '*': {
  116523. *tokenType = TK_STAR;
  116524. return 1;
  116525. }
  116526. case '/': {
  116527. if( z[1]!='*' || z[2]==0 ){
  116528. *tokenType = TK_SLASH;
  116529. return 1;
  116530. }
  116531. for(i=3, c=z[2]; (c!='*' || z[i]!='/') && (c=z[i])!=0; i++){}
  116532. if( c ) i++;
  116533. *tokenType = TK_SPACE; /* IMP: R-22934-25134 */
  116534. return i;
  116535. }
  116536. case '%': {
  116537. *tokenType = TK_REM;
  116538. return 1;
  116539. }
  116540. case '=': {
  116541. *tokenType = TK_EQ;
  116542. return 1 + (z[1]=='=');
  116543. }
  116544. case '<': {
  116545. if( (c=z[1])=='=' ){
  116546. *tokenType = TK_LE;
  116547. return 2;
  116548. }else if( c=='>' ){
  116549. *tokenType = TK_NE;
  116550. return 2;
  116551. }else if( c=='<' ){
  116552. *tokenType = TK_LSHIFT;
  116553. return 2;
  116554. }else{
  116555. *tokenType = TK_LT;
  116556. return 1;
  116557. }
  116558. }
  116559. case '>': {
  116560. if( (c=z[1])=='=' ){
  116561. *tokenType = TK_GE;
  116562. return 2;
  116563. }else if( c=='>' ){
  116564. *tokenType = TK_RSHIFT;
  116565. return 2;
  116566. }else{
  116567. *tokenType = TK_GT;
  116568. return 1;
  116569. }
  116570. }
  116571. case '!': {
  116572. if( z[1]!='=' ){
  116573. *tokenType = TK_ILLEGAL;
  116574. return 2;
  116575. }else{
  116576. *tokenType = TK_NE;
  116577. return 2;
  116578. }
  116579. }
  116580. case '|': {
  116581. if( z[1]!='|' ){
  116582. *tokenType = TK_BITOR;
  116583. return 1;
  116584. }else{
  116585. *tokenType = TK_CONCAT;
  116586. return 2;
  116587. }
  116588. }
  116589. case ',': {
  116590. *tokenType = TK_COMMA;
  116591. return 1;
  116592. }
  116593. case '&': {
  116594. *tokenType = TK_BITAND;
  116595. return 1;
  116596. }
  116597. case '~': {
  116598. *tokenType = TK_BITNOT;
  116599. return 1;
  116600. }
  116601. case '`':
  116602. case '\'':
  116603. case '"': {
  116604. int delim = z[0];
  116605. testcase( delim=='`' );
  116606. testcase( delim=='\'' );
  116607. testcase( delim=='"' );
  116608. for(i=1; (c=z[i])!=0; i++){
  116609. if( c==delim ){
  116610. if( z[i+1]==delim ){
  116611. i++;
  116612. }else{
  116613. break;
  116614. }
  116615. }
  116616. }
  116617. if( c=='\'' ){
  116618. *tokenType = TK_STRING;
  116619. return i+1;
  116620. }else if( c!=0 ){
  116621. *tokenType = TK_ID;
  116622. return i+1;
  116623. }else{
  116624. *tokenType = TK_ILLEGAL;
  116625. return i;
  116626. }
  116627. }
  116628. case '.': {
  116629. #ifndef SQLITE_OMIT_FLOATING_POINT
  116630. if( !sqlite3Isdigit(z[1]) )
  116631. #endif
  116632. {
  116633. *tokenType = TK_DOT;
  116634. return 1;
  116635. }
  116636. /* If the next character is a digit, this is a floating point
  116637. ** number that begins with ".". Fall thru into the next case */
  116638. }
  116639. case '0': case '1': case '2': case '3': case '4':
  116640. case '5': case '6': case '7': case '8': case '9': {
  116641. testcase( z[0]=='0' ); testcase( z[0]=='1' ); testcase( z[0]=='2' );
  116642. testcase( z[0]=='3' ); testcase( z[0]=='4' ); testcase( z[0]=='5' );
  116643. testcase( z[0]=='6' ); testcase( z[0]=='7' ); testcase( z[0]=='8' );
  116644. testcase( z[0]=='9' );
  116645. *tokenType = TK_INTEGER;
  116646. #ifndef SQLITE_OMIT_HEX_INTEGER
  116647. if( z[0]=='0' && (z[1]=='x' || z[1]=='X') && sqlite3Isxdigit(z[2]) ){
  116648. for(i=3; sqlite3Isxdigit(z[i]); i++){}
  116649. return i;
  116650. }
  116651. #endif
  116652. for(i=0; sqlite3Isdigit(z[i]); i++){}
  116653. #ifndef SQLITE_OMIT_FLOATING_POINT
  116654. if( z[i]=='.' ){
  116655. i++;
  116656. while( sqlite3Isdigit(z[i]) ){ i++; }
  116657. *tokenType = TK_FLOAT;
  116658. }
  116659. if( (z[i]=='e' || z[i]=='E') &&
  116660. ( sqlite3Isdigit(z[i+1])
  116661. || ((z[i+1]=='+' || z[i+1]=='-') && sqlite3Isdigit(z[i+2]))
  116662. )
  116663. ){
  116664. i += 2;
  116665. while( sqlite3Isdigit(z[i]) ){ i++; }
  116666. *tokenType = TK_FLOAT;
  116667. }
  116668. #endif
  116669. while( IdChar(z[i]) ){
  116670. *tokenType = TK_ILLEGAL;
  116671. i++;
  116672. }
  116673. return i;
  116674. }
  116675. case '[': {
  116676. for(i=1, c=z[0]; c!=']' && (c=z[i])!=0; i++){}
  116677. *tokenType = c==']' ? TK_ID : TK_ILLEGAL;
  116678. return i;
  116679. }
  116680. case '?': {
  116681. *tokenType = TK_VARIABLE;
  116682. for(i=1; sqlite3Isdigit(z[i]); i++){}
  116683. return i;
  116684. }
  116685. #ifndef SQLITE_OMIT_TCL_VARIABLE
  116686. case '$':
  116687. #endif
  116688. case '@': /* For compatibility with MS SQL Server */
  116689. case '#':
  116690. case ':': {
  116691. int n = 0;
  116692. testcase( z[0]=='$' ); testcase( z[0]=='@' );
  116693. testcase( z[0]==':' ); testcase( z[0]=='#' );
  116694. *tokenType = TK_VARIABLE;
  116695. for(i=1; (c=z[i])!=0; i++){
  116696. if( IdChar(c) ){
  116697. n++;
  116698. #ifndef SQLITE_OMIT_TCL_VARIABLE
  116699. }else if( c=='(' && n>0 ){
  116700. do{
  116701. i++;
  116702. }while( (c=z[i])!=0 && !sqlite3Isspace(c) && c!=')' );
  116703. if( c==')' ){
  116704. i++;
  116705. }else{
  116706. *tokenType = TK_ILLEGAL;
  116707. }
  116708. break;
  116709. }else if( c==':' && z[i+1]==':' ){
  116710. i++;
  116711. #endif
  116712. }else{
  116713. break;
  116714. }
  116715. }
  116716. if( n==0 ) *tokenType = TK_ILLEGAL;
  116717. return i;
  116718. }
  116719. #ifndef SQLITE_OMIT_BLOB_LITERAL
  116720. case 'x': case 'X': {
  116721. testcase( z[0]=='x' ); testcase( z[0]=='X' );
  116722. if( z[1]=='\'' ){
  116723. *tokenType = TK_BLOB;
  116724. for(i=2; sqlite3Isxdigit(z[i]); i++){}
  116725. if( z[i]!='\'' || i%2 ){
  116726. *tokenType = TK_ILLEGAL;
  116727. while( z[i] && z[i]!='\'' ){ i++; }
  116728. }
  116729. if( z[i] ) i++;
  116730. return i;
  116731. }
  116732. /* Otherwise fall through to the next case */
  116733. }
  116734. #endif
  116735. default: {
  116736. if( !IdChar(*z) ){
  116737. break;
  116738. }
  116739. for(i=1; IdChar(z[i]); i++){}
  116740. *tokenType = keywordCode((char*)z, i);
  116741. return i;
  116742. }
  116743. }
  116744. *tokenType = TK_ILLEGAL;
  116745. return 1;
  116746. }
  116747. /*
  116748. ** Run the parser on the given SQL string. The parser structure is
  116749. ** passed in. An SQLITE_ status code is returned. If an error occurs
  116750. ** then an and attempt is made to write an error message into
  116751. ** memory obtained from sqlite3_malloc() and to make *pzErrMsg point to that
  116752. ** error message.
  116753. */
  116754. SQLITE_PRIVATE int sqlite3RunParser(Parse *pParse, const char *zSql, char **pzErrMsg){
  116755. int nErr = 0; /* Number of errors encountered */
  116756. int i; /* Loop counter */
  116757. void *pEngine; /* The LEMON-generated LALR(1) parser */
  116758. int tokenType; /* type of the next token */
  116759. int lastTokenParsed = -1; /* type of the previous token */
  116760. u8 enableLookaside; /* Saved value of db->lookaside.bEnabled */
  116761. sqlite3 *db = pParse->db; /* The database connection */
  116762. int mxSqlLen; /* Max length of an SQL string */
  116763. mxSqlLen = db->aLimit[SQLITE_LIMIT_SQL_LENGTH];
  116764. if( db->nVdbeActive==0 ){
  116765. db->u1.isInterrupted = 0;
  116766. }
  116767. pParse->rc = SQLITE_OK;
  116768. pParse->zTail = zSql;
  116769. i = 0;
  116770. assert( pzErrMsg!=0 );
  116771. pEngine = sqlite3ParserAlloc(sqlite3Malloc);
  116772. if( pEngine==0 ){
  116773. db->mallocFailed = 1;
  116774. return SQLITE_NOMEM;
  116775. }
  116776. assert( pParse->pNewTable==0 );
  116777. assert( pParse->pNewTrigger==0 );
  116778. assert( pParse->nVar==0 );
  116779. assert( pParse->nzVar==0 );
  116780. assert( pParse->azVar==0 );
  116781. enableLookaside = db->lookaside.bEnabled;
  116782. if( db->lookaside.pStart ) db->lookaside.bEnabled = 1;
  116783. while( !db->mallocFailed && zSql[i]!=0 ){
  116784. assert( i>=0 );
  116785. pParse->sLastToken.z = &zSql[i];
  116786. pParse->sLastToken.n = sqlite3GetToken((unsigned char*)&zSql[i],&tokenType);
  116787. i += pParse->sLastToken.n;
  116788. if( i>mxSqlLen ){
  116789. pParse->rc = SQLITE_TOOBIG;
  116790. break;
  116791. }
  116792. switch( tokenType ){
  116793. case TK_SPACE: {
  116794. if( db->u1.isInterrupted ){
  116795. sqlite3ErrorMsg(pParse, "interrupt");
  116796. pParse->rc = SQLITE_INTERRUPT;
  116797. goto abort_parse;
  116798. }
  116799. break;
  116800. }
  116801. case TK_ILLEGAL: {
  116802. sqlite3DbFree(db, *pzErrMsg);
  116803. *pzErrMsg = sqlite3MPrintf(db, "unrecognized token: \"%T\"",
  116804. &pParse->sLastToken);
  116805. nErr++;
  116806. goto abort_parse;
  116807. }
  116808. case TK_SEMI: {
  116809. pParse->zTail = &zSql[i];
  116810. /* Fall thru into the default case */
  116811. }
  116812. default: {
  116813. sqlite3Parser(pEngine, tokenType, pParse->sLastToken, pParse);
  116814. lastTokenParsed = tokenType;
  116815. if( pParse->rc!=SQLITE_OK ){
  116816. goto abort_parse;
  116817. }
  116818. break;
  116819. }
  116820. }
  116821. }
  116822. abort_parse:
  116823. if( zSql[i]==0 && nErr==0 && pParse->rc==SQLITE_OK ){
  116824. if( lastTokenParsed!=TK_SEMI ){
  116825. sqlite3Parser(pEngine, TK_SEMI, pParse->sLastToken, pParse);
  116826. pParse->zTail = &zSql[i];
  116827. }
  116828. sqlite3Parser(pEngine, 0, pParse->sLastToken, pParse);
  116829. }
  116830. #ifdef YYTRACKMAXSTACKDEPTH
  116831. sqlite3StatusSet(SQLITE_STATUS_PARSER_STACK,
  116832. sqlite3ParserStackPeak(pEngine)
  116833. );
  116834. #endif /* YYDEBUG */
  116835. sqlite3ParserFree(pEngine, sqlite3_free);
  116836. db->lookaside.bEnabled = enableLookaside;
  116837. if( db->mallocFailed ){
  116838. pParse->rc = SQLITE_NOMEM;
  116839. }
  116840. if( pParse->rc!=SQLITE_OK && pParse->rc!=SQLITE_DONE && pParse->zErrMsg==0 ){
  116841. sqlite3SetString(&pParse->zErrMsg, db, "%s", sqlite3ErrStr(pParse->rc));
  116842. }
  116843. assert( pzErrMsg!=0 );
  116844. if( pParse->zErrMsg ){
  116845. *pzErrMsg = pParse->zErrMsg;
  116846. sqlite3_log(pParse->rc, "%s", *pzErrMsg);
  116847. pParse->zErrMsg = 0;
  116848. nErr++;
  116849. }
  116850. if( pParse->pVdbe && pParse->nErr>0 && pParse->nested==0 ){
  116851. sqlite3VdbeDelete(pParse->pVdbe);
  116852. pParse->pVdbe = 0;
  116853. }
  116854. #ifndef SQLITE_OMIT_SHARED_CACHE
  116855. if( pParse->nested==0 ){
  116856. sqlite3DbFree(db, pParse->aTableLock);
  116857. pParse->aTableLock = 0;
  116858. pParse->nTableLock = 0;
  116859. }
  116860. #endif
  116861. #ifndef SQLITE_OMIT_VIRTUALTABLE
  116862. sqlite3_free(pParse->apVtabLock);
  116863. #endif
  116864. if( !IN_DECLARE_VTAB ){
  116865. /* If the pParse->declareVtab flag is set, do not delete any table
  116866. ** structure built up in pParse->pNewTable. The calling code (see vtab.c)
  116867. ** will take responsibility for freeing the Table structure.
  116868. */
  116869. sqlite3DeleteTable(db, pParse->pNewTable);
  116870. }
  116871. if( pParse->bFreeWith ) sqlite3WithDelete(db, pParse->pWith);
  116872. sqlite3DeleteTrigger(db, pParse->pNewTrigger);
  116873. for(i=pParse->nzVar-1; i>=0; i--) sqlite3DbFree(db, pParse->azVar[i]);
  116874. sqlite3DbFree(db, pParse->azVar);
  116875. while( pParse->pAinc ){
  116876. AutoincInfo *p = pParse->pAinc;
  116877. pParse->pAinc = p->pNext;
  116878. sqlite3DbFree(db, p);
  116879. }
  116880. while( pParse->pZombieTab ){
  116881. Table *p = pParse->pZombieTab;
  116882. pParse->pZombieTab = p->pNextZombie;
  116883. sqlite3DeleteTable(db, p);
  116884. }
  116885. if( nErr>0 && pParse->rc==SQLITE_OK ){
  116886. pParse->rc = SQLITE_ERROR;
  116887. }
  116888. return nErr;
  116889. }
  116890. /************** End of tokenize.c ********************************************/
  116891. /************** Begin file complete.c ****************************************/
  116892. /*
  116893. ** 2001 September 15
  116894. **
  116895. ** The author disclaims copyright to this source code. In place of
  116896. ** a legal notice, here is a blessing:
  116897. **
  116898. ** May you do good and not evil.
  116899. ** May you find forgiveness for yourself and forgive others.
  116900. ** May you share freely, never taking more than you give.
  116901. **
  116902. *************************************************************************
  116903. ** An tokenizer for SQL
  116904. **
  116905. ** This file contains C code that implements the sqlite3_complete() API.
  116906. ** This code used to be part of the tokenizer.c source file. But by
  116907. ** separating it out, the code will be automatically omitted from
  116908. ** static links that do not use it.
  116909. */
  116910. #ifndef SQLITE_OMIT_COMPLETE
  116911. /*
  116912. ** This is defined in tokenize.c. We just have to import the definition.
  116913. */
  116914. #ifndef SQLITE_AMALGAMATION
  116915. #ifdef SQLITE_ASCII
  116916. #define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0)
  116917. #endif
  116918. #ifdef SQLITE_EBCDIC
  116919. SQLITE_PRIVATE const char sqlite3IsEbcdicIdChar[];
  116920. #define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40]))
  116921. #endif
  116922. #endif /* SQLITE_AMALGAMATION */
  116923. /*
  116924. ** Token types used by the sqlite3_complete() routine. See the header
  116925. ** comments on that procedure for additional information.
  116926. */
  116927. #define tkSEMI 0
  116928. #define tkWS 1
  116929. #define tkOTHER 2
  116930. #ifndef SQLITE_OMIT_TRIGGER
  116931. #define tkEXPLAIN 3
  116932. #define tkCREATE 4
  116933. #define tkTEMP 5
  116934. #define tkTRIGGER 6
  116935. #define tkEND 7
  116936. #endif
  116937. /*
  116938. ** Return TRUE if the given SQL string ends in a semicolon.
  116939. **
  116940. ** Special handling is require for CREATE TRIGGER statements.
  116941. ** Whenever the CREATE TRIGGER keywords are seen, the statement
  116942. ** must end with ";END;".
  116943. **
  116944. ** This implementation uses a state machine with 8 states:
  116945. **
  116946. ** (0) INVALID We have not yet seen a non-whitespace character.
  116947. **
  116948. ** (1) START At the beginning or end of an SQL statement. This routine
  116949. ** returns 1 if it ends in the START state and 0 if it ends
  116950. ** in any other state.
  116951. **
  116952. ** (2) NORMAL We are in the middle of statement which ends with a single
  116953. ** semicolon.
  116954. **
  116955. ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of
  116956. ** a statement.
  116957. **
  116958. ** (4) CREATE The keyword CREATE has been seen at the beginning of a
  116959. ** statement, possibly preceded by EXPLAIN and/or followed by
  116960. ** TEMP or TEMPORARY
  116961. **
  116962. ** (5) TRIGGER We are in the middle of a trigger definition that must be
  116963. ** ended by a semicolon, the keyword END, and another semicolon.
  116964. **
  116965. ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at
  116966. ** the end of a trigger definition.
  116967. **
  116968. ** (7) END We've seen the ";END" of the ";END;" that occurs at the end
  116969. ** of a trigger definition.
  116970. **
  116971. ** Transitions between states above are determined by tokens extracted
  116972. ** from the input. The following tokens are significant:
  116973. **
  116974. ** (0) tkSEMI A semicolon.
  116975. ** (1) tkWS Whitespace.
  116976. ** (2) tkOTHER Any other SQL token.
  116977. ** (3) tkEXPLAIN The "explain" keyword.
  116978. ** (4) tkCREATE The "create" keyword.
  116979. ** (5) tkTEMP The "temp" or "temporary" keyword.
  116980. ** (6) tkTRIGGER The "trigger" keyword.
  116981. ** (7) tkEND The "end" keyword.
  116982. **
  116983. ** Whitespace never causes a state transition and is always ignored.
  116984. ** This means that a SQL string of all whitespace is invalid.
  116985. **
  116986. ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed
  116987. ** to recognize the end of a trigger can be omitted. All we have to do
  116988. ** is look for a semicolon that is not part of an string or comment.
  116989. */
  116990. SQLITE_API int sqlite3_complete(const char *zSql){
  116991. u8 state = 0; /* Current state, using numbers defined in header comment */
  116992. u8 token; /* Value of the next token */
  116993. #ifndef SQLITE_OMIT_TRIGGER
  116994. /* A complex statement machine used to detect the end of a CREATE TRIGGER
  116995. ** statement. This is the normal case.
  116996. */
  116997. static const u8 trans[8][8] = {
  116998. /* Token: */
  116999. /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */
  117000. /* 0 INVALID: */ { 1, 0, 2, 3, 4, 2, 2, 2, },
  117001. /* 1 START: */ { 1, 1, 2, 3, 4, 2, 2, 2, },
  117002. /* 2 NORMAL: */ { 1, 2, 2, 2, 2, 2, 2, 2, },
  117003. /* 3 EXPLAIN: */ { 1, 3, 3, 2, 4, 2, 2, 2, },
  117004. /* 4 CREATE: */ { 1, 4, 2, 2, 2, 4, 5, 2, },
  117005. /* 5 TRIGGER: */ { 6, 5, 5, 5, 5, 5, 5, 5, },
  117006. /* 6 SEMI: */ { 6, 6, 5, 5, 5, 5, 5, 7, },
  117007. /* 7 END: */ { 1, 7, 5, 5, 5, 5, 5, 5, },
  117008. };
  117009. #else
  117010. /* If triggers are not supported by this compile then the statement machine
  117011. ** used to detect the end of a statement is much simpler
  117012. */
  117013. static const u8 trans[3][3] = {
  117014. /* Token: */
  117015. /* State: ** SEMI WS OTHER */
  117016. /* 0 INVALID: */ { 1, 0, 2, },
  117017. /* 1 START: */ { 1, 1, 2, },
  117018. /* 2 NORMAL: */ { 1, 2, 2, },
  117019. };
  117020. #endif /* SQLITE_OMIT_TRIGGER */
  117021. while( *zSql ){
  117022. switch( *zSql ){
  117023. case ';': { /* A semicolon */
  117024. token = tkSEMI;
  117025. break;
  117026. }
  117027. case ' ':
  117028. case '\r':
  117029. case '\t':
  117030. case '\n':
  117031. case '\f': { /* White space is ignored */
  117032. token = tkWS;
  117033. break;
  117034. }
  117035. case '/': { /* C-style comments */
  117036. if( zSql[1]!='*' ){
  117037. token = tkOTHER;
  117038. break;
  117039. }
  117040. zSql += 2;
  117041. while( zSql[0] && (zSql[0]!='*' || zSql[1]!='/') ){ zSql++; }
  117042. if( zSql[0]==0 ) return 0;
  117043. zSql++;
  117044. token = tkWS;
  117045. break;
  117046. }
  117047. case '-': { /* SQL-style comments from "--" to end of line */
  117048. if( zSql[1]!='-' ){
  117049. token = tkOTHER;
  117050. break;
  117051. }
  117052. while( *zSql && *zSql!='\n' ){ zSql++; }
  117053. if( *zSql==0 ) return state==1;
  117054. token = tkWS;
  117055. break;
  117056. }
  117057. case '[': { /* Microsoft-style identifiers in [...] */
  117058. zSql++;
  117059. while( *zSql && *zSql!=']' ){ zSql++; }
  117060. if( *zSql==0 ) return 0;
  117061. token = tkOTHER;
  117062. break;
  117063. }
  117064. case '`': /* Grave-accent quoted symbols used by MySQL */
  117065. case '"': /* single- and double-quoted strings */
  117066. case '\'': {
  117067. int c = *zSql;
  117068. zSql++;
  117069. while( *zSql && *zSql!=c ){ zSql++; }
  117070. if( *zSql==0 ) return 0;
  117071. token = tkOTHER;
  117072. break;
  117073. }
  117074. default: {
  117075. #ifdef SQLITE_EBCDIC
  117076. unsigned char c;
  117077. #endif
  117078. if( IdChar((u8)*zSql) ){
  117079. /* Keywords and unquoted identifiers */
  117080. int nId;
  117081. for(nId=1; IdChar(zSql[nId]); nId++){}
  117082. #ifdef SQLITE_OMIT_TRIGGER
  117083. token = tkOTHER;
  117084. #else
  117085. switch( *zSql ){
  117086. case 'c': case 'C': {
  117087. if( nId==6 && sqlite3StrNICmp(zSql, "create", 6)==0 ){
  117088. token = tkCREATE;
  117089. }else{
  117090. token = tkOTHER;
  117091. }
  117092. break;
  117093. }
  117094. case 't': case 'T': {
  117095. if( nId==7 && sqlite3StrNICmp(zSql, "trigger", 7)==0 ){
  117096. token = tkTRIGGER;
  117097. }else if( nId==4 && sqlite3StrNICmp(zSql, "temp", 4)==0 ){
  117098. token = tkTEMP;
  117099. }else if( nId==9 && sqlite3StrNICmp(zSql, "temporary", 9)==0 ){
  117100. token = tkTEMP;
  117101. }else{
  117102. token = tkOTHER;
  117103. }
  117104. break;
  117105. }
  117106. case 'e': case 'E': {
  117107. if( nId==3 && sqlite3StrNICmp(zSql, "end", 3)==0 ){
  117108. token = tkEND;
  117109. }else
  117110. #ifndef SQLITE_OMIT_EXPLAIN
  117111. if( nId==7 && sqlite3StrNICmp(zSql, "explain", 7)==0 ){
  117112. token = tkEXPLAIN;
  117113. }else
  117114. #endif
  117115. {
  117116. token = tkOTHER;
  117117. }
  117118. break;
  117119. }
  117120. default: {
  117121. token = tkOTHER;
  117122. break;
  117123. }
  117124. }
  117125. #endif /* SQLITE_OMIT_TRIGGER */
  117126. zSql += nId-1;
  117127. }else{
  117128. /* Operators and special symbols */
  117129. token = tkOTHER;
  117130. }
  117131. break;
  117132. }
  117133. }
  117134. state = trans[state][token];
  117135. zSql++;
  117136. }
  117137. return state==1;
  117138. }
  117139. #ifndef SQLITE_OMIT_UTF16
  117140. /*
  117141. ** This routine is the same as the sqlite3_complete() routine described
  117142. ** above, except that the parameter is required to be UTF-16 encoded, not
  117143. ** UTF-8.
  117144. */
  117145. SQLITE_API int sqlite3_complete16(const void *zSql){
  117146. sqlite3_value *pVal;
  117147. char const *zSql8;
  117148. int rc = SQLITE_NOMEM;
  117149. #ifndef SQLITE_OMIT_AUTOINIT
  117150. rc = sqlite3_initialize();
  117151. if( rc ) return rc;
  117152. #endif
  117153. pVal = sqlite3ValueNew(0);
  117154. sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  117155. zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  117156. if( zSql8 ){
  117157. rc = sqlite3_complete(zSql8);
  117158. }else{
  117159. rc = SQLITE_NOMEM;
  117160. }
  117161. sqlite3ValueFree(pVal);
  117162. return sqlite3ApiExit(0, rc);
  117163. }
  117164. #endif /* SQLITE_OMIT_UTF16 */
  117165. #endif /* SQLITE_OMIT_COMPLETE */
  117166. /************** End of complete.c ********************************************/
  117167. /************** Begin file main.c ********************************************/
  117168. /*
  117169. ** 2001 September 15
  117170. **
  117171. ** The author disclaims copyright to this source code. In place of
  117172. ** a legal notice, here is a blessing:
  117173. **
  117174. ** May you do good and not evil.
  117175. ** May you find forgiveness for yourself and forgive others.
  117176. ** May you share freely, never taking more than you give.
  117177. **
  117178. *************************************************************************
  117179. ** Main file for the SQLite library. The routines in this file
  117180. ** implement the programmer interface to the library. Routines in
  117181. ** other files are for internal use by SQLite and should not be
  117182. ** accessed by users of the library.
  117183. */
  117184. #ifdef SQLITE_ENABLE_FTS3
  117185. /************** Include fts3.h in the middle of main.c ***********************/
  117186. /************** Begin file fts3.h ********************************************/
  117187. /*
  117188. ** 2006 Oct 10
  117189. **
  117190. ** The author disclaims copyright to this source code. In place of
  117191. ** a legal notice, here is a blessing:
  117192. **
  117193. ** May you do good and not evil.
  117194. ** May you find forgiveness for yourself and forgive others.
  117195. ** May you share freely, never taking more than you give.
  117196. **
  117197. ******************************************************************************
  117198. **
  117199. ** This header file is used by programs that want to link against the
  117200. ** FTS3 library. All it does is declare the sqlite3Fts3Init() interface.
  117201. */
  117202. #if 0
  117203. extern "C" {
  117204. #endif /* __cplusplus */
  117205. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db);
  117206. #if 0
  117207. } /* extern "C" */
  117208. #endif /* __cplusplus */
  117209. /************** End of fts3.h ************************************************/
  117210. /************** Continuing where we left off in main.c ***********************/
  117211. #endif
  117212. #ifdef SQLITE_ENABLE_RTREE
  117213. /************** Include rtree.h in the middle of main.c **********************/
  117214. /************** Begin file rtree.h *******************************************/
  117215. /*
  117216. ** 2008 May 26
  117217. **
  117218. ** The author disclaims copyright to this source code. In place of
  117219. ** a legal notice, here is a blessing:
  117220. **
  117221. ** May you do good and not evil.
  117222. ** May you find forgiveness for yourself and forgive others.
  117223. ** May you share freely, never taking more than you give.
  117224. **
  117225. ******************************************************************************
  117226. **
  117227. ** This header file is used by programs that want to link against the
  117228. ** RTREE library. All it does is declare the sqlite3RtreeInit() interface.
  117229. */
  117230. #if 0
  117231. extern "C" {
  117232. #endif /* __cplusplus */
  117233. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db);
  117234. #if 0
  117235. } /* extern "C" */
  117236. #endif /* __cplusplus */
  117237. /************** End of rtree.h ***********************************************/
  117238. /************** Continuing where we left off in main.c ***********************/
  117239. #endif
  117240. #ifdef SQLITE_ENABLE_ICU
  117241. /************** Include sqliteicu.h in the middle of main.c ******************/
  117242. /************** Begin file sqliteicu.h ***************************************/
  117243. /*
  117244. ** 2008 May 26
  117245. **
  117246. ** The author disclaims copyright to this source code. In place of
  117247. ** a legal notice, here is a blessing:
  117248. **
  117249. ** May you do good and not evil.
  117250. ** May you find forgiveness for yourself and forgive others.
  117251. ** May you share freely, never taking more than you give.
  117252. **
  117253. ******************************************************************************
  117254. **
  117255. ** This header file is used by programs that want to link against the
  117256. ** ICU extension. All it does is declare the sqlite3IcuInit() interface.
  117257. */
  117258. #if 0
  117259. extern "C" {
  117260. #endif /* __cplusplus */
  117261. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db);
  117262. #if 0
  117263. } /* extern "C" */
  117264. #endif /* __cplusplus */
  117265. /************** End of sqliteicu.h *******************************************/
  117266. /************** Continuing where we left off in main.c ***********************/
  117267. #endif
  117268. #ifndef SQLITE_AMALGAMATION
  117269. /* IMPLEMENTATION-OF: R-46656-45156 The sqlite3_version[] string constant
  117270. ** contains the text of SQLITE_VERSION macro.
  117271. */
  117272. SQLITE_API const char sqlite3_version[] = SQLITE_VERSION;
  117273. #endif
  117274. /* IMPLEMENTATION-OF: R-53536-42575 The sqlite3_libversion() function returns
  117275. ** a pointer to the to the sqlite3_version[] string constant.
  117276. */
  117277. SQLITE_API const char *sqlite3_libversion(void){ return sqlite3_version; }
  117278. /* IMPLEMENTATION-OF: R-63124-39300 The sqlite3_sourceid() function returns a
  117279. ** pointer to a string constant whose value is the same as the
  117280. ** SQLITE_SOURCE_ID C preprocessor macro.
  117281. */
  117282. SQLITE_API const char *sqlite3_sourceid(void){ return SQLITE_SOURCE_ID; }
  117283. /* IMPLEMENTATION-OF: R-35210-63508 The sqlite3_libversion_number() function
  117284. ** returns an integer equal to SQLITE_VERSION_NUMBER.
  117285. */
  117286. SQLITE_API int sqlite3_libversion_number(void){ return SQLITE_VERSION_NUMBER; }
  117287. /* IMPLEMENTATION-OF: R-20790-14025 The sqlite3_threadsafe() function returns
  117288. ** zero if and only if SQLite was compiled with mutexing code omitted due to
  117289. ** the SQLITE_THREADSAFE compile-time option being set to 0.
  117290. */
  117291. SQLITE_API int sqlite3_threadsafe(void){ return SQLITE_THREADSAFE; }
  117292. #if !defined(SQLITE_OMIT_TRACE) && defined(SQLITE_ENABLE_IOTRACE)
  117293. /*
  117294. ** If the following function pointer is not NULL and if
  117295. ** SQLITE_ENABLE_IOTRACE is enabled, then messages describing
  117296. ** I/O active are written using this function. These messages
  117297. ** are intended for debugging activity only.
  117298. */
  117299. SQLITE_PRIVATE void (*sqlite3IoTrace)(const char*, ...) = 0;
  117300. #endif
  117301. /*
  117302. ** If the following global variable points to a string which is the
  117303. ** name of a directory, then that directory will be used to store
  117304. ** temporary files.
  117305. **
  117306. ** See also the "PRAGMA temp_store_directory" SQL command.
  117307. */
  117308. SQLITE_API char *sqlite3_temp_directory = 0;
  117309. /*
  117310. ** If the following global variable points to a string which is the
  117311. ** name of a directory, then that directory will be used to store
  117312. ** all database files specified with a relative pathname.
  117313. **
  117314. ** See also the "PRAGMA data_store_directory" SQL command.
  117315. */
  117316. SQLITE_API char *sqlite3_data_directory = 0;
  117317. /*
  117318. ** Initialize SQLite.
  117319. **
  117320. ** This routine must be called to initialize the memory allocation,
  117321. ** VFS, and mutex subsystems prior to doing any serious work with
  117322. ** SQLite. But as long as you do not compile with SQLITE_OMIT_AUTOINIT
  117323. ** this routine will be called automatically by key routines such as
  117324. ** sqlite3_open().
  117325. **
  117326. ** This routine is a no-op except on its very first call for the process,
  117327. ** or for the first call after a call to sqlite3_shutdown.
  117328. **
  117329. ** The first thread to call this routine runs the initialization to
  117330. ** completion. If subsequent threads call this routine before the first
  117331. ** thread has finished the initialization process, then the subsequent
  117332. ** threads must block until the first thread finishes with the initialization.
  117333. **
  117334. ** The first thread might call this routine recursively. Recursive
  117335. ** calls to this routine should not block, of course. Otherwise the
  117336. ** initialization process would never complete.
  117337. **
  117338. ** Let X be the first thread to enter this routine. Let Y be some other
  117339. ** thread. Then while the initial invocation of this routine by X is
  117340. ** incomplete, it is required that:
  117341. **
  117342. ** * Calls to this routine from Y must block until the outer-most
  117343. ** call by X completes.
  117344. **
  117345. ** * Recursive calls to this routine from thread X return immediately
  117346. ** without blocking.
  117347. */
  117348. SQLITE_API int sqlite3_initialize(void){
  117349. MUTEX_LOGIC( sqlite3_mutex *pMaster; ) /* The main static mutex */
  117350. int rc; /* Result code */
  117351. #ifdef SQLITE_EXTRA_INIT
  117352. int bRunExtraInit = 0; /* Extra initialization needed */
  117353. #endif
  117354. #ifdef SQLITE_OMIT_WSD
  117355. rc = sqlite3_wsd_init(4096, 24);
  117356. if( rc!=SQLITE_OK ){
  117357. return rc;
  117358. }
  117359. #endif
  117360. /* If SQLite is already completely initialized, then this call
  117361. ** to sqlite3_initialize() should be a no-op. But the initialization
  117362. ** must be complete. So isInit must not be set until the very end
  117363. ** of this routine.
  117364. */
  117365. if( sqlite3GlobalConfig.isInit ) return SQLITE_OK;
  117366. /* Make sure the mutex subsystem is initialized. If unable to
  117367. ** initialize the mutex subsystem, return early with the error.
  117368. ** If the system is so sick that we are unable to allocate a mutex,
  117369. ** there is not much SQLite is going to be able to do.
  117370. **
  117371. ** The mutex subsystem must take care of serializing its own
  117372. ** initialization.
  117373. */
  117374. rc = sqlite3MutexInit();
  117375. if( rc ) return rc;
  117376. /* Initialize the malloc() system and the recursive pInitMutex mutex.
  117377. ** This operation is protected by the STATIC_MASTER mutex. Note that
  117378. ** MutexAlloc() is called for a static mutex prior to initializing the
  117379. ** malloc subsystem - this implies that the allocation of a static
  117380. ** mutex must not require support from the malloc subsystem.
  117381. */
  117382. MUTEX_LOGIC( pMaster = sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER); )
  117383. sqlite3_mutex_enter(pMaster);
  117384. sqlite3GlobalConfig.isMutexInit = 1;
  117385. if( !sqlite3GlobalConfig.isMallocInit ){
  117386. rc = sqlite3MallocInit();
  117387. }
  117388. if( rc==SQLITE_OK ){
  117389. sqlite3GlobalConfig.isMallocInit = 1;
  117390. if( !sqlite3GlobalConfig.pInitMutex ){
  117391. sqlite3GlobalConfig.pInitMutex =
  117392. sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  117393. if( sqlite3GlobalConfig.bCoreMutex && !sqlite3GlobalConfig.pInitMutex ){
  117394. rc = SQLITE_NOMEM;
  117395. }
  117396. }
  117397. }
  117398. if( rc==SQLITE_OK ){
  117399. sqlite3GlobalConfig.nRefInitMutex++;
  117400. }
  117401. sqlite3_mutex_leave(pMaster);
  117402. /* If rc is not SQLITE_OK at this point, then either the malloc
  117403. ** subsystem could not be initialized or the system failed to allocate
  117404. ** the pInitMutex mutex. Return an error in either case. */
  117405. if( rc!=SQLITE_OK ){
  117406. return rc;
  117407. }
  117408. /* Do the rest of the initialization under the recursive mutex so
  117409. ** that we will be able to handle recursive calls into
  117410. ** sqlite3_initialize(). The recursive calls normally come through
  117411. ** sqlite3_os_init() when it invokes sqlite3_vfs_register(), but other
  117412. ** recursive calls might also be possible.
  117413. **
  117414. ** IMPLEMENTATION-OF: R-00140-37445 SQLite automatically serializes calls
  117415. ** to the xInit method, so the xInit method need not be threadsafe.
  117416. **
  117417. ** The following mutex is what serializes access to the appdef pcache xInit
  117418. ** methods. The sqlite3_pcache_methods.xInit() all is embedded in the
  117419. ** call to sqlite3PcacheInitialize().
  117420. */
  117421. sqlite3_mutex_enter(sqlite3GlobalConfig.pInitMutex);
  117422. if( sqlite3GlobalConfig.isInit==0 && sqlite3GlobalConfig.inProgress==0 ){
  117423. FuncDefHash *pHash = &GLOBAL(FuncDefHash, sqlite3GlobalFunctions);
  117424. sqlite3GlobalConfig.inProgress = 1;
  117425. memset(pHash, 0, sizeof(sqlite3GlobalFunctions));
  117426. sqlite3RegisterGlobalFunctions();
  117427. if( sqlite3GlobalConfig.isPCacheInit==0 ){
  117428. rc = sqlite3PcacheInitialize();
  117429. }
  117430. if( rc==SQLITE_OK ){
  117431. sqlite3GlobalConfig.isPCacheInit = 1;
  117432. rc = sqlite3OsInit();
  117433. }
  117434. if( rc==SQLITE_OK ){
  117435. sqlite3PCacheBufferSetup( sqlite3GlobalConfig.pPage,
  117436. sqlite3GlobalConfig.szPage, sqlite3GlobalConfig.nPage);
  117437. sqlite3GlobalConfig.isInit = 1;
  117438. #ifdef SQLITE_EXTRA_INIT
  117439. bRunExtraInit = 1;
  117440. #endif
  117441. }
  117442. sqlite3GlobalConfig.inProgress = 0;
  117443. }
  117444. sqlite3_mutex_leave(sqlite3GlobalConfig.pInitMutex);
  117445. /* Go back under the static mutex and clean up the recursive
  117446. ** mutex to prevent a resource leak.
  117447. */
  117448. sqlite3_mutex_enter(pMaster);
  117449. sqlite3GlobalConfig.nRefInitMutex--;
  117450. if( sqlite3GlobalConfig.nRefInitMutex<=0 ){
  117451. assert( sqlite3GlobalConfig.nRefInitMutex==0 );
  117452. sqlite3_mutex_free(sqlite3GlobalConfig.pInitMutex);
  117453. sqlite3GlobalConfig.pInitMutex = 0;
  117454. }
  117455. sqlite3_mutex_leave(pMaster);
  117456. /* The following is just a sanity check to make sure SQLite has
  117457. ** been compiled correctly. It is important to run this code, but
  117458. ** we don't want to run it too often and soak up CPU cycles for no
  117459. ** reason. So we run it once during initialization.
  117460. */
  117461. #ifndef NDEBUG
  117462. #ifndef SQLITE_OMIT_FLOATING_POINT
  117463. /* This section of code's only "output" is via assert() statements. */
  117464. if ( rc==SQLITE_OK ){
  117465. u64 x = (((u64)1)<<63)-1;
  117466. double y;
  117467. assert(sizeof(x)==8);
  117468. assert(sizeof(x)==sizeof(y));
  117469. memcpy(&y, &x, 8);
  117470. assert( sqlite3IsNaN(y) );
  117471. }
  117472. #endif
  117473. #endif
  117474. /* Do extra initialization steps requested by the SQLITE_EXTRA_INIT
  117475. ** compile-time option.
  117476. */
  117477. #ifdef SQLITE_EXTRA_INIT
  117478. if( bRunExtraInit ){
  117479. int SQLITE_EXTRA_INIT(const char*);
  117480. rc = SQLITE_EXTRA_INIT(0);
  117481. }
  117482. #endif
  117483. return rc;
  117484. }
  117485. /*
  117486. ** Undo the effects of sqlite3_initialize(). Must not be called while
  117487. ** there are outstanding database connections or memory allocations or
  117488. ** while any part of SQLite is otherwise in use in any thread. This
  117489. ** routine is not threadsafe. But it is safe to invoke this routine
  117490. ** on when SQLite is already shut down. If SQLite is already shut down
  117491. ** when this routine is invoked, then this routine is a harmless no-op.
  117492. */
  117493. SQLITE_API int sqlite3_shutdown(void){
  117494. if( sqlite3GlobalConfig.isInit ){
  117495. #ifdef SQLITE_EXTRA_SHUTDOWN
  117496. void SQLITE_EXTRA_SHUTDOWN(void);
  117497. SQLITE_EXTRA_SHUTDOWN();
  117498. #endif
  117499. sqlite3_os_end();
  117500. sqlite3_reset_auto_extension();
  117501. sqlite3GlobalConfig.isInit = 0;
  117502. }
  117503. if( sqlite3GlobalConfig.isPCacheInit ){
  117504. sqlite3PcacheShutdown();
  117505. sqlite3GlobalConfig.isPCacheInit = 0;
  117506. }
  117507. if( sqlite3GlobalConfig.isMallocInit ){
  117508. sqlite3MallocEnd();
  117509. sqlite3GlobalConfig.isMallocInit = 0;
  117510. #ifndef SQLITE_OMIT_SHUTDOWN_DIRECTORIES
  117511. /* The heap subsystem has now been shutdown and these values are supposed
  117512. ** to be NULL or point to memory that was obtained from sqlite3_malloc(),
  117513. ** which would rely on that heap subsystem; therefore, make sure these
  117514. ** values cannot refer to heap memory that was just invalidated when the
  117515. ** heap subsystem was shutdown. This is only done if the current call to
  117516. ** this function resulted in the heap subsystem actually being shutdown.
  117517. */
  117518. sqlite3_data_directory = 0;
  117519. sqlite3_temp_directory = 0;
  117520. #endif
  117521. }
  117522. if( sqlite3GlobalConfig.isMutexInit ){
  117523. sqlite3MutexEnd();
  117524. sqlite3GlobalConfig.isMutexInit = 0;
  117525. }
  117526. return SQLITE_OK;
  117527. }
  117528. /*
  117529. ** This API allows applications to modify the global configuration of
  117530. ** the SQLite library at run-time.
  117531. **
  117532. ** This routine should only be called when there are no outstanding
  117533. ** database connections or memory allocations. This routine is not
  117534. ** threadsafe. Failure to heed these warnings can lead to unpredictable
  117535. ** behavior.
  117536. */
  117537. SQLITE_API int sqlite3_config(int op, ...){
  117538. va_list ap;
  117539. int rc = SQLITE_OK;
  117540. /* sqlite3_config() shall return SQLITE_MISUSE if it is invoked while
  117541. ** the SQLite library is in use. */
  117542. if( sqlite3GlobalConfig.isInit ) return SQLITE_MISUSE_BKPT;
  117543. va_start(ap, op);
  117544. switch( op ){
  117545. /* Mutex configuration options are only available in a threadsafe
  117546. ** compile.
  117547. */
  117548. #if defined(SQLITE_THREADSAFE) && SQLITE_THREADSAFE>0
  117549. case SQLITE_CONFIG_SINGLETHREAD: {
  117550. /* Disable all mutexing */
  117551. sqlite3GlobalConfig.bCoreMutex = 0;
  117552. sqlite3GlobalConfig.bFullMutex = 0;
  117553. break;
  117554. }
  117555. case SQLITE_CONFIG_MULTITHREAD: {
  117556. /* Disable mutexing of database connections */
  117557. /* Enable mutexing of core data structures */
  117558. sqlite3GlobalConfig.bCoreMutex = 1;
  117559. sqlite3GlobalConfig.bFullMutex = 0;
  117560. break;
  117561. }
  117562. case SQLITE_CONFIG_SERIALIZED: {
  117563. /* Enable all mutexing */
  117564. sqlite3GlobalConfig.bCoreMutex = 1;
  117565. sqlite3GlobalConfig.bFullMutex = 1;
  117566. break;
  117567. }
  117568. case SQLITE_CONFIG_MUTEX: {
  117569. /* Specify an alternative mutex implementation */
  117570. sqlite3GlobalConfig.mutex = *va_arg(ap, sqlite3_mutex_methods*);
  117571. break;
  117572. }
  117573. case SQLITE_CONFIG_GETMUTEX: {
  117574. /* Retrieve the current mutex implementation */
  117575. *va_arg(ap, sqlite3_mutex_methods*) = sqlite3GlobalConfig.mutex;
  117576. break;
  117577. }
  117578. #endif
  117579. case SQLITE_CONFIG_MALLOC: {
  117580. /* Specify an alternative malloc implementation */
  117581. sqlite3GlobalConfig.m = *va_arg(ap, sqlite3_mem_methods*);
  117582. break;
  117583. }
  117584. case SQLITE_CONFIG_GETMALLOC: {
  117585. /* Retrieve the current malloc() implementation */
  117586. if( sqlite3GlobalConfig.m.xMalloc==0 ) sqlite3MemSetDefault();
  117587. *va_arg(ap, sqlite3_mem_methods*) = sqlite3GlobalConfig.m;
  117588. break;
  117589. }
  117590. case SQLITE_CONFIG_MEMSTATUS: {
  117591. /* Enable or disable the malloc status collection */
  117592. sqlite3GlobalConfig.bMemstat = va_arg(ap, int);
  117593. break;
  117594. }
  117595. case SQLITE_CONFIG_SCRATCH: {
  117596. /* Designate a buffer for scratch memory space */
  117597. sqlite3GlobalConfig.pScratch = va_arg(ap, void*);
  117598. sqlite3GlobalConfig.szScratch = va_arg(ap, int);
  117599. sqlite3GlobalConfig.nScratch = va_arg(ap, int);
  117600. break;
  117601. }
  117602. case SQLITE_CONFIG_PAGECACHE: {
  117603. /* Designate a buffer for page cache memory space */
  117604. sqlite3GlobalConfig.pPage = va_arg(ap, void*);
  117605. sqlite3GlobalConfig.szPage = va_arg(ap, int);
  117606. sqlite3GlobalConfig.nPage = va_arg(ap, int);
  117607. break;
  117608. }
  117609. case SQLITE_CONFIG_PCACHE: {
  117610. /* no-op */
  117611. break;
  117612. }
  117613. case SQLITE_CONFIG_GETPCACHE: {
  117614. /* now an error */
  117615. rc = SQLITE_ERROR;
  117616. break;
  117617. }
  117618. case SQLITE_CONFIG_PCACHE2: {
  117619. /* Specify an alternative page cache implementation */
  117620. sqlite3GlobalConfig.pcache2 = *va_arg(ap, sqlite3_pcache_methods2*);
  117621. break;
  117622. }
  117623. case SQLITE_CONFIG_GETPCACHE2: {
  117624. if( sqlite3GlobalConfig.pcache2.xInit==0 ){
  117625. sqlite3PCacheSetDefault();
  117626. }
  117627. *va_arg(ap, sqlite3_pcache_methods2*) = sqlite3GlobalConfig.pcache2;
  117628. break;
  117629. }
  117630. #if defined(SQLITE_ENABLE_MEMSYS3) || defined(SQLITE_ENABLE_MEMSYS5)
  117631. case SQLITE_CONFIG_HEAP: {
  117632. /* Designate a buffer for heap memory space */
  117633. sqlite3GlobalConfig.pHeap = va_arg(ap, void*);
  117634. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  117635. sqlite3GlobalConfig.mnReq = va_arg(ap, int);
  117636. if( sqlite3GlobalConfig.mnReq<1 ){
  117637. sqlite3GlobalConfig.mnReq = 1;
  117638. }else if( sqlite3GlobalConfig.mnReq>(1<<12) ){
  117639. /* cap min request size at 2^12 */
  117640. sqlite3GlobalConfig.mnReq = (1<<12);
  117641. }
  117642. if( sqlite3GlobalConfig.pHeap==0 ){
  117643. /* If the heap pointer is NULL, then restore the malloc implementation
  117644. ** back to NULL pointers too. This will cause the malloc to go
  117645. ** back to its default implementation when sqlite3_initialize() is
  117646. ** run.
  117647. */
  117648. memset(&sqlite3GlobalConfig.m, 0, sizeof(sqlite3GlobalConfig.m));
  117649. }else{
  117650. /* The heap pointer is not NULL, then install one of the
  117651. ** mem5.c/mem3.c methods. The enclosing #if guarantees at
  117652. ** least one of these methods is currently enabled.
  117653. */
  117654. #ifdef SQLITE_ENABLE_MEMSYS3
  117655. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys3();
  117656. #endif
  117657. #ifdef SQLITE_ENABLE_MEMSYS5
  117658. sqlite3GlobalConfig.m = *sqlite3MemGetMemsys5();
  117659. #endif
  117660. }
  117661. break;
  117662. }
  117663. #endif
  117664. case SQLITE_CONFIG_LOOKASIDE: {
  117665. sqlite3GlobalConfig.szLookaside = va_arg(ap, int);
  117666. sqlite3GlobalConfig.nLookaside = va_arg(ap, int);
  117667. break;
  117668. }
  117669. /* Record a pointer to the logger function and its first argument.
  117670. ** The default is NULL. Logging is disabled if the function pointer is
  117671. ** NULL.
  117672. */
  117673. case SQLITE_CONFIG_LOG: {
  117674. /* MSVC is picky about pulling func ptrs from va lists.
  117675. ** http://support.microsoft.com/kb/47961
  117676. ** sqlite3GlobalConfig.xLog = va_arg(ap, void(*)(void*,int,const char*));
  117677. */
  117678. typedef void(*LOGFUNC_t)(void*,int,const char*);
  117679. sqlite3GlobalConfig.xLog = va_arg(ap, LOGFUNC_t);
  117680. sqlite3GlobalConfig.pLogArg = va_arg(ap, void*);
  117681. break;
  117682. }
  117683. /* EVIDENCE-OF: R-55548-33817 The compile-time setting for URI filenames
  117684. ** can be changed at start-time using the
  117685. ** sqlite3_config(SQLITE_CONFIG_URI,1) or
  117686. ** sqlite3_config(SQLITE_CONFIG_URI,0) configuration calls.
  117687. */
  117688. case SQLITE_CONFIG_URI: {
  117689. sqlite3GlobalConfig.bOpenUri = va_arg(ap, int);
  117690. break;
  117691. }
  117692. case SQLITE_CONFIG_COVERING_INDEX_SCAN: {
  117693. sqlite3GlobalConfig.bUseCis = va_arg(ap, int);
  117694. break;
  117695. }
  117696. #ifdef SQLITE_ENABLE_SQLLOG
  117697. case SQLITE_CONFIG_SQLLOG: {
  117698. typedef void(*SQLLOGFUNC_t)(void*, sqlite3*, const char*, int);
  117699. sqlite3GlobalConfig.xSqllog = va_arg(ap, SQLLOGFUNC_t);
  117700. sqlite3GlobalConfig.pSqllogArg = va_arg(ap, void *);
  117701. break;
  117702. }
  117703. #endif
  117704. case SQLITE_CONFIG_MMAP_SIZE: {
  117705. sqlite3_int64 szMmap = va_arg(ap, sqlite3_int64);
  117706. sqlite3_int64 mxMmap = va_arg(ap, sqlite3_int64);
  117707. if( mxMmap<0 || mxMmap>SQLITE_MAX_MMAP_SIZE ){
  117708. mxMmap = SQLITE_MAX_MMAP_SIZE;
  117709. }
  117710. sqlite3GlobalConfig.mxMmap = mxMmap;
  117711. if( szMmap<0 ) szMmap = SQLITE_DEFAULT_MMAP_SIZE;
  117712. if( szMmap>mxMmap) szMmap = mxMmap;
  117713. sqlite3GlobalConfig.szMmap = szMmap;
  117714. break;
  117715. }
  117716. #if SQLITE_OS_WIN && defined(SQLITE_WIN32_MALLOC)
  117717. case SQLITE_CONFIG_WIN32_HEAPSIZE: {
  117718. sqlite3GlobalConfig.nHeap = va_arg(ap, int);
  117719. break;
  117720. }
  117721. #endif
  117722. default: {
  117723. rc = SQLITE_ERROR;
  117724. break;
  117725. }
  117726. }
  117727. va_end(ap);
  117728. return rc;
  117729. }
  117730. /*
  117731. ** Set up the lookaside buffers for a database connection.
  117732. ** Return SQLITE_OK on success.
  117733. ** If lookaside is already active, return SQLITE_BUSY.
  117734. **
  117735. ** The sz parameter is the number of bytes in each lookaside slot.
  117736. ** The cnt parameter is the number of slots. If pStart is NULL the
  117737. ** space for the lookaside memory is obtained from sqlite3_malloc().
  117738. ** If pStart is not NULL then it is sz*cnt bytes of memory to use for
  117739. ** the lookaside memory.
  117740. */
  117741. static int setupLookaside(sqlite3 *db, void *pBuf, int sz, int cnt){
  117742. void *pStart;
  117743. if( db->lookaside.nOut ){
  117744. return SQLITE_BUSY;
  117745. }
  117746. /* Free any existing lookaside buffer for this handle before
  117747. ** allocating a new one so we don't have to have space for
  117748. ** both at the same time.
  117749. */
  117750. if( db->lookaside.bMalloced ){
  117751. sqlite3_free(db->lookaside.pStart);
  117752. }
  117753. /* The size of a lookaside slot after ROUNDDOWN8 needs to be larger
  117754. ** than a pointer to be useful.
  117755. */
  117756. sz = ROUNDDOWN8(sz); /* IMP: R-33038-09382 */
  117757. if( sz<=(int)sizeof(LookasideSlot*) ) sz = 0;
  117758. if( cnt<0 ) cnt = 0;
  117759. if( sz==0 || cnt==0 ){
  117760. sz = 0;
  117761. pStart = 0;
  117762. }else if( pBuf==0 ){
  117763. sqlite3BeginBenignMalloc();
  117764. pStart = sqlite3Malloc( sz*cnt ); /* IMP: R-61949-35727 */
  117765. sqlite3EndBenignMalloc();
  117766. if( pStart ) cnt = sqlite3MallocSize(pStart)/sz;
  117767. }else{
  117768. pStart = pBuf;
  117769. }
  117770. db->lookaside.pStart = pStart;
  117771. db->lookaside.pFree = 0;
  117772. db->lookaside.sz = (u16)sz;
  117773. if( pStart ){
  117774. int i;
  117775. LookasideSlot *p;
  117776. assert( sz > (int)sizeof(LookasideSlot*) );
  117777. p = (LookasideSlot*)pStart;
  117778. for(i=cnt-1; i>=0; i--){
  117779. p->pNext = db->lookaside.pFree;
  117780. db->lookaside.pFree = p;
  117781. p = (LookasideSlot*)&((u8*)p)[sz];
  117782. }
  117783. db->lookaside.pEnd = p;
  117784. db->lookaside.bEnabled = 1;
  117785. db->lookaside.bMalloced = pBuf==0 ?1:0;
  117786. }else{
  117787. db->lookaside.pStart = db;
  117788. db->lookaside.pEnd = db;
  117789. db->lookaside.bEnabled = 0;
  117790. db->lookaside.bMalloced = 0;
  117791. }
  117792. return SQLITE_OK;
  117793. }
  117794. /*
  117795. ** Return the mutex associated with a database connection.
  117796. */
  117797. SQLITE_API sqlite3_mutex *sqlite3_db_mutex(sqlite3 *db){
  117798. return db->mutex;
  117799. }
  117800. /*
  117801. ** Free up as much memory as we can from the given database
  117802. ** connection.
  117803. */
  117804. SQLITE_API int sqlite3_db_release_memory(sqlite3 *db){
  117805. int i;
  117806. sqlite3_mutex_enter(db->mutex);
  117807. sqlite3BtreeEnterAll(db);
  117808. for(i=0; i<db->nDb; i++){
  117809. Btree *pBt = db->aDb[i].pBt;
  117810. if( pBt ){
  117811. Pager *pPager = sqlite3BtreePager(pBt);
  117812. sqlite3PagerShrink(pPager);
  117813. }
  117814. }
  117815. sqlite3BtreeLeaveAll(db);
  117816. sqlite3_mutex_leave(db->mutex);
  117817. return SQLITE_OK;
  117818. }
  117819. /*
  117820. ** Configuration settings for an individual database connection
  117821. */
  117822. SQLITE_API int sqlite3_db_config(sqlite3 *db, int op, ...){
  117823. va_list ap;
  117824. int rc;
  117825. va_start(ap, op);
  117826. switch( op ){
  117827. case SQLITE_DBCONFIG_LOOKASIDE: {
  117828. void *pBuf = va_arg(ap, void*); /* IMP: R-26835-10964 */
  117829. int sz = va_arg(ap, int); /* IMP: R-47871-25994 */
  117830. int cnt = va_arg(ap, int); /* IMP: R-04460-53386 */
  117831. rc = setupLookaside(db, pBuf, sz, cnt);
  117832. break;
  117833. }
  117834. default: {
  117835. static const struct {
  117836. int op; /* The opcode */
  117837. u32 mask; /* Mask of the bit in sqlite3.flags to set/clear */
  117838. } aFlagOp[] = {
  117839. { SQLITE_DBCONFIG_ENABLE_FKEY, SQLITE_ForeignKeys },
  117840. { SQLITE_DBCONFIG_ENABLE_TRIGGER, SQLITE_EnableTrigger },
  117841. };
  117842. unsigned int i;
  117843. rc = SQLITE_ERROR; /* IMP: R-42790-23372 */
  117844. for(i=0; i<ArraySize(aFlagOp); i++){
  117845. if( aFlagOp[i].op==op ){
  117846. int onoff = va_arg(ap, int);
  117847. int *pRes = va_arg(ap, int*);
  117848. int oldFlags = db->flags;
  117849. if( onoff>0 ){
  117850. db->flags |= aFlagOp[i].mask;
  117851. }else if( onoff==0 ){
  117852. db->flags &= ~aFlagOp[i].mask;
  117853. }
  117854. if( oldFlags!=db->flags ){
  117855. sqlite3ExpirePreparedStatements(db);
  117856. }
  117857. if( pRes ){
  117858. *pRes = (db->flags & aFlagOp[i].mask)!=0;
  117859. }
  117860. rc = SQLITE_OK;
  117861. break;
  117862. }
  117863. }
  117864. break;
  117865. }
  117866. }
  117867. va_end(ap);
  117868. return rc;
  117869. }
  117870. /*
  117871. ** Return true if the buffer z[0..n-1] contains all spaces.
  117872. */
  117873. static int allSpaces(const char *z, int n){
  117874. while( n>0 && z[n-1]==' ' ){ n--; }
  117875. return n==0;
  117876. }
  117877. /*
  117878. ** This is the default collating function named "BINARY" which is always
  117879. ** available.
  117880. **
  117881. ** If the padFlag argument is not NULL then space padding at the end
  117882. ** of strings is ignored. This implements the RTRIM collation.
  117883. */
  117884. static int binCollFunc(
  117885. void *padFlag,
  117886. int nKey1, const void *pKey1,
  117887. int nKey2, const void *pKey2
  117888. ){
  117889. int rc, n;
  117890. n = nKey1<nKey2 ? nKey1 : nKey2;
  117891. rc = memcmp(pKey1, pKey2, n);
  117892. if( rc==0 ){
  117893. if( padFlag
  117894. && allSpaces(((char*)pKey1)+n, nKey1-n)
  117895. && allSpaces(((char*)pKey2)+n, nKey2-n)
  117896. ){
  117897. /* Leave rc unchanged at 0 */
  117898. }else{
  117899. rc = nKey1 - nKey2;
  117900. }
  117901. }
  117902. return rc;
  117903. }
  117904. /*
  117905. ** Another built-in collating sequence: NOCASE.
  117906. **
  117907. ** This collating sequence is intended to be used for "case independent
  117908. ** comparison". SQLite's knowledge of upper and lower case equivalents
  117909. ** extends only to the 26 characters used in the English language.
  117910. **
  117911. ** At the moment there is only a UTF-8 implementation.
  117912. */
  117913. static int nocaseCollatingFunc(
  117914. void *NotUsed,
  117915. int nKey1, const void *pKey1,
  117916. int nKey2, const void *pKey2
  117917. ){
  117918. int r = sqlite3StrNICmp(
  117919. (const char *)pKey1, (const char *)pKey2, (nKey1<nKey2)?nKey1:nKey2);
  117920. UNUSED_PARAMETER(NotUsed);
  117921. if( 0==r ){
  117922. r = nKey1-nKey2;
  117923. }
  117924. return r;
  117925. }
  117926. /*
  117927. ** Return the ROWID of the most recent insert
  117928. */
  117929. SQLITE_API sqlite_int64 sqlite3_last_insert_rowid(sqlite3 *db){
  117930. return db->lastRowid;
  117931. }
  117932. /*
  117933. ** Return the number of changes in the most recent call to sqlite3_exec().
  117934. */
  117935. SQLITE_API int sqlite3_changes(sqlite3 *db){
  117936. return db->nChange;
  117937. }
  117938. /*
  117939. ** Return the number of changes since the database handle was opened.
  117940. */
  117941. SQLITE_API int sqlite3_total_changes(sqlite3 *db){
  117942. return db->nTotalChange;
  117943. }
  117944. /*
  117945. ** Close all open savepoints. This function only manipulates fields of the
  117946. ** database handle object, it does not close any savepoints that may be open
  117947. ** at the b-tree/pager level.
  117948. */
  117949. SQLITE_PRIVATE void sqlite3CloseSavepoints(sqlite3 *db){
  117950. while( db->pSavepoint ){
  117951. Savepoint *pTmp = db->pSavepoint;
  117952. db->pSavepoint = pTmp->pNext;
  117953. sqlite3DbFree(db, pTmp);
  117954. }
  117955. db->nSavepoint = 0;
  117956. db->nStatement = 0;
  117957. db->isTransactionSavepoint = 0;
  117958. }
  117959. /*
  117960. ** Invoke the destructor function associated with FuncDef p, if any. Except,
  117961. ** if this is not the last copy of the function, do not invoke it. Multiple
  117962. ** copies of a single function are created when create_function() is called
  117963. ** with SQLITE_ANY as the encoding.
  117964. */
  117965. static void functionDestroy(sqlite3 *db, FuncDef *p){
  117966. FuncDestructor *pDestructor = p->pDestructor;
  117967. if( pDestructor ){
  117968. pDestructor->nRef--;
  117969. if( pDestructor->nRef==0 ){
  117970. pDestructor->xDestroy(pDestructor->pUserData);
  117971. sqlite3DbFree(db, pDestructor);
  117972. }
  117973. }
  117974. }
  117975. /*
  117976. ** Disconnect all sqlite3_vtab objects that belong to database connection
  117977. ** db. This is called when db is being closed.
  117978. */
  117979. static void disconnectAllVtab(sqlite3 *db){
  117980. #ifndef SQLITE_OMIT_VIRTUALTABLE
  117981. int i;
  117982. sqlite3BtreeEnterAll(db);
  117983. for(i=0; i<db->nDb; i++){
  117984. Schema *pSchema = db->aDb[i].pSchema;
  117985. if( db->aDb[i].pSchema ){
  117986. HashElem *p;
  117987. for(p=sqliteHashFirst(&pSchema->tblHash); p; p=sqliteHashNext(p)){
  117988. Table *pTab = (Table *)sqliteHashData(p);
  117989. if( IsVirtual(pTab) ) sqlite3VtabDisconnect(db, pTab);
  117990. }
  117991. }
  117992. }
  117993. sqlite3VtabUnlockList(db);
  117994. sqlite3BtreeLeaveAll(db);
  117995. #else
  117996. UNUSED_PARAMETER(db);
  117997. #endif
  117998. }
  117999. /*
  118000. ** Return TRUE if database connection db has unfinalized prepared
  118001. ** statements or unfinished sqlite3_backup objects.
  118002. */
  118003. static int connectionIsBusy(sqlite3 *db){
  118004. int j;
  118005. assert( sqlite3_mutex_held(db->mutex) );
  118006. if( db->pVdbe ) return 1;
  118007. for(j=0; j<db->nDb; j++){
  118008. Btree *pBt = db->aDb[j].pBt;
  118009. if( pBt && sqlite3BtreeIsInBackup(pBt) ) return 1;
  118010. }
  118011. return 0;
  118012. }
  118013. /*
  118014. ** Close an existing SQLite database
  118015. */
  118016. static int sqlite3Close(sqlite3 *db, int forceZombie){
  118017. if( !db ){
  118018. /* EVIDENCE-OF: R-63257-11740 Calling sqlite3_close() or
  118019. ** sqlite3_close_v2() with a NULL pointer argument is a harmless no-op. */
  118020. return SQLITE_OK;
  118021. }
  118022. if( !sqlite3SafetyCheckSickOrOk(db) ){
  118023. return SQLITE_MISUSE_BKPT;
  118024. }
  118025. sqlite3_mutex_enter(db->mutex);
  118026. /* Force xDisconnect calls on all virtual tables */
  118027. disconnectAllVtab(db);
  118028. /* If a transaction is open, the disconnectAllVtab() call above
  118029. ** will not have called the xDisconnect() method on any virtual
  118030. ** tables in the db->aVTrans[] array. The following sqlite3VtabRollback()
  118031. ** call will do so. We need to do this before the check for active
  118032. ** SQL statements below, as the v-table implementation may be storing
  118033. ** some prepared statements internally.
  118034. */
  118035. sqlite3VtabRollback(db);
  118036. /* Legacy behavior (sqlite3_close() behavior) is to return
  118037. ** SQLITE_BUSY if the connection can not be closed immediately.
  118038. */
  118039. if( !forceZombie && connectionIsBusy(db) ){
  118040. sqlite3ErrorWithMsg(db, SQLITE_BUSY, "unable to close due to unfinalized "
  118041. "statements or unfinished backups");
  118042. sqlite3_mutex_leave(db->mutex);
  118043. return SQLITE_BUSY;
  118044. }
  118045. #ifdef SQLITE_ENABLE_SQLLOG
  118046. if( sqlite3GlobalConfig.xSqllog ){
  118047. /* Closing the handle. Fourth parameter is passed the value 2. */
  118048. sqlite3GlobalConfig.xSqllog(sqlite3GlobalConfig.pSqllogArg, db, 0, 2);
  118049. }
  118050. #endif
  118051. /* Convert the connection into a zombie and then close it.
  118052. */
  118053. db->magic = SQLITE_MAGIC_ZOMBIE;
  118054. sqlite3LeaveMutexAndCloseZombie(db);
  118055. return SQLITE_OK;
  118056. }
  118057. /*
  118058. ** Two variations on the public interface for closing a database
  118059. ** connection. The sqlite3_close() version returns SQLITE_BUSY and
  118060. ** leaves the connection option if there are unfinalized prepared
  118061. ** statements or unfinished sqlite3_backups. The sqlite3_close_v2()
  118062. ** version forces the connection to become a zombie if there are
  118063. ** unclosed resources, and arranges for deallocation when the last
  118064. ** prepare statement or sqlite3_backup closes.
  118065. */
  118066. SQLITE_API int sqlite3_close(sqlite3 *db){ return sqlite3Close(db,0); }
  118067. SQLITE_API int sqlite3_close_v2(sqlite3 *db){ return sqlite3Close(db,1); }
  118068. /*
  118069. ** Close the mutex on database connection db.
  118070. **
  118071. ** Furthermore, if database connection db is a zombie (meaning that there
  118072. ** has been a prior call to sqlite3_close(db) or sqlite3_close_v2(db)) and
  118073. ** every sqlite3_stmt has now been finalized and every sqlite3_backup has
  118074. ** finished, then free all resources.
  118075. */
  118076. SQLITE_PRIVATE void sqlite3LeaveMutexAndCloseZombie(sqlite3 *db){
  118077. HashElem *i; /* Hash table iterator */
  118078. int j;
  118079. /* If there are outstanding sqlite3_stmt or sqlite3_backup objects
  118080. ** or if the connection has not yet been closed by sqlite3_close_v2(),
  118081. ** then just leave the mutex and return.
  118082. */
  118083. if( db->magic!=SQLITE_MAGIC_ZOMBIE || connectionIsBusy(db) ){
  118084. sqlite3_mutex_leave(db->mutex);
  118085. return;
  118086. }
  118087. /* If we reach this point, it means that the database connection has
  118088. ** closed all sqlite3_stmt and sqlite3_backup objects and has been
  118089. ** passed to sqlite3_close (meaning that it is a zombie). Therefore,
  118090. ** go ahead and free all resources.
  118091. */
  118092. /* If a transaction is open, roll it back. This also ensures that if
  118093. ** any database schemas have been modified by an uncommitted transaction
  118094. ** they are reset. And that the required b-tree mutex is held to make
  118095. ** the pager rollback and schema reset an atomic operation. */
  118096. sqlite3RollbackAll(db, SQLITE_OK);
  118097. /* Free any outstanding Savepoint structures. */
  118098. sqlite3CloseSavepoints(db);
  118099. /* Close all database connections */
  118100. for(j=0; j<db->nDb; j++){
  118101. struct Db *pDb = &db->aDb[j];
  118102. if( pDb->pBt ){
  118103. if( pDb->pSchema ){
  118104. /* Must clear the KeyInfo cache. See ticket [e4a18565a36884b00edf] */
  118105. sqlite3BtreeEnter(pDb->pBt);
  118106. for(i=sqliteHashFirst(&pDb->pSchema->idxHash); i; i=sqliteHashNext(i)){
  118107. Index *pIdx = sqliteHashData(i);
  118108. sqlite3KeyInfoUnref(pIdx->pKeyInfo);
  118109. pIdx->pKeyInfo = 0;
  118110. }
  118111. sqlite3BtreeLeave(pDb->pBt);
  118112. }
  118113. sqlite3BtreeClose(pDb->pBt);
  118114. pDb->pBt = 0;
  118115. if( j!=1 ){
  118116. pDb->pSchema = 0;
  118117. }
  118118. }
  118119. }
  118120. /* Clear the TEMP schema separately and last */
  118121. if( db->aDb[1].pSchema ){
  118122. sqlite3SchemaClear(db->aDb[1].pSchema);
  118123. }
  118124. sqlite3VtabUnlockList(db);
  118125. /* Free up the array of auxiliary databases */
  118126. sqlite3CollapseDatabaseArray(db);
  118127. assert( db->nDb<=2 );
  118128. assert( db->aDb==db->aDbStatic );
  118129. /* Tell the code in notify.c that the connection no longer holds any
  118130. ** locks and does not require any further unlock-notify callbacks.
  118131. */
  118132. sqlite3ConnectionClosed(db);
  118133. for(j=0; j<ArraySize(db->aFunc.a); j++){
  118134. FuncDef *pNext, *pHash, *p;
  118135. for(p=db->aFunc.a[j]; p; p=pHash){
  118136. pHash = p->pHash;
  118137. while( p ){
  118138. functionDestroy(db, p);
  118139. pNext = p->pNext;
  118140. sqlite3DbFree(db, p);
  118141. p = pNext;
  118142. }
  118143. }
  118144. }
  118145. for(i=sqliteHashFirst(&db->aCollSeq); i; i=sqliteHashNext(i)){
  118146. CollSeq *pColl = (CollSeq *)sqliteHashData(i);
  118147. /* Invoke any destructors registered for collation sequence user data. */
  118148. for(j=0; j<3; j++){
  118149. if( pColl[j].xDel ){
  118150. pColl[j].xDel(pColl[j].pUser);
  118151. }
  118152. }
  118153. sqlite3DbFree(db, pColl);
  118154. }
  118155. sqlite3HashClear(&db->aCollSeq);
  118156. #ifndef SQLITE_OMIT_VIRTUALTABLE
  118157. for(i=sqliteHashFirst(&db->aModule); i; i=sqliteHashNext(i)){
  118158. Module *pMod = (Module *)sqliteHashData(i);
  118159. if( pMod->xDestroy ){
  118160. pMod->xDestroy(pMod->pAux);
  118161. }
  118162. sqlite3DbFree(db, pMod);
  118163. }
  118164. sqlite3HashClear(&db->aModule);
  118165. #endif
  118166. sqlite3Error(db, SQLITE_OK); /* Deallocates any cached error strings. */
  118167. sqlite3ValueFree(db->pErr);
  118168. sqlite3CloseExtensions(db);
  118169. #if SQLITE_USER_AUTHENTICATION
  118170. sqlite3_free(db->auth.zAuthUser);
  118171. sqlite3_free(db->auth.zAuthPW);
  118172. #endif
  118173. db->magic = SQLITE_MAGIC_ERROR;
  118174. /* The temp-database schema is allocated differently from the other schema
  118175. ** objects (using sqliteMalloc() directly, instead of sqlite3BtreeSchema()).
  118176. ** So it needs to be freed here. Todo: Why not roll the temp schema into
  118177. ** the same sqliteMalloc() as the one that allocates the database
  118178. ** structure?
  118179. */
  118180. sqlite3DbFree(db, db->aDb[1].pSchema);
  118181. sqlite3_mutex_leave(db->mutex);
  118182. db->magic = SQLITE_MAGIC_CLOSED;
  118183. sqlite3_mutex_free(db->mutex);
  118184. assert( db->lookaside.nOut==0 ); /* Fails on a lookaside memory leak */
  118185. if( db->lookaside.bMalloced ){
  118186. sqlite3_free(db->lookaside.pStart);
  118187. }
  118188. sqlite3_free(db);
  118189. }
  118190. /*
  118191. ** Rollback all database files. If tripCode is not SQLITE_OK, then
  118192. ** any write cursors are invalidated ("tripped" - as in "tripping a circuit
  118193. ** breaker") and made to return tripCode if there are any further
  118194. ** attempts to use that cursor. Read cursors remain open and valid
  118195. ** but are "saved" in case the table pages are moved around.
  118196. */
  118197. SQLITE_PRIVATE void sqlite3RollbackAll(sqlite3 *db, int tripCode){
  118198. int i;
  118199. int inTrans = 0;
  118200. int schemaChange;
  118201. assert( sqlite3_mutex_held(db->mutex) );
  118202. sqlite3BeginBenignMalloc();
  118203. /* Obtain all b-tree mutexes before making any calls to BtreeRollback().
  118204. ** This is important in case the transaction being rolled back has
  118205. ** modified the database schema. If the b-tree mutexes are not taken
  118206. ** here, then another shared-cache connection might sneak in between
  118207. ** the database rollback and schema reset, which can cause false
  118208. ** corruption reports in some cases. */
  118209. sqlite3BtreeEnterAll(db);
  118210. schemaChange = (db->flags & SQLITE_InternChanges)!=0 && db->init.busy==0;
  118211. for(i=0; i<db->nDb; i++){
  118212. Btree *p = db->aDb[i].pBt;
  118213. if( p ){
  118214. if( sqlite3BtreeIsInTrans(p) ){
  118215. inTrans = 1;
  118216. }
  118217. sqlite3BtreeRollback(p, tripCode, !schemaChange);
  118218. }
  118219. }
  118220. sqlite3VtabRollback(db);
  118221. sqlite3EndBenignMalloc();
  118222. if( (db->flags&SQLITE_InternChanges)!=0 && db->init.busy==0 ){
  118223. sqlite3ExpirePreparedStatements(db);
  118224. sqlite3ResetAllSchemasOfConnection(db);
  118225. }
  118226. sqlite3BtreeLeaveAll(db);
  118227. /* Any deferred constraint violations have now been resolved. */
  118228. db->nDeferredCons = 0;
  118229. db->nDeferredImmCons = 0;
  118230. db->flags &= ~SQLITE_DeferFKs;
  118231. /* If one has been configured, invoke the rollback-hook callback */
  118232. if( db->xRollbackCallback && (inTrans || !db->autoCommit) ){
  118233. db->xRollbackCallback(db->pRollbackArg);
  118234. }
  118235. }
  118236. /*
  118237. ** Return a static string containing the name corresponding to the error code
  118238. ** specified in the argument.
  118239. */
  118240. #if (defined(SQLITE_DEBUG) && SQLITE_OS_WIN) || defined(SQLITE_TEST)
  118241. SQLITE_PRIVATE const char *sqlite3ErrName(int rc){
  118242. const char *zName = 0;
  118243. int i, origRc = rc;
  118244. for(i=0; i<2 && zName==0; i++, rc &= 0xff){
  118245. switch( rc ){
  118246. case SQLITE_OK: zName = "SQLITE_OK"; break;
  118247. case SQLITE_ERROR: zName = "SQLITE_ERROR"; break;
  118248. case SQLITE_INTERNAL: zName = "SQLITE_INTERNAL"; break;
  118249. case SQLITE_PERM: zName = "SQLITE_PERM"; break;
  118250. case SQLITE_ABORT: zName = "SQLITE_ABORT"; break;
  118251. case SQLITE_ABORT_ROLLBACK: zName = "SQLITE_ABORT_ROLLBACK"; break;
  118252. case SQLITE_BUSY: zName = "SQLITE_BUSY"; break;
  118253. case SQLITE_BUSY_RECOVERY: zName = "SQLITE_BUSY_RECOVERY"; break;
  118254. case SQLITE_BUSY_SNAPSHOT: zName = "SQLITE_BUSY_SNAPSHOT"; break;
  118255. case SQLITE_LOCKED: zName = "SQLITE_LOCKED"; break;
  118256. case SQLITE_LOCKED_SHAREDCACHE: zName = "SQLITE_LOCKED_SHAREDCACHE";break;
  118257. case SQLITE_NOMEM: zName = "SQLITE_NOMEM"; break;
  118258. case SQLITE_READONLY: zName = "SQLITE_READONLY"; break;
  118259. case SQLITE_READONLY_RECOVERY: zName = "SQLITE_READONLY_RECOVERY"; break;
  118260. case SQLITE_READONLY_CANTLOCK: zName = "SQLITE_READONLY_CANTLOCK"; break;
  118261. case SQLITE_READONLY_ROLLBACK: zName = "SQLITE_READONLY_ROLLBACK"; break;
  118262. case SQLITE_READONLY_DBMOVED: zName = "SQLITE_READONLY_DBMOVED"; break;
  118263. case SQLITE_INTERRUPT: zName = "SQLITE_INTERRUPT"; break;
  118264. case SQLITE_IOERR: zName = "SQLITE_IOERR"; break;
  118265. case SQLITE_IOERR_READ: zName = "SQLITE_IOERR_READ"; break;
  118266. case SQLITE_IOERR_SHORT_READ: zName = "SQLITE_IOERR_SHORT_READ"; break;
  118267. case SQLITE_IOERR_WRITE: zName = "SQLITE_IOERR_WRITE"; break;
  118268. case SQLITE_IOERR_FSYNC: zName = "SQLITE_IOERR_FSYNC"; break;
  118269. case SQLITE_IOERR_DIR_FSYNC: zName = "SQLITE_IOERR_DIR_FSYNC"; break;
  118270. case SQLITE_IOERR_TRUNCATE: zName = "SQLITE_IOERR_TRUNCATE"; break;
  118271. case SQLITE_IOERR_FSTAT: zName = "SQLITE_IOERR_FSTAT"; break;
  118272. case SQLITE_IOERR_UNLOCK: zName = "SQLITE_IOERR_UNLOCK"; break;
  118273. case SQLITE_IOERR_RDLOCK: zName = "SQLITE_IOERR_RDLOCK"; break;
  118274. case SQLITE_IOERR_DELETE: zName = "SQLITE_IOERR_DELETE"; break;
  118275. case SQLITE_IOERR_NOMEM: zName = "SQLITE_IOERR_NOMEM"; break;
  118276. case SQLITE_IOERR_ACCESS: zName = "SQLITE_IOERR_ACCESS"; break;
  118277. case SQLITE_IOERR_CHECKRESERVEDLOCK:
  118278. zName = "SQLITE_IOERR_CHECKRESERVEDLOCK"; break;
  118279. case SQLITE_IOERR_LOCK: zName = "SQLITE_IOERR_LOCK"; break;
  118280. case SQLITE_IOERR_CLOSE: zName = "SQLITE_IOERR_CLOSE"; break;
  118281. case SQLITE_IOERR_DIR_CLOSE: zName = "SQLITE_IOERR_DIR_CLOSE"; break;
  118282. case SQLITE_IOERR_SHMOPEN: zName = "SQLITE_IOERR_SHMOPEN"; break;
  118283. case SQLITE_IOERR_SHMSIZE: zName = "SQLITE_IOERR_SHMSIZE"; break;
  118284. case SQLITE_IOERR_SHMLOCK: zName = "SQLITE_IOERR_SHMLOCK"; break;
  118285. case SQLITE_IOERR_SHMMAP: zName = "SQLITE_IOERR_SHMMAP"; break;
  118286. case SQLITE_IOERR_SEEK: zName = "SQLITE_IOERR_SEEK"; break;
  118287. case SQLITE_IOERR_DELETE_NOENT: zName = "SQLITE_IOERR_DELETE_NOENT";break;
  118288. case SQLITE_IOERR_MMAP: zName = "SQLITE_IOERR_MMAP"; break;
  118289. case SQLITE_IOERR_GETTEMPPATH: zName = "SQLITE_IOERR_GETTEMPPATH"; break;
  118290. case SQLITE_IOERR_CONVPATH: zName = "SQLITE_IOERR_CONVPATH"; break;
  118291. case SQLITE_CORRUPT: zName = "SQLITE_CORRUPT"; break;
  118292. case SQLITE_CORRUPT_VTAB: zName = "SQLITE_CORRUPT_VTAB"; break;
  118293. case SQLITE_NOTFOUND: zName = "SQLITE_NOTFOUND"; break;
  118294. case SQLITE_FULL: zName = "SQLITE_FULL"; break;
  118295. case SQLITE_CANTOPEN: zName = "SQLITE_CANTOPEN"; break;
  118296. case SQLITE_CANTOPEN_NOTEMPDIR: zName = "SQLITE_CANTOPEN_NOTEMPDIR";break;
  118297. case SQLITE_CANTOPEN_ISDIR: zName = "SQLITE_CANTOPEN_ISDIR"; break;
  118298. case SQLITE_CANTOPEN_FULLPATH: zName = "SQLITE_CANTOPEN_FULLPATH"; break;
  118299. case SQLITE_CANTOPEN_CONVPATH: zName = "SQLITE_CANTOPEN_CONVPATH"; break;
  118300. case SQLITE_PROTOCOL: zName = "SQLITE_PROTOCOL"; break;
  118301. case SQLITE_EMPTY: zName = "SQLITE_EMPTY"; break;
  118302. case SQLITE_SCHEMA: zName = "SQLITE_SCHEMA"; break;
  118303. case SQLITE_TOOBIG: zName = "SQLITE_TOOBIG"; break;
  118304. case SQLITE_CONSTRAINT: zName = "SQLITE_CONSTRAINT"; break;
  118305. case SQLITE_CONSTRAINT_UNIQUE: zName = "SQLITE_CONSTRAINT_UNIQUE"; break;
  118306. case SQLITE_CONSTRAINT_TRIGGER: zName = "SQLITE_CONSTRAINT_TRIGGER";break;
  118307. case SQLITE_CONSTRAINT_FOREIGNKEY:
  118308. zName = "SQLITE_CONSTRAINT_FOREIGNKEY"; break;
  118309. case SQLITE_CONSTRAINT_CHECK: zName = "SQLITE_CONSTRAINT_CHECK"; break;
  118310. case SQLITE_CONSTRAINT_PRIMARYKEY:
  118311. zName = "SQLITE_CONSTRAINT_PRIMARYKEY"; break;
  118312. case SQLITE_CONSTRAINT_NOTNULL: zName = "SQLITE_CONSTRAINT_NOTNULL";break;
  118313. case SQLITE_CONSTRAINT_COMMITHOOK:
  118314. zName = "SQLITE_CONSTRAINT_COMMITHOOK"; break;
  118315. case SQLITE_CONSTRAINT_VTAB: zName = "SQLITE_CONSTRAINT_VTAB"; break;
  118316. case SQLITE_CONSTRAINT_FUNCTION:
  118317. zName = "SQLITE_CONSTRAINT_FUNCTION"; break;
  118318. case SQLITE_CONSTRAINT_ROWID: zName = "SQLITE_CONSTRAINT_ROWID"; break;
  118319. case SQLITE_MISMATCH: zName = "SQLITE_MISMATCH"; break;
  118320. case SQLITE_MISUSE: zName = "SQLITE_MISUSE"; break;
  118321. case SQLITE_NOLFS: zName = "SQLITE_NOLFS"; break;
  118322. case SQLITE_AUTH: zName = "SQLITE_AUTH"; break;
  118323. case SQLITE_FORMAT: zName = "SQLITE_FORMAT"; break;
  118324. case SQLITE_RANGE: zName = "SQLITE_RANGE"; break;
  118325. case SQLITE_NOTADB: zName = "SQLITE_NOTADB"; break;
  118326. case SQLITE_ROW: zName = "SQLITE_ROW"; break;
  118327. case SQLITE_NOTICE: zName = "SQLITE_NOTICE"; break;
  118328. case SQLITE_NOTICE_RECOVER_WAL: zName = "SQLITE_NOTICE_RECOVER_WAL";break;
  118329. case SQLITE_NOTICE_RECOVER_ROLLBACK:
  118330. zName = "SQLITE_NOTICE_RECOVER_ROLLBACK"; break;
  118331. case SQLITE_WARNING: zName = "SQLITE_WARNING"; break;
  118332. case SQLITE_WARNING_AUTOINDEX: zName = "SQLITE_WARNING_AUTOINDEX"; break;
  118333. case SQLITE_DONE: zName = "SQLITE_DONE"; break;
  118334. }
  118335. }
  118336. if( zName==0 ){
  118337. static char zBuf[50];
  118338. sqlite3_snprintf(sizeof(zBuf), zBuf, "SQLITE_UNKNOWN(%d)", origRc);
  118339. zName = zBuf;
  118340. }
  118341. return zName;
  118342. }
  118343. #endif
  118344. /*
  118345. ** Return a static string that describes the kind of error specified in the
  118346. ** argument.
  118347. */
  118348. SQLITE_PRIVATE const char *sqlite3ErrStr(int rc){
  118349. static const char* const aMsg[] = {
  118350. /* SQLITE_OK */ "not an error",
  118351. /* SQLITE_ERROR */ "SQL logic error or missing database",
  118352. /* SQLITE_INTERNAL */ 0,
  118353. /* SQLITE_PERM */ "access permission denied",
  118354. /* SQLITE_ABORT */ "callback requested query abort",
  118355. /* SQLITE_BUSY */ "database is locked",
  118356. /* SQLITE_LOCKED */ "database table is locked",
  118357. /* SQLITE_NOMEM */ "out of memory",
  118358. /* SQLITE_READONLY */ "attempt to write a readonly database",
  118359. /* SQLITE_INTERRUPT */ "interrupted",
  118360. /* SQLITE_IOERR */ "disk I/O error",
  118361. /* SQLITE_CORRUPT */ "database disk image is malformed",
  118362. /* SQLITE_NOTFOUND */ "unknown operation",
  118363. /* SQLITE_FULL */ "database or disk is full",
  118364. /* SQLITE_CANTOPEN */ "unable to open database file",
  118365. /* SQLITE_PROTOCOL */ "locking protocol",
  118366. /* SQLITE_EMPTY */ "table contains no data",
  118367. /* SQLITE_SCHEMA */ "database schema has changed",
  118368. /* SQLITE_TOOBIG */ "string or blob too big",
  118369. /* SQLITE_CONSTRAINT */ "constraint failed",
  118370. /* SQLITE_MISMATCH */ "datatype mismatch",
  118371. /* SQLITE_MISUSE */ "library routine called out of sequence",
  118372. /* SQLITE_NOLFS */ "large file support is disabled",
  118373. /* SQLITE_AUTH */ "authorization denied",
  118374. /* SQLITE_FORMAT */ "auxiliary database format error",
  118375. /* SQLITE_RANGE */ "bind or column index out of range",
  118376. /* SQLITE_NOTADB */ "file is encrypted or is not a database",
  118377. };
  118378. const char *zErr = "unknown error";
  118379. switch( rc ){
  118380. case SQLITE_ABORT_ROLLBACK: {
  118381. zErr = "abort due to ROLLBACK";
  118382. break;
  118383. }
  118384. default: {
  118385. rc &= 0xff;
  118386. if( ALWAYS(rc>=0) && rc<ArraySize(aMsg) && aMsg[rc]!=0 ){
  118387. zErr = aMsg[rc];
  118388. }
  118389. break;
  118390. }
  118391. }
  118392. return zErr;
  118393. }
  118394. /*
  118395. ** This routine implements a busy callback that sleeps and tries
  118396. ** again until a timeout value is reached. The timeout value is
  118397. ** an integer number of milliseconds passed in as the first
  118398. ** argument.
  118399. */
  118400. static int sqliteDefaultBusyCallback(
  118401. void *ptr, /* Database connection */
  118402. int count /* Number of times table has been busy */
  118403. ){
  118404. #if SQLITE_OS_WIN || (defined(HAVE_USLEEP) && HAVE_USLEEP)
  118405. static const u8 delays[] =
  118406. { 1, 2, 5, 10, 15, 20, 25, 25, 25, 50, 50, 100 };
  118407. static const u8 totals[] =
  118408. { 0, 1, 3, 8, 18, 33, 53, 78, 103, 128, 178, 228 };
  118409. # define NDELAY ArraySize(delays)
  118410. sqlite3 *db = (sqlite3 *)ptr;
  118411. int timeout = db->busyTimeout;
  118412. int delay, prior;
  118413. assert( count>=0 );
  118414. if( count < NDELAY ){
  118415. delay = delays[count];
  118416. prior = totals[count];
  118417. }else{
  118418. delay = delays[NDELAY-1];
  118419. prior = totals[NDELAY-1] + delay*(count-(NDELAY-1));
  118420. }
  118421. if( prior + delay > timeout ){
  118422. delay = timeout - prior;
  118423. if( delay<=0 ) return 0;
  118424. }
  118425. sqlite3OsSleep(db->pVfs, delay*1000);
  118426. return 1;
  118427. #else
  118428. sqlite3 *db = (sqlite3 *)ptr;
  118429. int timeout = ((sqlite3 *)ptr)->busyTimeout;
  118430. if( (count+1)*1000 > timeout ){
  118431. return 0;
  118432. }
  118433. sqlite3OsSleep(db->pVfs, 1000000);
  118434. return 1;
  118435. #endif
  118436. }
  118437. /*
  118438. ** Invoke the given busy handler.
  118439. **
  118440. ** This routine is called when an operation failed with a lock.
  118441. ** If this routine returns non-zero, the lock is retried. If it
  118442. ** returns 0, the operation aborts with an SQLITE_BUSY error.
  118443. */
  118444. SQLITE_PRIVATE int sqlite3InvokeBusyHandler(BusyHandler *p){
  118445. int rc;
  118446. if( NEVER(p==0) || p->xFunc==0 || p->nBusy<0 ) return 0;
  118447. rc = p->xFunc(p->pArg, p->nBusy);
  118448. if( rc==0 ){
  118449. p->nBusy = -1;
  118450. }else{
  118451. p->nBusy++;
  118452. }
  118453. return rc;
  118454. }
  118455. /*
  118456. ** This routine sets the busy callback for an Sqlite database to the
  118457. ** given callback function with the given argument.
  118458. */
  118459. SQLITE_API int sqlite3_busy_handler(
  118460. sqlite3 *db,
  118461. int (*xBusy)(void*,int),
  118462. void *pArg
  118463. ){
  118464. sqlite3_mutex_enter(db->mutex);
  118465. db->busyHandler.xFunc = xBusy;
  118466. db->busyHandler.pArg = pArg;
  118467. db->busyHandler.nBusy = 0;
  118468. db->busyTimeout = 0;
  118469. sqlite3_mutex_leave(db->mutex);
  118470. return SQLITE_OK;
  118471. }
  118472. #ifndef SQLITE_OMIT_PROGRESS_CALLBACK
  118473. /*
  118474. ** This routine sets the progress callback for an Sqlite database to the
  118475. ** given callback function with the given argument. The progress callback will
  118476. ** be invoked every nOps opcodes.
  118477. */
  118478. SQLITE_API void sqlite3_progress_handler(
  118479. sqlite3 *db,
  118480. int nOps,
  118481. int (*xProgress)(void*),
  118482. void *pArg
  118483. ){
  118484. sqlite3_mutex_enter(db->mutex);
  118485. if( nOps>0 ){
  118486. db->xProgress = xProgress;
  118487. db->nProgressOps = (unsigned)nOps;
  118488. db->pProgressArg = pArg;
  118489. }else{
  118490. db->xProgress = 0;
  118491. db->nProgressOps = 0;
  118492. db->pProgressArg = 0;
  118493. }
  118494. sqlite3_mutex_leave(db->mutex);
  118495. }
  118496. #endif
  118497. /*
  118498. ** This routine installs a default busy handler that waits for the
  118499. ** specified number of milliseconds before returning 0.
  118500. */
  118501. SQLITE_API int sqlite3_busy_timeout(sqlite3 *db, int ms){
  118502. if( ms>0 ){
  118503. sqlite3_busy_handler(db, sqliteDefaultBusyCallback, (void*)db);
  118504. db->busyTimeout = ms;
  118505. }else{
  118506. sqlite3_busy_handler(db, 0, 0);
  118507. }
  118508. return SQLITE_OK;
  118509. }
  118510. /*
  118511. ** Cause any pending operation to stop at its earliest opportunity.
  118512. */
  118513. SQLITE_API void sqlite3_interrupt(sqlite3 *db){
  118514. db->u1.isInterrupted = 1;
  118515. }
  118516. /*
  118517. ** This function is exactly the same as sqlite3_create_function(), except
  118518. ** that it is designed to be called by internal code. The difference is
  118519. ** that if a malloc() fails in sqlite3_create_function(), an error code
  118520. ** is returned and the mallocFailed flag cleared.
  118521. */
  118522. SQLITE_PRIVATE int sqlite3CreateFunc(
  118523. sqlite3 *db,
  118524. const char *zFunctionName,
  118525. int nArg,
  118526. int enc,
  118527. void *pUserData,
  118528. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  118529. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  118530. void (*xFinal)(sqlite3_context*),
  118531. FuncDestructor *pDestructor
  118532. ){
  118533. FuncDef *p;
  118534. int nName;
  118535. int extraFlags;
  118536. assert( sqlite3_mutex_held(db->mutex) );
  118537. if( zFunctionName==0 ||
  118538. (xFunc && (xFinal || xStep)) ||
  118539. (!xFunc && (xFinal && !xStep)) ||
  118540. (!xFunc && (!xFinal && xStep)) ||
  118541. (nArg<-1 || nArg>SQLITE_MAX_FUNCTION_ARG) ||
  118542. (255<(nName = sqlite3Strlen30( zFunctionName))) ){
  118543. return SQLITE_MISUSE_BKPT;
  118544. }
  118545. assert( SQLITE_FUNC_CONSTANT==SQLITE_DETERMINISTIC );
  118546. extraFlags = enc & SQLITE_DETERMINISTIC;
  118547. enc &= (SQLITE_FUNC_ENCMASK|SQLITE_ANY);
  118548. #ifndef SQLITE_OMIT_UTF16
  118549. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  118550. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  118551. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  118552. **
  118553. ** If SQLITE_ANY is specified, add three versions of the function
  118554. ** to the hash table.
  118555. */
  118556. if( enc==SQLITE_UTF16 ){
  118557. enc = SQLITE_UTF16NATIVE;
  118558. }else if( enc==SQLITE_ANY ){
  118559. int rc;
  118560. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF8|extraFlags,
  118561. pUserData, xFunc, xStep, xFinal, pDestructor);
  118562. if( rc==SQLITE_OK ){
  118563. rc = sqlite3CreateFunc(db, zFunctionName, nArg, SQLITE_UTF16LE|extraFlags,
  118564. pUserData, xFunc, xStep, xFinal, pDestructor);
  118565. }
  118566. if( rc!=SQLITE_OK ){
  118567. return rc;
  118568. }
  118569. enc = SQLITE_UTF16BE;
  118570. }
  118571. #else
  118572. enc = SQLITE_UTF8;
  118573. #endif
  118574. /* Check if an existing function is being overridden or deleted. If so,
  118575. ** and there are active VMs, then return SQLITE_BUSY. If a function
  118576. ** is being overridden/deleted but there are no active VMs, allow the
  118577. ** operation to continue but invalidate all precompiled statements.
  118578. */
  118579. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 0);
  118580. if( p && (p->funcFlags & SQLITE_FUNC_ENCMASK)==enc && p->nArg==nArg ){
  118581. if( db->nVdbeActive ){
  118582. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  118583. "unable to delete/modify user-function due to active statements");
  118584. assert( !db->mallocFailed );
  118585. return SQLITE_BUSY;
  118586. }else{
  118587. sqlite3ExpirePreparedStatements(db);
  118588. }
  118589. }
  118590. p = sqlite3FindFunction(db, zFunctionName, nName, nArg, (u8)enc, 1);
  118591. assert(p || db->mallocFailed);
  118592. if( !p ){
  118593. return SQLITE_NOMEM;
  118594. }
  118595. /* If an older version of the function with a configured destructor is
  118596. ** being replaced invoke the destructor function here. */
  118597. functionDestroy(db, p);
  118598. if( pDestructor ){
  118599. pDestructor->nRef++;
  118600. }
  118601. p->pDestructor = pDestructor;
  118602. p->funcFlags = (p->funcFlags & SQLITE_FUNC_ENCMASK) | extraFlags;
  118603. testcase( p->funcFlags & SQLITE_DETERMINISTIC );
  118604. p->xFunc = xFunc;
  118605. p->xStep = xStep;
  118606. p->xFinalize = xFinal;
  118607. p->pUserData = pUserData;
  118608. p->nArg = (u16)nArg;
  118609. return SQLITE_OK;
  118610. }
  118611. /*
  118612. ** Create new user functions.
  118613. */
  118614. SQLITE_API int sqlite3_create_function(
  118615. sqlite3 *db,
  118616. const char *zFunc,
  118617. int nArg,
  118618. int enc,
  118619. void *p,
  118620. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  118621. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  118622. void (*xFinal)(sqlite3_context*)
  118623. ){
  118624. return sqlite3_create_function_v2(db, zFunc, nArg, enc, p, xFunc, xStep,
  118625. xFinal, 0);
  118626. }
  118627. SQLITE_API int sqlite3_create_function_v2(
  118628. sqlite3 *db,
  118629. const char *zFunc,
  118630. int nArg,
  118631. int enc,
  118632. void *p,
  118633. void (*xFunc)(sqlite3_context*,int,sqlite3_value **),
  118634. void (*xStep)(sqlite3_context*,int,sqlite3_value **),
  118635. void (*xFinal)(sqlite3_context*),
  118636. void (*xDestroy)(void *)
  118637. ){
  118638. int rc = SQLITE_ERROR;
  118639. FuncDestructor *pArg = 0;
  118640. sqlite3_mutex_enter(db->mutex);
  118641. if( xDestroy ){
  118642. pArg = (FuncDestructor *)sqlite3DbMallocZero(db, sizeof(FuncDestructor));
  118643. if( !pArg ){
  118644. xDestroy(p);
  118645. goto out;
  118646. }
  118647. pArg->xDestroy = xDestroy;
  118648. pArg->pUserData = p;
  118649. }
  118650. rc = sqlite3CreateFunc(db, zFunc, nArg, enc, p, xFunc, xStep, xFinal, pArg);
  118651. if( pArg && pArg->nRef==0 ){
  118652. assert( rc!=SQLITE_OK );
  118653. xDestroy(p);
  118654. sqlite3DbFree(db, pArg);
  118655. }
  118656. out:
  118657. rc = sqlite3ApiExit(db, rc);
  118658. sqlite3_mutex_leave(db->mutex);
  118659. return rc;
  118660. }
  118661. #ifndef SQLITE_OMIT_UTF16
  118662. SQLITE_API int sqlite3_create_function16(
  118663. sqlite3 *db,
  118664. const void *zFunctionName,
  118665. int nArg,
  118666. int eTextRep,
  118667. void *p,
  118668. void (*xFunc)(sqlite3_context*,int,sqlite3_value**),
  118669. void (*xStep)(sqlite3_context*,int,sqlite3_value**),
  118670. void (*xFinal)(sqlite3_context*)
  118671. ){
  118672. int rc;
  118673. char *zFunc8;
  118674. sqlite3_mutex_enter(db->mutex);
  118675. assert( !db->mallocFailed );
  118676. zFunc8 = sqlite3Utf16to8(db, zFunctionName, -1, SQLITE_UTF16NATIVE);
  118677. rc = sqlite3CreateFunc(db, zFunc8, nArg, eTextRep, p, xFunc, xStep, xFinal,0);
  118678. sqlite3DbFree(db, zFunc8);
  118679. rc = sqlite3ApiExit(db, rc);
  118680. sqlite3_mutex_leave(db->mutex);
  118681. return rc;
  118682. }
  118683. #endif
  118684. /*
  118685. ** Declare that a function has been overloaded by a virtual table.
  118686. **
  118687. ** If the function already exists as a regular global function, then
  118688. ** this routine is a no-op. If the function does not exist, then create
  118689. ** a new one that always throws a run-time error.
  118690. **
  118691. ** When virtual tables intend to provide an overloaded function, they
  118692. ** should call this routine to make sure the global function exists.
  118693. ** A global function must exist in order for name resolution to work
  118694. ** properly.
  118695. */
  118696. SQLITE_API int sqlite3_overload_function(
  118697. sqlite3 *db,
  118698. const char *zName,
  118699. int nArg
  118700. ){
  118701. int nName = sqlite3Strlen30(zName);
  118702. int rc = SQLITE_OK;
  118703. sqlite3_mutex_enter(db->mutex);
  118704. if( sqlite3FindFunction(db, zName, nName, nArg, SQLITE_UTF8, 0)==0 ){
  118705. rc = sqlite3CreateFunc(db, zName, nArg, SQLITE_UTF8,
  118706. 0, sqlite3InvalidFunction, 0, 0, 0);
  118707. }
  118708. rc = sqlite3ApiExit(db, rc);
  118709. sqlite3_mutex_leave(db->mutex);
  118710. return rc;
  118711. }
  118712. #ifndef SQLITE_OMIT_TRACE
  118713. /*
  118714. ** Register a trace function. The pArg from the previously registered trace
  118715. ** is returned.
  118716. **
  118717. ** A NULL trace function means that no tracing is executes. A non-NULL
  118718. ** trace is a pointer to a function that is invoked at the start of each
  118719. ** SQL statement.
  118720. */
  118721. SQLITE_API void *sqlite3_trace(sqlite3 *db, void (*xTrace)(void*,const char*), void *pArg){
  118722. void *pOld;
  118723. sqlite3_mutex_enter(db->mutex);
  118724. pOld = db->pTraceArg;
  118725. db->xTrace = xTrace;
  118726. db->pTraceArg = pArg;
  118727. sqlite3_mutex_leave(db->mutex);
  118728. return pOld;
  118729. }
  118730. /*
  118731. ** Register a profile function. The pArg from the previously registered
  118732. ** profile function is returned.
  118733. **
  118734. ** A NULL profile function means that no profiling is executes. A non-NULL
  118735. ** profile is a pointer to a function that is invoked at the conclusion of
  118736. ** each SQL statement that is run.
  118737. */
  118738. SQLITE_API void *sqlite3_profile(
  118739. sqlite3 *db,
  118740. void (*xProfile)(void*,const char*,sqlite_uint64),
  118741. void *pArg
  118742. ){
  118743. void *pOld;
  118744. sqlite3_mutex_enter(db->mutex);
  118745. pOld = db->pProfileArg;
  118746. db->xProfile = xProfile;
  118747. db->pProfileArg = pArg;
  118748. sqlite3_mutex_leave(db->mutex);
  118749. return pOld;
  118750. }
  118751. #endif /* SQLITE_OMIT_TRACE */
  118752. /*
  118753. ** Register a function to be invoked when a transaction commits.
  118754. ** If the invoked function returns non-zero, then the commit becomes a
  118755. ** rollback.
  118756. */
  118757. SQLITE_API void *sqlite3_commit_hook(
  118758. sqlite3 *db, /* Attach the hook to this database */
  118759. int (*xCallback)(void*), /* Function to invoke on each commit */
  118760. void *pArg /* Argument to the function */
  118761. ){
  118762. void *pOld;
  118763. sqlite3_mutex_enter(db->mutex);
  118764. pOld = db->pCommitArg;
  118765. db->xCommitCallback = xCallback;
  118766. db->pCommitArg = pArg;
  118767. sqlite3_mutex_leave(db->mutex);
  118768. return pOld;
  118769. }
  118770. /*
  118771. ** Register a callback to be invoked each time a row is updated,
  118772. ** inserted or deleted using this database connection.
  118773. */
  118774. SQLITE_API void *sqlite3_update_hook(
  118775. sqlite3 *db, /* Attach the hook to this database */
  118776. void (*xCallback)(void*,int,char const *,char const *,sqlite_int64),
  118777. void *pArg /* Argument to the function */
  118778. ){
  118779. void *pRet;
  118780. sqlite3_mutex_enter(db->mutex);
  118781. pRet = db->pUpdateArg;
  118782. db->xUpdateCallback = xCallback;
  118783. db->pUpdateArg = pArg;
  118784. sqlite3_mutex_leave(db->mutex);
  118785. return pRet;
  118786. }
  118787. /*
  118788. ** Register a callback to be invoked each time a transaction is rolled
  118789. ** back by this database connection.
  118790. */
  118791. SQLITE_API void *sqlite3_rollback_hook(
  118792. sqlite3 *db, /* Attach the hook to this database */
  118793. void (*xCallback)(void*), /* Callback function */
  118794. void *pArg /* Argument to the function */
  118795. ){
  118796. void *pRet;
  118797. sqlite3_mutex_enter(db->mutex);
  118798. pRet = db->pRollbackArg;
  118799. db->xRollbackCallback = xCallback;
  118800. db->pRollbackArg = pArg;
  118801. sqlite3_mutex_leave(db->mutex);
  118802. return pRet;
  118803. }
  118804. #ifndef SQLITE_OMIT_WAL
  118805. /*
  118806. ** The sqlite3_wal_hook() callback registered by sqlite3_wal_autocheckpoint().
  118807. ** Invoke sqlite3_wal_checkpoint if the number of frames in the log file
  118808. ** is greater than sqlite3.pWalArg cast to an integer (the value configured by
  118809. ** wal_autocheckpoint()).
  118810. */
  118811. SQLITE_PRIVATE int sqlite3WalDefaultHook(
  118812. void *pClientData, /* Argument */
  118813. sqlite3 *db, /* Connection */
  118814. const char *zDb, /* Database */
  118815. int nFrame /* Size of WAL */
  118816. ){
  118817. if( nFrame>=SQLITE_PTR_TO_INT(pClientData) ){
  118818. sqlite3BeginBenignMalloc();
  118819. sqlite3_wal_checkpoint(db, zDb);
  118820. sqlite3EndBenignMalloc();
  118821. }
  118822. return SQLITE_OK;
  118823. }
  118824. #endif /* SQLITE_OMIT_WAL */
  118825. /*
  118826. ** Configure an sqlite3_wal_hook() callback to automatically checkpoint
  118827. ** a database after committing a transaction if there are nFrame or
  118828. ** more frames in the log file. Passing zero or a negative value as the
  118829. ** nFrame parameter disables automatic checkpoints entirely.
  118830. **
  118831. ** The callback registered by this function replaces any existing callback
  118832. ** registered using sqlite3_wal_hook(). Likewise, registering a callback
  118833. ** using sqlite3_wal_hook() disables the automatic checkpoint mechanism
  118834. ** configured by this function.
  118835. */
  118836. SQLITE_API int sqlite3_wal_autocheckpoint(sqlite3 *db, int nFrame){
  118837. #ifdef SQLITE_OMIT_WAL
  118838. UNUSED_PARAMETER(db);
  118839. UNUSED_PARAMETER(nFrame);
  118840. #else
  118841. if( nFrame>0 ){
  118842. sqlite3_wal_hook(db, sqlite3WalDefaultHook, SQLITE_INT_TO_PTR(nFrame));
  118843. }else{
  118844. sqlite3_wal_hook(db, 0, 0);
  118845. }
  118846. #endif
  118847. return SQLITE_OK;
  118848. }
  118849. /*
  118850. ** Register a callback to be invoked each time a transaction is written
  118851. ** into the write-ahead-log by this database connection.
  118852. */
  118853. SQLITE_API void *sqlite3_wal_hook(
  118854. sqlite3 *db, /* Attach the hook to this db handle */
  118855. int(*xCallback)(void *, sqlite3*, const char*, int),
  118856. void *pArg /* First argument passed to xCallback() */
  118857. ){
  118858. #ifndef SQLITE_OMIT_WAL
  118859. void *pRet;
  118860. sqlite3_mutex_enter(db->mutex);
  118861. pRet = db->pWalArg;
  118862. db->xWalCallback = xCallback;
  118863. db->pWalArg = pArg;
  118864. sqlite3_mutex_leave(db->mutex);
  118865. return pRet;
  118866. #else
  118867. return 0;
  118868. #endif
  118869. }
  118870. /*
  118871. ** Checkpoint database zDb.
  118872. */
  118873. SQLITE_API int sqlite3_wal_checkpoint_v2(
  118874. sqlite3 *db, /* Database handle */
  118875. const char *zDb, /* Name of attached database (or NULL) */
  118876. int eMode, /* SQLITE_CHECKPOINT_* value */
  118877. int *pnLog, /* OUT: Size of WAL log in frames */
  118878. int *pnCkpt /* OUT: Total number of frames checkpointed */
  118879. ){
  118880. #ifdef SQLITE_OMIT_WAL
  118881. return SQLITE_OK;
  118882. #else
  118883. int rc; /* Return code */
  118884. int iDb = SQLITE_MAX_ATTACHED; /* sqlite3.aDb[] index of db to checkpoint */
  118885. /* Initialize the output variables to -1 in case an error occurs. */
  118886. if( pnLog ) *pnLog = -1;
  118887. if( pnCkpt ) *pnCkpt = -1;
  118888. assert( SQLITE_CHECKPOINT_FULL>SQLITE_CHECKPOINT_PASSIVE );
  118889. assert( SQLITE_CHECKPOINT_FULL<SQLITE_CHECKPOINT_RESTART );
  118890. assert( SQLITE_CHECKPOINT_PASSIVE+2==SQLITE_CHECKPOINT_RESTART );
  118891. if( eMode<SQLITE_CHECKPOINT_PASSIVE || eMode>SQLITE_CHECKPOINT_RESTART ){
  118892. return SQLITE_MISUSE;
  118893. }
  118894. sqlite3_mutex_enter(db->mutex);
  118895. if( zDb && zDb[0] ){
  118896. iDb = sqlite3FindDbName(db, zDb);
  118897. }
  118898. if( iDb<0 ){
  118899. rc = SQLITE_ERROR;
  118900. sqlite3ErrorWithMsg(db, SQLITE_ERROR, "unknown database: %s", zDb);
  118901. }else{
  118902. rc = sqlite3Checkpoint(db, iDb, eMode, pnLog, pnCkpt);
  118903. sqlite3Error(db, rc);
  118904. }
  118905. rc = sqlite3ApiExit(db, rc);
  118906. sqlite3_mutex_leave(db->mutex);
  118907. return rc;
  118908. #endif
  118909. }
  118910. /*
  118911. ** Checkpoint database zDb. If zDb is NULL, or if the buffer zDb points
  118912. ** to contains a zero-length string, all attached databases are
  118913. ** checkpointed.
  118914. */
  118915. SQLITE_API int sqlite3_wal_checkpoint(sqlite3 *db, const char *zDb){
  118916. return sqlite3_wal_checkpoint_v2(db, zDb, SQLITE_CHECKPOINT_PASSIVE, 0, 0);
  118917. }
  118918. #ifndef SQLITE_OMIT_WAL
  118919. /*
  118920. ** Run a checkpoint on database iDb. This is a no-op if database iDb is
  118921. ** not currently open in WAL mode.
  118922. **
  118923. ** If a transaction is open on the database being checkpointed, this
  118924. ** function returns SQLITE_LOCKED and a checkpoint is not attempted. If
  118925. ** an error occurs while running the checkpoint, an SQLite error code is
  118926. ** returned (i.e. SQLITE_IOERR). Otherwise, SQLITE_OK.
  118927. **
  118928. ** The mutex on database handle db should be held by the caller. The mutex
  118929. ** associated with the specific b-tree being checkpointed is taken by
  118930. ** this function while the checkpoint is running.
  118931. **
  118932. ** If iDb is passed SQLITE_MAX_ATTACHED, then all attached databases are
  118933. ** checkpointed. If an error is encountered it is returned immediately -
  118934. ** no attempt is made to checkpoint any remaining databases.
  118935. **
  118936. ** Parameter eMode is one of SQLITE_CHECKPOINT_PASSIVE, FULL or RESTART.
  118937. */
  118938. SQLITE_PRIVATE int sqlite3Checkpoint(sqlite3 *db, int iDb, int eMode, int *pnLog, int *pnCkpt){
  118939. int rc = SQLITE_OK; /* Return code */
  118940. int i; /* Used to iterate through attached dbs */
  118941. int bBusy = 0; /* True if SQLITE_BUSY has been encountered */
  118942. assert( sqlite3_mutex_held(db->mutex) );
  118943. assert( !pnLog || *pnLog==-1 );
  118944. assert( !pnCkpt || *pnCkpt==-1 );
  118945. for(i=0; i<db->nDb && rc==SQLITE_OK; i++){
  118946. if( i==iDb || iDb==SQLITE_MAX_ATTACHED ){
  118947. rc = sqlite3BtreeCheckpoint(db->aDb[i].pBt, eMode, pnLog, pnCkpt);
  118948. pnLog = 0;
  118949. pnCkpt = 0;
  118950. if( rc==SQLITE_BUSY ){
  118951. bBusy = 1;
  118952. rc = SQLITE_OK;
  118953. }
  118954. }
  118955. }
  118956. return (rc==SQLITE_OK && bBusy) ? SQLITE_BUSY : rc;
  118957. }
  118958. #endif /* SQLITE_OMIT_WAL */
  118959. /*
  118960. ** This function returns true if main-memory should be used instead of
  118961. ** a temporary file for transient pager files and statement journals.
  118962. ** The value returned depends on the value of db->temp_store (runtime
  118963. ** parameter) and the compile time value of SQLITE_TEMP_STORE. The
  118964. ** following table describes the relationship between these two values
  118965. ** and this functions return value.
  118966. **
  118967. ** SQLITE_TEMP_STORE db->temp_store Location of temporary database
  118968. ** ----------------- -------------- ------------------------------
  118969. ** 0 any file (return 0)
  118970. ** 1 1 file (return 0)
  118971. ** 1 2 memory (return 1)
  118972. ** 1 0 file (return 0)
  118973. ** 2 1 file (return 0)
  118974. ** 2 2 memory (return 1)
  118975. ** 2 0 memory (return 1)
  118976. ** 3 any memory (return 1)
  118977. */
  118978. SQLITE_PRIVATE int sqlite3TempInMemory(const sqlite3 *db){
  118979. #if SQLITE_TEMP_STORE==1
  118980. return ( db->temp_store==2 );
  118981. #endif
  118982. #if SQLITE_TEMP_STORE==2
  118983. return ( db->temp_store!=1 );
  118984. #endif
  118985. #if SQLITE_TEMP_STORE==3
  118986. return 1;
  118987. #endif
  118988. #if SQLITE_TEMP_STORE<1 || SQLITE_TEMP_STORE>3
  118989. return 0;
  118990. #endif
  118991. }
  118992. /*
  118993. ** Return UTF-8 encoded English language explanation of the most recent
  118994. ** error.
  118995. */
  118996. SQLITE_API const char *sqlite3_errmsg(sqlite3 *db){
  118997. const char *z;
  118998. if( !db ){
  118999. return sqlite3ErrStr(SQLITE_NOMEM);
  119000. }
  119001. if( !sqlite3SafetyCheckSickOrOk(db) ){
  119002. return sqlite3ErrStr(SQLITE_MISUSE_BKPT);
  119003. }
  119004. sqlite3_mutex_enter(db->mutex);
  119005. if( db->mallocFailed ){
  119006. z = sqlite3ErrStr(SQLITE_NOMEM);
  119007. }else{
  119008. testcase( db->pErr==0 );
  119009. z = (char*)sqlite3_value_text(db->pErr);
  119010. assert( !db->mallocFailed );
  119011. if( z==0 ){
  119012. z = sqlite3ErrStr(db->errCode);
  119013. }
  119014. }
  119015. sqlite3_mutex_leave(db->mutex);
  119016. return z;
  119017. }
  119018. #ifndef SQLITE_OMIT_UTF16
  119019. /*
  119020. ** Return UTF-16 encoded English language explanation of the most recent
  119021. ** error.
  119022. */
  119023. SQLITE_API const void *sqlite3_errmsg16(sqlite3 *db){
  119024. static const u16 outOfMem[] = {
  119025. 'o', 'u', 't', ' ', 'o', 'f', ' ', 'm', 'e', 'm', 'o', 'r', 'y', 0
  119026. };
  119027. static const u16 misuse[] = {
  119028. 'l', 'i', 'b', 'r', 'a', 'r', 'y', ' ',
  119029. 'r', 'o', 'u', 't', 'i', 'n', 'e', ' ',
  119030. 'c', 'a', 'l', 'l', 'e', 'd', ' ',
  119031. 'o', 'u', 't', ' ',
  119032. 'o', 'f', ' ',
  119033. 's', 'e', 'q', 'u', 'e', 'n', 'c', 'e', 0
  119034. };
  119035. const void *z;
  119036. if( !db ){
  119037. return (void *)outOfMem;
  119038. }
  119039. if( !sqlite3SafetyCheckSickOrOk(db) ){
  119040. return (void *)misuse;
  119041. }
  119042. sqlite3_mutex_enter(db->mutex);
  119043. if( db->mallocFailed ){
  119044. z = (void *)outOfMem;
  119045. }else{
  119046. z = sqlite3_value_text16(db->pErr);
  119047. if( z==0 ){
  119048. sqlite3ErrorWithMsg(db, db->errCode, sqlite3ErrStr(db->errCode));
  119049. z = sqlite3_value_text16(db->pErr);
  119050. }
  119051. /* A malloc() may have failed within the call to sqlite3_value_text16()
  119052. ** above. If this is the case, then the db->mallocFailed flag needs to
  119053. ** be cleared before returning. Do this directly, instead of via
  119054. ** sqlite3ApiExit(), to avoid setting the database handle error message.
  119055. */
  119056. db->mallocFailed = 0;
  119057. }
  119058. sqlite3_mutex_leave(db->mutex);
  119059. return z;
  119060. }
  119061. #endif /* SQLITE_OMIT_UTF16 */
  119062. /*
  119063. ** Return the most recent error code generated by an SQLite routine. If NULL is
  119064. ** passed to this function, we assume a malloc() failed during sqlite3_open().
  119065. */
  119066. SQLITE_API int sqlite3_errcode(sqlite3 *db){
  119067. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  119068. return SQLITE_MISUSE_BKPT;
  119069. }
  119070. if( !db || db->mallocFailed ){
  119071. return SQLITE_NOMEM;
  119072. }
  119073. return db->errCode & db->errMask;
  119074. }
  119075. SQLITE_API int sqlite3_extended_errcode(sqlite3 *db){
  119076. if( db && !sqlite3SafetyCheckSickOrOk(db) ){
  119077. return SQLITE_MISUSE_BKPT;
  119078. }
  119079. if( !db || db->mallocFailed ){
  119080. return SQLITE_NOMEM;
  119081. }
  119082. return db->errCode;
  119083. }
  119084. /*
  119085. ** Return a string that describes the kind of error specified in the
  119086. ** argument. For now, this simply calls the internal sqlite3ErrStr()
  119087. ** function.
  119088. */
  119089. SQLITE_API const char *sqlite3_errstr(int rc){
  119090. return sqlite3ErrStr(rc);
  119091. }
  119092. /*
  119093. ** Invalidate all cached KeyInfo objects for database connection "db"
  119094. */
  119095. static void invalidateCachedKeyInfo(sqlite3 *db){
  119096. Db *pDb; /* A single database */
  119097. int iDb; /* The database index number */
  119098. HashElem *k; /* For looping over tables in pDb */
  119099. Table *pTab; /* A table in the database */
  119100. Index *pIdx; /* Each index */
  119101. for(iDb=0, pDb=db->aDb; iDb<db->nDb; iDb++, pDb++){
  119102. if( pDb->pBt==0 ) continue;
  119103. sqlite3BtreeEnter(pDb->pBt);
  119104. for(k=sqliteHashFirst(&pDb->pSchema->tblHash); k; k=sqliteHashNext(k)){
  119105. pTab = (Table*)sqliteHashData(k);
  119106. for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
  119107. if( pIdx->pKeyInfo && pIdx->pKeyInfo->db==db ){
  119108. sqlite3KeyInfoUnref(pIdx->pKeyInfo);
  119109. pIdx->pKeyInfo = 0;
  119110. }
  119111. }
  119112. }
  119113. sqlite3BtreeLeave(pDb->pBt);
  119114. }
  119115. }
  119116. /*
  119117. ** Create a new collating function for database "db". The name is zName
  119118. ** and the encoding is enc.
  119119. */
  119120. static int createCollation(
  119121. sqlite3* db,
  119122. const char *zName,
  119123. u8 enc,
  119124. void* pCtx,
  119125. int(*xCompare)(void*,int,const void*,int,const void*),
  119126. void(*xDel)(void*)
  119127. ){
  119128. CollSeq *pColl;
  119129. int enc2;
  119130. assert( sqlite3_mutex_held(db->mutex) );
  119131. /* If SQLITE_UTF16 is specified as the encoding type, transform this
  119132. ** to one of SQLITE_UTF16LE or SQLITE_UTF16BE using the
  119133. ** SQLITE_UTF16NATIVE macro. SQLITE_UTF16 is not used internally.
  119134. */
  119135. enc2 = enc;
  119136. testcase( enc2==SQLITE_UTF16 );
  119137. testcase( enc2==SQLITE_UTF16_ALIGNED );
  119138. if( enc2==SQLITE_UTF16 || enc2==SQLITE_UTF16_ALIGNED ){
  119139. enc2 = SQLITE_UTF16NATIVE;
  119140. }
  119141. if( enc2<SQLITE_UTF8 || enc2>SQLITE_UTF16BE ){
  119142. return SQLITE_MISUSE_BKPT;
  119143. }
  119144. /* Check if this call is removing or replacing an existing collation
  119145. ** sequence. If so, and there are active VMs, return busy. If there
  119146. ** are no active VMs, invalidate any pre-compiled statements.
  119147. */
  119148. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 0);
  119149. if( pColl && pColl->xCmp ){
  119150. if( db->nVdbeActive ){
  119151. sqlite3ErrorWithMsg(db, SQLITE_BUSY,
  119152. "unable to delete/modify collation sequence due to active statements");
  119153. return SQLITE_BUSY;
  119154. }
  119155. sqlite3ExpirePreparedStatements(db);
  119156. invalidateCachedKeyInfo(db);
  119157. /* If collation sequence pColl was created directly by a call to
  119158. ** sqlite3_create_collation, and not generated by synthCollSeq(),
  119159. ** then any copies made by synthCollSeq() need to be invalidated.
  119160. ** Also, collation destructor - CollSeq.xDel() - function may need
  119161. ** to be called.
  119162. */
  119163. if( (pColl->enc & ~SQLITE_UTF16_ALIGNED)==enc2 ){
  119164. CollSeq *aColl = sqlite3HashFind(&db->aCollSeq, zName);
  119165. int j;
  119166. for(j=0; j<3; j++){
  119167. CollSeq *p = &aColl[j];
  119168. if( p->enc==pColl->enc ){
  119169. if( p->xDel ){
  119170. p->xDel(p->pUser);
  119171. }
  119172. p->xCmp = 0;
  119173. }
  119174. }
  119175. }
  119176. }
  119177. pColl = sqlite3FindCollSeq(db, (u8)enc2, zName, 1);
  119178. if( pColl==0 ) return SQLITE_NOMEM;
  119179. pColl->xCmp = xCompare;
  119180. pColl->pUser = pCtx;
  119181. pColl->xDel = xDel;
  119182. pColl->enc = (u8)(enc2 | (enc & SQLITE_UTF16_ALIGNED));
  119183. sqlite3Error(db, SQLITE_OK);
  119184. return SQLITE_OK;
  119185. }
  119186. /*
  119187. ** This array defines hard upper bounds on limit values. The
  119188. ** initializer must be kept in sync with the SQLITE_LIMIT_*
  119189. ** #defines in sqlite3.h.
  119190. */
  119191. static const int aHardLimit[] = {
  119192. SQLITE_MAX_LENGTH,
  119193. SQLITE_MAX_SQL_LENGTH,
  119194. SQLITE_MAX_COLUMN,
  119195. SQLITE_MAX_EXPR_DEPTH,
  119196. SQLITE_MAX_COMPOUND_SELECT,
  119197. SQLITE_MAX_VDBE_OP,
  119198. SQLITE_MAX_FUNCTION_ARG,
  119199. SQLITE_MAX_ATTACHED,
  119200. SQLITE_MAX_LIKE_PATTERN_LENGTH,
  119201. SQLITE_MAX_VARIABLE_NUMBER, /* IMP: R-38091-32352 */
  119202. SQLITE_MAX_TRIGGER_DEPTH,
  119203. SQLITE_MAX_WORKER_THREADS,
  119204. };
  119205. /*
  119206. ** Make sure the hard limits are set to reasonable values
  119207. */
  119208. #if SQLITE_MAX_LENGTH<100
  119209. # error SQLITE_MAX_LENGTH must be at least 100
  119210. #endif
  119211. #if SQLITE_MAX_SQL_LENGTH<100
  119212. # error SQLITE_MAX_SQL_LENGTH must be at least 100
  119213. #endif
  119214. #if SQLITE_MAX_SQL_LENGTH>SQLITE_MAX_LENGTH
  119215. # error SQLITE_MAX_SQL_LENGTH must not be greater than SQLITE_MAX_LENGTH
  119216. #endif
  119217. #if SQLITE_MAX_COMPOUND_SELECT<2
  119218. # error SQLITE_MAX_COMPOUND_SELECT must be at least 2
  119219. #endif
  119220. #if SQLITE_MAX_VDBE_OP<40
  119221. # error SQLITE_MAX_VDBE_OP must be at least 40
  119222. #endif
  119223. #if SQLITE_MAX_FUNCTION_ARG<0 || SQLITE_MAX_FUNCTION_ARG>1000
  119224. # error SQLITE_MAX_FUNCTION_ARG must be between 0 and 1000
  119225. #endif
  119226. #if SQLITE_MAX_ATTACHED<0 || SQLITE_MAX_ATTACHED>125
  119227. # error SQLITE_MAX_ATTACHED must be between 0 and 125
  119228. #endif
  119229. #if SQLITE_MAX_LIKE_PATTERN_LENGTH<1
  119230. # error SQLITE_MAX_LIKE_PATTERN_LENGTH must be at least 1
  119231. #endif
  119232. #if SQLITE_MAX_COLUMN>32767
  119233. # error SQLITE_MAX_COLUMN must not exceed 32767
  119234. #endif
  119235. #if SQLITE_MAX_TRIGGER_DEPTH<1
  119236. # error SQLITE_MAX_TRIGGER_DEPTH must be at least 1
  119237. #endif
  119238. #if SQLITE_MAX_WORKER_THREADS<0 || SQLITE_MAX_WORKER_THREADS>50
  119239. # error SQLITE_MAX_WORKER_THREADS must be between 0 and 50
  119240. #endif
  119241. /*
  119242. ** Change the value of a limit. Report the old value.
  119243. ** If an invalid limit index is supplied, report -1.
  119244. ** Make no changes but still report the old value if the
  119245. ** new limit is negative.
  119246. **
  119247. ** A new lower limit does not shrink existing constructs.
  119248. ** It merely prevents new constructs that exceed the limit
  119249. ** from forming.
  119250. */
  119251. SQLITE_API int sqlite3_limit(sqlite3 *db, int limitId, int newLimit){
  119252. int oldLimit;
  119253. /* EVIDENCE-OF: R-30189-54097 For each limit category SQLITE_LIMIT_NAME
  119254. ** there is a hard upper bound set at compile-time by a C preprocessor
  119255. ** macro called SQLITE_MAX_NAME. (The "_LIMIT_" in the name is changed to
  119256. ** "_MAX_".)
  119257. */
  119258. assert( aHardLimit[SQLITE_LIMIT_LENGTH]==SQLITE_MAX_LENGTH );
  119259. assert( aHardLimit[SQLITE_LIMIT_SQL_LENGTH]==SQLITE_MAX_SQL_LENGTH );
  119260. assert( aHardLimit[SQLITE_LIMIT_COLUMN]==SQLITE_MAX_COLUMN );
  119261. assert( aHardLimit[SQLITE_LIMIT_EXPR_DEPTH]==SQLITE_MAX_EXPR_DEPTH );
  119262. assert( aHardLimit[SQLITE_LIMIT_COMPOUND_SELECT]==SQLITE_MAX_COMPOUND_SELECT);
  119263. assert( aHardLimit[SQLITE_LIMIT_VDBE_OP]==SQLITE_MAX_VDBE_OP );
  119264. assert( aHardLimit[SQLITE_LIMIT_FUNCTION_ARG]==SQLITE_MAX_FUNCTION_ARG );
  119265. assert( aHardLimit[SQLITE_LIMIT_ATTACHED]==SQLITE_MAX_ATTACHED );
  119266. assert( aHardLimit[SQLITE_LIMIT_LIKE_PATTERN_LENGTH]==
  119267. SQLITE_MAX_LIKE_PATTERN_LENGTH );
  119268. assert( aHardLimit[SQLITE_LIMIT_VARIABLE_NUMBER]==SQLITE_MAX_VARIABLE_NUMBER);
  119269. assert( aHardLimit[SQLITE_LIMIT_TRIGGER_DEPTH]==SQLITE_MAX_TRIGGER_DEPTH );
  119270. assert( aHardLimit[SQLITE_LIMIT_WORKER_THREADS]==SQLITE_MAX_WORKER_THREADS );
  119271. assert( SQLITE_LIMIT_WORKER_THREADS==(SQLITE_N_LIMIT-1) );
  119272. if( limitId<0 || limitId>=SQLITE_N_LIMIT ){
  119273. return -1;
  119274. }
  119275. oldLimit = db->aLimit[limitId];
  119276. if( newLimit>=0 ){ /* IMP: R-52476-28732 */
  119277. if( newLimit>aHardLimit[limitId] ){
  119278. newLimit = aHardLimit[limitId]; /* IMP: R-51463-25634 */
  119279. }
  119280. db->aLimit[limitId] = newLimit;
  119281. }
  119282. return oldLimit; /* IMP: R-53341-35419 */
  119283. }
  119284. /*
  119285. ** This function is used to parse both URIs and non-URI filenames passed by the
  119286. ** user to API functions sqlite3_open() or sqlite3_open_v2(), and for database
  119287. ** URIs specified as part of ATTACH statements.
  119288. **
  119289. ** The first argument to this function is the name of the VFS to use (or
  119290. ** a NULL to signify the default VFS) if the URI does not contain a "vfs=xxx"
  119291. ** query parameter. The second argument contains the URI (or non-URI filename)
  119292. ** itself. When this function is called the *pFlags variable should contain
  119293. ** the default flags to open the database handle with. The value stored in
  119294. ** *pFlags may be updated before returning if the URI filename contains
  119295. ** "cache=xxx" or "mode=xxx" query parameters.
  119296. **
  119297. ** If successful, SQLITE_OK is returned. In this case *ppVfs is set to point to
  119298. ** the VFS that should be used to open the database file. *pzFile is set to
  119299. ** point to a buffer containing the name of the file to open. It is the
  119300. ** responsibility of the caller to eventually call sqlite3_free() to release
  119301. ** this buffer.
  119302. **
  119303. ** If an error occurs, then an SQLite error code is returned and *pzErrMsg
  119304. ** may be set to point to a buffer containing an English language error
  119305. ** message. It is the responsibility of the caller to eventually release
  119306. ** this buffer by calling sqlite3_free().
  119307. */
  119308. SQLITE_PRIVATE int sqlite3ParseUri(
  119309. const char *zDefaultVfs, /* VFS to use if no "vfs=xxx" query option */
  119310. const char *zUri, /* Nul-terminated URI to parse */
  119311. unsigned int *pFlags, /* IN/OUT: SQLITE_OPEN_XXX flags */
  119312. sqlite3_vfs **ppVfs, /* OUT: VFS to use */
  119313. char **pzFile, /* OUT: Filename component of URI */
  119314. char **pzErrMsg /* OUT: Error message (if rc!=SQLITE_OK) */
  119315. ){
  119316. int rc = SQLITE_OK;
  119317. unsigned int flags = *pFlags;
  119318. const char *zVfs = zDefaultVfs;
  119319. char *zFile;
  119320. char c;
  119321. int nUri = sqlite3Strlen30(zUri);
  119322. assert( *pzErrMsg==0 );
  119323. if( ((flags & SQLITE_OPEN_URI) || sqlite3GlobalConfig.bOpenUri)
  119324. && nUri>=5 && memcmp(zUri, "file:", 5)==0 /* IMP: R-57884-37496 */
  119325. ){
  119326. char *zOpt;
  119327. int eState; /* Parser state when parsing URI */
  119328. int iIn; /* Input character index */
  119329. int iOut = 0; /* Output character index */
  119330. int nByte = nUri+2; /* Bytes of space to allocate */
  119331. /* Make sure the SQLITE_OPEN_URI flag is set to indicate to the VFS xOpen
  119332. ** method that there may be extra parameters following the file-name. */
  119333. flags |= SQLITE_OPEN_URI;
  119334. for(iIn=0; iIn<nUri; iIn++) nByte += (zUri[iIn]=='&');
  119335. zFile = sqlite3_malloc(nByte);
  119336. if( !zFile ) return SQLITE_NOMEM;
  119337. iIn = 5;
  119338. #ifndef SQLITE_ALLOW_URI_AUTHORITY
  119339. /* Discard the scheme and authority segments of the URI. */
  119340. if( zUri[5]=='/' && zUri[6]=='/' ){
  119341. iIn = 7;
  119342. while( zUri[iIn] && zUri[iIn]!='/' ) iIn++;
  119343. if( iIn!=7 && (iIn!=16 || memcmp("localhost", &zUri[7], 9)) ){
  119344. *pzErrMsg = sqlite3_mprintf("invalid uri authority: %.*s",
  119345. iIn-7, &zUri[7]);
  119346. rc = SQLITE_ERROR;
  119347. goto parse_uri_out;
  119348. }
  119349. }
  119350. #endif
  119351. /* Copy the filename and any query parameters into the zFile buffer.
  119352. ** Decode %HH escape codes along the way.
  119353. **
  119354. ** Within this loop, variable eState may be set to 0, 1 or 2, depending
  119355. ** on the parsing context. As follows:
  119356. **
  119357. ** 0: Parsing file-name.
  119358. ** 1: Parsing name section of a name=value query parameter.
  119359. ** 2: Parsing value section of a name=value query parameter.
  119360. */
  119361. eState = 0;
  119362. while( (c = zUri[iIn])!=0 && c!='#' ){
  119363. iIn++;
  119364. if( c=='%'
  119365. && sqlite3Isxdigit(zUri[iIn])
  119366. && sqlite3Isxdigit(zUri[iIn+1])
  119367. ){
  119368. int octet = (sqlite3HexToInt(zUri[iIn++]) << 4);
  119369. octet += sqlite3HexToInt(zUri[iIn++]);
  119370. assert( octet>=0 && octet<256 );
  119371. if( octet==0 ){
  119372. /* This branch is taken when "%00" appears within the URI. In this
  119373. ** case we ignore all text in the remainder of the path, name or
  119374. ** value currently being parsed. So ignore the current character
  119375. ** and skip to the next "?", "=" or "&", as appropriate. */
  119376. while( (c = zUri[iIn])!=0 && c!='#'
  119377. && (eState!=0 || c!='?')
  119378. && (eState!=1 || (c!='=' && c!='&'))
  119379. && (eState!=2 || c!='&')
  119380. ){
  119381. iIn++;
  119382. }
  119383. continue;
  119384. }
  119385. c = octet;
  119386. }else if( eState==1 && (c=='&' || c=='=') ){
  119387. if( zFile[iOut-1]==0 ){
  119388. /* An empty option name. Ignore this option altogether. */
  119389. while( zUri[iIn] && zUri[iIn]!='#' && zUri[iIn-1]!='&' ) iIn++;
  119390. continue;
  119391. }
  119392. if( c=='&' ){
  119393. zFile[iOut++] = '\0';
  119394. }else{
  119395. eState = 2;
  119396. }
  119397. c = 0;
  119398. }else if( (eState==0 && c=='?') || (eState==2 && c=='&') ){
  119399. c = 0;
  119400. eState = 1;
  119401. }
  119402. zFile[iOut++] = c;
  119403. }
  119404. if( eState==1 ) zFile[iOut++] = '\0';
  119405. zFile[iOut++] = '\0';
  119406. zFile[iOut++] = '\0';
  119407. /* Check if there were any options specified that should be interpreted
  119408. ** here. Options that are interpreted here include "vfs" and those that
  119409. ** correspond to flags that may be passed to the sqlite3_open_v2()
  119410. ** method. */
  119411. zOpt = &zFile[sqlite3Strlen30(zFile)+1];
  119412. while( zOpt[0] ){
  119413. int nOpt = sqlite3Strlen30(zOpt);
  119414. char *zVal = &zOpt[nOpt+1];
  119415. int nVal = sqlite3Strlen30(zVal);
  119416. if( nOpt==3 && memcmp("vfs", zOpt, 3)==0 ){
  119417. zVfs = zVal;
  119418. }else{
  119419. struct OpenMode {
  119420. const char *z;
  119421. int mode;
  119422. } *aMode = 0;
  119423. char *zModeType = 0;
  119424. int mask = 0;
  119425. int limit = 0;
  119426. if( nOpt==5 && memcmp("cache", zOpt, 5)==0 ){
  119427. static struct OpenMode aCacheMode[] = {
  119428. { "shared", SQLITE_OPEN_SHAREDCACHE },
  119429. { "private", SQLITE_OPEN_PRIVATECACHE },
  119430. { 0, 0 }
  119431. };
  119432. mask = SQLITE_OPEN_SHAREDCACHE|SQLITE_OPEN_PRIVATECACHE;
  119433. aMode = aCacheMode;
  119434. limit = mask;
  119435. zModeType = "cache";
  119436. }
  119437. if( nOpt==4 && memcmp("mode", zOpt, 4)==0 ){
  119438. static struct OpenMode aOpenMode[] = {
  119439. { "ro", SQLITE_OPEN_READONLY },
  119440. { "rw", SQLITE_OPEN_READWRITE },
  119441. { "rwc", SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE },
  119442. { "memory", SQLITE_OPEN_MEMORY },
  119443. { 0, 0 }
  119444. };
  119445. mask = SQLITE_OPEN_READONLY | SQLITE_OPEN_READWRITE
  119446. | SQLITE_OPEN_CREATE | SQLITE_OPEN_MEMORY;
  119447. aMode = aOpenMode;
  119448. limit = mask & flags;
  119449. zModeType = "access";
  119450. }
  119451. if( aMode ){
  119452. int i;
  119453. int mode = 0;
  119454. for(i=0; aMode[i].z; i++){
  119455. const char *z = aMode[i].z;
  119456. if( nVal==sqlite3Strlen30(z) && 0==memcmp(zVal, z, nVal) ){
  119457. mode = aMode[i].mode;
  119458. break;
  119459. }
  119460. }
  119461. if( mode==0 ){
  119462. *pzErrMsg = sqlite3_mprintf("no such %s mode: %s", zModeType, zVal);
  119463. rc = SQLITE_ERROR;
  119464. goto parse_uri_out;
  119465. }
  119466. if( (mode & ~SQLITE_OPEN_MEMORY)>limit ){
  119467. *pzErrMsg = sqlite3_mprintf("%s mode not allowed: %s",
  119468. zModeType, zVal);
  119469. rc = SQLITE_PERM;
  119470. goto parse_uri_out;
  119471. }
  119472. flags = (flags & ~mask) | mode;
  119473. }
  119474. }
  119475. zOpt = &zVal[nVal+1];
  119476. }
  119477. }else{
  119478. zFile = sqlite3_malloc(nUri+2);
  119479. if( !zFile ) return SQLITE_NOMEM;
  119480. memcpy(zFile, zUri, nUri);
  119481. zFile[nUri] = '\0';
  119482. zFile[nUri+1] = '\0';
  119483. flags &= ~SQLITE_OPEN_URI;
  119484. }
  119485. *ppVfs = sqlite3_vfs_find(zVfs);
  119486. if( *ppVfs==0 ){
  119487. *pzErrMsg = sqlite3_mprintf("no such vfs: %s", zVfs);
  119488. rc = SQLITE_ERROR;
  119489. }
  119490. parse_uri_out:
  119491. if( rc!=SQLITE_OK ){
  119492. sqlite3_free(zFile);
  119493. zFile = 0;
  119494. }
  119495. *pFlags = flags;
  119496. *pzFile = zFile;
  119497. return rc;
  119498. }
  119499. /*
  119500. ** This routine does the work of opening a database on behalf of
  119501. ** sqlite3_open() and sqlite3_open16(). The database filename "zFilename"
  119502. ** is UTF-8 encoded.
  119503. */
  119504. static int openDatabase(
  119505. const char *zFilename, /* Database filename UTF-8 encoded */
  119506. sqlite3 **ppDb, /* OUT: Returned database handle */
  119507. unsigned int flags, /* Operational flags */
  119508. const char *zVfs /* Name of the VFS to use */
  119509. ){
  119510. sqlite3 *db; /* Store allocated handle here */
  119511. int rc; /* Return code */
  119512. int isThreadsafe; /* True for threadsafe connections */
  119513. char *zOpen = 0; /* Filename argument to pass to BtreeOpen() */
  119514. char *zErrMsg = 0; /* Error message from sqlite3ParseUri() */
  119515. *ppDb = 0;
  119516. #ifndef SQLITE_OMIT_AUTOINIT
  119517. rc = sqlite3_initialize();
  119518. if( rc ) return rc;
  119519. #endif
  119520. /* Only allow sensible combinations of bits in the flags argument.
  119521. ** Throw an error if any non-sense combination is used. If we
  119522. ** do not block illegal combinations here, it could trigger
  119523. ** assert() statements in deeper layers. Sensible combinations
  119524. ** are:
  119525. **
  119526. ** 1: SQLITE_OPEN_READONLY
  119527. ** 2: SQLITE_OPEN_READWRITE
  119528. ** 6: SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE
  119529. */
  119530. assert( SQLITE_OPEN_READONLY == 0x01 );
  119531. assert( SQLITE_OPEN_READWRITE == 0x02 );
  119532. assert( SQLITE_OPEN_CREATE == 0x04 );
  119533. testcase( (1<<(flags&7))==0x02 ); /* READONLY */
  119534. testcase( (1<<(flags&7))==0x04 ); /* READWRITE */
  119535. testcase( (1<<(flags&7))==0x40 ); /* READWRITE | CREATE */
  119536. if( ((1<<(flags&7)) & 0x46)==0 ){
  119537. return SQLITE_MISUSE_BKPT; /* IMP: R-65497-44594 */
  119538. }
  119539. if( sqlite3GlobalConfig.bCoreMutex==0 ){
  119540. isThreadsafe = 0;
  119541. }else if( flags & SQLITE_OPEN_NOMUTEX ){
  119542. isThreadsafe = 0;
  119543. }else if( flags & SQLITE_OPEN_FULLMUTEX ){
  119544. isThreadsafe = 1;
  119545. }else{
  119546. isThreadsafe = sqlite3GlobalConfig.bFullMutex;
  119547. }
  119548. if( flags & SQLITE_OPEN_PRIVATECACHE ){
  119549. flags &= ~SQLITE_OPEN_SHAREDCACHE;
  119550. }else if( sqlite3GlobalConfig.sharedCacheEnabled ){
  119551. flags |= SQLITE_OPEN_SHAREDCACHE;
  119552. }
  119553. /* Remove harmful bits from the flags parameter
  119554. **
  119555. ** The SQLITE_OPEN_NOMUTEX and SQLITE_OPEN_FULLMUTEX flags were
  119556. ** dealt with in the previous code block. Besides these, the only
  119557. ** valid input flags for sqlite3_open_v2() are SQLITE_OPEN_READONLY,
  119558. ** SQLITE_OPEN_READWRITE, SQLITE_OPEN_CREATE, SQLITE_OPEN_SHAREDCACHE,
  119559. ** SQLITE_OPEN_PRIVATECACHE, and some reserved bits. Silently mask
  119560. ** off all other flags.
  119561. */
  119562. flags &= ~( SQLITE_OPEN_DELETEONCLOSE |
  119563. SQLITE_OPEN_EXCLUSIVE |
  119564. SQLITE_OPEN_MAIN_DB |
  119565. SQLITE_OPEN_TEMP_DB |
  119566. SQLITE_OPEN_TRANSIENT_DB |
  119567. SQLITE_OPEN_MAIN_JOURNAL |
  119568. SQLITE_OPEN_TEMP_JOURNAL |
  119569. SQLITE_OPEN_SUBJOURNAL |
  119570. SQLITE_OPEN_MASTER_JOURNAL |
  119571. SQLITE_OPEN_NOMUTEX |
  119572. SQLITE_OPEN_FULLMUTEX |
  119573. SQLITE_OPEN_WAL
  119574. );
  119575. /* Allocate the sqlite data structure */
  119576. db = sqlite3MallocZero( sizeof(sqlite3) );
  119577. if( db==0 ) goto opendb_out;
  119578. if( isThreadsafe ){
  119579. db->mutex = sqlite3MutexAlloc(SQLITE_MUTEX_RECURSIVE);
  119580. if( db->mutex==0 ){
  119581. sqlite3_free(db);
  119582. db = 0;
  119583. goto opendb_out;
  119584. }
  119585. }
  119586. sqlite3_mutex_enter(db->mutex);
  119587. db->errMask = 0xff;
  119588. db->nDb = 2;
  119589. db->magic = SQLITE_MAGIC_BUSY;
  119590. db->aDb = db->aDbStatic;
  119591. assert( sizeof(db->aLimit)==sizeof(aHardLimit) );
  119592. memcpy(db->aLimit, aHardLimit, sizeof(db->aLimit));
  119593. db->aLimit[SQLITE_LIMIT_WORKER_THREADS] = SQLITE_DEFAULT_WORKER_THREADS;
  119594. db->autoCommit = 1;
  119595. db->nextAutovac = -1;
  119596. db->szMmap = sqlite3GlobalConfig.szMmap;
  119597. db->nextPagesize = 0;
  119598. db->nMaxSorterMmap = 0x7FFFFFFF;
  119599. db->flags |= SQLITE_ShortColNames | SQLITE_EnableTrigger | SQLITE_CacheSpill
  119600. #if !defined(SQLITE_DEFAULT_AUTOMATIC_INDEX) || SQLITE_DEFAULT_AUTOMATIC_INDEX
  119601. | SQLITE_AutoIndex
  119602. #endif
  119603. #if SQLITE_DEFAULT_FILE_FORMAT<4
  119604. | SQLITE_LegacyFileFmt
  119605. #endif
  119606. #ifdef SQLITE_ENABLE_LOAD_EXTENSION
  119607. | SQLITE_LoadExtension
  119608. #endif
  119609. #if SQLITE_DEFAULT_RECURSIVE_TRIGGERS
  119610. | SQLITE_RecTriggers
  119611. #endif
  119612. #if defined(SQLITE_DEFAULT_FOREIGN_KEYS) && SQLITE_DEFAULT_FOREIGN_KEYS
  119613. | SQLITE_ForeignKeys
  119614. #endif
  119615. ;
  119616. sqlite3HashInit(&db->aCollSeq);
  119617. #ifndef SQLITE_OMIT_VIRTUALTABLE
  119618. sqlite3HashInit(&db->aModule);
  119619. #endif
  119620. /* Add the default collation sequence BINARY. BINARY works for both UTF-8
  119621. ** and UTF-16, so add a version for each to avoid any unnecessary
  119622. ** conversions. The only error that can occur here is a malloc() failure.
  119623. */
  119624. createCollation(db, "BINARY", SQLITE_UTF8, 0, binCollFunc, 0);
  119625. createCollation(db, "BINARY", SQLITE_UTF16BE, 0, binCollFunc, 0);
  119626. createCollation(db, "BINARY", SQLITE_UTF16LE, 0, binCollFunc, 0);
  119627. createCollation(db, "RTRIM", SQLITE_UTF8, (void*)1, binCollFunc, 0);
  119628. if( db->mallocFailed ){
  119629. goto opendb_out;
  119630. }
  119631. db->pDfltColl = sqlite3FindCollSeq(db, SQLITE_UTF8, "BINARY", 0);
  119632. assert( db->pDfltColl!=0 );
  119633. /* Also add a UTF-8 case-insensitive collation sequence. */
  119634. createCollation(db, "NOCASE", SQLITE_UTF8, 0, nocaseCollatingFunc, 0);
  119635. /* Parse the filename/URI argument. */
  119636. db->openFlags = flags;
  119637. rc = sqlite3ParseUri(zVfs, zFilename, &flags, &db->pVfs, &zOpen, &zErrMsg);
  119638. if( rc!=SQLITE_OK ){
  119639. if( rc==SQLITE_NOMEM ) db->mallocFailed = 1;
  119640. sqlite3ErrorWithMsg(db, rc, zErrMsg ? "%s" : 0, zErrMsg);
  119641. sqlite3_free(zErrMsg);
  119642. goto opendb_out;
  119643. }
  119644. /* Open the backend database driver */
  119645. rc = sqlite3BtreeOpen(db->pVfs, zOpen, db, &db->aDb[0].pBt, 0,
  119646. flags | SQLITE_OPEN_MAIN_DB);
  119647. if( rc!=SQLITE_OK ){
  119648. if( rc==SQLITE_IOERR_NOMEM ){
  119649. rc = SQLITE_NOMEM;
  119650. }
  119651. sqlite3Error(db, rc);
  119652. goto opendb_out;
  119653. }
  119654. sqlite3BtreeEnter(db->aDb[0].pBt);
  119655. db->aDb[0].pSchema = sqlite3SchemaGet(db, db->aDb[0].pBt);
  119656. sqlite3BtreeLeave(db->aDb[0].pBt);
  119657. db->aDb[1].pSchema = sqlite3SchemaGet(db, 0);
  119658. /* The default safety_level for the main database is 'full'; for the temp
  119659. ** database it is 'NONE'. This matches the pager layer defaults.
  119660. */
  119661. db->aDb[0].zName = "main";
  119662. db->aDb[0].safety_level = 3;
  119663. db->aDb[1].zName = "temp";
  119664. db->aDb[1].safety_level = 1;
  119665. db->magic = SQLITE_MAGIC_OPEN;
  119666. if( db->mallocFailed ){
  119667. goto opendb_out;
  119668. }
  119669. /* Register all built-in functions, but do not attempt to read the
  119670. ** database schema yet. This is delayed until the first time the database
  119671. ** is accessed.
  119672. */
  119673. sqlite3Error(db, SQLITE_OK);
  119674. sqlite3RegisterBuiltinFunctions(db);
  119675. /* Load automatic extensions - extensions that have been registered
  119676. ** using the sqlite3_automatic_extension() API.
  119677. */
  119678. rc = sqlite3_errcode(db);
  119679. if( rc==SQLITE_OK ){
  119680. sqlite3AutoLoadExtensions(db);
  119681. rc = sqlite3_errcode(db);
  119682. if( rc!=SQLITE_OK ){
  119683. goto opendb_out;
  119684. }
  119685. }
  119686. #ifdef SQLITE_ENABLE_FTS1
  119687. if( !db->mallocFailed ){
  119688. extern int sqlite3Fts1Init(sqlite3*);
  119689. rc = sqlite3Fts1Init(db);
  119690. }
  119691. #endif
  119692. #ifdef SQLITE_ENABLE_FTS2
  119693. if( !db->mallocFailed && rc==SQLITE_OK ){
  119694. extern int sqlite3Fts2Init(sqlite3*);
  119695. rc = sqlite3Fts2Init(db);
  119696. }
  119697. #endif
  119698. #ifdef SQLITE_ENABLE_FTS3
  119699. if( !db->mallocFailed && rc==SQLITE_OK ){
  119700. rc = sqlite3Fts3Init(db);
  119701. }
  119702. #endif
  119703. #ifdef SQLITE_ENABLE_ICU
  119704. if( !db->mallocFailed && rc==SQLITE_OK ){
  119705. rc = sqlite3IcuInit(db);
  119706. }
  119707. #endif
  119708. #ifdef SQLITE_ENABLE_RTREE
  119709. if( !db->mallocFailed && rc==SQLITE_OK){
  119710. rc = sqlite3RtreeInit(db);
  119711. }
  119712. #endif
  119713. /* -DSQLITE_DEFAULT_LOCKING_MODE=1 makes EXCLUSIVE the default locking
  119714. ** mode. -DSQLITE_DEFAULT_LOCKING_MODE=0 make NORMAL the default locking
  119715. ** mode. Doing nothing at all also makes NORMAL the default.
  119716. */
  119717. #ifdef SQLITE_DEFAULT_LOCKING_MODE
  119718. db->dfltLockMode = SQLITE_DEFAULT_LOCKING_MODE;
  119719. sqlite3PagerLockingMode(sqlite3BtreePager(db->aDb[0].pBt),
  119720. SQLITE_DEFAULT_LOCKING_MODE);
  119721. #endif
  119722. if( rc ) sqlite3Error(db, rc);
  119723. /* Enable the lookaside-malloc subsystem */
  119724. setupLookaside(db, 0, sqlite3GlobalConfig.szLookaside,
  119725. sqlite3GlobalConfig.nLookaside);
  119726. sqlite3_wal_autocheckpoint(db, SQLITE_DEFAULT_WAL_AUTOCHECKPOINT);
  119727. opendb_out:
  119728. sqlite3_free(zOpen);
  119729. if( db ){
  119730. assert( db->mutex!=0 || isThreadsafe==0 || sqlite3GlobalConfig.bFullMutex==0 );
  119731. sqlite3_mutex_leave(db->mutex);
  119732. }
  119733. rc = sqlite3_errcode(db);
  119734. assert( db!=0 || rc==SQLITE_NOMEM );
  119735. if( rc==SQLITE_NOMEM ){
  119736. sqlite3_close(db);
  119737. db = 0;
  119738. }else if( rc!=SQLITE_OK ){
  119739. db->magic = SQLITE_MAGIC_SICK;
  119740. }
  119741. *ppDb = db;
  119742. #ifdef SQLITE_ENABLE_SQLLOG
  119743. if( sqlite3GlobalConfig.xSqllog ){
  119744. /* Opening a db handle. Fourth parameter is passed 0. */
  119745. void *pArg = sqlite3GlobalConfig.pSqllogArg;
  119746. sqlite3GlobalConfig.xSqllog(pArg, db, zFilename, 0);
  119747. }
  119748. #endif
  119749. return sqlite3ApiExit(0, rc);
  119750. }
  119751. /*
  119752. ** Open a new database handle.
  119753. */
  119754. SQLITE_API int sqlite3_open(
  119755. const char *zFilename,
  119756. sqlite3 **ppDb
  119757. ){
  119758. return openDatabase(zFilename, ppDb,
  119759. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  119760. }
  119761. SQLITE_API int sqlite3_open_v2(
  119762. const char *filename, /* Database filename (UTF-8) */
  119763. sqlite3 **ppDb, /* OUT: SQLite db handle */
  119764. int flags, /* Flags */
  119765. const char *zVfs /* Name of VFS module to use */
  119766. ){
  119767. return openDatabase(filename, ppDb, (unsigned int)flags, zVfs);
  119768. }
  119769. #ifndef SQLITE_OMIT_UTF16
  119770. /*
  119771. ** Open a new database handle.
  119772. */
  119773. SQLITE_API int sqlite3_open16(
  119774. const void *zFilename,
  119775. sqlite3 **ppDb
  119776. ){
  119777. char const *zFilename8; /* zFilename encoded in UTF-8 instead of UTF-16 */
  119778. sqlite3_value *pVal;
  119779. int rc;
  119780. assert( zFilename );
  119781. assert( ppDb );
  119782. *ppDb = 0;
  119783. #ifndef SQLITE_OMIT_AUTOINIT
  119784. rc = sqlite3_initialize();
  119785. if( rc ) return rc;
  119786. #endif
  119787. pVal = sqlite3ValueNew(0);
  119788. sqlite3ValueSetStr(pVal, -1, zFilename, SQLITE_UTF16NATIVE, SQLITE_STATIC);
  119789. zFilename8 = sqlite3ValueText(pVal, SQLITE_UTF8);
  119790. if( zFilename8 ){
  119791. rc = openDatabase(zFilename8, ppDb,
  119792. SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, 0);
  119793. assert( *ppDb || rc==SQLITE_NOMEM );
  119794. if( rc==SQLITE_OK && !DbHasProperty(*ppDb, 0, DB_SchemaLoaded) ){
  119795. ENC(*ppDb) = SQLITE_UTF16NATIVE;
  119796. }
  119797. }else{
  119798. rc = SQLITE_NOMEM;
  119799. }
  119800. sqlite3ValueFree(pVal);
  119801. return sqlite3ApiExit(0, rc);
  119802. }
  119803. #endif /* SQLITE_OMIT_UTF16 */
  119804. /*
  119805. ** Register a new collation sequence with the database handle db.
  119806. */
  119807. SQLITE_API int sqlite3_create_collation(
  119808. sqlite3* db,
  119809. const char *zName,
  119810. int enc,
  119811. void* pCtx,
  119812. int(*xCompare)(void*,int,const void*,int,const void*)
  119813. ){
  119814. int rc;
  119815. sqlite3_mutex_enter(db->mutex);
  119816. assert( !db->mallocFailed );
  119817. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, 0);
  119818. rc = sqlite3ApiExit(db, rc);
  119819. sqlite3_mutex_leave(db->mutex);
  119820. return rc;
  119821. }
  119822. /*
  119823. ** Register a new collation sequence with the database handle db.
  119824. */
  119825. SQLITE_API int sqlite3_create_collation_v2(
  119826. sqlite3* db,
  119827. const char *zName,
  119828. int enc,
  119829. void* pCtx,
  119830. int(*xCompare)(void*,int,const void*,int,const void*),
  119831. void(*xDel)(void*)
  119832. ){
  119833. int rc;
  119834. sqlite3_mutex_enter(db->mutex);
  119835. assert( !db->mallocFailed );
  119836. rc = createCollation(db, zName, (u8)enc, pCtx, xCompare, xDel);
  119837. rc = sqlite3ApiExit(db, rc);
  119838. sqlite3_mutex_leave(db->mutex);
  119839. return rc;
  119840. }
  119841. #ifndef SQLITE_OMIT_UTF16
  119842. /*
  119843. ** Register a new collation sequence with the database handle db.
  119844. */
  119845. SQLITE_API int sqlite3_create_collation16(
  119846. sqlite3* db,
  119847. const void *zName,
  119848. int enc,
  119849. void* pCtx,
  119850. int(*xCompare)(void*,int,const void*,int,const void*)
  119851. ){
  119852. int rc = SQLITE_OK;
  119853. char *zName8;
  119854. sqlite3_mutex_enter(db->mutex);
  119855. assert( !db->mallocFailed );
  119856. zName8 = sqlite3Utf16to8(db, zName, -1, SQLITE_UTF16NATIVE);
  119857. if( zName8 ){
  119858. rc = createCollation(db, zName8, (u8)enc, pCtx, xCompare, 0);
  119859. sqlite3DbFree(db, zName8);
  119860. }
  119861. rc = sqlite3ApiExit(db, rc);
  119862. sqlite3_mutex_leave(db->mutex);
  119863. return rc;
  119864. }
  119865. #endif /* SQLITE_OMIT_UTF16 */
  119866. /*
  119867. ** Register a collation sequence factory callback with the database handle
  119868. ** db. Replace any previously installed collation sequence factory.
  119869. */
  119870. SQLITE_API int sqlite3_collation_needed(
  119871. sqlite3 *db,
  119872. void *pCollNeededArg,
  119873. void(*xCollNeeded)(void*,sqlite3*,int eTextRep,const char*)
  119874. ){
  119875. sqlite3_mutex_enter(db->mutex);
  119876. db->xCollNeeded = xCollNeeded;
  119877. db->xCollNeeded16 = 0;
  119878. db->pCollNeededArg = pCollNeededArg;
  119879. sqlite3_mutex_leave(db->mutex);
  119880. return SQLITE_OK;
  119881. }
  119882. #ifndef SQLITE_OMIT_UTF16
  119883. /*
  119884. ** Register a collation sequence factory callback with the database handle
  119885. ** db. Replace any previously installed collation sequence factory.
  119886. */
  119887. SQLITE_API int sqlite3_collation_needed16(
  119888. sqlite3 *db,
  119889. void *pCollNeededArg,
  119890. void(*xCollNeeded16)(void*,sqlite3*,int eTextRep,const void*)
  119891. ){
  119892. sqlite3_mutex_enter(db->mutex);
  119893. db->xCollNeeded = 0;
  119894. db->xCollNeeded16 = xCollNeeded16;
  119895. db->pCollNeededArg = pCollNeededArg;
  119896. sqlite3_mutex_leave(db->mutex);
  119897. return SQLITE_OK;
  119898. }
  119899. #endif /* SQLITE_OMIT_UTF16 */
  119900. #ifndef SQLITE_OMIT_DEPRECATED
  119901. /*
  119902. ** This function is now an anachronism. It used to be used to recover from a
  119903. ** malloc() failure, but SQLite now does this automatically.
  119904. */
  119905. SQLITE_API int sqlite3_global_recover(void){
  119906. return SQLITE_OK;
  119907. }
  119908. #endif
  119909. /*
  119910. ** Test to see whether or not the database connection is in autocommit
  119911. ** mode. Return TRUE if it is and FALSE if not. Autocommit mode is on
  119912. ** by default. Autocommit is disabled by a BEGIN statement and reenabled
  119913. ** by the next COMMIT or ROLLBACK.
  119914. */
  119915. SQLITE_API int sqlite3_get_autocommit(sqlite3 *db){
  119916. return db->autoCommit;
  119917. }
  119918. /*
  119919. ** The following routines are substitutes for constants SQLITE_CORRUPT,
  119920. ** SQLITE_MISUSE, SQLITE_CANTOPEN, SQLITE_IOERR and possibly other error
  119921. ** constants. They serve two purposes:
  119922. **
  119923. ** 1. Serve as a convenient place to set a breakpoint in a debugger
  119924. ** to detect when version error conditions occurs.
  119925. **
  119926. ** 2. Invoke sqlite3_log() to provide the source code location where
  119927. ** a low-level error is first detected.
  119928. */
  119929. SQLITE_PRIVATE int sqlite3CorruptError(int lineno){
  119930. testcase( sqlite3GlobalConfig.xLog!=0 );
  119931. sqlite3_log(SQLITE_CORRUPT,
  119932. "database corruption at line %d of [%.10s]",
  119933. lineno, 20+sqlite3_sourceid());
  119934. return SQLITE_CORRUPT;
  119935. }
  119936. SQLITE_PRIVATE int sqlite3MisuseError(int lineno){
  119937. testcase( sqlite3GlobalConfig.xLog!=0 );
  119938. sqlite3_log(SQLITE_MISUSE,
  119939. "misuse at line %d of [%.10s]",
  119940. lineno, 20+sqlite3_sourceid());
  119941. return SQLITE_MISUSE;
  119942. }
  119943. SQLITE_PRIVATE int sqlite3CantopenError(int lineno){
  119944. testcase( sqlite3GlobalConfig.xLog!=0 );
  119945. sqlite3_log(SQLITE_CANTOPEN,
  119946. "cannot open file at line %d of [%.10s]",
  119947. lineno, 20+sqlite3_sourceid());
  119948. return SQLITE_CANTOPEN;
  119949. }
  119950. #ifndef SQLITE_OMIT_DEPRECATED
  119951. /*
  119952. ** This is a convenience routine that makes sure that all thread-specific
  119953. ** data for this thread has been deallocated.
  119954. **
  119955. ** SQLite no longer uses thread-specific data so this routine is now a
  119956. ** no-op. It is retained for historical compatibility.
  119957. */
  119958. SQLITE_API void sqlite3_thread_cleanup(void){
  119959. }
  119960. #endif
  119961. /*
  119962. ** Return meta information about a specific column of a database table.
  119963. ** See comment in sqlite3.h (sqlite.h.in) for details.
  119964. */
  119965. #ifdef SQLITE_ENABLE_COLUMN_METADATA
  119966. SQLITE_API int sqlite3_table_column_metadata(
  119967. sqlite3 *db, /* Connection handle */
  119968. const char *zDbName, /* Database name or NULL */
  119969. const char *zTableName, /* Table name */
  119970. const char *zColumnName, /* Column name */
  119971. char const **pzDataType, /* OUTPUT: Declared data type */
  119972. char const **pzCollSeq, /* OUTPUT: Collation sequence name */
  119973. int *pNotNull, /* OUTPUT: True if NOT NULL constraint exists */
  119974. int *pPrimaryKey, /* OUTPUT: True if column part of PK */
  119975. int *pAutoinc /* OUTPUT: True if column is auto-increment */
  119976. ){
  119977. int rc;
  119978. char *zErrMsg = 0;
  119979. Table *pTab = 0;
  119980. Column *pCol = 0;
  119981. int iCol;
  119982. char const *zDataType = 0;
  119983. char const *zCollSeq = 0;
  119984. int notnull = 0;
  119985. int primarykey = 0;
  119986. int autoinc = 0;
  119987. /* Ensure the database schema has been loaded */
  119988. sqlite3_mutex_enter(db->mutex);
  119989. sqlite3BtreeEnterAll(db);
  119990. rc = sqlite3Init(db, &zErrMsg);
  119991. if( SQLITE_OK!=rc ){
  119992. goto error_out;
  119993. }
  119994. /* Locate the table in question */
  119995. pTab = sqlite3FindTable(db, zTableName, zDbName);
  119996. if( !pTab || pTab->pSelect ){
  119997. pTab = 0;
  119998. goto error_out;
  119999. }
  120000. /* Find the column for which info is requested */
  120001. if( sqlite3IsRowid(zColumnName) ){
  120002. iCol = pTab->iPKey;
  120003. if( iCol>=0 ){
  120004. pCol = &pTab->aCol[iCol];
  120005. }
  120006. }else{
  120007. for(iCol=0; iCol<pTab->nCol; iCol++){
  120008. pCol = &pTab->aCol[iCol];
  120009. if( 0==sqlite3StrICmp(pCol->zName, zColumnName) ){
  120010. break;
  120011. }
  120012. }
  120013. if( iCol==pTab->nCol ){
  120014. pTab = 0;
  120015. goto error_out;
  120016. }
  120017. }
  120018. /* The following block stores the meta information that will be returned
  120019. ** to the caller in local variables zDataType, zCollSeq, notnull, primarykey
  120020. ** and autoinc. At this point there are two possibilities:
  120021. **
  120022. ** 1. The specified column name was rowid", "oid" or "_rowid_"
  120023. ** and there is no explicitly declared IPK column.
  120024. **
  120025. ** 2. The table is not a view and the column name identified an
  120026. ** explicitly declared column. Copy meta information from *pCol.
  120027. */
  120028. if( pCol ){
  120029. zDataType = pCol->zType;
  120030. zCollSeq = pCol->zColl;
  120031. notnull = pCol->notNull!=0;
  120032. primarykey = (pCol->colFlags & COLFLAG_PRIMKEY)!=0;
  120033. autoinc = pTab->iPKey==iCol && (pTab->tabFlags & TF_Autoincrement)!=0;
  120034. }else{
  120035. zDataType = "INTEGER";
  120036. primarykey = 1;
  120037. }
  120038. if( !zCollSeq ){
  120039. zCollSeq = "BINARY";
  120040. }
  120041. error_out:
  120042. sqlite3BtreeLeaveAll(db);
  120043. /* Whether the function call succeeded or failed, set the output parameters
  120044. ** to whatever their local counterparts contain. If an error did occur,
  120045. ** this has the effect of zeroing all output parameters.
  120046. */
  120047. if( pzDataType ) *pzDataType = zDataType;
  120048. if( pzCollSeq ) *pzCollSeq = zCollSeq;
  120049. if( pNotNull ) *pNotNull = notnull;
  120050. if( pPrimaryKey ) *pPrimaryKey = primarykey;
  120051. if( pAutoinc ) *pAutoinc = autoinc;
  120052. if( SQLITE_OK==rc && !pTab ){
  120053. sqlite3DbFree(db, zErrMsg);
  120054. zErrMsg = sqlite3MPrintf(db, "no such table column: %s.%s", zTableName,
  120055. zColumnName);
  120056. rc = SQLITE_ERROR;
  120057. }
  120058. sqlite3ErrorWithMsg(db, rc, (zErrMsg?"%s":0), zErrMsg);
  120059. sqlite3DbFree(db, zErrMsg);
  120060. rc = sqlite3ApiExit(db, rc);
  120061. sqlite3_mutex_leave(db->mutex);
  120062. return rc;
  120063. }
  120064. #endif
  120065. /*
  120066. ** Sleep for a little while. Return the amount of time slept.
  120067. */
  120068. SQLITE_API int sqlite3_sleep(int ms){
  120069. sqlite3_vfs *pVfs;
  120070. int rc;
  120071. pVfs = sqlite3_vfs_find(0);
  120072. if( pVfs==0 ) return 0;
  120073. /* This function works in milliseconds, but the underlying OsSleep()
  120074. ** API uses microseconds. Hence the 1000's.
  120075. */
  120076. rc = (sqlite3OsSleep(pVfs, 1000*ms)/1000);
  120077. return rc;
  120078. }
  120079. /*
  120080. ** Enable or disable the extended result codes.
  120081. */
  120082. SQLITE_API int sqlite3_extended_result_codes(sqlite3 *db, int onoff){
  120083. sqlite3_mutex_enter(db->mutex);
  120084. db->errMask = onoff ? 0xffffffff : 0xff;
  120085. sqlite3_mutex_leave(db->mutex);
  120086. return SQLITE_OK;
  120087. }
  120088. /*
  120089. ** Invoke the xFileControl method on a particular database.
  120090. */
  120091. SQLITE_API int sqlite3_file_control(sqlite3 *db, const char *zDbName, int op, void *pArg){
  120092. int rc = SQLITE_ERROR;
  120093. Btree *pBtree;
  120094. sqlite3_mutex_enter(db->mutex);
  120095. pBtree = sqlite3DbNameToBtree(db, zDbName);
  120096. if( pBtree ){
  120097. Pager *pPager;
  120098. sqlite3_file *fd;
  120099. sqlite3BtreeEnter(pBtree);
  120100. pPager = sqlite3BtreePager(pBtree);
  120101. assert( pPager!=0 );
  120102. fd = sqlite3PagerFile(pPager);
  120103. assert( fd!=0 );
  120104. if( op==SQLITE_FCNTL_FILE_POINTER ){
  120105. *(sqlite3_file**)pArg = fd;
  120106. rc = SQLITE_OK;
  120107. }else if( fd->pMethods ){
  120108. rc = sqlite3OsFileControl(fd, op, pArg);
  120109. }else{
  120110. rc = SQLITE_NOTFOUND;
  120111. }
  120112. sqlite3BtreeLeave(pBtree);
  120113. }
  120114. sqlite3_mutex_leave(db->mutex);
  120115. return rc;
  120116. }
  120117. /*
  120118. ** Interface to the testing logic.
  120119. */
  120120. SQLITE_API int sqlite3_test_control(int op, ...){
  120121. int rc = 0;
  120122. #ifndef SQLITE_OMIT_BUILTIN_TEST
  120123. va_list ap;
  120124. va_start(ap, op);
  120125. switch( op ){
  120126. /*
  120127. ** Save the current state of the PRNG.
  120128. */
  120129. case SQLITE_TESTCTRL_PRNG_SAVE: {
  120130. sqlite3PrngSaveState();
  120131. break;
  120132. }
  120133. /*
  120134. ** Restore the state of the PRNG to the last state saved using
  120135. ** PRNG_SAVE. If PRNG_SAVE has never before been called, then
  120136. ** this verb acts like PRNG_RESET.
  120137. */
  120138. case SQLITE_TESTCTRL_PRNG_RESTORE: {
  120139. sqlite3PrngRestoreState();
  120140. break;
  120141. }
  120142. /*
  120143. ** Reset the PRNG back to its uninitialized state. The next call
  120144. ** to sqlite3_randomness() will reseed the PRNG using a single call
  120145. ** to the xRandomness method of the default VFS.
  120146. */
  120147. case SQLITE_TESTCTRL_PRNG_RESET: {
  120148. sqlite3_randomness(0,0);
  120149. break;
  120150. }
  120151. /*
  120152. ** sqlite3_test_control(BITVEC_TEST, size, program)
  120153. **
  120154. ** Run a test against a Bitvec object of size. The program argument
  120155. ** is an array of integers that defines the test. Return -1 on a
  120156. ** memory allocation error, 0 on success, or non-zero for an error.
  120157. ** See the sqlite3BitvecBuiltinTest() for additional information.
  120158. */
  120159. case SQLITE_TESTCTRL_BITVEC_TEST: {
  120160. int sz = va_arg(ap, int);
  120161. int *aProg = va_arg(ap, int*);
  120162. rc = sqlite3BitvecBuiltinTest(sz, aProg);
  120163. break;
  120164. }
  120165. /*
  120166. ** sqlite3_test_control(FAULT_INSTALL, xCallback)
  120167. **
  120168. ** Arrange to invoke xCallback() whenever sqlite3FaultSim() is called,
  120169. ** if xCallback is not NULL.
  120170. **
  120171. ** As a test of the fault simulator mechanism itself, sqlite3FaultSim(0)
  120172. ** is called immediately after installing the new callback and the return
  120173. ** value from sqlite3FaultSim(0) becomes the return from
  120174. ** sqlite3_test_control().
  120175. */
  120176. case SQLITE_TESTCTRL_FAULT_INSTALL: {
  120177. /* MSVC is picky about pulling func ptrs from va lists.
  120178. ** http://support.microsoft.com/kb/47961
  120179. ** sqlite3GlobalConfig.xTestCallback = va_arg(ap, int(*)(int));
  120180. */
  120181. typedef int(*TESTCALLBACKFUNC_t)(int);
  120182. sqlite3GlobalConfig.xTestCallback = va_arg(ap, TESTCALLBACKFUNC_t);
  120183. rc = sqlite3FaultSim(0);
  120184. break;
  120185. }
  120186. /*
  120187. ** sqlite3_test_control(BENIGN_MALLOC_HOOKS, xBegin, xEnd)
  120188. **
  120189. ** Register hooks to call to indicate which malloc() failures
  120190. ** are benign.
  120191. */
  120192. case SQLITE_TESTCTRL_BENIGN_MALLOC_HOOKS: {
  120193. typedef void (*void_function)(void);
  120194. void_function xBenignBegin;
  120195. void_function xBenignEnd;
  120196. xBenignBegin = va_arg(ap, void_function);
  120197. xBenignEnd = va_arg(ap, void_function);
  120198. sqlite3BenignMallocHooks(xBenignBegin, xBenignEnd);
  120199. break;
  120200. }
  120201. /*
  120202. ** sqlite3_test_control(SQLITE_TESTCTRL_PENDING_BYTE, unsigned int X)
  120203. **
  120204. ** Set the PENDING byte to the value in the argument, if X>0.
  120205. ** Make no changes if X==0. Return the value of the pending byte
  120206. ** as it existing before this routine was called.
  120207. **
  120208. ** IMPORTANT: Changing the PENDING byte from 0x40000000 results in
  120209. ** an incompatible database file format. Changing the PENDING byte
  120210. ** while any database connection is open results in undefined and
  120211. ** deleterious behavior.
  120212. */
  120213. case SQLITE_TESTCTRL_PENDING_BYTE: {
  120214. rc = PENDING_BYTE;
  120215. #ifndef SQLITE_OMIT_WSD
  120216. {
  120217. unsigned int newVal = va_arg(ap, unsigned int);
  120218. if( newVal ) sqlite3PendingByte = newVal;
  120219. }
  120220. #endif
  120221. break;
  120222. }
  120223. /*
  120224. ** sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, int X)
  120225. **
  120226. ** This action provides a run-time test to see whether or not
  120227. ** assert() was enabled at compile-time. If X is true and assert()
  120228. ** is enabled, then the return value is true. If X is true and
  120229. ** assert() is disabled, then the return value is zero. If X is
  120230. ** false and assert() is enabled, then the assertion fires and the
  120231. ** process aborts. If X is false and assert() is disabled, then the
  120232. ** return value is zero.
  120233. */
  120234. case SQLITE_TESTCTRL_ASSERT: {
  120235. volatile int x = 0;
  120236. assert( (x = va_arg(ap,int))!=0 );
  120237. rc = x;
  120238. break;
  120239. }
  120240. /*
  120241. ** sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, int X)
  120242. **
  120243. ** This action provides a run-time test to see how the ALWAYS and
  120244. ** NEVER macros were defined at compile-time.
  120245. **
  120246. ** The return value is ALWAYS(X).
  120247. **
  120248. ** The recommended test is X==2. If the return value is 2, that means
  120249. ** ALWAYS() and NEVER() are both no-op pass-through macros, which is the
  120250. ** default setting. If the return value is 1, then ALWAYS() is either
  120251. ** hard-coded to true or else it asserts if its argument is false.
  120252. ** The first behavior (hard-coded to true) is the case if
  120253. ** SQLITE_TESTCTRL_ASSERT shows that assert() is disabled and the second
  120254. ** behavior (assert if the argument to ALWAYS() is false) is the case if
  120255. ** SQLITE_TESTCTRL_ASSERT shows that assert() is enabled.
  120256. **
  120257. ** The run-time test procedure might look something like this:
  120258. **
  120259. ** if( sqlite3_test_control(SQLITE_TESTCTRL_ALWAYS, 2)==2 ){
  120260. ** // ALWAYS() and NEVER() are no-op pass-through macros
  120261. ** }else if( sqlite3_test_control(SQLITE_TESTCTRL_ASSERT, 1) ){
  120262. ** // ALWAYS(x) asserts that x is true. NEVER(x) asserts x is false.
  120263. ** }else{
  120264. ** // ALWAYS(x) is a constant 1. NEVER(x) is a constant 0.
  120265. ** }
  120266. */
  120267. case SQLITE_TESTCTRL_ALWAYS: {
  120268. int x = va_arg(ap,int);
  120269. rc = ALWAYS(x);
  120270. break;
  120271. }
  120272. /*
  120273. ** sqlite3_test_control(SQLITE_TESTCTRL_BYTEORDER);
  120274. **
  120275. ** The integer returned reveals the byte-order of the computer on which
  120276. ** SQLite is running:
  120277. **
  120278. ** 1 big-endian, determined at run-time
  120279. ** 10 little-endian, determined at run-time
  120280. ** 432101 big-endian, determined at compile-time
  120281. ** 123410 little-endian, determined at compile-time
  120282. */
  120283. case SQLITE_TESTCTRL_BYTEORDER: {
  120284. rc = SQLITE_BYTEORDER*100 + SQLITE_LITTLEENDIAN*10 + SQLITE_BIGENDIAN;
  120285. break;
  120286. }
  120287. /* sqlite3_test_control(SQLITE_TESTCTRL_RESERVE, sqlite3 *db, int N)
  120288. **
  120289. ** Set the nReserve size to N for the main database on the database
  120290. ** connection db.
  120291. */
  120292. case SQLITE_TESTCTRL_RESERVE: {
  120293. sqlite3 *db = va_arg(ap, sqlite3*);
  120294. int x = va_arg(ap,int);
  120295. sqlite3_mutex_enter(db->mutex);
  120296. sqlite3BtreeSetPageSize(db->aDb[0].pBt, 0, x, 0);
  120297. sqlite3_mutex_leave(db->mutex);
  120298. break;
  120299. }
  120300. /* sqlite3_test_control(SQLITE_TESTCTRL_OPTIMIZATIONS, sqlite3 *db, int N)
  120301. **
  120302. ** Enable or disable various optimizations for testing purposes. The
  120303. ** argument N is a bitmask of optimizations to be disabled. For normal
  120304. ** operation N should be 0. The idea is that a test program (like the
  120305. ** SQL Logic Test or SLT test module) can run the same SQL multiple times
  120306. ** with various optimizations disabled to verify that the same answer
  120307. ** is obtained in every case.
  120308. */
  120309. case SQLITE_TESTCTRL_OPTIMIZATIONS: {
  120310. sqlite3 *db = va_arg(ap, sqlite3*);
  120311. db->dbOptFlags = (u16)(va_arg(ap, int) & 0xffff);
  120312. break;
  120313. }
  120314. #ifdef SQLITE_N_KEYWORD
  120315. /* sqlite3_test_control(SQLITE_TESTCTRL_ISKEYWORD, const char *zWord)
  120316. **
  120317. ** If zWord is a keyword recognized by the parser, then return the
  120318. ** number of keywords. Or if zWord is not a keyword, return 0.
  120319. **
  120320. ** This test feature is only available in the amalgamation since
  120321. ** the SQLITE_N_KEYWORD macro is not defined in this file if SQLite
  120322. ** is built using separate source files.
  120323. */
  120324. case SQLITE_TESTCTRL_ISKEYWORD: {
  120325. const char *zWord = va_arg(ap, const char*);
  120326. int n = sqlite3Strlen30(zWord);
  120327. rc = (sqlite3KeywordCode((u8*)zWord, n)!=TK_ID) ? SQLITE_N_KEYWORD : 0;
  120328. break;
  120329. }
  120330. #endif
  120331. /* sqlite3_test_control(SQLITE_TESTCTRL_SCRATCHMALLOC, sz, &pNew, pFree);
  120332. **
  120333. ** Pass pFree into sqlite3ScratchFree().
  120334. ** If sz>0 then allocate a scratch buffer into pNew.
  120335. */
  120336. case SQLITE_TESTCTRL_SCRATCHMALLOC: {
  120337. void *pFree, **ppNew;
  120338. int sz;
  120339. sz = va_arg(ap, int);
  120340. ppNew = va_arg(ap, void**);
  120341. pFree = va_arg(ap, void*);
  120342. if( sz ) *ppNew = sqlite3ScratchMalloc(sz);
  120343. sqlite3ScratchFree(pFree);
  120344. break;
  120345. }
  120346. /* sqlite3_test_control(SQLITE_TESTCTRL_LOCALTIME_FAULT, int onoff);
  120347. **
  120348. ** If parameter onoff is non-zero, configure the wrappers so that all
  120349. ** subsequent calls to localtime() and variants fail. If onoff is zero,
  120350. ** undo this setting.
  120351. */
  120352. case SQLITE_TESTCTRL_LOCALTIME_FAULT: {
  120353. sqlite3GlobalConfig.bLocaltimeFault = va_arg(ap, int);
  120354. break;
  120355. }
  120356. /* sqlite3_test_control(SQLITE_TESTCTRL_NEVER_CORRUPT, int);
  120357. **
  120358. ** Set or clear a flag that indicates that the database file is always well-
  120359. ** formed and never corrupt. This flag is clear by default, indicating that
  120360. ** database files might have arbitrary corruption. Setting the flag during
  120361. ** testing causes certain assert() statements in the code to be activated
  120362. ** that demonstrat invariants on well-formed database files.
  120363. */
  120364. case SQLITE_TESTCTRL_NEVER_CORRUPT: {
  120365. sqlite3GlobalConfig.neverCorrupt = va_arg(ap, int);
  120366. break;
  120367. }
  120368. /* sqlite3_test_control(SQLITE_TESTCTRL_VDBE_COVERAGE, xCallback, ptr);
  120369. **
  120370. ** Set the VDBE coverage callback function to xCallback with context
  120371. ** pointer ptr.
  120372. */
  120373. case SQLITE_TESTCTRL_VDBE_COVERAGE: {
  120374. #ifdef SQLITE_VDBE_COVERAGE
  120375. typedef void (*branch_callback)(void*,int,u8,u8);
  120376. sqlite3GlobalConfig.xVdbeBranch = va_arg(ap,branch_callback);
  120377. sqlite3GlobalConfig.pVdbeBranchArg = va_arg(ap,void*);
  120378. #endif
  120379. break;
  120380. }
  120381. /* sqlite3_test_control(SQLITE_TESTCTRL_SORTER_MMAP, db, nMax); */
  120382. case SQLITE_TESTCTRL_SORTER_MMAP: {
  120383. sqlite3 *db = va_arg(ap, sqlite3*);
  120384. db->nMaxSorterMmap = va_arg(ap, int);
  120385. break;
  120386. }
  120387. /* sqlite3_test_control(SQLITE_TESTCTRL_ISINIT);
  120388. **
  120389. ** Return SQLITE_OK if SQLite has been initialized and SQLITE_ERROR if
  120390. ** not.
  120391. */
  120392. case SQLITE_TESTCTRL_ISINIT: {
  120393. if( sqlite3GlobalConfig.isInit==0 ) rc = SQLITE_ERROR;
  120394. break;
  120395. }
  120396. }
  120397. va_end(ap);
  120398. #endif /* SQLITE_OMIT_BUILTIN_TEST */
  120399. return rc;
  120400. }
  120401. /*
  120402. ** This is a utility routine, useful to VFS implementations, that checks
  120403. ** to see if a database file was a URI that contained a specific query
  120404. ** parameter, and if so obtains the value of the query parameter.
  120405. **
  120406. ** The zFilename argument is the filename pointer passed into the xOpen()
  120407. ** method of a VFS implementation. The zParam argument is the name of the
  120408. ** query parameter we seek. This routine returns the value of the zParam
  120409. ** parameter if it exists. If the parameter does not exist, this routine
  120410. ** returns a NULL pointer.
  120411. */
  120412. SQLITE_API const char *sqlite3_uri_parameter(const char *zFilename, const char *zParam){
  120413. if( zFilename==0 ) return 0;
  120414. zFilename += sqlite3Strlen30(zFilename) + 1;
  120415. while( zFilename[0] ){
  120416. int x = strcmp(zFilename, zParam);
  120417. zFilename += sqlite3Strlen30(zFilename) + 1;
  120418. if( x==0 ) return zFilename;
  120419. zFilename += sqlite3Strlen30(zFilename) + 1;
  120420. }
  120421. return 0;
  120422. }
  120423. /*
  120424. ** Return a boolean value for a query parameter.
  120425. */
  120426. SQLITE_API int sqlite3_uri_boolean(const char *zFilename, const char *zParam, int bDflt){
  120427. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  120428. bDflt = bDflt!=0;
  120429. return z ? sqlite3GetBoolean(z, bDflt) : bDflt;
  120430. }
  120431. /*
  120432. ** Return a 64-bit integer value for a query parameter.
  120433. */
  120434. SQLITE_API sqlite3_int64 sqlite3_uri_int64(
  120435. const char *zFilename, /* Filename as passed to xOpen */
  120436. const char *zParam, /* URI parameter sought */
  120437. sqlite3_int64 bDflt /* return if parameter is missing */
  120438. ){
  120439. const char *z = sqlite3_uri_parameter(zFilename, zParam);
  120440. sqlite3_int64 v;
  120441. if( z && sqlite3DecOrHexToI64(z, &v)==SQLITE_OK ){
  120442. bDflt = v;
  120443. }
  120444. return bDflt;
  120445. }
  120446. /*
  120447. ** Return the Btree pointer identified by zDbName. Return NULL if not found.
  120448. */
  120449. SQLITE_PRIVATE Btree *sqlite3DbNameToBtree(sqlite3 *db, const char *zDbName){
  120450. int i;
  120451. for(i=0; i<db->nDb; i++){
  120452. if( db->aDb[i].pBt
  120453. && (zDbName==0 || sqlite3StrICmp(zDbName, db->aDb[i].zName)==0)
  120454. ){
  120455. return db->aDb[i].pBt;
  120456. }
  120457. }
  120458. return 0;
  120459. }
  120460. /*
  120461. ** Return the filename of the database associated with a database
  120462. ** connection.
  120463. */
  120464. SQLITE_API const char *sqlite3_db_filename(sqlite3 *db, const char *zDbName){
  120465. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  120466. return pBt ? sqlite3BtreeGetFilename(pBt) : 0;
  120467. }
  120468. /*
  120469. ** Return 1 if database is read-only or 0 if read/write. Return -1 if
  120470. ** no such database exists.
  120471. */
  120472. SQLITE_API int sqlite3_db_readonly(sqlite3 *db, const char *zDbName){
  120473. Btree *pBt = sqlite3DbNameToBtree(db, zDbName);
  120474. return pBt ? sqlite3BtreeIsReadonly(pBt) : -1;
  120475. }
  120476. /************** End of main.c ************************************************/
  120477. /************** Begin file notify.c ******************************************/
  120478. /*
  120479. ** 2009 March 3
  120480. **
  120481. ** The author disclaims copyright to this source code. In place of
  120482. ** a legal notice, here is a blessing:
  120483. **
  120484. ** May you do good and not evil.
  120485. ** May you find forgiveness for yourself and forgive others.
  120486. ** May you share freely, never taking more than you give.
  120487. **
  120488. *************************************************************************
  120489. **
  120490. ** This file contains the implementation of the sqlite3_unlock_notify()
  120491. ** API method and its associated functionality.
  120492. */
  120493. /* Omit this entire file if SQLITE_ENABLE_UNLOCK_NOTIFY is not defined. */
  120494. #ifdef SQLITE_ENABLE_UNLOCK_NOTIFY
  120495. /*
  120496. ** Public interfaces:
  120497. **
  120498. ** sqlite3ConnectionBlocked()
  120499. ** sqlite3ConnectionUnlocked()
  120500. ** sqlite3ConnectionClosed()
  120501. ** sqlite3_unlock_notify()
  120502. */
  120503. #define assertMutexHeld() \
  120504. assert( sqlite3_mutex_held(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER)) )
  120505. /*
  120506. ** Head of a linked list of all sqlite3 objects created by this process
  120507. ** for which either sqlite3.pBlockingConnection or sqlite3.pUnlockConnection
  120508. ** is not NULL. This variable may only accessed while the STATIC_MASTER
  120509. ** mutex is held.
  120510. */
  120511. static sqlite3 *SQLITE_WSD sqlite3BlockedList = 0;
  120512. #ifndef NDEBUG
  120513. /*
  120514. ** This function is a complex assert() that verifies the following
  120515. ** properties of the blocked connections list:
  120516. **
  120517. ** 1) Each entry in the list has a non-NULL value for either
  120518. ** pUnlockConnection or pBlockingConnection, or both.
  120519. **
  120520. ** 2) All entries in the list that share a common value for
  120521. ** xUnlockNotify are grouped together.
  120522. **
  120523. ** 3) If the argument db is not NULL, then none of the entries in the
  120524. ** blocked connections list have pUnlockConnection or pBlockingConnection
  120525. ** set to db. This is used when closing connection db.
  120526. */
  120527. static void checkListProperties(sqlite3 *db){
  120528. sqlite3 *p;
  120529. for(p=sqlite3BlockedList; p; p=p->pNextBlocked){
  120530. int seen = 0;
  120531. sqlite3 *p2;
  120532. /* Verify property (1) */
  120533. assert( p->pUnlockConnection || p->pBlockingConnection );
  120534. /* Verify property (2) */
  120535. for(p2=sqlite3BlockedList; p2!=p; p2=p2->pNextBlocked){
  120536. if( p2->xUnlockNotify==p->xUnlockNotify ) seen = 1;
  120537. assert( p2->xUnlockNotify==p->xUnlockNotify || !seen );
  120538. assert( db==0 || p->pUnlockConnection!=db );
  120539. assert( db==0 || p->pBlockingConnection!=db );
  120540. }
  120541. }
  120542. }
  120543. #else
  120544. # define checkListProperties(x)
  120545. #endif
  120546. /*
  120547. ** Remove connection db from the blocked connections list. If connection
  120548. ** db is not currently a part of the list, this function is a no-op.
  120549. */
  120550. static void removeFromBlockedList(sqlite3 *db){
  120551. sqlite3 **pp;
  120552. assertMutexHeld();
  120553. for(pp=&sqlite3BlockedList; *pp; pp = &(*pp)->pNextBlocked){
  120554. if( *pp==db ){
  120555. *pp = (*pp)->pNextBlocked;
  120556. break;
  120557. }
  120558. }
  120559. }
  120560. /*
  120561. ** Add connection db to the blocked connections list. It is assumed
  120562. ** that it is not already a part of the list.
  120563. */
  120564. static void addToBlockedList(sqlite3 *db){
  120565. sqlite3 **pp;
  120566. assertMutexHeld();
  120567. for(
  120568. pp=&sqlite3BlockedList;
  120569. *pp && (*pp)->xUnlockNotify!=db->xUnlockNotify;
  120570. pp=&(*pp)->pNextBlocked
  120571. );
  120572. db->pNextBlocked = *pp;
  120573. *pp = db;
  120574. }
  120575. /*
  120576. ** Obtain the STATIC_MASTER mutex.
  120577. */
  120578. static void enterMutex(void){
  120579. sqlite3_mutex_enter(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  120580. checkListProperties(0);
  120581. }
  120582. /*
  120583. ** Release the STATIC_MASTER mutex.
  120584. */
  120585. static void leaveMutex(void){
  120586. assertMutexHeld();
  120587. checkListProperties(0);
  120588. sqlite3_mutex_leave(sqlite3MutexAlloc(SQLITE_MUTEX_STATIC_MASTER));
  120589. }
  120590. /*
  120591. ** Register an unlock-notify callback.
  120592. **
  120593. ** This is called after connection "db" has attempted some operation
  120594. ** but has received an SQLITE_LOCKED error because another connection
  120595. ** (call it pOther) in the same process was busy using the same shared
  120596. ** cache. pOther is found by looking at db->pBlockingConnection.
  120597. **
  120598. ** If there is no blocking connection, the callback is invoked immediately,
  120599. ** before this routine returns.
  120600. **
  120601. ** If pOther is already blocked on db, then report SQLITE_LOCKED, to indicate
  120602. ** a deadlock.
  120603. **
  120604. ** Otherwise, make arrangements to invoke xNotify when pOther drops
  120605. ** its locks.
  120606. **
  120607. ** Each call to this routine overrides any prior callbacks registered
  120608. ** on the same "db". If xNotify==0 then any prior callbacks are immediately
  120609. ** cancelled.
  120610. */
  120611. SQLITE_API int sqlite3_unlock_notify(
  120612. sqlite3 *db,
  120613. void (*xNotify)(void **, int),
  120614. void *pArg
  120615. ){
  120616. int rc = SQLITE_OK;
  120617. sqlite3_mutex_enter(db->mutex);
  120618. enterMutex();
  120619. if( xNotify==0 ){
  120620. removeFromBlockedList(db);
  120621. db->pBlockingConnection = 0;
  120622. db->pUnlockConnection = 0;
  120623. db->xUnlockNotify = 0;
  120624. db->pUnlockArg = 0;
  120625. }else if( 0==db->pBlockingConnection ){
  120626. /* The blocking transaction has been concluded. Or there never was a
  120627. ** blocking transaction. In either case, invoke the notify callback
  120628. ** immediately.
  120629. */
  120630. xNotify(&pArg, 1);
  120631. }else{
  120632. sqlite3 *p;
  120633. for(p=db->pBlockingConnection; p && p!=db; p=p->pUnlockConnection){}
  120634. if( p ){
  120635. rc = SQLITE_LOCKED; /* Deadlock detected. */
  120636. }else{
  120637. db->pUnlockConnection = db->pBlockingConnection;
  120638. db->xUnlockNotify = xNotify;
  120639. db->pUnlockArg = pArg;
  120640. removeFromBlockedList(db);
  120641. addToBlockedList(db);
  120642. }
  120643. }
  120644. leaveMutex();
  120645. assert( !db->mallocFailed );
  120646. sqlite3ErrorWithMsg(db, rc, (rc?"database is deadlocked":0));
  120647. sqlite3_mutex_leave(db->mutex);
  120648. return rc;
  120649. }
  120650. /*
  120651. ** This function is called while stepping or preparing a statement
  120652. ** associated with connection db. The operation will return SQLITE_LOCKED
  120653. ** to the user because it requires a lock that will not be available
  120654. ** until connection pBlocker concludes its current transaction.
  120655. */
  120656. SQLITE_PRIVATE void sqlite3ConnectionBlocked(sqlite3 *db, sqlite3 *pBlocker){
  120657. enterMutex();
  120658. if( db->pBlockingConnection==0 && db->pUnlockConnection==0 ){
  120659. addToBlockedList(db);
  120660. }
  120661. db->pBlockingConnection = pBlocker;
  120662. leaveMutex();
  120663. }
  120664. /*
  120665. ** This function is called when
  120666. ** the transaction opened by database db has just finished. Locks held
  120667. ** by database connection db have been released.
  120668. **
  120669. ** This function loops through each entry in the blocked connections
  120670. ** list and does the following:
  120671. **
  120672. ** 1) If the sqlite3.pBlockingConnection member of a list entry is
  120673. ** set to db, then set pBlockingConnection=0.
  120674. **
  120675. ** 2) If the sqlite3.pUnlockConnection member of a list entry is
  120676. ** set to db, then invoke the configured unlock-notify callback and
  120677. ** set pUnlockConnection=0.
  120678. **
  120679. ** 3) If the two steps above mean that pBlockingConnection==0 and
  120680. ** pUnlockConnection==0, remove the entry from the blocked connections
  120681. ** list.
  120682. */
  120683. SQLITE_PRIVATE void sqlite3ConnectionUnlocked(sqlite3 *db){
  120684. void (*xUnlockNotify)(void **, int) = 0; /* Unlock-notify cb to invoke */
  120685. int nArg = 0; /* Number of entries in aArg[] */
  120686. sqlite3 **pp; /* Iterator variable */
  120687. void **aArg; /* Arguments to the unlock callback */
  120688. void **aDyn = 0; /* Dynamically allocated space for aArg[] */
  120689. void *aStatic[16]; /* Starter space for aArg[]. No malloc required */
  120690. aArg = aStatic;
  120691. enterMutex(); /* Enter STATIC_MASTER mutex */
  120692. /* This loop runs once for each entry in the blocked-connections list. */
  120693. for(pp=&sqlite3BlockedList; *pp; /* no-op */ ){
  120694. sqlite3 *p = *pp;
  120695. /* Step 1. */
  120696. if( p->pBlockingConnection==db ){
  120697. p->pBlockingConnection = 0;
  120698. }
  120699. /* Step 2. */
  120700. if( p->pUnlockConnection==db ){
  120701. assert( p->xUnlockNotify );
  120702. if( p->xUnlockNotify!=xUnlockNotify && nArg!=0 ){
  120703. xUnlockNotify(aArg, nArg);
  120704. nArg = 0;
  120705. }
  120706. sqlite3BeginBenignMalloc();
  120707. assert( aArg==aDyn || (aDyn==0 && aArg==aStatic) );
  120708. assert( nArg<=(int)ArraySize(aStatic) || aArg==aDyn );
  120709. if( (!aDyn && nArg==(int)ArraySize(aStatic))
  120710. || (aDyn && nArg==(int)(sqlite3MallocSize(aDyn)/sizeof(void*)))
  120711. ){
  120712. /* The aArg[] array needs to grow. */
  120713. void **pNew = (void **)sqlite3Malloc(nArg*sizeof(void *)*2);
  120714. if( pNew ){
  120715. memcpy(pNew, aArg, nArg*sizeof(void *));
  120716. sqlite3_free(aDyn);
  120717. aDyn = aArg = pNew;
  120718. }else{
  120719. /* This occurs when the array of context pointers that need to
  120720. ** be passed to the unlock-notify callback is larger than the
  120721. ** aStatic[] array allocated on the stack and the attempt to
  120722. ** allocate a larger array from the heap has failed.
  120723. **
  120724. ** This is a difficult situation to handle. Returning an error
  120725. ** code to the caller is insufficient, as even if an error code
  120726. ** is returned the transaction on connection db will still be
  120727. ** closed and the unlock-notify callbacks on blocked connections
  120728. ** will go unissued. This might cause the application to wait
  120729. ** indefinitely for an unlock-notify callback that will never
  120730. ** arrive.
  120731. **
  120732. ** Instead, invoke the unlock-notify callback with the context
  120733. ** array already accumulated. We can then clear the array and
  120734. ** begin accumulating any further context pointers without
  120735. ** requiring any dynamic allocation. This is sub-optimal because
  120736. ** it means that instead of one callback with a large array of
  120737. ** context pointers the application will receive two or more
  120738. ** callbacks with smaller arrays of context pointers, which will
  120739. ** reduce the applications ability to prioritize multiple
  120740. ** connections. But it is the best that can be done under the
  120741. ** circumstances.
  120742. */
  120743. xUnlockNotify(aArg, nArg);
  120744. nArg = 0;
  120745. }
  120746. }
  120747. sqlite3EndBenignMalloc();
  120748. aArg[nArg++] = p->pUnlockArg;
  120749. xUnlockNotify = p->xUnlockNotify;
  120750. p->pUnlockConnection = 0;
  120751. p->xUnlockNotify = 0;
  120752. p->pUnlockArg = 0;
  120753. }
  120754. /* Step 3. */
  120755. if( p->pBlockingConnection==0 && p->pUnlockConnection==0 ){
  120756. /* Remove connection p from the blocked connections list. */
  120757. *pp = p->pNextBlocked;
  120758. p->pNextBlocked = 0;
  120759. }else{
  120760. pp = &p->pNextBlocked;
  120761. }
  120762. }
  120763. if( nArg!=0 ){
  120764. xUnlockNotify(aArg, nArg);
  120765. }
  120766. sqlite3_free(aDyn);
  120767. leaveMutex(); /* Leave STATIC_MASTER mutex */
  120768. }
  120769. /*
  120770. ** This is called when the database connection passed as an argument is
  120771. ** being closed. The connection is removed from the blocked list.
  120772. */
  120773. SQLITE_PRIVATE void sqlite3ConnectionClosed(sqlite3 *db){
  120774. sqlite3ConnectionUnlocked(db);
  120775. enterMutex();
  120776. removeFromBlockedList(db);
  120777. checkListProperties(db);
  120778. leaveMutex();
  120779. }
  120780. #endif
  120781. /************** End of notify.c **********************************************/
  120782. /************** Begin file fts3.c ********************************************/
  120783. /*
  120784. ** 2006 Oct 10
  120785. **
  120786. ** The author disclaims copyright to this source code. In place of
  120787. ** a legal notice, here is a blessing:
  120788. **
  120789. ** May you do good and not evil.
  120790. ** May you find forgiveness for yourself and forgive others.
  120791. ** May you share freely, never taking more than you give.
  120792. **
  120793. ******************************************************************************
  120794. **
  120795. ** This is an SQLite module implementing full-text search.
  120796. */
  120797. /*
  120798. ** The code in this file is only compiled if:
  120799. **
  120800. ** * The FTS3 module is being built as an extension
  120801. ** (in which case SQLITE_CORE is not defined), or
  120802. **
  120803. ** * The FTS3 module is being built into the core of
  120804. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  120805. */
  120806. /* The full-text index is stored in a series of b+tree (-like)
  120807. ** structures called segments which map terms to doclists. The
  120808. ** structures are like b+trees in layout, but are constructed from the
  120809. ** bottom up in optimal fashion and are not updatable. Since trees
  120810. ** are built from the bottom up, things will be described from the
  120811. ** bottom up.
  120812. **
  120813. **
  120814. **** Varints ****
  120815. ** The basic unit of encoding is a variable-length integer called a
  120816. ** varint. We encode variable-length integers in little-endian order
  120817. ** using seven bits * per byte as follows:
  120818. **
  120819. ** KEY:
  120820. ** A = 0xxxxxxx 7 bits of data and one flag bit
  120821. ** B = 1xxxxxxx 7 bits of data and one flag bit
  120822. **
  120823. ** 7 bits - A
  120824. ** 14 bits - BA
  120825. ** 21 bits - BBA
  120826. ** and so on.
  120827. **
  120828. ** This is similar in concept to how sqlite encodes "varints" but
  120829. ** the encoding is not the same. SQLite varints are big-endian
  120830. ** are are limited to 9 bytes in length whereas FTS3 varints are
  120831. ** little-endian and can be up to 10 bytes in length (in theory).
  120832. **
  120833. ** Example encodings:
  120834. **
  120835. ** 1: 0x01
  120836. ** 127: 0x7f
  120837. ** 128: 0x81 0x00
  120838. **
  120839. **
  120840. **** Document lists ****
  120841. ** A doclist (document list) holds a docid-sorted list of hits for a
  120842. ** given term. Doclists hold docids and associated token positions.
  120843. ** A docid is the unique integer identifier for a single document.
  120844. ** A position is the index of a word within the document. The first
  120845. ** word of the document has a position of 0.
  120846. **
  120847. ** FTS3 used to optionally store character offsets using a compile-time
  120848. ** option. But that functionality is no longer supported.
  120849. **
  120850. ** A doclist is stored like this:
  120851. **
  120852. ** array {
  120853. ** varint docid; (delta from previous doclist)
  120854. ** array { (position list for column 0)
  120855. ** varint position; (2 more than the delta from previous position)
  120856. ** }
  120857. ** array {
  120858. ** varint POS_COLUMN; (marks start of position list for new column)
  120859. ** varint column; (index of new column)
  120860. ** array {
  120861. ** varint position; (2 more than the delta from previous position)
  120862. ** }
  120863. ** }
  120864. ** varint POS_END; (marks end of positions for this document.
  120865. ** }
  120866. **
  120867. ** Here, array { X } means zero or more occurrences of X, adjacent in
  120868. ** memory. A "position" is an index of a token in the token stream
  120869. ** generated by the tokenizer. Note that POS_END and POS_COLUMN occur
  120870. ** in the same logical place as the position element, and act as sentinals
  120871. ** ending a position list array. POS_END is 0. POS_COLUMN is 1.
  120872. ** The positions numbers are not stored literally but rather as two more
  120873. ** than the difference from the prior position, or the just the position plus
  120874. ** 2 for the first position. Example:
  120875. **
  120876. ** label: A B C D E F G H I J K
  120877. ** value: 123 5 9 1 1 14 35 0 234 72 0
  120878. **
  120879. ** The 123 value is the first docid. For column zero in this document
  120880. ** there are two matches at positions 3 and 10 (5-2 and 9-2+3). The 1
  120881. ** at D signals the start of a new column; the 1 at E indicates that the
  120882. ** new column is column number 1. There are two positions at 12 and 45
  120883. ** (14-2 and 35-2+12). The 0 at H indicate the end-of-document. The
  120884. ** 234 at I is the delta to next docid (357). It has one position 70
  120885. ** (72-2) and then terminates with the 0 at K.
  120886. **
  120887. ** A "position-list" is the list of positions for multiple columns for
  120888. ** a single docid. A "column-list" is the set of positions for a single
  120889. ** column. Hence, a position-list consists of one or more column-lists,
  120890. ** a document record consists of a docid followed by a position-list and
  120891. ** a doclist consists of one or more document records.
  120892. **
  120893. ** A bare doclist omits the position information, becoming an
  120894. ** array of varint-encoded docids.
  120895. **
  120896. **** Segment leaf nodes ****
  120897. ** Segment leaf nodes store terms and doclists, ordered by term. Leaf
  120898. ** nodes are written using LeafWriter, and read using LeafReader (to
  120899. ** iterate through a single leaf node's data) and LeavesReader (to
  120900. ** iterate through a segment's entire leaf layer). Leaf nodes have
  120901. ** the format:
  120902. **
  120903. ** varint iHeight; (height from leaf level, always 0)
  120904. ** varint nTerm; (length of first term)
  120905. ** char pTerm[nTerm]; (content of first term)
  120906. ** varint nDoclist; (length of term's associated doclist)
  120907. ** char pDoclist[nDoclist]; (content of doclist)
  120908. ** array {
  120909. ** (further terms are delta-encoded)
  120910. ** varint nPrefix; (length of prefix shared with previous term)
  120911. ** varint nSuffix; (length of unshared suffix)
  120912. ** char pTermSuffix[nSuffix];(unshared suffix of next term)
  120913. ** varint nDoclist; (length of term's associated doclist)
  120914. ** char pDoclist[nDoclist]; (content of doclist)
  120915. ** }
  120916. **
  120917. ** Here, array { X } means zero or more occurrences of X, adjacent in
  120918. ** memory.
  120919. **
  120920. ** Leaf nodes are broken into blocks which are stored contiguously in
  120921. ** the %_segments table in sorted order. This means that when the end
  120922. ** of a node is reached, the next term is in the node with the next
  120923. ** greater node id.
  120924. **
  120925. ** New data is spilled to a new leaf node when the current node
  120926. ** exceeds LEAF_MAX bytes (default 2048). New data which itself is
  120927. ** larger than STANDALONE_MIN (default 1024) is placed in a standalone
  120928. ** node (a leaf node with a single term and doclist). The goal of
  120929. ** these settings is to pack together groups of small doclists while
  120930. ** making it efficient to directly access large doclists. The
  120931. ** assumption is that large doclists represent terms which are more
  120932. ** likely to be query targets.
  120933. **
  120934. ** TODO(shess) It may be useful for blocking decisions to be more
  120935. ** dynamic. For instance, it may make more sense to have a 2.5k leaf
  120936. ** node rather than splitting into 2k and .5k nodes. My intuition is
  120937. ** that this might extend through 2x or 4x the pagesize.
  120938. **
  120939. **
  120940. **** Segment interior nodes ****
  120941. ** Segment interior nodes store blockids for subtree nodes and terms
  120942. ** to describe what data is stored by the each subtree. Interior
  120943. ** nodes are written using InteriorWriter, and read using
  120944. ** InteriorReader. InteriorWriters are created as needed when
  120945. ** SegmentWriter creates new leaf nodes, or when an interior node
  120946. ** itself grows too big and must be split. The format of interior
  120947. ** nodes:
  120948. **
  120949. ** varint iHeight; (height from leaf level, always >0)
  120950. ** varint iBlockid; (block id of node's leftmost subtree)
  120951. ** optional {
  120952. ** varint nTerm; (length of first term)
  120953. ** char pTerm[nTerm]; (content of first term)
  120954. ** array {
  120955. ** (further terms are delta-encoded)
  120956. ** varint nPrefix; (length of shared prefix with previous term)
  120957. ** varint nSuffix; (length of unshared suffix)
  120958. ** char pTermSuffix[nSuffix]; (unshared suffix of next term)
  120959. ** }
  120960. ** }
  120961. **
  120962. ** Here, optional { X } means an optional element, while array { X }
  120963. ** means zero or more occurrences of X, adjacent in memory.
  120964. **
  120965. ** An interior node encodes n terms separating n+1 subtrees. The
  120966. ** subtree blocks are contiguous, so only the first subtree's blockid
  120967. ** is encoded. The subtree at iBlockid will contain all terms less
  120968. ** than the first term encoded (or all terms if no term is encoded).
  120969. ** Otherwise, for terms greater than or equal to pTerm[i] but less
  120970. ** than pTerm[i+1], the subtree for that term will be rooted at
  120971. ** iBlockid+i. Interior nodes only store enough term data to
  120972. ** distinguish adjacent children (if the rightmost term of the left
  120973. ** child is "something", and the leftmost term of the right child is
  120974. ** "wicked", only "w" is stored).
  120975. **
  120976. ** New data is spilled to a new interior node at the same height when
  120977. ** the current node exceeds INTERIOR_MAX bytes (default 2048).
  120978. ** INTERIOR_MIN_TERMS (default 7) keeps large terms from monopolizing
  120979. ** interior nodes and making the tree too skinny. The interior nodes
  120980. ** at a given height are naturally tracked by interior nodes at
  120981. ** height+1, and so on.
  120982. **
  120983. **
  120984. **** Segment directory ****
  120985. ** The segment directory in table %_segdir stores meta-information for
  120986. ** merging and deleting segments, and also the root node of the
  120987. ** segment's tree.
  120988. **
  120989. ** The root node is the top node of the segment's tree after encoding
  120990. ** the entire segment, restricted to ROOT_MAX bytes (default 1024).
  120991. ** This could be either a leaf node or an interior node. If the top
  120992. ** node requires more than ROOT_MAX bytes, it is flushed to %_segments
  120993. ** and a new root interior node is generated (which should always fit
  120994. ** within ROOT_MAX because it only needs space for 2 varints, the
  120995. ** height and the blockid of the previous root).
  120996. **
  120997. ** The meta-information in the segment directory is:
  120998. ** level - segment level (see below)
  120999. ** idx - index within level
  121000. ** - (level,idx uniquely identify a segment)
  121001. ** start_block - first leaf node
  121002. ** leaves_end_block - last leaf node
  121003. ** end_block - last block (including interior nodes)
  121004. ** root - contents of root node
  121005. **
  121006. ** If the root node is a leaf node, then start_block,
  121007. ** leaves_end_block, and end_block are all 0.
  121008. **
  121009. **
  121010. **** Segment merging ****
  121011. ** To amortize update costs, segments are grouped into levels and
  121012. ** merged in batches. Each increase in level represents exponentially
  121013. ** more documents.
  121014. **
  121015. ** New documents (actually, document updates) are tokenized and
  121016. ** written individually (using LeafWriter) to a level 0 segment, with
  121017. ** incrementing idx. When idx reaches MERGE_COUNT (default 16), all
  121018. ** level 0 segments are merged into a single level 1 segment. Level 1
  121019. ** is populated like level 0, and eventually MERGE_COUNT level 1
  121020. ** segments are merged to a single level 2 segment (representing
  121021. ** MERGE_COUNT^2 updates), and so on.
  121022. **
  121023. ** A segment merge traverses all segments at a given level in
  121024. ** parallel, performing a straightforward sorted merge. Since segment
  121025. ** leaf nodes are written in to the %_segments table in order, this
  121026. ** merge traverses the underlying sqlite disk structures efficiently.
  121027. ** After the merge, all segment blocks from the merged level are
  121028. ** deleted.
  121029. **
  121030. ** MERGE_COUNT controls how often we merge segments. 16 seems to be
  121031. ** somewhat of a sweet spot for insertion performance. 32 and 64 show
  121032. ** very similar performance numbers to 16 on insertion, though they're
  121033. ** a tiny bit slower (perhaps due to more overhead in merge-time
  121034. ** sorting). 8 is about 20% slower than 16, 4 about 50% slower than
  121035. ** 16, 2 about 66% slower than 16.
  121036. **
  121037. ** At query time, high MERGE_COUNT increases the number of segments
  121038. ** which need to be scanned and merged. For instance, with 100k docs
  121039. ** inserted:
  121040. **
  121041. ** MERGE_COUNT segments
  121042. ** 16 25
  121043. ** 8 12
  121044. ** 4 10
  121045. ** 2 6
  121046. **
  121047. ** This appears to have only a moderate impact on queries for very
  121048. ** frequent terms (which are somewhat dominated by segment merge
  121049. ** costs), and infrequent and non-existent terms still seem to be fast
  121050. ** even with many segments.
  121051. **
  121052. ** TODO(shess) That said, it would be nice to have a better query-side
  121053. ** argument for MERGE_COUNT of 16. Also, it is possible/likely that
  121054. ** optimizations to things like doclist merging will swing the sweet
  121055. ** spot around.
  121056. **
  121057. **
  121058. **
  121059. **** Handling of deletions and updates ****
  121060. ** Since we're using a segmented structure, with no docid-oriented
  121061. ** index into the term index, we clearly cannot simply update the term
  121062. ** index when a document is deleted or updated. For deletions, we
  121063. ** write an empty doclist (varint(docid) varint(POS_END)), for updates
  121064. ** we simply write the new doclist. Segment merges overwrite older
  121065. ** data for a particular docid with newer data, so deletes or updates
  121066. ** will eventually overtake the earlier data and knock it out. The
  121067. ** query logic likewise merges doclists so that newer data knocks out
  121068. ** older data.
  121069. */
  121070. /************** Include fts3Int.h in the middle of fts3.c ********************/
  121071. /************** Begin file fts3Int.h *****************************************/
  121072. /*
  121073. ** 2009 Nov 12
  121074. **
  121075. ** The author disclaims copyright to this source code. In place of
  121076. ** a legal notice, here is a blessing:
  121077. **
  121078. ** May you do good and not evil.
  121079. ** May you find forgiveness for yourself and forgive others.
  121080. ** May you share freely, never taking more than you give.
  121081. **
  121082. ******************************************************************************
  121083. **
  121084. */
  121085. #ifndef _FTSINT_H
  121086. #define _FTSINT_H
  121087. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  121088. # define NDEBUG 1
  121089. #endif
  121090. /*
  121091. ** FTS4 is really an extension for FTS3. It is enabled using the
  121092. ** SQLITE_ENABLE_FTS3 macro. But to avoid confusion we also all
  121093. ** the SQLITE_ENABLE_FTS4 macro to serve as an alisse for SQLITE_ENABLE_FTS3.
  121094. */
  121095. #if defined(SQLITE_ENABLE_FTS4) && !defined(SQLITE_ENABLE_FTS3)
  121096. # define SQLITE_ENABLE_FTS3
  121097. #endif
  121098. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  121099. /* If not building as part of the core, include sqlite3ext.h. */
  121100. #ifndef SQLITE_CORE
  121101. SQLITE_EXTENSION_INIT3
  121102. #endif
  121103. /************** Include fts3_tokenizer.h in the middle of fts3Int.h **********/
  121104. /************** Begin file fts3_tokenizer.h **********************************/
  121105. /*
  121106. ** 2006 July 10
  121107. **
  121108. ** The author disclaims copyright to this source code.
  121109. **
  121110. *************************************************************************
  121111. ** Defines the interface to tokenizers used by fulltext-search. There
  121112. ** are three basic components:
  121113. **
  121114. ** sqlite3_tokenizer_module is a singleton defining the tokenizer
  121115. ** interface functions. This is essentially the class structure for
  121116. ** tokenizers.
  121117. **
  121118. ** sqlite3_tokenizer is used to define a particular tokenizer, perhaps
  121119. ** including customization information defined at creation time.
  121120. **
  121121. ** sqlite3_tokenizer_cursor is generated by a tokenizer to generate
  121122. ** tokens from a particular input.
  121123. */
  121124. #ifndef _FTS3_TOKENIZER_H_
  121125. #define _FTS3_TOKENIZER_H_
  121126. /* TODO(shess) Only used for SQLITE_OK and SQLITE_DONE at this time.
  121127. ** If tokenizers are to be allowed to call sqlite3_*() functions, then
  121128. ** we will need a way to register the API consistently.
  121129. */
  121130. /*
  121131. ** Structures used by the tokenizer interface. When a new tokenizer
  121132. ** implementation is registered, the caller provides a pointer to
  121133. ** an sqlite3_tokenizer_module containing pointers to the callback
  121134. ** functions that make up an implementation.
  121135. **
  121136. ** When an fts3 table is created, it passes any arguments passed to
  121137. ** the tokenizer clause of the CREATE VIRTUAL TABLE statement to the
  121138. ** sqlite3_tokenizer_module.xCreate() function of the requested tokenizer
  121139. ** implementation. The xCreate() function in turn returns an
  121140. ** sqlite3_tokenizer structure representing the specific tokenizer to
  121141. ** be used for the fts3 table (customized by the tokenizer clause arguments).
  121142. **
  121143. ** To tokenize an input buffer, the sqlite3_tokenizer_module.xOpen()
  121144. ** method is called. It returns an sqlite3_tokenizer_cursor object
  121145. ** that may be used to tokenize a specific input buffer based on
  121146. ** the tokenization rules supplied by a specific sqlite3_tokenizer
  121147. ** object.
  121148. */
  121149. typedef struct sqlite3_tokenizer_module sqlite3_tokenizer_module;
  121150. typedef struct sqlite3_tokenizer sqlite3_tokenizer;
  121151. typedef struct sqlite3_tokenizer_cursor sqlite3_tokenizer_cursor;
  121152. struct sqlite3_tokenizer_module {
  121153. /*
  121154. ** Structure version. Should always be set to 0 or 1.
  121155. */
  121156. int iVersion;
  121157. /*
  121158. ** Create a new tokenizer. The values in the argv[] array are the
  121159. ** arguments passed to the "tokenizer" clause of the CREATE VIRTUAL
  121160. ** TABLE statement that created the fts3 table. For example, if
  121161. ** the following SQL is executed:
  121162. **
  121163. ** CREATE .. USING fts3( ... , tokenizer <tokenizer-name> arg1 arg2)
  121164. **
  121165. ** then argc is set to 2, and the argv[] array contains pointers
  121166. ** to the strings "arg1" and "arg2".
  121167. **
  121168. ** This method should return either SQLITE_OK (0), or an SQLite error
  121169. ** code. If SQLITE_OK is returned, then *ppTokenizer should be set
  121170. ** to point at the newly created tokenizer structure. The generic
  121171. ** sqlite3_tokenizer.pModule variable should not be initialized by
  121172. ** this callback. The caller will do so.
  121173. */
  121174. int (*xCreate)(
  121175. int argc, /* Size of argv array */
  121176. const char *const*argv, /* Tokenizer argument strings */
  121177. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  121178. );
  121179. /*
  121180. ** Destroy an existing tokenizer. The fts3 module calls this method
  121181. ** exactly once for each successful call to xCreate().
  121182. */
  121183. int (*xDestroy)(sqlite3_tokenizer *pTokenizer);
  121184. /*
  121185. ** Create a tokenizer cursor to tokenize an input buffer. The caller
  121186. ** is responsible for ensuring that the input buffer remains valid
  121187. ** until the cursor is closed (using the xClose() method).
  121188. */
  121189. int (*xOpen)(
  121190. sqlite3_tokenizer *pTokenizer, /* Tokenizer object */
  121191. const char *pInput, int nBytes, /* Input buffer */
  121192. sqlite3_tokenizer_cursor **ppCursor /* OUT: Created tokenizer cursor */
  121193. );
  121194. /*
  121195. ** Destroy an existing tokenizer cursor. The fts3 module calls this
  121196. ** method exactly once for each successful call to xOpen().
  121197. */
  121198. int (*xClose)(sqlite3_tokenizer_cursor *pCursor);
  121199. /*
  121200. ** Retrieve the next token from the tokenizer cursor pCursor. This
  121201. ** method should either return SQLITE_OK and set the values of the
  121202. ** "OUT" variables identified below, or SQLITE_DONE to indicate that
  121203. ** the end of the buffer has been reached, or an SQLite error code.
  121204. **
  121205. ** *ppToken should be set to point at a buffer containing the
  121206. ** normalized version of the token (i.e. after any case-folding and/or
  121207. ** stemming has been performed). *pnBytes should be set to the length
  121208. ** of this buffer in bytes. The input text that generated the token is
  121209. ** identified by the byte offsets returned in *piStartOffset and
  121210. ** *piEndOffset. *piStartOffset should be set to the index of the first
  121211. ** byte of the token in the input buffer. *piEndOffset should be set
  121212. ** to the index of the first byte just past the end of the token in
  121213. ** the input buffer.
  121214. **
  121215. ** The buffer *ppToken is set to point at is managed by the tokenizer
  121216. ** implementation. It is only required to be valid until the next call
  121217. ** to xNext() or xClose().
  121218. */
  121219. /* TODO(shess) current implementation requires pInput to be
  121220. ** nul-terminated. This should either be fixed, or pInput/nBytes
  121221. ** should be converted to zInput.
  121222. */
  121223. int (*xNext)(
  121224. sqlite3_tokenizer_cursor *pCursor, /* Tokenizer cursor */
  121225. const char **ppToken, int *pnBytes, /* OUT: Normalized text for token */
  121226. int *piStartOffset, /* OUT: Byte offset of token in input buffer */
  121227. int *piEndOffset, /* OUT: Byte offset of end of token in input buffer */
  121228. int *piPosition /* OUT: Number of tokens returned before this one */
  121229. );
  121230. /***********************************************************************
  121231. ** Methods below this point are only available if iVersion>=1.
  121232. */
  121233. /*
  121234. ** Configure the language id of a tokenizer cursor.
  121235. */
  121236. int (*xLanguageid)(sqlite3_tokenizer_cursor *pCsr, int iLangid);
  121237. };
  121238. struct sqlite3_tokenizer {
  121239. const sqlite3_tokenizer_module *pModule; /* The module for this tokenizer */
  121240. /* Tokenizer implementations will typically add additional fields */
  121241. };
  121242. struct sqlite3_tokenizer_cursor {
  121243. sqlite3_tokenizer *pTokenizer; /* Tokenizer for this cursor. */
  121244. /* Tokenizer implementations will typically add additional fields */
  121245. };
  121246. int fts3_global_term_cnt(int iTerm, int iCol);
  121247. int fts3_term_cnt(int iTerm, int iCol);
  121248. #endif /* _FTS3_TOKENIZER_H_ */
  121249. /************** End of fts3_tokenizer.h **************************************/
  121250. /************** Continuing where we left off in fts3Int.h ********************/
  121251. /************** Include fts3_hash.h in the middle of fts3Int.h ***************/
  121252. /************** Begin file fts3_hash.h ***************************************/
  121253. /*
  121254. ** 2001 September 22
  121255. **
  121256. ** The author disclaims copyright to this source code. In place of
  121257. ** a legal notice, here is a blessing:
  121258. **
  121259. ** May you do good and not evil.
  121260. ** May you find forgiveness for yourself and forgive others.
  121261. ** May you share freely, never taking more than you give.
  121262. **
  121263. *************************************************************************
  121264. ** This is the header file for the generic hash-table implementation
  121265. ** used in SQLite. We've modified it slightly to serve as a standalone
  121266. ** hash table implementation for the full-text indexing module.
  121267. **
  121268. */
  121269. #ifndef _FTS3_HASH_H_
  121270. #define _FTS3_HASH_H_
  121271. /* Forward declarations of structures. */
  121272. typedef struct Fts3Hash Fts3Hash;
  121273. typedef struct Fts3HashElem Fts3HashElem;
  121274. /* A complete hash table is an instance of the following structure.
  121275. ** The internals of this structure are intended to be opaque -- client
  121276. ** code should not attempt to access or modify the fields of this structure
  121277. ** directly. Change this structure only by using the routines below.
  121278. ** However, many of the "procedures" and "functions" for modifying and
  121279. ** accessing this structure are really macros, so we can't really make
  121280. ** this structure opaque.
  121281. */
  121282. struct Fts3Hash {
  121283. char keyClass; /* HASH_INT, _POINTER, _STRING, _BINARY */
  121284. char copyKey; /* True if copy of key made on insert */
  121285. int count; /* Number of entries in this table */
  121286. Fts3HashElem *first; /* The first element of the array */
  121287. int htsize; /* Number of buckets in the hash table */
  121288. struct _fts3ht { /* the hash table */
  121289. int count; /* Number of entries with this hash */
  121290. Fts3HashElem *chain; /* Pointer to first entry with this hash */
  121291. } *ht;
  121292. };
  121293. /* Each element in the hash table is an instance of the following
  121294. ** structure. All elements are stored on a single doubly-linked list.
  121295. **
  121296. ** Again, this structure is intended to be opaque, but it can't really
  121297. ** be opaque because it is used by macros.
  121298. */
  121299. struct Fts3HashElem {
  121300. Fts3HashElem *next, *prev; /* Next and previous elements in the table */
  121301. void *data; /* Data associated with this element */
  121302. void *pKey; int nKey; /* Key associated with this element */
  121303. };
  121304. /*
  121305. ** There are 2 different modes of operation for a hash table:
  121306. **
  121307. ** FTS3_HASH_STRING pKey points to a string that is nKey bytes long
  121308. ** (including the null-terminator, if any). Case
  121309. ** is respected in comparisons.
  121310. **
  121311. ** FTS3_HASH_BINARY pKey points to binary data nKey bytes long.
  121312. ** memcmp() is used to compare keys.
  121313. **
  121314. ** A copy of the key is made if the copyKey parameter to fts3HashInit is 1.
  121315. */
  121316. #define FTS3_HASH_STRING 1
  121317. #define FTS3_HASH_BINARY 2
  121318. /*
  121319. ** Access routines. To delete, insert a NULL pointer.
  121320. */
  121321. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey);
  121322. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(Fts3Hash*, const void *pKey, int nKey, void *pData);
  121323. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash*, const void *pKey, int nKey);
  121324. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash*);
  121325. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(const Fts3Hash *, const void *, int);
  121326. /*
  121327. ** Shorthand for the functions above
  121328. */
  121329. #define fts3HashInit sqlite3Fts3HashInit
  121330. #define fts3HashInsert sqlite3Fts3HashInsert
  121331. #define fts3HashFind sqlite3Fts3HashFind
  121332. #define fts3HashClear sqlite3Fts3HashClear
  121333. #define fts3HashFindElem sqlite3Fts3HashFindElem
  121334. /*
  121335. ** Macros for looping over all elements of a hash table. The idiom is
  121336. ** like this:
  121337. **
  121338. ** Fts3Hash h;
  121339. ** Fts3HashElem *p;
  121340. ** ...
  121341. ** for(p=fts3HashFirst(&h); p; p=fts3HashNext(p)){
  121342. ** SomeStructure *pData = fts3HashData(p);
  121343. ** // do something with pData
  121344. ** }
  121345. */
  121346. #define fts3HashFirst(H) ((H)->first)
  121347. #define fts3HashNext(E) ((E)->next)
  121348. #define fts3HashData(E) ((E)->data)
  121349. #define fts3HashKey(E) ((E)->pKey)
  121350. #define fts3HashKeysize(E) ((E)->nKey)
  121351. /*
  121352. ** Number of entries in a hash table
  121353. */
  121354. #define fts3HashCount(H) ((H)->count)
  121355. #endif /* _FTS3_HASH_H_ */
  121356. /************** End of fts3_hash.h *******************************************/
  121357. /************** Continuing where we left off in fts3Int.h ********************/
  121358. /*
  121359. ** This constant determines the maximum depth of an FTS expression tree
  121360. ** that the library will create and use. FTS uses recursion to perform
  121361. ** various operations on the query tree, so the disadvantage of a large
  121362. ** limit is that it may allow very large queries to use large amounts
  121363. ** of stack space (perhaps causing a stack overflow).
  121364. */
  121365. #ifndef SQLITE_FTS3_MAX_EXPR_DEPTH
  121366. # define SQLITE_FTS3_MAX_EXPR_DEPTH 12
  121367. #endif
  121368. /*
  121369. ** This constant controls how often segments are merged. Once there are
  121370. ** FTS3_MERGE_COUNT segments of level N, they are merged into a single
  121371. ** segment of level N+1.
  121372. */
  121373. #define FTS3_MERGE_COUNT 16
  121374. /*
  121375. ** This is the maximum amount of data (in bytes) to store in the
  121376. ** Fts3Table.pendingTerms hash table. Normally, the hash table is
  121377. ** populated as documents are inserted/updated/deleted in a transaction
  121378. ** and used to create a new segment when the transaction is committed.
  121379. ** However if this limit is reached midway through a transaction, a new
  121380. ** segment is created and the hash table cleared immediately.
  121381. */
  121382. #define FTS3_MAX_PENDING_DATA (1*1024*1024)
  121383. /*
  121384. ** Macro to return the number of elements in an array. SQLite has a
  121385. ** similar macro called ArraySize(). Use a different name to avoid
  121386. ** a collision when building an amalgamation with built-in FTS3.
  121387. */
  121388. #define SizeofArray(X) ((int)(sizeof(X)/sizeof(X[0])))
  121389. #ifndef MIN
  121390. # define MIN(x,y) ((x)<(y)?(x):(y))
  121391. #endif
  121392. #ifndef MAX
  121393. # define MAX(x,y) ((x)>(y)?(x):(y))
  121394. #endif
  121395. /*
  121396. ** Maximum length of a varint encoded integer. The varint format is different
  121397. ** from that used by SQLite, so the maximum length is 10, not 9.
  121398. */
  121399. #define FTS3_VARINT_MAX 10
  121400. /*
  121401. ** FTS4 virtual tables may maintain multiple indexes - one index of all terms
  121402. ** in the document set and zero or more prefix indexes. All indexes are stored
  121403. ** as one or more b+-trees in the %_segments and %_segdir tables.
  121404. **
  121405. ** It is possible to determine which index a b+-tree belongs to based on the
  121406. ** value stored in the "%_segdir.level" column. Given this value L, the index
  121407. ** that the b+-tree belongs to is (L<<10). In other words, all b+-trees with
  121408. ** level values between 0 and 1023 (inclusive) belong to index 0, all levels
  121409. ** between 1024 and 2047 to index 1, and so on.
  121410. **
  121411. ** It is considered impossible for an index to use more than 1024 levels. In
  121412. ** theory though this may happen, but only after at least
  121413. ** (FTS3_MERGE_COUNT^1024) separate flushes of the pending-terms tables.
  121414. */
  121415. #define FTS3_SEGDIR_MAXLEVEL 1024
  121416. #define FTS3_SEGDIR_MAXLEVEL_STR "1024"
  121417. /*
  121418. ** The testcase() macro is only used by the amalgamation. If undefined,
  121419. ** make it a no-op.
  121420. */
  121421. #ifndef testcase
  121422. # define testcase(X)
  121423. #endif
  121424. /*
  121425. ** Terminator values for position-lists and column-lists.
  121426. */
  121427. #define POS_COLUMN (1) /* Column-list terminator */
  121428. #define POS_END (0) /* Position-list terminator */
  121429. /*
  121430. ** This section provides definitions to allow the
  121431. ** FTS3 extension to be compiled outside of the
  121432. ** amalgamation.
  121433. */
  121434. #ifndef SQLITE_AMALGAMATION
  121435. /*
  121436. ** Macros indicating that conditional expressions are always true or
  121437. ** false.
  121438. */
  121439. #ifdef SQLITE_COVERAGE_TEST
  121440. # define ALWAYS(x) (1)
  121441. # define NEVER(X) (0)
  121442. #else
  121443. # define ALWAYS(x) (x)
  121444. # define NEVER(x) (x)
  121445. #endif
  121446. /*
  121447. ** Internal types used by SQLite.
  121448. */
  121449. typedef unsigned char u8; /* 1-byte (or larger) unsigned integer */
  121450. typedef short int i16; /* 2-byte (or larger) signed integer */
  121451. typedef unsigned int u32; /* 4-byte unsigned integer */
  121452. typedef sqlite3_uint64 u64; /* 8-byte unsigned integer */
  121453. typedef sqlite3_int64 i64; /* 8-byte signed integer */
  121454. /*
  121455. ** Macro used to suppress compiler warnings for unused parameters.
  121456. */
  121457. #define UNUSED_PARAMETER(x) (void)(x)
  121458. /*
  121459. ** Activate assert() only if SQLITE_TEST is enabled.
  121460. */
  121461. #if !defined(NDEBUG) && !defined(SQLITE_DEBUG)
  121462. # define NDEBUG 1
  121463. #endif
  121464. /*
  121465. ** The TESTONLY macro is used to enclose variable declarations or
  121466. ** other bits of code that are needed to support the arguments
  121467. ** within testcase() and assert() macros.
  121468. */
  121469. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  121470. # define TESTONLY(X) X
  121471. #else
  121472. # define TESTONLY(X)
  121473. #endif
  121474. #endif /* SQLITE_AMALGAMATION */
  121475. #ifdef SQLITE_DEBUG
  121476. SQLITE_PRIVATE int sqlite3Fts3Corrupt(void);
  121477. # define FTS_CORRUPT_VTAB sqlite3Fts3Corrupt()
  121478. #else
  121479. # define FTS_CORRUPT_VTAB SQLITE_CORRUPT_VTAB
  121480. #endif
  121481. typedef struct Fts3Table Fts3Table;
  121482. typedef struct Fts3Cursor Fts3Cursor;
  121483. typedef struct Fts3Expr Fts3Expr;
  121484. typedef struct Fts3Phrase Fts3Phrase;
  121485. typedef struct Fts3PhraseToken Fts3PhraseToken;
  121486. typedef struct Fts3Doclist Fts3Doclist;
  121487. typedef struct Fts3SegFilter Fts3SegFilter;
  121488. typedef struct Fts3DeferredToken Fts3DeferredToken;
  121489. typedef struct Fts3SegReader Fts3SegReader;
  121490. typedef struct Fts3MultiSegReader Fts3MultiSegReader;
  121491. /*
  121492. ** A connection to a fulltext index is an instance of the following
  121493. ** structure. The xCreate and xConnect methods create an instance
  121494. ** of this structure and xDestroy and xDisconnect free that instance.
  121495. ** All other methods receive a pointer to the structure as one of their
  121496. ** arguments.
  121497. */
  121498. struct Fts3Table {
  121499. sqlite3_vtab base; /* Base class used by SQLite core */
  121500. sqlite3 *db; /* The database connection */
  121501. const char *zDb; /* logical database name */
  121502. const char *zName; /* virtual table name */
  121503. int nColumn; /* number of named columns in virtual table */
  121504. char **azColumn; /* column names. malloced */
  121505. u8 *abNotindexed; /* True for 'notindexed' columns */
  121506. sqlite3_tokenizer *pTokenizer; /* tokenizer for inserts and queries */
  121507. char *zContentTbl; /* content=xxx option, or NULL */
  121508. char *zLanguageid; /* languageid=xxx option, or NULL */
  121509. int nAutoincrmerge; /* Value configured by 'automerge' */
  121510. u32 nLeafAdd; /* Number of leaf blocks added this trans */
  121511. /* Precompiled statements used by the implementation. Each of these
  121512. ** statements is run and reset within a single virtual table API call.
  121513. */
  121514. sqlite3_stmt *aStmt[40];
  121515. char *zReadExprlist;
  121516. char *zWriteExprlist;
  121517. int nNodeSize; /* Soft limit for node size */
  121518. u8 bFts4; /* True for FTS4, false for FTS3 */
  121519. u8 bHasStat; /* True if %_stat table exists (2==unknown) */
  121520. u8 bHasDocsize; /* True if %_docsize table exists */
  121521. u8 bDescIdx; /* True if doclists are in reverse order */
  121522. u8 bIgnoreSavepoint; /* True to ignore xSavepoint invocations */
  121523. int nPgsz; /* Page size for host database */
  121524. char *zSegmentsTbl; /* Name of %_segments table */
  121525. sqlite3_blob *pSegments; /* Blob handle open on %_segments table */
  121526. /*
  121527. ** The following array of hash tables is used to buffer pending index
  121528. ** updates during transactions. All pending updates buffered at any one
  121529. ** time must share a common language-id (see the FTS4 langid= feature).
  121530. ** The current language id is stored in variable iPrevLangid.
  121531. **
  121532. ** A single FTS4 table may have multiple full-text indexes. For each index
  121533. ** there is an entry in the aIndex[] array. Index 0 is an index of all the
  121534. ** terms that appear in the document set. Each subsequent index in aIndex[]
  121535. ** is an index of prefixes of a specific length.
  121536. **
  121537. ** Variable nPendingData contains an estimate the memory consumed by the
  121538. ** pending data structures, including hash table overhead, but not including
  121539. ** malloc overhead. When nPendingData exceeds nMaxPendingData, all hash
  121540. ** tables are flushed to disk. Variable iPrevDocid is the docid of the most
  121541. ** recently inserted record.
  121542. */
  121543. int nIndex; /* Size of aIndex[] */
  121544. struct Fts3Index {
  121545. int nPrefix; /* Prefix length (0 for main terms index) */
  121546. Fts3Hash hPending; /* Pending terms table for this index */
  121547. } *aIndex;
  121548. int nMaxPendingData; /* Max pending data before flush to disk */
  121549. int nPendingData; /* Current bytes of pending data */
  121550. sqlite_int64 iPrevDocid; /* Docid of most recently inserted document */
  121551. int iPrevLangid; /* Langid of recently inserted document */
  121552. #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
  121553. /* State variables used for validating that the transaction control
  121554. ** methods of the virtual table are called at appropriate times. These
  121555. ** values do not contribute to FTS functionality; they are used for
  121556. ** verifying the operation of the SQLite core.
  121557. */
  121558. int inTransaction; /* True after xBegin but before xCommit/xRollback */
  121559. int mxSavepoint; /* Largest valid xSavepoint integer */
  121560. #endif
  121561. #ifdef SQLITE_TEST
  121562. /* True to disable the incremental doclist optimization. This is controled
  121563. ** by special insert command 'test-no-incr-doclist'. */
  121564. int bNoIncrDoclist;
  121565. #endif
  121566. };
  121567. /*
  121568. ** When the core wants to read from the virtual table, it creates a
  121569. ** virtual table cursor (an instance of the following structure) using
  121570. ** the xOpen method. Cursors are destroyed using the xClose method.
  121571. */
  121572. struct Fts3Cursor {
  121573. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  121574. i16 eSearch; /* Search strategy (see below) */
  121575. u8 isEof; /* True if at End Of Results */
  121576. u8 isRequireSeek; /* True if must seek pStmt to %_content row */
  121577. sqlite3_stmt *pStmt; /* Prepared statement in use by the cursor */
  121578. Fts3Expr *pExpr; /* Parsed MATCH query string */
  121579. int iLangid; /* Language being queried for */
  121580. int nPhrase; /* Number of matchable phrases in query */
  121581. Fts3DeferredToken *pDeferred; /* Deferred search tokens, if any */
  121582. sqlite3_int64 iPrevId; /* Previous id read from aDoclist */
  121583. char *pNextId; /* Pointer into the body of aDoclist */
  121584. char *aDoclist; /* List of docids for full-text queries */
  121585. int nDoclist; /* Size of buffer at aDoclist */
  121586. u8 bDesc; /* True to sort in descending order */
  121587. int eEvalmode; /* An FTS3_EVAL_XX constant */
  121588. int nRowAvg; /* Average size of database rows, in pages */
  121589. sqlite3_int64 nDoc; /* Documents in table */
  121590. i64 iMinDocid; /* Minimum docid to return */
  121591. i64 iMaxDocid; /* Maximum docid to return */
  121592. int isMatchinfoNeeded; /* True when aMatchinfo[] needs filling in */
  121593. u32 *aMatchinfo; /* Information about most recent match */
  121594. int nMatchinfo; /* Number of elements in aMatchinfo[] */
  121595. char *zMatchinfo; /* Matchinfo specification */
  121596. };
  121597. #define FTS3_EVAL_FILTER 0
  121598. #define FTS3_EVAL_NEXT 1
  121599. #define FTS3_EVAL_MATCHINFO 2
  121600. /*
  121601. ** The Fts3Cursor.eSearch member is always set to one of the following.
  121602. ** Actualy, Fts3Cursor.eSearch can be greater than or equal to
  121603. ** FTS3_FULLTEXT_SEARCH. If so, then Fts3Cursor.eSearch - 2 is the index
  121604. ** of the column to be searched. For example, in
  121605. **
  121606. ** CREATE VIRTUAL TABLE ex1 USING fts3(a,b,c,d);
  121607. ** SELECT docid FROM ex1 WHERE b MATCH 'one two three';
  121608. **
  121609. ** Because the LHS of the MATCH operator is 2nd column "b",
  121610. ** Fts3Cursor.eSearch will be set to FTS3_FULLTEXT_SEARCH+1. (+0 for a,
  121611. ** +1 for b, +2 for c, +3 for d.) If the LHS of MATCH were "ex1"
  121612. ** indicating that all columns should be searched,
  121613. ** then eSearch would be set to FTS3_FULLTEXT_SEARCH+4.
  121614. */
  121615. #define FTS3_FULLSCAN_SEARCH 0 /* Linear scan of %_content table */
  121616. #define FTS3_DOCID_SEARCH 1 /* Lookup by rowid on %_content table */
  121617. #define FTS3_FULLTEXT_SEARCH 2 /* Full-text index search */
  121618. /*
  121619. ** The lower 16-bits of the sqlite3_index_info.idxNum value set by
  121620. ** the xBestIndex() method contains the Fts3Cursor.eSearch value described
  121621. ** above. The upper 16-bits contain a combination of the following
  121622. ** bits, used to describe extra constraints on full-text searches.
  121623. */
  121624. #define FTS3_HAVE_LANGID 0x00010000 /* languageid=? */
  121625. #define FTS3_HAVE_DOCID_GE 0x00020000 /* docid>=? */
  121626. #define FTS3_HAVE_DOCID_LE 0x00040000 /* docid<=? */
  121627. struct Fts3Doclist {
  121628. char *aAll; /* Array containing doclist (or NULL) */
  121629. int nAll; /* Size of a[] in bytes */
  121630. char *pNextDocid; /* Pointer to next docid */
  121631. sqlite3_int64 iDocid; /* Current docid (if pList!=0) */
  121632. int bFreeList; /* True if pList should be sqlite3_free()d */
  121633. char *pList; /* Pointer to position list following iDocid */
  121634. int nList; /* Length of position list */
  121635. };
  121636. /*
  121637. ** A "phrase" is a sequence of one or more tokens that must match in
  121638. ** sequence. A single token is the base case and the most common case.
  121639. ** For a sequence of tokens contained in double-quotes (i.e. "one two three")
  121640. ** nToken will be the number of tokens in the string.
  121641. */
  121642. struct Fts3PhraseToken {
  121643. char *z; /* Text of the token */
  121644. int n; /* Number of bytes in buffer z */
  121645. int isPrefix; /* True if token ends with a "*" character */
  121646. int bFirst; /* True if token must appear at position 0 */
  121647. /* Variables above this point are populated when the expression is
  121648. ** parsed (by code in fts3_expr.c). Below this point the variables are
  121649. ** used when evaluating the expression. */
  121650. Fts3DeferredToken *pDeferred; /* Deferred token object for this token */
  121651. Fts3MultiSegReader *pSegcsr; /* Segment-reader for this token */
  121652. };
  121653. struct Fts3Phrase {
  121654. /* Cache of doclist for this phrase. */
  121655. Fts3Doclist doclist;
  121656. int bIncr; /* True if doclist is loaded incrementally */
  121657. int iDoclistToken;
  121658. /* Variables below this point are populated by fts3_expr.c when parsing
  121659. ** a MATCH expression. Everything above is part of the evaluation phase.
  121660. */
  121661. int nToken; /* Number of tokens in the phrase */
  121662. int iColumn; /* Index of column this phrase must match */
  121663. Fts3PhraseToken aToken[1]; /* One entry for each token in the phrase */
  121664. };
  121665. /*
  121666. ** A tree of these objects forms the RHS of a MATCH operator.
  121667. **
  121668. ** If Fts3Expr.eType is FTSQUERY_PHRASE and isLoaded is true, then aDoclist
  121669. ** points to a malloced buffer, size nDoclist bytes, containing the results
  121670. ** of this phrase query in FTS3 doclist format. As usual, the initial
  121671. ** "Length" field found in doclists stored on disk is omitted from this
  121672. ** buffer.
  121673. **
  121674. ** Variable aMI is used only for FTSQUERY_NEAR nodes to store the global
  121675. ** matchinfo data. If it is not NULL, it points to an array of size nCol*3,
  121676. ** where nCol is the number of columns in the queried FTS table. The array
  121677. ** is populated as follows:
  121678. **
  121679. ** aMI[iCol*3 + 0] = Undefined
  121680. ** aMI[iCol*3 + 1] = Number of occurrences
  121681. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  121682. **
  121683. ** The aMI array is allocated using sqlite3_malloc(). It should be freed
  121684. ** when the expression node is.
  121685. */
  121686. struct Fts3Expr {
  121687. int eType; /* One of the FTSQUERY_XXX values defined below */
  121688. int nNear; /* Valid if eType==FTSQUERY_NEAR */
  121689. Fts3Expr *pParent; /* pParent->pLeft==this or pParent->pRight==this */
  121690. Fts3Expr *pLeft; /* Left operand */
  121691. Fts3Expr *pRight; /* Right operand */
  121692. Fts3Phrase *pPhrase; /* Valid if eType==FTSQUERY_PHRASE */
  121693. /* The following are used by the fts3_eval.c module. */
  121694. sqlite3_int64 iDocid; /* Current docid */
  121695. u8 bEof; /* True this expression is at EOF already */
  121696. u8 bStart; /* True if iDocid is valid */
  121697. u8 bDeferred; /* True if this expression is entirely deferred */
  121698. u32 *aMI;
  121699. };
  121700. /*
  121701. ** Candidate values for Fts3Query.eType. Note that the order of the first
  121702. ** four values is in order of precedence when parsing expressions. For
  121703. ** example, the following:
  121704. **
  121705. ** "a OR b AND c NOT d NEAR e"
  121706. **
  121707. ** is equivalent to:
  121708. **
  121709. ** "a OR (b AND (c NOT (d NEAR e)))"
  121710. */
  121711. #define FTSQUERY_NEAR 1
  121712. #define FTSQUERY_NOT 2
  121713. #define FTSQUERY_AND 3
  121714. #define FTSQUERY_OR 4
  121715. #define FTSQUERY_PHRASE 5
  121716. /* fts3_write.c */
  121717. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(sqlite3_vtab*,int,sqlite3_value**,sqlite3_int64*);
  121718. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *);
  121719. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *);
  121720. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *);
  121721. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(int, int, sqlite3_int64,
  121722. sqlite3_int64, sqlite3_int64, const char *, int, Fts3SegReader**);
  121723. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  121724. Fts3Table*,int,const char*,int,int,Fts3SegReader**);
  121725. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *);
  121726. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(Fts3Table*, int, int, int, sqlite3_stmt **);
  121727. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(Fts3Table*, sqlite3_int64, char **, int*, int*);
  121728. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(Fts3Table *, sqlite3_stmt **);
  121729. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(Fts3Table *, sqlite3_int64, sqlite3_stmt **);
  121730. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  121731. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *);
  121732. SQLITE_PRIVATE int sqlite3Fts3DeferToken(Fts3Cursor *, Fts3PhraseToken *, int);
  121733. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *);
  121734. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *);
  121735. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(Fts3DeferredToken *, char **, int *);
  121736. #else
  121737. # define sqlite3Fts3FreeDeferredTokens(x)
  121738. # define sqlite3Fts3DeferToken(x,y,z) SQLITE_OK
  121739. # define sqlite3Fts3CacheDeferredDoclists(x) SQLITE_OK
  121740. # define sqlite3Fts3FreeDeferredDoclists(x)
  121741. # define sqlite3Fts3DeferredTokenList(x,y,z) SQLITE_OK
  121742. #endif
  121743. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *);
  121744. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *, int *);
  121745. /* Special values interpreted by sqlite3SegReaderCursor() */
  121746. #define FTS3_SEGCURSOR_PENDING -1
  121747. #define FTS3_SEGCURSOR_ALL -2
  121748. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(Fts3Table*, Fts3MultiSegReader*, Fts3SegFilter*);
  121749. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(Fts3Table *, Fts3MultiSegReader *);
  121750. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(Fts3MultiSegReader *);
  121751. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(Fts3Table *,
  121752. int, int, int, const char *, int, int, int, Fts3MultiSegReader *);
  121753. /* Flags allowed as part of the 4th argument to SegmentReaderIterate() */
  121754. #define FTS3_SEGMENT_REQUIRE_POS 0x00000001
  121755. #define FTS3_SEGMENT_IGNORE_EMPTY 0x00000002
  121756. #define FTS3_SEGMENT_COLUMN_FILTER 0x00000004
  121757. #define FTS3_SEGMENT_PREFIX 0x00000008
  121758. #define FTS3_SEGMENT_SCAN 0x00000010
  121759. #define FTS3_SEGMENT_FIRST 0x00000020
  121760. /* Type passed as 4th argument to SegmentReaderIterate() */
  121761. struct Fts3SegFilter {
  121762. const char *zTerm;
  121763. int nTerm;
  121764. int iCol;
  121765. int flags;
  121766. };
  121767. struct Fts3MultiSegReader {
  121768. /* Used internally by sqlite3Fts3SegReaderXXX() calls */
  121769. Fts3SegReader **apSegment; /* Array of Fts3SegReader objects */
  121770. int nSegment; /* Size of apSegment array */
  121771. int nAdvance; /* How many seg-readers to advance */
  121772. Fts3SegFilter *pFilter; /* Pointer to filter object */
  121773. char *aBuffer; /* Buffer to merge doclists in */
  121774. int nBuffer; /* Allocated size of aBuffer[] in bytes */
  121775. int iColFilter; /* If >=0, filter for this column */
  121776. int bRestart;
  121777. /* Used by fts3.c only. */
  121778. int nCost; /* Cost of running iterator */
  121779. int bLookup; /* True if a lookup of a single entry. */
  121780. /* Output values. Valid only after Fts3SegReaderStep() returns SQLITE_ROW. */
  121781. char *zTerm; /* Pointer to term buffer */
  121782. int nTerm; /* Size of zTerm in bytes */
  121783. char *aDoclist; /* Pointer to doclist buffer */
  121784. int nDoclist; /* Size of aDoclist[] in bytes */
  121785. };
  121786. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table*,int,int);
  121787. #define fts3GetVarint32(p, piVal) ( \
  121788. (*(u8*)(p)&0x80) ? sqlite3Fts3GetVarint32(p, piVal) : (*piVal=*(u8*)(p), 1) \
  121789. )
  121790. /* fts3.c */
  121791. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *, sqlite3_int64);
  121792. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *, sqlite_int64 *);
  121793. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *, int *);
  121794. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64);
  121795. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *);
  121796. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(int,char*,int,char**,sqlite3_int64*,int*,u8*);
  121797. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(Fts3Cursor *, Fts3Expr *, u32 *);
  121798. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(sqlite3_int64, char *, int, char *);
  121799. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int*, Fts3Table*);
  121800. /* fts3_tokenizer.c */
  121801. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *, int *);
  121802. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(sqlite3 *, Fts3Hash *, const char *);
  121803. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(Fts3Hash *pHash, const char *,
  121804. sqlite3_tokenizer **, char **
  121805. );
  121806. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char);
  121807. /* fts3_snippet.c */
  121808. SQLITE_PRIVATE void sqlite3Fts3Offsets(sqlite3_context*, Fts3Cursor*);
  121809. SQLITE_PRIVATE void sqlite3Fts3Snippet(sqlite3_context *, Fts3Cursor *, const char *,
  121810. const char *, const char *, int, int
  121811. );
  121812. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(sqlite3_context *, Fts3Cursor *, const char *);
  121813. /* fts3_expr.c */
  121814. SQLITE_PRIVATE int sqlite3Fts3ExprParse(sqlite3_tokenizer *, int,
  121815. char **, int, int, int, const char *, int, Fts3Expr **, char **
  121816. );
  121817. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *);
  121818. #ifdef SQLITE_TEST
  121819. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3 *db);
  121820. SQLITE_PRIVATE int sqlite3Fts3InitTerm(sqlite3 *db);
  121821. #endif
  121822. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(sqlite3_tokenizer *, int, const char *, int,
  121823. sqlite3_tokenizer_cursor **
  121824. );
  121825. /* fts3_aux.c */
  121826. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db);
  121827. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *);
  121828. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  121829. Fts3Table*, Fts3MultiSegReader*, int, const char*, int);
  121830. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  121831. Fts3Table *, Fts3MultiSegReader *, sqlite3_int64 *, char **, int *);
  121832. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(Fts3Cursor *, Fts3Expr *, int iCol, char **);
  121833. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(Fts3Cursor *, Fts3MultiSegReader *, int *);
  121834. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr);
  121835. /* fts3_tokenize_vtab.c */
  121836. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3*, Fts3Hash *);
  121837. /* fts3_unicode2.c (functions generated by parsing unicode text files) */
  121838. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  121839. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int, int);
  121840. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int);
  121841. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int);
  121842. #endif
  121843. #endif /* !SQLITE_CORE || SQLITE_ENABLE_FTS3 */
  121844. #endif /* _FTSINT_H */
  121845. /************** End of fts3Int.h *********************************************/
  121846. /************** Continuing where we left off in fts3.c ***********************/
  121847. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  121848. #if defined(SQLITE_ENABLE_FTS3) && !defined(SQLITE_CORE)
  121849. # define SQLITE_CORE 1
  121850. #endif
  121851. /* #include <assert.h> */
  121852. /* #include <stdlib.h> */
  121853. /* #include <stddef.h> */
  121854. /* #include <stdio.h> */
  121855. /* #include <string.h> */
  121856. /* #include <stdarg.h> */
  121857. #ifndef SQLITE_CORE
  121858. SQLITE_EXTENSION_INIT1
  121859. #endif
  121860. static int fts3EvalNext(Fts3Cursor *pCsr);
  121861. static int fts3EvalStart(Fts3Cursor *pCsr);
  121862. static int fts3TermSegReaderCursor(
  121863. Fts3Cursor *, const char *, int, int, Fts3MultiSegReader **);
  121864. /*
  121865. ** Write a 64-bit variable-length integer to memory starting at p[0].
  121866. ** The length of data written will be between 1 and FTS3_VARINT_MAX bytes.
  121867. ** The number of bytes written is returned.
  121868. */
  121869. SQLITE_PRIVATE int sqlite3Fts3PutVarint(char *p, sqlite_int64 v){
  121870. unsigned char *q = (unsigned char *) p;
  121871. sqlite_uint64 vu = v;
  121872. do{
  121873. *q++ = (unsigned char) ((vu & 0x7f) | 0x80);
  121874. vu >>= 7;
  121875. }while( vu!=0 );
  121876. q[-1] &= 0x7f; /* turn off high bit in final byte */
  121877. assert( q - (unsigned char *)p <= FTS3_VARINT_MAX );
  121878. return (int) (q - (unsigned char *)p);
  121879. }
  121880. #define GETVARINT_STEP(v, ptr, shift, mask1, mask2, var, ret) \
  121881. v = (v & mask1) | ( (*ptr++) << shift ); \
  121882. if( (v & mask2)==0 ){ var = v; return ret; }
  121883. #define GETVARINT_INIT(v, ptr, shift, mask1, mask2, var, ret) \
  121884. v = (*ptr++); \
  121885. if( (v & mask2)==0 ){ var = v; return ret; }
  121886. /*
  121887. ** Read a 64-bit variable-length integer from memory starting at p[0].
  121888. ** Return the number of bytes read, or 0 on error.
  121889. ** The value is stored in *v.
  121890. */
  121891. SQLITE_PRIVATE int sqlite3Fts3GetVarint(const char *p, sqlite_int64 *v){
  121892. const char *pStart = p;
  121893. u32 a;
  121894. u64 b;
  121895. int shift;
  121896. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *v, 1);
  121897. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *v, 2);
  121898. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *v, 3);
  121899. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *v, 4);
  121900. b = (a & 0x0FFFFFFF );
  121901. for(shift=28; shift<=63; shift+=7){
  121902. u64 c = *p++;
  121903. b += (c&0x7F) << shift;
  121904. if( (c & 0x80)==0 ) break;
  121905. }
  121906. *v = b;
  121907. return (int)(p - pStart);
  121908. }
  121909. /*
  121910. ** Similar to sqlite3Fts3GetVarint(), except that the output is truncated to a
  121911. ** 32-bit integer before it is returned.
  121912. */
  121913. SQLITE_PRIVATE int sqlite3Fts3GetVarint32(const char *p, int *pi){
  121914. u32 a;
  121915. #ifndef fts3GetVarint32
  121916. GETVARINT_INIT(a, p, 0, 0x00, 0x80, *pi, 1);
  121917. #else
  121918. a = (*p++);
  121919. assert( a & 0x80 );
  121920. #endif
  121921. GETVARINT_STEP(a, p, 7, 0x7F, 0x4000, *pi, 2);
  121922. GETVARINT_STEP(a, p, 14, 0x3FFF, 0x200000, *pi, 3);
  121923. GETVARINT_STEP(a, p, 21, 0x1FFFFF, 0x10000000, *pi, 4);
  121924. a = (a & 0x0FFFFFFF );
  121925. *pi = (int)(a | ((u32)(*p & 0x0F) << 28));
  121926. return 5;
  121927. }
  121928. /*
  121929. ** Return the number of bytes required to encode v as a varint
  121930. */
  121931. SQLITE_PRIVATE int sqlite3Fts3VarintLen(sqlite3_uint64 v){
  121932. int i = 0;
  121933. do{
  121934. i++;
  121935. v >>= 7;
  121936. }while( v!=0 );
  121937. return i;
  121938. }
  121939. /*
  121940. ** Convert an SQL-style quoted string into a normal string by removing
  121941. ** the quote characters. The conversion is done in-place. If the
  121942. ** input does not begin with a quote character, then this routine
  121943. ** is a no-op.
  121944. **
  121945. ** Examples:
  121946. **
  121947. ** "abc" becomes abc
  121948. ** 'xyz' becomes xyz
  121949. ** [pqr] becomes pqr
  121950. ** `mno` becomes mno
  121951. **
  121952. */
  121953. SQLITE_PRIVATE void sqlite3Fts3Dequote(char *z){
  121954. char quote; /* Quote character (if any ) */
  121955. quote = z[0];
  121956. if( quote=='[' || quote=='\'' || quote=='"' || quote=='`' ){
  121957. int iIn = 1; /* Index of next byte to read from input */
  121958. int iOut = 0; /* Index of next byte to write to output */
  121959. /* If the first byte was a '[', then the close-quote character is a ']' */
  121960. if( quote=='[' ) quote = ']';
  121961. while( ALWAYS(z[iIn]) ){
  121962. if( z[iIn]==quote ){
  121963. if( z[iIn+1]!=quote ) break;
  121964. z[iOut++] = quote;
  121965. iIn += 2;
  121966. }else{
  121967. z[iOut++] = z[iIn++];
  121968. }
  121969. }
  121970. z[iOut] = '\0';
  121971. }
  121972. }
  121973. /*
  121974. ** Read a single varint from the doclist at *pp and advance *pp to point
  121975. ** to the first byte past the end of the varint. Add the value of the varint
  121976. ** to *pVal.
  121977. */
  121978. static void fts3GetDeltaVarint(char **pp, sqlite3_int64 *pVal){
  121979. sqlite3_int64 iVal;
  121980. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  121981. *pVal += iVal;
  121982. }
  121983. /*
  121984. ** When this function is called, *pp points to the first byte following a
  121985. ** varint that is part of a doclist (or position-list, or any other list
  121986. ** of varints). This function moves *pp to point to the start of that varint,
  121987. ** and sets *pVal by the varint value.
  121988. **
  121989. ** Argument pStart points to the first byte of the doclist that the
  121990. ** varint is part of.
  121991. */
  121992. static void fts3GetReverseVarint(
  121993. char **pp,
  121994. char *pStart,
  121995. sqlite3_int64 *pVal
  121996. ){
  121997. sqlite3_int64 iVal;
  121998. char *p;
  121999. /* Pointer p now points at the first byte past the varint we are
  122000. ** interested in. So, unless the doclist is corrupt, the 0x80 bit is
  122001. ** clear on character p[-1]. */
  122002. for(p = (*pp)-2; p>=pStart && *p&0x80; p--);
  122003. p++;
  122004. *pp = p;
  122005. sqlite3Fts3GetVarint(p, &iVal);
  122006. *pVal = iVal;
  122007. }
  122008. /*
  122009. ** The xDisconnect() virtual table method.
  122010. */
  122011. static int fts3DisconnectMethod(sqlite3_vtab *pVtab){
  122012. Fts3Table *p = (Fts3Table *)pVtab;
  122013. int i;
  122014. assert( p->nPendingData==0 );
  122015. assert( p->pSegments==0 );
  122016. /* Free any prepared statements held */
  122017. for(i=0; i<SizeofArray(p->aStmt); i++){
  122018. sqlite3_finalize(p->aStmt[i]);
  122019. }
  122020. sqlite3_free(p->zSegmentsTbl);
  122021. sqlite3_free(p->zReadExprlist);
  122022. sqlite3_free(p->zWriteExprlist);
  122023. sqlite3_free(p->zContentTbl);
  122024. sqlite3_free(p->zLanguageid);
  122025. /* Invoke the tokenizer destructor to free the tokenizer. */
  122026. p->pTokenizer->pModule->xDestroy(p->pTokenizer);
  122027. sqlite3_free(p);
  122028. return SQLITE_OK;
  122029. }
  122030. /*
  122031. ** Construct one or more SQL statements from the format string given
  122032. ** and then evaluate those statements. The success code is written
  122033. ** into *pRc.
  122034. **
  122035. ** If *pRc is initially non-zero then this routine is a no-op.
  122036. */
  122037. static void fts3DbExec(
  122038. int *pRc, /* Success code */
  122039. sqlite3 *db, /* Database in which to run SQL */
  122040. const char *zFormat, /* Format string for SQL */
  122041. ... /* Arguments to the format string */
  122042. ){
  122043. va_list ap;
  122044. char *zSql;
  122045. if( *pRc ) return;
  122046. va_start(ap, zFormat);
  122047. zSql = sqlite3_vmprintf(zFormat, ap);
  122048. va_end(ap);
  122049. if( zSql==0 ){
  122050. *pRc = SQLITE_NOMEM;
  122051. }else{
  122052. *pRc = sqlite3_exec(db, zSql, 0, 0, 0);
  122053. sqlite3_free(zSql);
  122054. }
  122055. }
  122056. /*
  122057. ** The xDestroy() virtual table method.
  122058. */
  122059. static int fts3DestroyMethod(sqlite3_vtab *pVtab){
  122060. Fts3Table *p = (Fts3Table *)pVtab;
  122061. int rc = SQLITE_OK; /* Return code */
  122062. const char *zDb = p->zDb; /* Name of database (e.g. "main", "temp") */
  122063. sqlite3 *db = p->db; /* Database handle */
  122064. /* Drop the shadow tables */
  122065. if( p->zContentTbl==0 ){
  122066. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_content'", zDb, p->zName);
  122067. }
  122068. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segments'", zDb,p->zName);
  122069. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_segdir'", zDb, p->zName);
  122070. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_docsize'", zDb, p->zName);
  122071. fts3DbExec(&rc, db, "DROP TABLE IF EXISTS %Q.'%q_stat'", zDb, p->zName);
  122072. /* If everything has worked, invoke fts3DisconnectMethod() to free the
  122073. ** memory associated with the Fts3Table structure and return SQLITE_OK.
  122074. ** Otherwise, return an SQLite error code.
  122075. */
  122076. return (rc==SQLITE_OK ? fts3DisconnectMethod(pVtab) : rc);
  122077. }
  122078. /*
  122079. ** Invoke sqlite3_declare_vtab() to declare the schema for the FTS3 table
  122080. ** passed as the first argument. This is done as part of the xConnect()
  122081. ** and xCreate() methods.
  122082. **
  122083. ** If *pRc is non-zero when this function is called, it is a no-op.
  122084. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  122085. ** before returning.
  122086. */
  122087. static void fts3DeclareVtab(int *pRc, Fts3Table *p){
  122088. if( *pRc==SQLITE_OK ){
  122089. int i; /* Iterator variable */
  122090. int rc; /* Return code */
  122091. char *zSql; /* SQL statement passed to declare_vtab() */
  122092. char *zCols; /* List of user defined columns */
  122093. const char *zLanguageid;
  122094. zLanguageid = (p->zLanguageid ? p->zLanguageid : "__langid");
  122095. sqlite3_vtab_config(p->db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  122096. /* Create a list of user columns for the virtual table */
  122097. zCols = sqlite3_mprintf("%Q, ", p->azColumn[0]);
  122098. for(i=1; zCols && i<p->nColumn; i++){
  122099. zCols = sqlite3_mprintf("%z%Q, ", zCols, p->azColumn[i]);
  122100. }
  122101. /* Create the whole "CREATE TABLE" statement to pass to SQLite */
  122102. zSql = sqlite3_mprintf(
  122103. "CREATE TABLE x(%s %Q HIDDEN, docid HIDDEN, %Q HIDDEN)",
  122104. zCols, p->zName, zLanguageid
  122105. );
  122106. if( !zCols || !zSql ){
  122107. rc = SQLITE_NOMEM;
  122108. }else{
  122109. rc = sqlite3_declare_vtab(p->db, zSql);
  122110. }
  122111. sqlite3_free(zSql);
  122112. sqlite3_free(zCols);
  122113. *pRc = rc;
  122114. }
  122115. }
  122116. /*
  122117. ** Create the %_stat table if it does not already exist.
  122118. */
  122119. SQLITE_PRIVATE void sqlite3Fts3CreateStatTable(int *pRc, Fts3Table *p){
  122120. fts3DbExec(pRc, p->db,
  122121. "CREATE TABLE IF NOT EXISTS %Q.'%q_stat'"
  122122. "(id INTEGER PRIMARY KEY, value BLOB);",
  122123. p->zDb, p->zName
  122124. );
  122125. if( (*pRc)==SQLITE_OK ) p->bHasStat = 1;
  122126. }
  122127. /*
  122128. ** Create the backing store tables (%_content, %_segments and %_segdir)
  122129. ** required by the FTS3 table passed as the only argument. This is done
  122130. ** as part of the vtab xCreate() method.
  122131. **
  122132. ** If the p->bHasDocsize boolean is true (indicating that this is an
  122133. ** FTS4 table, not an FTS3 table) then also create the %_docsize and
  122134. ** %_stat tables required by FTS4.
  122135. */
  122136. static int fts3CreateTables(Fts3Table *p){
  122137. int rc = SQLITE_OK; /* Return code */
  122138. int i; /* Iterator variable */
  122139. sqlite3 *db = p->db; /* The database connection */
  122140. if( p->zContentTbl==0 ){
  122141. const char *zLanguageid = p->zLanguageid;
  122142. char *zContentCols; /* Columns of %_content table */
  122143. /* Create a list of user columns for the content table */
  122144. zContentCols = sqlite3_mprintf("docid INTEGER PRIMARY KEY");
  122145. for(i=0; zContentCols && i<p->nColumn; i++){
  122146. char *z = p->azColumn[i];
  122147. zContentCols = sqlite3_mprintf("%z, 'c%d%q'", zContentCols, i, z);
  122148. }
  122149. if( zLanguageid && zContentCols ){
  122150. zContentCols = sqlite3_mprintf("%z, langid", zContentCols, zLanguageid);
  122151. }
  122152. if( zContentCols==0 ) rc = SQLITE_NOMEM;
  122153. /* Create the content table */
  122154. fts3DbExec(&rc, db,
  122155. "CREATE TABLE %Q.'%q_content'(%s)",
  122156. p->zDb, p->zName, zContentCols
  122157. );
  122158. sqlite3_free(zContentCols);
  122159. }
  122160. /* Create other tables */
  122161. fts3DbExec(&rc, db,
  122162. "CREATE TABLE %Q.'%q_segments'(blockid INTEGER PRIMARY KEY, block BLOB);",
  122163. p->zDb, p->zName
  122164. );
  122165. fts3DbExec(&rc, db,
  122166. "CREATE TABLE %Q.'%q_segdir'("
  122167. "level INTEGER,"
  122168. "idx INTEGER,"
  122169. "start_block INTEGER,"
  122170. "leaves_end_block INTEGER,"
  122171. "end_block INTEGER,"
  122172. "root BLOB,"
  122173. "PRIMARY KEY(level, idx)"
  122174. ");",
  122175. p->zDb, p->zName
  122176. );
  122177. if( p->bHasDocsize ){
  122178. fts3DbExec(&rc, db,
  122179. "CREATE TABLE %Q.'%q_docsize'(docid INTEGER PRIMARY KEY, size BLOB);",
  122180. p->zDb, p->zName
  122181. );
  122182. }
  122183. assert( p->bHasStat==p->bFts4 );
  122184. if( p->bHasStat ){
  122185. sqlite3Fts3CreateStatTable(&rc, p);
  122186. }
  122187. return rc;
  122188. }
  122189. /*
  122190. ** Store the current database page-size in bytes in p->nPgsz.
  122191. **
  122192. ** If *pRc is non-zero when this function is called, it is a no-op.
  122193. ** Otherwise, if an error occurs, an SQLite error code is stored in *pRc
  122194. ** before returning.
  122195. */
  122196. static void fts3DatabasePageSize(int *pRc, Fts3Table *p){
  122197. if( *pRc==SQLITE_OK ){
  122198. int rc; /* Return code */
  122199. char *zSql; /* SQL text "PRAGMA %Q.page_size" */
  122200. sqlite3_stmt *pStmt; /* Compiled "PRAGMA %Q.page_size" statement */
  122201. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", p->zDb);
  122202. if( !zSql ){
  122203. rc = SQLITE_NOMEM;
  122204. }else{
  122205. rc = sqlite3_prepare(p->db, zSql, -1, &pStmt, 0);
  122206. if( rc==SQLITE_OK ){
  122207. sqlite3_step(pStmt);
  122208. p->nPgsz = sqlite3_column_int(pStmt, 0);
  122209. rc = sqlite3_finalize(pStmt);
  122210. }else if( rc==SQLITE_AUTH ){
  122211. p->nPgsz = 1024;
  122212. rc = SQLITE_OK;
  122213. }
  122214. }
  122215. assert( p->nPgsz>0 || rc!=SQLITE_OK );
  122216. sqlite3_free(zSql);
  122217. *pRc = rc;
  122218. }
  122219. }
  122220. /*
  122221. ** "Special" FTS4 arguments are column specifications of the following form:
  122222. **
  122223. ** <key> = <value>
  122224. **
  122225. ** There may not be whitespace surrounding the "=" character. The <value>
  122226. ** term may be quoted, but the <key> may not.
  122227. */
  122228. static int fts3IsSpecialColumn(
  122229. const char *z,
  122230. int *pnKey,
  122231. char **pzValue
  122232. ){
  122233. char *zValue;
  122234. const char *zCsr = z;
  122235. while( *zCsr!='=' ){
  122236. if( *zCsr=='\0' ) return 0;
  122237. zCsr++;
  122238. }
  122239. *pnKey = (int)(zCsr-z);
  122240. zValue = sqlite3_mprintf("%s", &zCsr[1]);
  122241. if( zValue ){
  122242. sqlite3Fts3Dequote(zValue);
  122243. }
  122244. *pzValue = zValue;
  122245. return 1;
  122246. }
  122247. /*
  122248. ** Append the output of a printf() style formatting to an existing string.
  122249. */
  122250. static void fts3Appendf(
  122251. int *pRc, /* IN/OUT: Error code */
  122252. char **pz, /* IN/OUT: Pointer to string buffer */
  122253. const char *zFormat, /* Printf format string to append */
  122254. ... /* Arguments for printf format string */
  122255. ){
  122256. if( *pRc==SQLITE_OK ){
  122257. va_list ap;
  122258. char *z;
  122259. va_start(ap, zFormat);
  122260. z = sqlite3_vmprintf(zFormat, ap);
  122261. va_end(ap);
  122262. if( z && *pz ){
  122263. char *z2 = sqlite3_mprintf("%s%s", *pz, z);
  122264. sqlite3_free(z);
  122265. z = z2;
  122266. }
  122267. if( z==0 ) *pRc = SQLITE_NOMEM;
  122268. sqlite3_free(*pz);
  122269. *pz = z;
  122270. }
  122271. }
  122272. /*
  122273. ** Return a copy of input string zInput enclosed in double-quotes (") and
  122274. ** with all double quote characters escaped. For example:
  122275. **
  122276. ** fts3QuoteId("un \"zip\"") -> "un \"\"zip\"\""
  122277. **
  122278. ** The pointer returned points to memory obtained from sqlite3_malloc(). It
  122279. ** is the callers responsibility to call sqlite3_free() to release this
  122280. ** memory.
  122281. */
  122282. static char *fts3QuoteId(char const *zInput){
  122283. int nRet;
  122284. char *zRet;
  122285. nRet = 2 + (int)strlen(zInput)*2 + 1;
  122286. zRet = sqlite3_malloc(nRet);
  122287. if( zRet ){
  122288. int i;
  122289. char *z = zRet;
  122290. *(z++) = '"';
  122291. for(i=0; zInput[i]; i++){
  122292. if( zInput[i]=='"' ) *(z++) = '"';
  122293. *(z++) = zInput[i];
  122294. }
  122295. *(z++) = '"';
  122296. *(z++) = '\0';
  122297. }
  122298. return zRet;
  122299. }
  122300. /*
  122301. ** Return a list of comma separated SQL expressions and a FROM clause that
  122302. ** could be used in a SELECT statement such as the following:
  122303. **
  122304. ** SELECT <list of expressions> FROM %_content AS x ...
  122305. **
  122306. ** to return the docid, followed by each column of text data in order
  122307. ** from left to write. If parameter zFunc is not NULL, then instead of
  122308. ** being returned directly each column of text data is passed to an SQL
  122309. ** function named zFunc first. For example, if zFunc is "unzip" and the
  122310. ** table has the three user-defined columns "a", "b", and "c", the following
  122311. ** string is returned:
  122312. **
  122313. ** "docid, unzip(x.'a'), unzip(x.'b'), unzip(x.'c') FROM %_content AS x"
  122314. **
  122315. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  122316. ** is the responsibility of the caller to eventually free it.
  122317. **
  122318. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  122319. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  122320. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  122321. ** no error occurs, *pRc is left unmodified.
  122322. */
  122323. static char *fts3ReadExprList(Fts3Table *p, const char *zFunc, int *pRc){
  122324. char *zRet = 0;
  122325. char *zFree = 0;
  122326. char *zFunction;
  122327. int i;
  122328. if( p->zContentTbl==0 ){
  122329. if( !zFunc ){
  122330. zFunction = "";
  122331. }else{
  122332. zFree = zFunction = fts3QuoteId(zFunc);
  122333. }
  122334. fts3Appendf(pRc, &zRet, "docid");
  122335. for(i=0; i<p->nColumn; i++){
  122336. fts3Appendf(pRc, &zRet, ",%s(x.'c%d%q')", zFunction, i, p->azColumn[i]);
  122337. }
  122338. if( p->zLanguageid ){
  122339. fts3Appendf(pRc, &zRet, ", x.%Q", "langid");
  122340. }
  122341. sqlite3_free(zFree);
  122342. }else{
  122343. fts3Appendf(pRc, &zRet, "rowid");
  122344. for(i=0; i<p->nColumn; i++){
  122345. fts3Appendf(pRc, &zRet, ", x.'%q'", p->azColumn[i]);
  122346. }
  122347. if( p->zLanguageid ){
  122348. fts3Appendf(pRc, &zRet, ", x.%Q", p->zLanguageid);
  122349. }
  122350. }
  122351. fts3Appendf(pRc, &zRet, " FROM '%q'.'%q%s' AS x",
  122352. p->zDb,
  122353. (p->zContentTbl ? p->zContentTbl : p->zName),
  122354. (p->zContentTbl ? "" : "_content")
  122355. );
  122356. return zRet;
  122357. }
  122358. /*
  122359. ** Return a list of N comma separated question marks, where N is the number
  122360. ** of columns in the %_content table (one for the docid plus one for each
  122361. ** user-defined text column).
  122362. **
  122363. ** If argument zFunc is not NULL, then all but the first question mark
  122364. ** is preceded by zFunc and an open bracket, and followed by a closed
  122365. ** bracket. For example, if zFunc is "zip" and the FTS3 table has three
  122366. ** user-defined text columns, the following string is returned:
  122367. **
  122368. ** "?, zip(?), zip(?), zip(?)"
  122369. **
  122370. ** The pointer returned points to a buffer allocated by sqlite3_malloc(). It
  122371. ** is the responsibility of the caller to eventually free it.
  122372. **
  122373. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op (and
  122374. ** a NULL pointer is returned). Otherwise, if an OOM error is encountered
  122375. ** by this function, NULL is returned and *pRc is set to SQLITE_NOMEM. If
  122376. ** no error occurs, *pRc is left unmodified.
  122377. */
  122378. static char *fts3WriteExprList(Fts3Table *p, const char *zFunc, int *pRc){
  122379. char *zRet = 0;
  122380. char *zFree = 0;
  122381. char *zFunction;
  122382. int i;
  122383. if( !zFunc ){
  122384. zFunction = "";
  122385. }else{
  122386. zFree = zFunction = fts3QuoteId(zFunc);
  122387. }
  122388. fts3Appendf(pRc, &zRet, "?");
  122389. for(i=0; i<p->nColumn; i++){
  122390. fts3Appendf(pRc, &zRet, ",%s(?)", zFunction);
  122391. }
  122392. if( p->zLanguageid ){
  122393. fts3Appendf(pRc, &zRet, ", ?");
  122394. }
  122395. sqlite3_free(zFree);
  122396. return zRet;
  122397. }
  122398. /*
  122399. ** This function interprets the string at (*pp) as a non-negative integer
  122400. ** value. It reads the integer and sets *pnOut to the value read, then
  122401. ** sets *pp to point to the byte immediately following the last byte of
  122402. ** the integer value.
  122403. **
  122404. ** Only decimal digits ('0'..'9') may be part of an integer value.
  122405. **
  122406. ** If *pp does not being with a decimal digit SQLITE_ERROR is returned and
  122407. ** the output value undefined. Otherwise SQLITE_OK is returned.
  122408. **
  122409. ** This function is used when parsing the "prefix=" FTS4 parameter.
  122410. */
  122411. static int fts3GobbleInt(const char **pp, int *pnOut){
  122412. const char *p; /* Iterator pointer */
  122413. int nInt = 0; /* Output value */
  122414. for(p=*pp; p[0]>='0' && p[0]<='9'; p++){
  122415. nInt = nInt * 10 + (p[0] - '0');
  122416. }
  122417. if( p==*pp ) return SQLITE_ERROR;
  122418. *pnOut = nInt;
  122419. *pp = p;
  122420. return SQLITE_OK;
  122421. }
  122422. /*
  122423. ** This function is called to allocate an array of Fts3Index structures
  122424. ** representing the indexes maintained by the current FTS table. FTS tables
  122425. ** always maintain the main "terms" index, but may also maintain one or
  122426. ** more "prefix" indexes, depending on the value of the "prefix=" parameter
  122427. ** (if any) specified as part of the CREATE VIRTUAL TABLE statement.
  122428. **
  122429. ** Argument zParam is passed the value of the "prefix=" option if one was
  122430. ** specified, or NULL otherwise.
  122431. **
  122432. ** If no error occurs, SQLITE_OK is returned and *apIndex set to point to
  122433. ** the allocated array. *pnIndex is set to the number of elements in the
  122434. ** array. If an error does occur, an SQLite error code is returned.
  122435. **
  122436. ** Regardless of whether or not an error is returned, it is the responsibility
  122437. ** of the caller to call sqlite3_free() on the output array to free it.
  122438. */
  122439. static int fts3PrefixParameter(
  122440. const char *zParam, /* ABC in prefix=ABC parameter to parse */
  122441. int *pnIndex, /* OUT: size of *apIndex[] array */
  122442. struct Fts3Index **apIndex /* OUT: Array of indexes for this table */
  122443. ){
  122444. struct Fts3Index *aIndex; /* Allocated array */
  122445. int nIndex = 1; /* Number of entries in array */
  122446. if( zParam && zParam[0] ){
  122447. const char *p;
  122448. nIndex++;
  122449. for(p=zParam; *p; p++){
  122450. if( *p==',' ) nIndex++;
  122451. }
  122452. }
  122453. aIndex = sqlite3_malloc(sizeof(struct Fts3Index) * nIndex);
  122454. *apIndex = aIndex;
  122455. *pnIndex = nIndex;
  122456. if( !aIndex ){
  122457. return SQLITE_NOMEM;
  122458. }
  122459. memset(aIndex, 0, sizeof(struct Fts3Index) * nIndex);
  122460. if( zParam ){
  122461. const char *p = zParam;
  122462. int i;
  122463. for(i=1; i<nIndex; i++){
  122464. int nPrefix;
  122465. if( fts3GobbleInt(&p, &nPrefix) ) return SQLITE_ERROR;
  122466. aIndex[i].nPrefix = nPrefix;
  122467. p++;
  122468. }
  122469. }
  122470. return SQLITE_OK;
  122471. }
  122472. /*
  122473. ** This function is called when initializing an FTS4 table that uses the
  122474. ** content=xxx option. It determines the number of and names of the columns
  122475. ** of the new FTS4 table.
  122476. **
  122477. ** The third argument passed to this function is the value passed to the
  122478. ** config=xxx option (i.e. "xxx"). This function queries the database for
  122479. ** a table of that name. If found, the output variables are populated
  122480. ** as follows:
  122481. **
  122482. ** *pnCol: Set to the number of columns table xxx has,
  122483. **
  122484. ** *pnStr: Set to the total amount of space required to store a copy
  122485. ** of each columns name, including the nul-terminator.
  122486. **
  122487. ** *pazCol: Set to point to an array of *pnCol strings. Each string is
  122488. ** the name of the corresponding column in table xxx. The array
  122489. ** and its contents are allocated using a single allocation. It
  122490. ** is the responsibility of the caller to free this allocation
  122491. ** by eventually passing the *pazCol value to sqlite3_free().
  122492. **
  122493. ** If the table cannot be found, an error code is returned and the output
  122494. ** variables are undefined. Or, if an OOM is encountered, SQLITE_NOMEM is
  122495. ** returned (and the output variables are undefined).
  122496. */
  122497. static int fts3ContentColumns(
  122498. sqlite3 *db, /* Database handle */
  122499. const char *zDb, /* Name of db (i.e. "main", "temp" etc.) */
  122500. const char *zTbl, /* Name of content table */
  122501. const char ***pazCol, /* OUT: Malloc'd array of column names */
  122502. int *pnCol, /* OUT: Size of array *pazCol */
  122503. int *pnStr /* OUT: Bytes of string content */
  122504. ){
  122505. int rc = SQLITE_OK; /* Return code */
  122506. char *zSql; /* "SELECT *" statement on zTbl */
  122507. sqlite3_stmt *pStmt = 0; /* Compiled version of zSql */
  122508. zSql = sqlite3_mprintf("SELECT * FROM %Q.%Q", zDb, zTbl);
  122509. if( !zSql ){
  122510. rc = SQLITE_NOMEM;
  122511. }else{
  122512. rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
  122513. }
  122514. sqlite3_free(zSql);
  122515. if( rc==SQLITE_OK ){
  122516. const char **azCol; /* Output array */
  122517. int nStr = 0; /* Size of all column names (incl. 0x00) */
  122518. int nCol; /* Number of table columns */
  122519. int i; /* Used to iterate through columns */
  122520. /* Loop through the returned columns. Set nStr to the number of bytes of
  122521. ** space required to store a copy of each column name, including the
  122522. ** nul-terminator byte. */
  122523. nCol = sqlite3_column_count(pStmt);
  122524. for(i=0; i<nCol; i++){
  122525. const char *zCol = sqlite3_column_name(pStmt, i);
  122526. nStr += (int)strlen(zCol) + 1;
  122527. }
  122528. /* Allocate and populate the array to return. */
  122529. azCol = (const char **)sqlite3_malloc(sizeof(char *) * nCol + nStr);
  122530. if( azCol==0 ){
  122531. rc = SQLITE_NOMEM;
  122532. }else{
  122533. char *p = (char *)&azCol[nCol];
  122534. for(i=0; i<nCol; i++){
  122535. const char *zCol = sqlite3_column_name(pStmt, i);
  122536. int n = (int)strlen(zCol)+1;
  122537. memcpy(p, zCol, n);
  122538. azCol[i] = p;
  122539. p += n;
  122540. }
  122541. }
  122542. sqlite3_finalize(pStmt);
  122543. /* Set the output variables. */
  122544. *pnCol = nCol;
  122545. *pnStr = nStr;
  122546. *pazCol = azCol;
  122547. }
  122548. return rc;
  122549. }
  122550. /*
  122551. ** This function is the implementation of both the xConnect and xCreate
  122552. ** methods of the FTS3 virtual table.
  122553. **
  122554. ** The argv[] array contains the following:
  122555. **
  122556. ** argv[0] -> module name ("fts3" or "fts4")
  122557. ** argv[1] -> database name
  122558. ** argv[2] -> table name
  122559. ** argv[...] -> "column name" and other module argument fields.
  122560. */
  122561. static int fts3InitVtab(
  122562. int isCreate, /* True for xCreate, false for xConnect */
  122563. sqlite3 *db, /* The SQLite database connection */
  122564. void *pAux, /* Hash table containing tokenizers */
  122565. int argc, /* Number of elements in argv array */
  122566. const char * const *argv, /* xCreate/xConnect argument array */
  122567. sqlite3_vtab **ppVTab, /* Write the resulting vtab structure here */
  122568. char **pzErr /* Write any error message here */
  122569. ){
  122570. Fts3Hash *pHash = (Fts3Hash *)pAux;
  122571. Fts3Table *p = 0; /* Pointer to allocated vtab */
  122572. int rc = SQLITE_OK; /* Return code */
  122573. int i; /* Iterator variable */
  122574. int nByte; /* Size of allocation used for *p */
  122575. int iCol; /* Column index */
  122576. int nString = 0; /* Bytes required to hold all column names */
  122577. int nCol = 0; /* Number of columns in the FTS table */
  122578. char *zCsr; /* Space for holding column names */
  122579. int nDb; /* Bytes required to hold database name */
  122580. int nName; /* Bytes required to hold table name */
  122581. int isFts4 = (argv[0][3]=='4'); /* True for FTS4, false for FTS3 */
  122582. const char **aCol; /* Array of column names */
  122583. sqlite3_tokenizer *pTokenizer = 0; /* Tokenizer for this table */
  122584. int nIndex; /* Size of aIndex[] array */
  122585. struct Fts3Index *aIndex = 0; /* Array of indexes for this table */
  122586. /* The results of parsing supported FTS4 key=value options: */
  122587. int bNoDocsize = 0; /* True to omit %_docsize table */
  122588. int bDescIdx = 0; /* True to store descending indexes */
  122589. char *zPrefix = 0; /* Prefix parameter value (or NULL) */
  122590. char *zCompress = 0; /* compress=? parameter (or NULL) */
  122591. char *zUncompress = 0; /* uncompress=? parameter (or NULL) */
  122592. char *zContent = 0; /* content=? parameter (or NULL) */
  122593. char *zLanguageid = 0; /* languageid=? parameter (or NULL) */
  122594. char **azNotindexed = 0; /* The set of notindexed= columns */
  122595. int nNotindexed = 0; /* Size of azNotindexed[] array */
  122596. assert( strlen(argv[0])==4 );
  122597. assert( (sqlite3_strnicmp(argv[0], "fts4", 4)==0 && isFts4)
  122598. || (sqlite3_strnicmp(argv[0], "fts3", 4)==0 && !isFts4)
  122599. );
  122600. nDb = (int)strlen(argv[1]) + 1;
  122601. nName = (int)strlen(argv[2]) + 1;
  122602. nByte = sizeof(const char *) * (argc-2);
  122603. aCol = (const char **)sqlite3_malloc(nByte);
  122604. if( aCol ){
  122605. memset((void*)aCol, 0, nByte);
  122606. azNotindexed = (char **)sqlite3_malloc(nByte);
  122607. }
  122608. if( azNotindexed ){
  122609. memset(azNotindexed, 0, nByte);
  122610. }
  122611. if( !aCol || !azNotindexed ){
  122612. rc = SQLITE_NOMEM;
  122613. goto fts3_init_out;
  122614. }
  122615. /* Loop through all of the arguments passed by the user to the FTS3/4
  122616. ** module (i.e. all the column names and special arguments). This loop
  122617. ** does the following:
  122618. **
  122619. ** + Figures out the number of columns the FTSX table will have, and
  122620. ** the number of bytes of space that must be allocated to store copies
  122621. ** of the column names.
  122622. **
  122623. ** + If there is a tokenizer specification included in the arguments,
  122624. ** initializes the tokenizer pTokenizer.
  122625. */
  122626. for(i=3; rc==SQLITE_OK && i<argc; i++){
  122627. char const *z = argv[i];
  122628. int nKey;
  122629. char *zVal;
  122630. /* Check if this is a tokenizer specification */
  122631. if( !pTokenizer
  122632. && strlen(z)>8
  122633. && 0==sqlite3_strnicmp(z, "tokenize", 8)
  122634. && 0==sqlite3Fts3IsIdChar(z[8])
  122635. ){
  122636. rc = sqlite3Fts3InitTokenizer(pHash, &z[9], &pTokenizer, pzErr);
  122637. }
  122638. /* Check if it is an FTS4 special argument. */
  122639. else if( isFts4 && fts3IsSpecialColumn(z, &nKey, &zVal) ){
  122640. struct Fts4Option {
  122641. const char *zOpt;
  122642. int nOpt;
  122643. } aFts4Opt[] = {
  122644. { "matchinfo", 9 }, /* 0 -> MATCHINFO */
  122645. { "prefix", 6 }, /* 1 -> PREFIX */
  122646. { "compress", 8 }, /* 2 -> COMPRESS */
  122647. { "uncompress", 10 }, /* 3 -> UNCOMPRESS */
  122648. { "order", 5 }, /* 4 -> ORDER */
  122649. { "content", 7 }, /* 5 -> CONTENT */
  122650. { "languageid", 10 }, /* 6 -> LANGUAGEID */
  122651. { "notindexed", 10 } /* 7 -> NOTINDEXED */
  122652. };
  122653. int iOpt;
  122654. if( !zVal ){
  122655. rc = SQLITE_NOMEM;
  122656. }else{
  122657. for(iOpt=0; iOpt<SizeofArray(aFts4Opt); iOpt++){
  122658. struct Fts4Option *pOp = &aFts4Opt[iOpt];
  122659. if( nKey==pOp->nOpt && !sqlite3_strnicmp(z, pOp->zOpt, pOp->nOpt) ){
  122660. break;
  122661. }
  122662. }
  122663. if( iOpt==SizeofArray(aFts4Opt) ){
  122664. *pzErr = sqlite3_mprintf("unrecognized parameter: %s", z);
  122665. rc = SQLITE_ERROR;
  122666. }else{
  122667. switch( iOpt ){
  122668. case 0: /* MATCHINFO */
  122669. if( strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "fts3", 4) ){
  122670. *pzErr = sqlite3_mprintf("unrecognized matchinfo: %s", zVal);
  122671. rc = SQLITE_ERROR;
  122672. }
  122673. bNoDocsize = 1;
  122674. break;
  122675. case 1: /* PREFIX */
  122676. sqlite3_free(zPrefix);
  122677. zPrefix = zVal;
  122678. zVal = 0;
  122679. break;
  122680. case 2: /* COMPRESS */
  122681. sqlite3_free(zCompress);
  122682. zCompress = zVal;
  122683. zVal = 0;
  122684. break;
  122685. case 3: /* UNCOMPRESS */
  122686. sqlite3_free(zUncompress);
  122687. zUncompress = zVal;
  122688. zVal = 0;
  122689. break;
  122690. case 4: /* ORDER */
  122691. if( (strlen(zVal)!=3 || sqlite3_strnicmp(zVal, "asc", 3))
  122692. && (strlen(zVal)!=4 || sqlite3_strnicmp(zVal, "desc", 4))
  122693. ){
  122694. *pzErr = sqlite3_mprintf("unrecognized order: %s", zVal);
  122695. rc = SQLITE_ERROR;
  122696. }
  122697. bDescIdx = (zVal[0]=='d' || zVal[0]=='D');
  122698. break;
  122699. case 5: /* CONTENT */
  122700. sqlite3_free(zContent);
  122701. zContent = zVal;
  122702. zVal = 0;
  122703. break;
  122704. case 6: /* LANGUAGEID */
  122705. assert( iOpt==6 );
  122706. sqlite3_free(zLanguageid);
  122707. zLanguageid = zVal;
  122708. zVal = 0;
  122709. break;
  122710. case 7: /* NOTINDEXED */
  122711. azNotindexed[nNotindexed++] = zVal;
  122712. zVal = 0;
  122713. break;
  122714. }
  122715. }
  122716. sqlite3_free(zVal);
  122717. }
  122718. }
  122719. /* Otherwise, the argument is a column name. */
  122720. else {
  122721. nString += (int)(strlen(z) + 1);
  122722. aCol[nCol++] = z;
  122723. }
  122724. }
  122725. /* If a content=xxx option was specified, the following:
  122726. **
  122727. ** 1. Ignore any compress= and uncompress= options.
  122728. **
  122729. ** 2. If no column names were specified as part of the CREATE VIRTUAL
  122730. ** TABLE statement, use all columns from the content table.
  122731. */
  122732. if( rc==SQLITE_OK && zContent ){
  122733. sqlite3_free(zCompress);
  122734. sqlite3_free(zUncompress);
  122735. zCompress = 0;
  122736. zUncompress = 0;
  122737. if( nCol==0 ){
  122738. sqlite3_free((void*)aCol);
  122739. aCol = 0;
  122740. rc = fts3ContentColumns(db, argv[1], zContent, &aCol, &nCol, &nString);
  122741. /* If a languageid= option was specified, remove the language id
  122742. ** column from the aCol[] array. */
  122743. if( rc==SQLITE_OK && zLanguageid ){
  122744. int j;
  122745. for(j=0; j<nCol; j++){
  122746. if( sqlite3_stricmp(zLanguageid, aCol[j])==0 ){
  122747. int k;
  122748. for(k=j; k<nCol; k++) aCol[k] = aCol[k+1];
  122749. nCol--;
  122750. break;
  122751. }
  122752. }
  122753. }
  122754. }
  122755. }
  122756. if( rc!=SQLITE_OK ) goto fts3_init_out;
  122757. if( nCol==0 ){
  122758. assert( nString==0 );
  122759. aCol[0] = "content";
  122760. nString = 8;
  122761. nCol = 1;
  122762. }
  122763. if( pTokenizer==0 ){
  122764. rc = sqlite3Fts3InitTokenizer(pHash, "simple", &pTokenizer, pzErr);
  122765. if( rc!=SQLITE_OK ) goto fts3_init_out;
  122766. }
  122767. assert( pTokenizer );
  122768. rc = fts3PrefixParameter(zPrefix, &nIndex, &aIndex);
  122769. if( rc==SQLITE_ERROR ){
  122770. assert( zPrefix );
  122771. *pzErr = sqlite3_mprintf("error parsing prefix parameter: %s", zPrefix);
  122772. }
  122773. if( rc!=SQLITE_OK ) goto fts3_init_out;
  122774. /* Allocate and populate the Fts3Table structure. */
  122775. nByte = sizeof(Fts3Table) + /* Fts3Table */
  122776. nCol * sizeof(char *) + /* azColumn */
  122777. nIndex * sizeof(struct Fts3Index) + /* aIndex */
  122778. nCol * sizeof(u8) + /* abNotindexed */
  122779. nName + /* zName */
  122780. nDb + /* zDb */
  122781. nString; /* Space for azColumn strings */
  122782. p = (Fts3Table*)sqlite3_malloc(nByte);
  122783. if( p==0 ){
  122784. rc = SQLITE_NOMEM;
  122785. goto fts3_init_out;
  122786. }
  122787. memset(p, 0, nByte);
  122788. p->db = db;
  122789. p->nColumn = nCol;
  122790. p->nPendingData = 0;
  122791. p->azColumn = (char **)&p[1];
  122792. p->pTokenizer = pTokenizer;
  122793. p->nMaxPendingData = FTS3_MAX_PENDING_DATA;
  122794. p->bHasDocsize = (isFts4 && bNoDocsize==0);
  122795. p->bHasStat = isFts4;
  122796. p->bFts4 = isFts4;
  122797. p->bDescIdx = bDescIdx;
  122798. p->nAutoincrmerge = 0xff; /* 0xff means setting unknown */
  122799. p->zContentTbl = zContent;
  122800. p->zLanguageid = zLanguageid;
  122801. zContent = 0;
  122802. zLanguageid = 0;
  122803. TESTONLY( p->inTransaction = -1 );
  122804. TESTONLY( p->mxSavepoint = -1 );
  122805. p->aIndex = (struct Fts3Index *)&p->azColumn[nCol];
  122806. memcpy(p->aIndex, aIndex, sizeof(struct Fts3Index) * nIndex);
  122807. p->nIndex = nIndex;
  122808. for(i=0; i<nIndex; i++){
  122809. fts3HashInit(&p->aIndex[i].hPending, FTS3_HASH_STRING, 1);
  122810. }
  122811. p->abNotindexed = (u8 *)&p->aIndex[nIndex];
  122812. /* Fill in the zName and zDb fields of the vtab structure. */
  122813. zCsr = (char *)&p->abNotindexed[nCol];
  122814. p->zName = zCsr;
  122815. memcpy(zCsr, argv[2], nName);
  122816. zCsr += nName;
  122817. p->zDb = zCsr;
  122818. memcpy(zCsr, argv[1], nDb);
  122819. zCsr += nDb;
  122820. /* Fill in the azColumn array */
  122821. for(iCol=0; iCol<nCol; iCol++){
  122822. char *z;
  122823. int n = 0;
  122824. z = (char *)sqlite3Fts3NextToken(aCol[iCol], &n);
  122825. memcpy(zCsr, z, n);
  122826. zCsr[n] = '\0';
  122827. sqlite3Fts3Dequote(zCsr);
  122828. p->azColumn[iCol] = zCsr;
  122829. zCsr += n+1;
  122830. assert( zCsr <= &((char *)p)[nByte] );
  122831. }
  122832. /* Fill in the abNotindexed array */
  122833. for(iCol=0; iCol<nCol; iCol++){
  122834. int n = (int)strlen(p->azColumn[iCol]);
  122835. for(i=0; i<nNotindexed; i++){
  122836. char *zNot = azNotindexed[i];
  122837. if( zNot && n==(int)strlen(zNot)
  122838. && 0==sqlite3_strnicmp(p->azColumn[iCol], zNot, n)
  122839. ){
  122840. p->abNotindexed[iCol] = 1;
  122841. sqlite3_free(zNot);
  122842. azNotindexed[i] = 0;
  122843. }
  122844. }
  122845. }
  122846. for(i=0; i<nNotindexed; i++){
  122847. if( azNotindexed[i] ){
  122848. *pzErr = sqlite3_mprintf("no such column: %s", azNotindexed[i]);
  122849. rc = SQLITE_ERROR;
  122850. }
  122851. }
  122852. if( rc==SQLITE_OK && (zCompress==0)!=(zUncompress==0) ){
  122853. char const *zMiss = (zCompress==0 ? "compress" : "uncompress");
  122854. rc = SQLITE_ERROR;
  122855. *pzErr = sqlite3_mprintf("missing %s parameter in fts4 constructor", zMiss);
  122856. }
  122857. p->zReadExprlist = fts3ReadExprList(p, zUncompress, &rc);
  122858. p->zWriteExprlist = fts3WriteExprList(p, zCompress, &rc);
  122859. if( rc!=SQLITE_OK ) goto fts3_init_out;
  122860. /* If this is an xCreate call, create the underlying tables in the
  122861. ** database. TODO: For xConnect(), it could verify that said tables exist.
  122862. */
  122863. if( isCreate ){
  122864. rc = fts3CreateTables(p);
  122865. }
  122866. /* Check to see if a legacy fts3 table has been "upgraded" by the
  122867. ** addition of a %_stat table so that it can use incremental merge.
  122868. */
  122869. if( !isFts4 && !isCreate ){
  122870. p->bHasStat = 2;
  122871. }
  122872. /* Figure out the page-size for the database. This is required in order to
  122873. ** estimate the cost of loading large doclists from the database. */
  122874. fts3DatabasePageSize(&rc, p);
  122875. p->nNodeSize = p->nPgsz-35;
  122876. /* Declare the table schema to SQLite. */
  122877. fts3DeclareVtab(&rc, p);
  122878. fts3_init_out:
  122879. sqlite3_free(zPrefix);
  122880. sqlite3_free(aIndex);
  122881. sqlite3_free(zCompress);
  122882. sqlite3_free(zUncompress);
  122883. sqlite3_free(zContent);
  122884. sqlite3_free(zLanguageid);
  122885. for(i=0; i<nNotindexed; i++) sqlite3_free(azNotindexed[i]);
  122886. sqlite3_free((void *)aCol);
  122887. sqlite3_free((void *)azNotindexed);
  122888. if( rc!=SQLITE_OK ){
  122889. if( p ){
  122890. fts3DisconnectMethod((sqlite3_vtab *)p);
  122891. }else if( pTokenizer ){
  122892. pTokenizer->pModule->xDestroy(pTokenizer);
  122893. }
  122894. }else{
  122895. assert( p->pSegments==0 );
  122896. *ppVTab = &p->base;
  122897. }
  122898. return rc;
  122899. }
  122900. /*
  122901. ** The xConnect() and xCreate() methods for the virtual table. All the
  122902. ** work is done in function fts3InitVtab().
  122903. */
  122904. static int fts3ConnectMethod(
  122905. sqlite3 *db, /* Database connection */
  122906. void *pAux, /* Pointer to tokenizer hash table */
  122907. int argc, /* Number of elements in argv array */
  122908. const char * const *argv, /* xCreate/xConnect argument array */
  122909. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  122910. char **pzErr /* OUT: sqlite3_malloc'd error message */
  122911. ){
  122912. return fts3InitVtab(0, db, pAux, argc, argv, ppVtab, pzErr);
  122913. }
  122914. static int fts3CreateMethod(
  122915. sqlite3 *db, /* Database connection */
  122916. void *pAux, /* Pointer to tokenizer hash table */
  122917. int argc, /* Number of elements in argv array */
  122918. const char * const *argv, /* xCreate/xConnect argument array */
  122919. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  122920. char **pzErr /* OUT: sqlite3_malloc'd error message */
  122921. ){
  122922. return fts3InitVtab(1, db, pAux, argc, argv, ppVtab, pzErr);
  122923. }
  122924. /*
  122925. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  122926. ** extension is currently being used by a version of SQLite too old to
  122927. ** support estimatedRows. In that case this function is a no-op.
  122928. */
  122929. static void fts3SetEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  122930. #if SQLITE_VERSION_NUMBER>=3008002
  122931. if( sqlite3_libversion_number()>=3008002 ){
  122932. pIdxInfo->estimatedRows = nRow;
  122933. }
  122934. #endif
  122935. }
  122936. /*
  122937. ** Implementation of the xBestIndex method for FTS3 tables. There
  122938. ** are three possible strategies, in order of preference:
  122939. **
  122940. ** 1. Direct lookup by rowid or docid.
  122941. ** 2. Full-text search using a MATCH operator on a non-docid column.
  122942. ** 3. Linear scan of %_content table.
  122943. */
  122944. static int fts3BestIndexMethod(sqlite3_vtab *pVTab, sqlite3_index_info *pInfo){
  122945. Fts3Table *p = (Fts3Table *)pVTab;
  122946. int i; /* Iterator variable */
  122947. int iCons = -1; /* Index of constraint to use */
  122948. int iLangidCons = -1; /* Index of langid=x constraint, if present */
  122949. int iDocidGe = -1; /* Index of docid>=x constraint, if present */
  122950. int iDocidLe = -1; /* Index of docid<=x constraint, if present */
  122951. int iIdx;
  122952. /* By default use a full table scan. This is an expensive option,
  122953. ** so search through the constraints to see if a more efficient
  122954. ** strategy is possible.
  122955. */
  122956. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  122957. pInfo->estimatedCost = 5000000;
  122958. for(i=0; i<pInfo->nConstraint; i++){
  122959. int bDocid; /* True if this constraint is on docid */
  122960. struct sqlite3_index_constraint *pCons = &pInfo->aConstraint[i];
  122961. if( pCons->usable==0 ){
  122962. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH ){
  122963. /* There exists an unusable MATCH constraint. This means that if
  122964. ** the planner does elect to use the results of this call as part
  122965. ** of the overall query plan the user will see an "unable to use
  122966. ** function MATCH in the requested context" error. To discourage
  122967. ** this, return a very high cost here. */
  122968. pInfo->idxNum = FTS3_FULLSCAN_SEARCH;
  122969. pInfo->estimatedCost = 1e50;
  122970. fts3SetEstimatedRows(pInfo, ((sqlite3_int64)1) << 50);
  122971. return SQLITE_OK;
  122972. }
  122973. continue;
  122974. }
  122975. bDocid = (pCons->iColumn<0 || pCons->iColumn==p->nColumn+1);
  122976. /* A direct lookup on the rowid or docid column. Assign a cost of 1.0. */
  122977. if( iCons<0 && pCons->op==SQLITE_INDEX_CONSTRAINT_EQ && bDocid ){
  122978. pInfo->idxNum = FTS3_DOCID_SEARCH;
  122979. pInfo->estimatedCost = 1.0;
  122980. iCons = i;
  122981. }
  122982. /* A MATCH constraint. Use a full-text search.
  122983. **
  122984. ** If there is more than one MATCH constraint available, use the first
  122985. ** one encountered. If there is both a MATCH constraint and a direct
  122986. ** rowid/docid lookup, prefer the MATCH strategy. This is done even
  122987. ** though the rowid/docid lookup is faster than a MATCH query, selecting
  122988. ** it would lead to an "unable to use function MATCH in the requested
  122989. ** context" error.
  122990. */
  122991. if( pCons->op==SQLITE_INDEX_CONSTRAINT_MATCH
  122992. && pCons->iColumn>=0 && pCons->iColumn<=p->nColumn
  122993. ){
  122994. pInfo->idxNum = FTS3_FULLTEXT_SEARCH + pCons->iColumn;
  122995. pInfo->estimatedCost = 2.0;
  122996. iCons = i;
  122997. }
  122998. /* Equality constraint on the langid column */
  122999. if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ
  123000. && pCons->iColumn==p->nColumn + 2
  123001. ){
  123002. iLangidCons = i;
  123003. }
  123004. if( bDocid ){
  123005. switch( pCons->op ){
  123006. case SQLITE_INDEX_CONSTRAINT_GE:
  123007. case SQLITE_INDEX_CONSTRAINT_GT:
  123008. iDocidGe = i;
  123009. break;
  123010. case SQLITE_INDEX_CONSTRAINT_LE:
  123011. case SQLITE_INDEX_CONSTRAINT_LT:
  123012. iDocidLe = i;
  123013. break;
  123014. }
  123015. }
  123016. }
  123017. iIdx = 1;
  123018. if( iCons>=0 ){
  123019. pInfo->aConstraintUsage[iCons].argvIndex = iIdx++;
  123020. pInfo->aConstraintUsage[iCons].omit = 1;
  123021. }
  123022. if( iLangidCons>=0 ){
  123023. pInfo->idxNum |= FTS3_HAVE_LANGID;
  123024. pInfo->aConstraintUsage[iLangidCons].argvIndex = iIdx++;
  123025. }
  123026. if( iDocidGe>=0 ){
  123027. pInfo->idxNum |= FTS3_HAVE_DOCID_GE;
  123028. pInfo->aConstraintUsage[iDocidGe].argvIndex = iIdx++;
  123029. }
  123030. if( iDocidLe>=0 ){
  123031. pInfo->idxNum |= FTS3_HAVE_DOCID_LE;
  123032. pInfo->aConstraintUsage[iDocidLe].argvIndex = iIdx++;
  123033. }
  123034. /* Regardless of the strategy selected, FTS can deliver rows in rowid (or
  123035. ** docid) order. Both ascending and descending are possible.
  123036. */
  123037. if( pInfo->nOrderBy==1 ){
  123038. struct sqlite3_index_orderby *pOrder = &pInfo->aOrderBy[0];
  123039. if( pOrder->iColumn<0 || pOrder->iColumn==p->nColumn+1 ){
  123040. if( pOrder->desc ){
  123041. pInfo->idxStr = "DESC";
  123042. }else{
  123043. pInfo->idxStr = "ASC";
  123044. }
  123045. pInfo->orderByConsumed = 1;
  123046. }
  123047. }
  123048. assert( p->pSegments==0 );
  123049. return SQLITE_OK;
  123050. }
  123051. /*
  123052. ** Implementation of xOpen method.
  123053. */
  123054. static int fts3OpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  123055. sqlite3_vtab_cursor *pCsr; /* Allocated cursor */
  123056. UNUSED_PARAMETER(pVTab);
  123057. /* Allocate a buffer large enough for an Fts3Cursor structure. If the
  123058. ** allocation succeeds, zero it and return SQLITE_OK. Otherwise,
  123059. ** if the allocation fails, return SQLITE_NOMEM.
  123060. */
  123061. *ppCsr = pCsr = (sqlite3_vtab_cursor *)sqlite3_malloc(sizeof(Fts3Cursor));
  123062. if( !pCsr ){
  123063. return SQLITE_NOMEM;
  123064. }
  123065. memset(pCsr, 0, sizeof(Fts3Cursor));
  123066. return SQLITE_OK;
  123067. }
  123068. /*
  123069. ** Close the cursor. For additional information see the documentation
  123070. ** on the xClose method of the virtual table interface.
  123071. */
  123072. static int fts3CloseMethod(sqlite3_vtab_cursor *pCursor){
  123073. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  123074. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  123075. sqlite3_finalize(pCsr->pStmt);
  123076. sqlite3Fts3ExprFree(pCsr->pExpr);
  123077. sqlite3Fts3FreeDeferredTokens(pCsr);
  123078. sqlite3_free(pCsr->aDoclist);
  123079. sqlite3_free(pCsr->aMatchinfo);
  123080. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  123081. sqlite3_free(pCsr);
  123082. return SQLITE_OK;
  123083. }
  123084. /*
  123085. ** If pCsr->pStmt has not been prepared (i.e. if pCsr->pStmt==0), then
  123086. ** compose and prepare an SQL statement of the form:
  123087. **
  123088. ** "SELECT <columns> FROM %_content WHERE rowid = ?"
  123089. **
  123090. ** (or the equivalent for a content=xxx table) and set pCsr->pStmt to
  123091. ** it. If an error occurs, return an SQLite error code.
  123092. **
  123093. ** Otherwise, set *ppStmt to point to pCsr->pStmt and return SQLITE_OK.
  123094. */
  123095. static int fts3CursorSeekStmt(Fts3Cursor *pCsr, sqlite3_stmt **ppStmt){
  123096. int rc = SQLITE_OK;
  123097. if( pCsr->pStmt==0 ){
  123098. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  123099. char *zSql;
  123100. zSql = sqlite3_mprintf("SELECT %s WHERE rowid = ?", p->zReadExprlist);
  123101. if( !zSql ) return SQLITE_NOMEM;
  123102. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  123103. sqlite3_free(zSql);
  123104. }
  123105. *ppStmt = pCsr->pStmt;
  123106. return rc;
  123107. }
  123108. /*
  123109. ** Position the pCsr->pStmt statement so that it is on the row
  123110. ** of the %_content table that contains the last match. Return
  123111. ** SQLITE_OK on success.
  123112. */
  123113. static int fts3CursorSeek(sqlite3_context *pContext, Fts3Cursor *pCsr){
  123114. int rc = SQLITE_OK;
  123115. if( pCsr->isRequireSeek ){
  123116. sqlite3_stmt *pStmt = 0;
  123117. rc = fts3CursorSeekStmt(pCsr, &pStmt);
  123118. if( rc==SQLITE_OK ){
  123119. sqlite3_bind_int64(pCsr->pStmt, 1, pCsr->iPrevId);
  123120. pCsr->isRequireSeek = 0;
  123121. if( SQLITE_ROW==sqlite3_step(pCsr->pStmt) ){
  123122. return SQLITE_OK;
  123123. }else{
  123124. rc = sqlite3_reset(pCsr->pStmt);
  123125. if( rc==SQLITE_OK && ((Fts3Table *)pCsr->base.pVtab)->zContentTbl==0 ){
  123126. /* If no row was found and no error has occurred, then the %_content
  123127. ** table is missing a row that is present in the full-text index.
  123128. ** The data structures are corrupt. */
  123129. rc = FTS_CORRUPT_VTAB;
  123130. pCsr->isEof = 1;
  123131. }
  123132. }
  123133. }
  123134. }
  123135. if( rc!=SQLITE_OK && pContext ){
  123136. sqlite3_result_error_code(pContext, rc);
  123137. }
  123138. return rc;
  123139. }
  123140. /*
  123141. ** This function is used to process a single interior node when searching
  123142. ** a b-tree for a term or term prefix. The node data is passed to this
  123143. ** function via the zNode/nNode parameters. The term to search for is
  123144. ** passed in zTerm/nTerm.
  123145. **
  123146. ** If piFirst is not NULL, then this function sets *piFirst to the blockid
  123147. ** of the child node that heads the sub-tree that may contain the term.
  123148. **
  123149. ** If piLast is not NULL, then *piLast is set to the right-most child node
  123150. ** that heads a sub-tree that may contain a term for which zTerm/nTerm is
  123151. ** a prefix.
  123152. **
  123153. ** If an OOM error occurs, SQLITE_NOMEM is returned. Otherwise, SQLITE_OK.
  123154. */
  123155. static int fts3ScanInteriorNode(
  123156. const char *zTerm, /* Term to select leaves for */
  123157. int nTerm, /* Size of term zTerm in bytes */
  123158. const char *zNode, /* Buffer containing segment interior node */
  123159. int nNode, /* Size of buffer at zNode */
  123160. sqlite3_int64 *piFirst, /* OUT: Selected child node */
  123161. sqlite3_int64 *piLast /* OUT: Selected child node */
  123162. ){
  123163. int rc = SQLITE_OK; /* Return code */
  123164. const char *zCsr = zNode; /* Cursor to iterate through node */
  123165. const char *zEnd = &zCsr[nNode];/* End of interior node buffer */
  123166. char *zBuffer = 0; /* Buffer to load terms into */
  123167. int nAlloc = 0; /* Size of allocated buffer */
  123168. int isFirstTerm = 1; /* True when processing first term on page */
  123169. sqlite3_int64 iChild; /* Block id of child node to descend to */
  123170. /* Skip over the 'height' varint that occurs at the start of every
  123171. ** interior node. Then load the blockid of the left-child of the b-tree
  123172. ** node into variable iChild.
  123173. **
  123174. ** Even if the data structure on disk is corrupted, this (reading two
  123175. ** varints from the buffer) does not risk an overread. If zNode is a
  123176. ** root node, then the buffer comes from a SELECT statement. SQLite does
  123177. ** not make this guarantee explicitly, but in practice there are always
  123178. ** either more than 20 bytes of allocated space following the nNode bytes of
  123179. ** contents, or two zero bytes. Or, if the node is read from the %_segments
  123180. ** table, then there are always 20 bytes of zeroed padding following the
  123181. ** nNode bytes of content (see sqlite3Fts3ReadBlock() for details).
  123182. */
  123183. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  123184. zCsr += sqlite3Fts3GetVarint(zCsr, &iChild);
  123185. if( zCsr>zEnd ){
  123186. return FTS_CORRUPT_VTAB;
  123187. }
  123188. while( zCsr<zEnd && (piFirst || piLast) ){
  123189. int cmp; /* memcmp() result */
  123190. int nSuffix; /* Size of term suffix */
  123191. int nPrefix = 0; /* Size of term prefix */
  123192. int nBuffer; /* Total term size */
  123193. /* Load the next term on the node into zBuffer. Use realloc() to expand
  123194. ** the size of zBuffer if required. */
  123195. if( !isFirstTerm ){
  123196. zCsr += fts3GetVarint32(zCsr, &nPrefix);
  123197. }
  123198. isFirstTerm = 0;
  123199. zCsr += fts3GetVarint32(zCsr, &nSuffix);
  123200. if( nPrefix<0 || nSuffix<0 || &zCsr[nSuffix]>zEnd ){
  123201. rc = FTS_CORRUPT_VTAB;
  123202. goto finish_scan;
  123203. }
  123204. if( nPrefix+nSuffix>nAlloc ){
  123205. char *zNew;
  123206. nAlloc = (nPrefix+nSuffix) * 2;
  123207. zNew = (char *)sqlite3_realloc(zBuffer, nAlloc);
  123208. if( !zNew ){
  123209. rc = SQLITE_NOMEM;
  123210. goto finish_scan;
  123211. }
  123212. zBuffer = zNew;
  123213. }
  123214. assert( zBuffer );
  123215. memcpy(&zBuffer[nPrefix], zCsr, nSuffix);
  123216. nBuffer = nPrefix + nSuffix;
  123217. zCsr += nSuffix;
  123218. /* Compare the term we are searching for with the term just loaded from
  123219. ** the interior node. If the specified term is greater than or equal
  123220. ** to the term from the interior node, then all terms on the sub-tree
  123221. ** headed by node iChild are smaller than zTerm. No need to search
  123222. ** iChild.
  123223. **
  123224. ** If the interior node term is larger than the specified term, then
  123225. ** the tree headed by iChild may contain the specified term.
  123226. */
  123227. cmp = memcmp(zTerm, zBuffer, (nBuffer>nTerm ? nTerm : nBuffer));
  123228. if( piFirst && (cmp<0 || (cmp==0 && nBuffer>nTerm)) ){
  123229. *piFirst = iChild;
  123230. piFirst = 0;
  123231. }
  123232. if( piLast && cmp<0 ){
  123233. *piLast = iChild;
  123234. piLast = 0;
  123235. }
  123236. iChild++;
  123237. };
  123238. if( piFirst ) *piFirst = iChild;
  123239. if( piLast ) *piLast = iChild;
  123240. finish_scan:
  123241. sqlite3_free(zBuffer);
  123242. return rc;
  123243. }
  123244. /*
  123245. ** The buffer pointed to by argument zNode (size nNode bytes) contains an
  123246. ** interior node of a b-tree segment. The zTerm buffer (size nTerm bytes)
  123247. ** contains a term. This function searches the sub-tree headed by the zNode
  123248. ** node for the range of leaf nodes that may contain the specified term
  123249. ** or terms for which the specified term is a prefix.
  123250. **
  123251. ** If piLeaf is not NULL, then *piLeaf is set to the blockid of the
  123252. ** left-most leaf node in the tree that may contain the specified term.
  123253. ** If piLeaf2 is not NULL, then *piLeaf2 is set to the blockid of the
  123254. ** right-most leaf node that may contain a term for which the specified
  123255. ** term is a prefix.
  123256. **
  123257. ** It is possible that the range of returned leaf nodes does not contain
  123258. ** the specified term or any terms for which it is a prefix. However, if the
  123259. ** segment does contain any such terms, they are stored within the identified
  123260. ** range. Because this function only inspects interior segment nodes (and
  123261. ** never loads leaf nodes into memory), it is not possible to be sure.
  123262. **
  123263. ** If an error occurs, an error code other than SQLITE_OK is returned.
  123264. */
  123265. static int fts3SelectLeaf(
  123266. Fts3Table *p, /* Virtual table handle */
  123267. const char *zTerm, /* Term to select leaves for */
  123268. int nTerm, /* Size of term zTerm in bytes */
  123269. const char *zNode, /* Buffer containing segment interior node */
  123270. int nNode, /* Size of buffer at zNode */
  123271. sqlite3_int64 *piLeaf, /* Selected leaf node */
  123272. sqlite3_int64 *piLeaf2 /* Selected leaf node */
  123273. ){
  123274. int rc; /* Return code */
  123275. int iHeight; /* Height of this node in tree */
  123276. assert( piLeaf || piLeaf2 );
  123277. fts3GetVarint32(zNode, &iHeight);
  123278. rc = fts3ScanInteriorNode(zTerm, nTerm, zNode, nNode, piLeaf, piLeaf2);
  123279. assert( !piLeaf2 || !piLeaf || rc!=SQLITE_OK || (*piLeaf<=*piLeaf2) );
  123280. if( rc==SQLITE_OK && iHeight>1 ){
  123281. char *zBlob = 0; /* Blob read from %_segments table */
  123282. int nBlob; /* Size of zBlob in bytes */
  123283. if( piLeaf && piLeaf2 && (*piLeaf!=*piLeaf2) ){
  123284. rc = sqlite3Fts3ReadBlock(p, *piLeaf, &zBlob, &nBlob, 0);
  123285. if( rc==SQLITE_OK ){
  123286. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, 0);
  123287. }
  123288. sqlite3_free(zBlob);
  123289. piLeaf = 0;
  123290. zBlob = 0;
  123291. }
  123292. if( rc==SQLITE_OK ){
  123293. rc = sqlite3Fts3ReadBlock(p, piLeaf?*piLeaf:*piLeaf2, &zBlob, &nBlob, 0);
  123294. }
  123295. if( rc==SQLITE_OK ){
  123296. rc = fts3SelectLeaf(p, zTerm, nTerm, zBlob, nBlob, piLeaf, piLeaf2);
  123297. }
  123298. sqlite3_free(zBlob);
  123299. }
  123300. return rc;
  123301. }
  123302. /*
  123303. ** This function is used to create delta-encoded serialized lists of FTS3
  123304. ** varints. Each call to this function appends a single varint to a list.
  123305. */
  123306. static void fts3PutDeltaVarint(
  123307. char **pp, /* IN/OUT: Output pointer */
  123308. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  123309. sqlite3_int64 iVal /* Write this value to the list */
  123310. ){
  123311. assert( iVal-*piPrev > 0 || (*piPrev==0 && iVal==0) );
  123312. *pp += sqlite3Fts3PutVarint(*pp, iVal-*piPrev);
  123313. *piPrev = iVal;
  123314. }
  123315. /*
  123316. ** When this function is called, *ppPoslist is assumed to point to the
  123317. ** start of a position-list. After it returns, *ppPoslist points to the
  123318. ** first byte after the position-list.
  123319. **
  123320. ** A position list is list of positions (delta encoded) and columns for
  123321. ** a single document record of a doclist. So, in other words, this
  123322. ** routine advances *ppPoslist so that it points to the next docid in
  123323. ** the doclist, or to the first byte past the end of the doclist.
  123324. **
  123325. ** If pp is not NULL, then the contents of the position list are copied
  123326. ** to *pp. *pp is set to point to the first byte past the last byte copied
  123327. ** before this function returns.
  123328. */
  123329. static void fts3PoslistCopy(char **pp, char **ppPoslist){
  123330. char *pEnd = *ppPoslist;
  123331. char c = 0;
  123332. /* The end of a position list is marked by a zero encoded as an FTS3
  123333. ** varint. A single POS_END (0) byte. Except, if the 0 byte is preceded by
  123334. ** a byte with the 0x80 bit set, then it is not a varint 0, but the tail
  123335. ** of some other, multi-byte, value.
  123336. **
  123337. ** The following while-loop moves pEnd to point to the first byte that is not
  123338. ** immediately preceded by a byte with the 0x80 bit set. Then increments
  123339. ** pEnd once more so that it points to the byte immediately following the
  123340. ** last byte in the position-list.
  123341. */
  123342. while( *pEnd | c ){
  123343. c = *pEnd++ & 0x80;
  123344. testcase( c!=0 && (*pEnd)==0 );
  123345. }
  123346. pEnd++; /* Advance past the POS_END terminator byte */
  123347. if( pp ){
  123348. int n = (int)(pEnd - *ppPoslist);
  123349. char *p = *pp;
  123350. memcpy(p, *ppPoslist, n);
  123351. p += n;
  123352. *pp = p;
  123353. }
  123354. *ppPoslist = pEnd;
  123355. }
  123356. /*
  123357. ** When this function is called, *ppPoslist is assumed to point to the
  123358. ** start of a column-list. After it returns, *ppPoslist points to the
  123359. ** to the terminator (POS_COLUMN or POS_END) byte of the column-list.
  123360. **
  123361. ** A column-list is list of delta-encoded positions for a single column
  123362. ** within a single document within a doclist.
  123363. **
  123364. ** The column-list is terminated either by a POS_COLUMN varint (1) or
  123365. ** a POS_END varint (0). This routine leaves *ppPoslist pointing to
  123366. ** the POS_COLUMN or POS_END that terminates the column-list.
  123367. **
  123368. ** If pp is not NULL, then the contents of the column-list are copied
  123369. ** to *pp. *pp is set to point to the first byte past the last byte copied
  123370. ** before this function returns. The POS_COLUMN or POS_END terminator
  123371. ** is not copied into *pp.
  123372. */
  123373. static void fts3ColumnlistCopy(char **pp, char **ppPoslist){
  123374. char *pEnd = *ppPoslist;
  123375. char c = 0;
  123376. /* A column-list is terminated by either a 0x01 or 0x00 byte that is
  123377. ** not part of a multi-byte varint.
  123378. */
  123379. while( 0xFE & (*pEnd | c) ){
  123380. c = *pEnd++ & 0x80;
  123381. testcase( c!=0 && ((*pEnd)&0xfe)==0 );
  123382. }
  123383. if( pp ){
  123384. int n = (int)(pEnd - *ppPoslist);
  123385. char *p = *pp;
  123386. memcpy(p, *ppPoslist, n);
  123387. p += n;
  123388. *pp = p;
  123389. }
  123390. *ppPoslist = pEnd;
  123391. }
  123392. /*
  123393. ** Value used to signify the end of an position-list. This is safe because
  123394. ** it is not possible to have a document with 2^31 terms.
  123395. */
  123396. #define POSITION_LIST_END 0x7fffffff
  123397. /*
  123398. ** This function is used to help parse position-lists. When this function is
  123399. ** called, *pp may point to the start of the next varint in the position-list
  123400. ** being parsed, or it may point to 1 byte past the end of the position-list
  123401. ** (in which case **pp will be a terminator bytes POS_END (0) or
  123402. ** (1)).
  123403. **
  123404. ** If *pp points past the end of the current position-list, set *pi to
  123405. ** POSITION_LIST_END and return. Otherwise, read the next varint from *pp,
  123406. ** increment the current value of *pi by the value read, and set *pp to
  123407. ** point to the next value before returning.
  123408. **
  123409. ** Before calling this routine *pi must be initialized to the value of
  123410. ** the previous position, or zero if we are reading the first position
  123411. ** in the position-list. Because positions are delta-encoded, the value
  123412. ** of the previous position is needed in order to compute the value of
  123413. ** the next position.
  123414. */
  123415. static void fts3ReadNextPos(
  123416. char **pp, /* IN/OUT: Pointer into position-list buffer */
  123417. sqlite3_int64 *pi /* IN/OUT: Value read from position-list */
  123418. ){
  123419. if( (**pp)&0xFE ){
  123420. fts3GetDeltaVarint(pp, pi);
  123421. *pi -= 2;
  123422. }else{
  123423. *pi = POSITION_LIST_END;
  123424. }
  123425. }
  123426. /*
  123427. ** If parameter iCol is not 0, write an POS_COLUMN (1) byte followed by
  123428. ** the value of iCol encoded as a varint to *pp. This will start a new
  123429. ** column list.
  123430. **
  123431. ** Set *pp to point to the byte just after the last byte written before
  123432. ** returning (do not modify it if iCol==0). Return the total number of bytes
  123433. ** written (0 if iCol==0).
  123434. */
  123435. static int fts3PutColNumber(char **pp, int iCol){
  123436. int n = 0; /* Number of bytes written */
  123437. if( iCol ){
  123438. char *p = *pp; /* Output pointer */
  123439. n = 1 + sqlite3Fts3PutVarint(&p[1], iCol);
  123440. *p = 0x01;
  123441. *pp = &p[n];
  123442. }
  123443. return n;
  123444. }
  123445. /*
  123446. ** Compute the union of two position lists. The output written
  123447. ** into *pp contains all positions of both *pp1 and *pp2 in sorted
  123448. ** order and with any duplicates removed. All pointers are
  123449. ** updated appropriately. The caller is responsible for insuring
  123450. ** that there is enough space in *pp to hold the complete output.
  123451. */
  123452. static void fts3PoslistMerge(
  123453. char **pp, /* Output buffer */
  123454. char **pp1, /* Left input list */
  123455. char **pp2 /* Right input list */
  123456. ){
  123457. char *p = *pp;
  123458. char *p1 = *pp1;
  123459. char *p2 = *pp2;
  123460. while( *p1 || *p2 ){
  123461. int iCol1; /* The current column index in pp1 */
  123462. int iCol2; /* The current column index in pp2 */
  123463. if( *p1==POS_COLUMN ) fts3GetVarint32(&p1[1], &iCol1);
  123464. else if( *p1==POS_END ) iCol1 = POSITION_LIST_END;
  123465. else iCol1 = 0;
  123466. if( *p2==POS_COLUMN ) fts3GetVarint32(&p2[1], &iCol2);
  123467. else if( *p2==POS_END ) iCol2 = POSITION_LIST_END;
  123468. else iCol2 = 0;
  123469. if( iCol1==iCol2 ){
  123470. sqlite3_int64 i1 = 0; /* Last position from pp1 */
  123471. sqlite3_int64 i2 = 0; /* Last position from pp2 */
  123472. sqlite3_int64 iPrev = 0;
  123473. int n = fts3PutColNumber(&p, iCol1);
  123474. p1 += n;
  123475. p2 += n;
  123476. /* At this point, both p1 and p2 point to the start of column-lists
  123477. ** for the same column (the column with index iCol1 and iCol2).
  123478. ** A column-list is a list of non-negative delta-encoded varints, each
  123479. ** incremented by 2 before being stored. Each list is terminated by a
  123480. ** POS_END (0) or POS_COLUMN (1). The following block merges the two lists
  123481. ** and writes the results to buffer p. p is left pointing to the byte
  123482. ** after the list written. No terminator (POS_END or POS_COLUMN) is
  123483. ** written to the output.
  123484. */
  123485. fts3GetDeltaVarint(&p1, &i1);
  123486. fts3GetDeltaVarint(&p2, &i2);
  123487. do {
  123488. fts3PutDeltaVarint(&p, &iPrev, (i1<i2) ? i1 : i2);
  123489. iPrev -= 2;
  123490. if( i1==i2 ){
  123491. fts3ReadNextPos(&p1, &i1);
  123492. fts3ReadNextPos(&p2, &i2);
  123493. }else if( i1<i2 ){
  123494. fts3ReadNextPos(&p1, &i1);
  123495. }else{
  123496. fts3ReadNextPos(&p2, &i2);
  123497. }
  123498. }while( i1!=POSITION_LIST_END || i2!=POSITION_LIST_END );
  123499. }else if( iCol1<iCol2 ){
  123500. p1 += fts3PutColNumber(&p, iCol1);
  123501. fts3ColumnlistCopy(&p, &p1);
  123502. }else{
  123503. p2 += fts3PutColNumber(&p, iCol2);
  123504. fts3ColumnlistCopy(&p, &p2);
  123505. }
  123506. }
  123507. *p++ = POS_END;
  123508. *pp = p;
  123509. *pp1 = p1 + 1;
  123510. *pp2 = p2 + 1;
  123511. }
  123512. /*
  123513. ** This function is used to merge two position lists into one. When it is
  123514. ** called, *pp1 and *pp2 must both point to position lists. A position-list is
  123515. ** the part of a doclist that follows each document id. For example, if a row
  123516. ** contains:
  123517. **
  123518. ** 'a b c'|'x y z'|'a b b a'
  123519. **
  123520. ** Then the position list for this row for token 'b' would consist of:
  123521. **
  123522. ** 0x02 0x01 0x02 0x03 0x03 0x00
  123523. **
  123524. ** When this function returns, both *pp1 and *pp2 are left pointing to the
  123525. ** byte following the 0x00 terminator of their respective position lists.
  123526. **
  123527. ** If isSaveLeft is 0, an entry is added to the output position list for
  123528. ** each position in *pp2 for which there exists one or more positions in
  123529. ** *pp1 so that (pos(*pp2)>pos(*pp1) && pos(*pp2)-pos(*pp1)<=nToken). i.e.
  123530. ** when the *pp1 token appears before the *pp2 token, but not more than nToken
  123531. ** slots before it.
  123532. **
  123533. ** e.g. nToken==1 searches for adjacent positions.
  123534. */
  123535. static int fts3PoslistPhraseMerge(
  123536. char **pp, /* IN/OUT: Preallocated output buffer */
  123537. int nToken, /* Maximum difference in token positions */
  123538. int isSaveLeft, /* Save the left position */
  123539. int isExact, /* If *pp1 is exactly nTokens before *pp2 */
  123540. char **pp1, /* IN/OUT: Left input list */
  123541. char **pp2 /* IN/OUT: Right input list */
  123542. ){
  123543. char *p = *pp;
  123544. char *p1 = *pp1;
  123545. char *p2 = *pp2;
  123546. int iCol1 = 0;
  123547. int iCol2 = 0;
  123548. /* Never set both isSaveLeft and isExact for the same invocation. */
  123549. assert( isSaveLeft==0 || isExact==0 );
  123550. assert( p!=0 && *p1!=0 && *p2!=0 );
  123551. if( *p1==POS_COLUMN ){
  123552. p1++;
  123553. p1 += fts3GetVarint32(p1, &iCol1);
  123554. }
  123555. if( *p2==POS_COLUMN ){
  123556. p2++;
  123557. p2 += fts3GetVarint32(p2, &iCol2);
  123558. }
  123559. while( 1 ){
  123560. if( iCol1==iCol2 ){
  123561. char *pSave = p;
  123562. sqlite3_int64 iPrev = 0;
  123563. sqlite3_int64 iPos1 = 0;
  123564. sqlite3_int64 iPos2 = 0;
  123565. if( iCol1 ){
  123566. *p++ = POS_COLUMN;
  123567. p += sqlite3Fts3PutVarint(p, iCol1);
  123568. }
  123569. assert( *p1!=POS_END && *p1!=POS_COLUMN );
  123570. assert( *p2!=POS_END && *p2!=POS_COLUMN );
  123571. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  123572. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  123573. while( 1 ){
  123574. if( iPos2==iPos1+nToken
  123575. || (isExact==0 && iPos2>iPos1 && iPos2<=iPos1+nToken)
  123576. ){
  123577. sqlite3_int64 iSave;
  123578. iSave = isSaveLeft ? iPos1 : iPos2;
  123579. fts3PutDeltaVarint(&p, &iPrev, iSave+2); iPrev -= 2;
  123580. pSave = 0;
  123581. assert( p );
  123582. }
  123583. if( (!isSaveLeft && iPos2<=(iPos1+nToken)) || iPos2<=iPos1 ){
  123584. if( (*p2&0xFE)==0 ) break;
  123585. fts3GetDeltaVarint(&p2, &iPos2); iPos2 -= 2;
  123586. }else{
  123587. if( (*p1&0xFE)==0 ) break;
  123588. fts3GetDeltaVarint(&p1, &iPos1); iPos1 -= 2;
  123589. }
  123590. }
  123591. if( pSave ){
  123592. assert( pp && p );
  123593. p = pSave;
  123594. }
  123595. fts3ColumnlistCopy(0, &p1);
  123596. fts3ColumnlistCopy(0, &p2);
  123597. assert( (*p1&0xFE)==0 && (*p2&0xFE)==0 );
  123598. if( 0==*p1 || 0==*p2 ) break;
  123599. p1++;
  123600. p1 += fts3GetVarint32(p1, &iCol1);
  123601. p2++;
  123602. p2 += fts3GetVarint32(p2, &iCol2);
  123603. }
  123604. /* Advance pointer p1 or p2 (whichever corresponds to the smaller of
  123605. ** iCol1 and iCol2) so that it points to either the 0x00 that marks the
  123606. ** end of the position list, or the 0x01 that precedes the next
  123607. ** column-number in the position list.
  123608. */
  123609. else if( iCol1<iCol2 ){
  123610. fts3ColumnlistCopy(0, &p1);
  123611. if( 0==*p1 ) break;
  123612. p1++;
  123613. p1 += fts3GetVarint32(p1, &iCol1);
  123614. }else{
  123615. fts3ColumnlistCopy(0, &p2);
  123616. if( 0==*p2 ) break;
  123617. p2++;
  123618. p2 += fts3GetVarint32(p2, &iCol2);
  123619. }
  123620. }
  123621. fts3PoslistCopy(0, &p2);
  123622. fts3PoslistCopy(0, &p1);
  123623. *pp1 = p1;
  123624. *pp2 = p2;
  123625. if( *pp==p ){
  123626. return 0;
  123627. }
  123628. *p++ = 0x00;
  123629. *pp = p;
  123630. return 1;
  123631. }
  123632. /*
  123633. ** Merge two position-lists as required by the NEAR operator. The argument
  123634. ** position lists correspond to the left and right phrases of an expression
  123635. ** like:
  123636. **
  123637. ** "phrase 1" NEAR "phrase number 2"
  123638. **
  123639. ** Position list *pp1 corresponds to the left-hand side of the NEAR
  123640. ** expression and *pp2 to the right. As usual, the indexes in the position
  123641. ** lists are the offsets of the last token in each phrase (tokens "1" and "2"
  123642. ** in the example above).
  123643. **
  123644. ** The output position list - written to *pp - is a copy of *pp2 with those
  123645. ** entries that are not sufficiently NEAR entries in *pp1 removed.
  123646. */
  123647. static int fts3PoslistNearMerge(
  123648. char **pp, /* Output buffer */
  123649. char *aTmp, /* Temporary buffer space */
  123650. int nRight, /* Maximum difference in token positions */
  123651. int nLeft, /* Maximum difference in token positions */
  123652. char **pp1, /* IN/OUT: Left input list */
  123653. char **pp2 /* IN/OUT: Right input list */
  123654. ){
  123655. char *p1 = *pp1;
  123656. char *p2 = *pp2;
  123657. char *pTmp1 = aTmp;
  123658. char *pTmp2;
  123659. char *aTmp2;
  123660. int res = 1;
  123661. fts3PoslistPhraseMerge(&pTmp1, nRight, 0, 0, pp1, pp2);
  123662. aTmp2 = pTmp2 = pTmp1;
  123663. *pp1 = p1;
  123664. *pp2 = p2;
  123665. fts3PoslistPhraseMerge(&pTmp2, nLeft, 1, 0, pp2, pp1);
  123666. if( pTmp1!=aTmp && pTmp2!=aTmp2 ){
  123667. fts3PoslistMerge(pp, &aTmp, &aTmp2);
  123668. }else if( pTmp1!=aTmp ){
  123669. fts3PoslistCopy(pp, &aTmp);
  123670. }else if( pTmp2!=aTmp2 ){
  123671. fts3PoslistCopy(pp, &aTmp2);
  123672. }else{
  123673. res = 0;
  123674. }
  123675. return res;
  123676. }
  123677. /*
  123678. ** An instance of this function is used to merge together the (potentially
  123679. ** large number of) doclists for each term that matches a prefix query.
  123680. ** See function fts3TermSelectMerge() for details.
  123681. */
  123682. typedef struct TermSelect TermSelect;
  123683. struct TermSelect {
  123684. char *aaOutput[16]; /* Malloc'd output buffers */
  123685. int anOutput[16]; /* Size each output buffer in bytes */
  123686. };
  123687. /*
  123688. ** This function is used to read a single varint from a buffer. Parameter
  123689. ** pEnd points 1 byte past the end of the buffer. When this function is
  123690. ** called, if *pp points to pEnd or greater, then the end of the buffer
  123691. ** has been reached. In this case *pp is set to 0 and the function returns.
  123692. **
  123693. ** If *pp does not point to or past pEnd, then a single varint is read
  123694. ** from *pp. *pp is then set to point 1 byte past the end of the read varint.
  123695. **
  123696. ** If bDescIdx is false, the value read is added to *pVal before returning.
  123697. ** If it is true, the value read is subtracted from *pVal before this
  123698. ** function returns.
  123699. */
  123700. static void fts3GetDeltaVarint3(
  123701. char **pp, /* IN/OUT: Point to read varint from */
  123702. char *pEnd, /* End of buffer */
  123703. int bDescIdx, /* True if docids are descending */
  123704. sqlite3_int64 *pVal /* IN/OUT: Integer value */
  123705. ){
  123706. if( *pp>=pEnd ){
  123707. *pp = 0;
  123708. }else{
  123709. sqlite3_int64 iVal;
  123710. *pp += sqlite3Fts3GetVarint(*pp, &iVal);
  123711. if( bDescIdx ){
  123712. *pVal -= iVal;
  123713. }else{
  123714. *pVal += iVal;
  123715. }
  123716. }
  123717. }
  123718. /*
  123719. ** This function is used to write a single varint to a buffer. The varint
  123720. ** is written to *pp. Before returning, *pp is set to point 1 byte past the
  123721. ** end of the value written.
  123722. **
  123723. ** If *pbFirst is zero when this function is called, the value written to
  123724. ** the buffer is that of parameter iVal.
  123725. **
  123726. ** If *pbFirst is non-zero when this function is called, then the value
  123727. ** written is either (iVal-*piPrev) (if bDescIdx is zero) or (*piPrev-iVal)
  123728. ** (if bDescIdx is non-zero).
  123729. **
  123730. ** Before returning, this function always sets *pbFirst to 1 and *piPrev
  123731. ** to the value of parameter iVal.
  123732. */
  123733. static void fts3PutDeltaVarint3(
  123734. char **pp, /* IN/OUT: Output pointer */
  123735. int bDescIdx, /* True for descending docids */
  123736. sqlite3_int64 *piPrev, /* IN/OUT: Previous value written to list */
  123737. int *pbFirst, /* IN/OUT: True after first int written */
  123738. sqlite3_int64 iVal /* Write this value to the list */
  123739. ){
  123740. sqlite3_int64 iWrite;
  123741. if( bDescIdx==0 || *pbFirst==0 ){
  123742. iWrite = iVal - *piPrev;
  123743. }else{
  123744. iWrite = *piPrev - iVal;
  123745. }
  123746. assert( *pbFirst || *piPrev==0 );
  123747. assert( *pbFirst==0 || iWrite>0 );
  123748. *pp += sqlite3Fts3PutVarint(*pp, iWrite);
  123749. *piPrev = iVal;
  123750. *pbFirst = 1;
  123751. }
  123752. /*
  123753. ** This macro is used by various functions that merge doclists. The two
  123754. ** arguments are 64-bit docid values. If the value of the stack variable
  123755. ** bDescDoclist is 0 when this macro is invoked, then it returns (i1-i2).
  123756. ** Otherwise, (i2-i1).
  123757. **
  123758. ** Using this makes it easier to write code that can merge doclists that are
  123759. ** sorted in either ascending or descending order.
  123760. */
  123761. #define DOCID_CMP(i1, i2) ((bDescDoclist?-1:1) * (i1-i2))
  123762. /*
  123763. ** This function does an "OR" merge of two doclists (output contains all
  123764. ** positions contained in either argument doclist). If the docids in the
  123765. ** input doclists are sorted in ascending order, parameter bDescDoclist
  123766. ** should be false. If they are sorted in ascending order, it should be
  123767. ** passed a non-zero value.
  123768. **
  123769. ** If no error occurs, *paOut is set to point at an sqlite3_malloc'd buffer
  123770. ** containing the output doclist and SQLITE_OK is returned. In this case
  123771. ** *pnOut is set to the number of bytes in the output doclist.
  123772. **
  123773. ** If an error occurs, an SQLite error code is returned. The output values
  123774. ** are undefined in this case.
  123775. */
  123776. static int fts3DoclistOrMerge(
  123777. int bDescDoclist, /* True if arguments are desc */
  123778. char *a1, int n1, /* First doclist */
  123779. char *a2, int n2, /* Second doclist */
  123780. char **paOut, int *pnOut /* OUT: Malloc'd doclist */
  123781. ){
  123782. sqlite3_int64 i1 = 0;
  123783. sqlite3_int64 i2 = 0;
  123784. sqlite3_int64 iPrev = 0;
  123785. char *pEnd1 = &a1[n1];
  123786. char *pEnd2 = &a2[n2];
  123787. char *p1 = a1;
  123788. char *p2 = a2;
  123789. char *p;
  123790. char *aOut;
  123791. int bFirstOut = 0;
  123792. *paOut = 0;
  123793. *pnOut = 0;
  123794. /* Allocate space for the output. Both the input and output doclists
  123795. ** are delta encoded. If they are in ascending order (bDescDoclist==0),
  123796. ** then the first docid in each list is simply encoded as a varint. For
  123797. ** each subsequent docid, the varint stored is the difference between the
  123798. ** current and previous docid (a positive number - since the list is in
  123799. ** ascending order).
  123800. **
  123801. ** The first docid written to the output is therefore encoded using the
  123802. ** same number of bytes as it is in whichever of the input lists it is
  123803. ** read from. And each subsequent docid read from the same input list
  123804. ** consumes either the same or less bytes as it did in the input (since
  123805. ** the difference between it and the previous value in the output must
  123806. ** be a positive value less than or equal to the delta value read from
  123807. ** the input list). The same argument applies to all but the first docid
  123808. ** read from the 'other' list. And to the contents of all position lists
  123809. ** that will be copied and merged from the input to the output.
  123810. **
  123811. ** However, if the first docid copied to the output is a negative number,
  123812. ** then the encoding of the first docid from the 'other' input list may
  123813. ** be larger in the output than it was in the input (since the delta value
  123814. ** may be a larger positive integer than the actual docid).
  123815. **
  123816. ** The space required to store the output is therefore the sum of the
  123817. ** sizes of the two inputs, plus enough space for exactly one of the input
  123818. ** docids to grow.
  123819. **
  123820. ** A symetric argument may be made if the doclists are in descending
  123821. ** order.
  123822. */
  123823. aOut = sqlite3_malloc(n1+n2+FTS3_VARINT_MAX-1);
  123824. if( !aOut ) return SQLITE_NOMEM;
  123825. p = aOut;
  123826. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  123827. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  123828. while( p1 || p2 ){
  123829. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  123830. if( p2 && p1 && iDiff==0 ){
  123831. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  123832. fts3PoslistMerge(&p, &p1, &p2);
  123833. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  123834. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  123835. }else if( !p2 || (p1 && iDiff<0) ){
  123836. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  123837. fts3PoslistCopy(&p, &p1);
  123838. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  123839. }else{
  123840. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i2);
  123841. fts3PoslistCopy(&p, &p2);
  123842. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  123843. }
  123844. }
  123845. *paOut = aOut;
  123846. *pnOut = (int)(p-aOut);
  123847. assert( *pnOut<=n1+n2+FTS3_VARINT_MAX-1 );
  123848. return SQLITE_OK;
  123849. }
  123850. /*
  123851. ** This function does a "phrase" merge of two doclists. In a phrase merge,
  123852. ** the output contains a copy of each position from the right-hand input
  123853. ** doclist for which there is a position in the left-hand input doclist
  123854. ** exactly nDist tokens before it.
  123855. **
  123856. ** If the docids in the input doclists are sorted in ascending order,
  123857. ** parameter bDescDoclist should be false. If they are sorted in ascending
  123858. ** order, it should be passed a non-zero value.
  123859. **
  123860. ** The right-hand input doclist is overwritten by this function.
  123861. */
  123862. static void fts3DoclistPhraseMerge(
  123863. int bDescDoclist, /* True if arguments are desc */
  123864. int nDist, /* Distance from left to right (1=adjacent) */
  123865. char *aLeft, int nLeft, /* Left doclist */
  123866. char *aRight, int *pnRight /* IN/OUT: Right/output doclist */
  123867. ){
  123868. sqlite3_int64 i1 = 0;
  123869. sqlite3_int64 i2 = 0;
  123870. sqlite3_int64 iPrev = 0;
  123871. char *pEnd1 = &aLeft[nLeft];
  123872. char *pEnd2 = &aRight[*pnRight];
  123873. char *p1 = aLeft;
  123874. char *p2 = aRight;
  123875. char *p;
  123876. int bFirstOut = 0;
  123877. char *aOut = aRight;
  123878. assert( nDist>0 );
  123879. p = aOut;
  123880. fts3GetDeltaVarint3(&p1, pEnd1, 0, &i1);
  123881. fts3GetDeltaVarint3(&p2, pEnd2, 0, &i2);
  123882. while( p1 && p2 ){
  123883. sqlite3_int64 iDiff = DOCID_CMP(i1, i2);
  123884. if( iDiff==0 ){
  123885. char *pSave = p;
  123886. sqlite3_int64 iPrevSave = iPrev;
  123887. int bFirstOutSave = bFirstOut;
  123888. fts3PutDeltaVarint3(&p, bDescDoclist, &iPrev, &bFirstOut, i1);
  123889. if( 0==fts3PoslistPhraseMerge(&p, nDist, 0, 1, &p1, &p2) ){
  123890. p = pSave;
  123891. iPrev = iPrevSave;
  123892. bFirstOut = bFirstOutSave;
  123893. }
  123894. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  123895. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  123896. }else if( iDiff<0 ){
  123897. fts3PoslistCopy(0, &p1);
  123898. fts3GetDeltaVarint3(&p1, pEnd1, bDescDoclist, &i1);
  123899. }else{
  123900. fts3PoslistCopy(0, &p2);
  123901. fts3GetDeltaVarint3(&p2, pEnd2, bDescDoclist, &i2);
  123902. }
  123903. }
  123904. *pnRight = (int)(p - aOut);
  123905. }
  123906. /*
  123907. ** Argument pList points to a position list nList bytes in size. This
  123908. ** function checks to see if the position list contains any entries for
  123909. ** a token in position 0 (of any column). If so, it writes argument iDelta
  123910. ** to the output buffer pOut, followed by a position list consisting only
  123911. ** of the entries from pList at position 0, and terminated by an 0x00 byte.
  123912. ** The value returned is the number of bytes written to pOut (if any).
  123913. */
  123914. SQLITE_PRIVATE int sqlite3Fts3FirstFilter(
  123915. sqlite3_int64 iDelta, /* Varint that may be written to pOut */
  123916. char *pList, /* Position list (no 0x00 term) */
  123917. int nList, /* Size of pList in bytes */
  123918. char *pOut /* Write output here */
  123919. ){
  123920. int nOut = 0;
  123921. int bWritten = 0; /* True once iDelta has been written */
  123922. char *p = pList;
  123923. char *pEnd = &pList[nList];
  123924. if( *p!=0x01 ){
  123925. if( *p==0x02 ){
  123926. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  123927. pOut[nOut++] = 0x02;
  123928. bWritten = 1;
  123929. }
  123930. fts3ColumnlistCopy(0, &p);
  123931. }
  123932. while( p<pEnd && *p==0x01 ){
  123933. sqlite3_int64 iCol;
  123934. p++;
  123935. p += sqlite3Fts3GetVarint(p, &iCol);
  123936. if( *p==0x02 ){
  123937. if( bWritten==0 ){
  123938. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iDelta);
  123939. bWritten = 1;
  123940. }
  123941. pOut[nOut++] = 0x01;
  123942. nOut += sqlite3Fts3PutVarint(&pOut[nOut], iCol);
  123943. pOut[nOut++] = 0x02;
  123944. }
  123945. fts3ColumnlistCopy(0, &p);
  123946. }
  123947. if( bWritten ){
  123948. pOut[nOut++] = 0x00;
  123949. }
  123950. return nOut;
  123951. }
  123952. /*
  123953. ** Merge all doclists in the TermSelect.aaOutput[] array into a single
  123954. ** doclist stored in TermSelect.aaOutput[0]. If successful, delete all
  123955. ** other doclists (except the aaOutput[0] one) and return SQLITE_OK.
  123956. **
  123957. ** If an OOM error occurs, return SQLITE_NOMEM. In this case it is
  123958. ** the responsibility of the caller to free any doclists left in the
  123959. ** TermSelect.aaOutput[] array.
  123960. */
  123961. static int fts3TermSelectFinishMerge(Fts3Table *p, TermSelect *pTS){
  123962. char *aOut = 0;
  123963. int nOut = 0;
  123964. int i;
  123965. /* Loop through the doclists in the aaOutput[] array. Merge them all
  123966. ** into a single doclist.
  123967. */
  123968. for(i=0; i<SizeofArray(pTS->aaOutput); i++){
  123969. if( pTS->aaOutput[i] ){
  123970. if( !aOut ){
  123971. aOut = pTS->aaOutput[i];
  123972. nOut = pTS->anOutput[i];
  123973. pTS->aaOutput[i] = 0;
  123974. }else{
  123975. int nNew;
  123976. char *aNew;
  123977. int rc = fts3DoclistOrMerge(p->bDescIdx,
  123978. pTS->aaOutput[i], pTS->anOutput[i], aOut, nOut, &aNew, &nNew
  123979. );
  123980. if( rc!=SQLITE_OK ){
  123981. sqlite3_free(aOut);
  123982. return rc;
  123983. }
  123984. sqlite3_free(pTS->aaOutput[i]);
  123985. sqlite3_free(aOut);
  123986. pTS->aaOutput[i] = 0;
  123987. aOut = aNew;
  123988. nOut = nNew;
  123989. }
  123990. }
  123991. }
  123992. pTS->aaOutput[0] = aOut;
  123993. pTS->anOutput[0] = nOut;
  123994. return SQLITE_OK;
  123995. }
  123996. /*
  123997. ** Merge the doclist aDoclist/nDoclist into the TermSelect object passed
  123998. ** as the first argument. The merge is an "OR" merge (see function
  123999. ** fts3DoclistOrMerge() for details).
  124000. **
  124001. ** This function is called with the doclist for each term that matches
  124002. ** a queried prefix. It merges all these doclists into one, the doclist
  124003. ** for the specified prefix. Since there can be a very large number of
  124004. ** doclists to merge, the merging is done pair-wise using the TermSelect
  124005. ** object.
  124006. **
  124007. ** This function returns SQLITE_OK if the merge is successful, or an
  124008. ** SQLite error code (SQLITE_NOMEM) if an error occurs.
  124009. */
  124010. static int fts3TermSelectMerge(
  124011. Fts3Table *p, /* FTS table handle */
  124012. TermSelect *pTS, /* TermSelect object to merge into */
  124013. char *aDoclist, /* Pointer to doclist */
  124014. int nDoclist /* Size of aDoclist in bytes */
  124015. ){
  124016. if( pTS->aaOutput[0]==0 ){
  124017. /* If this is the first term selected, copy the doclist to the output
  124018. ** buffer using memcpy(). */
  124019. pTS->aaOutput[0] = sqlite3_malloc(nDoclist);
  124020. pTS->anOutput[0] = nDoclist;
  124021. if( pTS->aaOutput[0] ){
  124022. memcpy(pTS->aaOutput[0], aDoclist, nDoclist);
  124023. }else{
  124024. return SQLITE_NOMEM;
  124025. }
  124026. }else{
  124027. char *aMerge = aDoclist;
  124028. int nMerge = nDoclist;
  124029. int iOut;
  124030. for(iOut=0; iOut<SizeofArray(pTS->aaOutput); iOut++){
  124031. if( pTS->aaOutput[iOut]==0 ){
  124032. assert( iOut>0 );
  124033. pTS->aaOutput[iOut] = aMerge;
  124034. pTS->anOutput[iOut] = nMerge;
  124035. break;
  124036. }else{
  124037. char *aNew;
  124038. int nNew;
  124039. int rc = fts3DoclistOrMerge(p->bDescIdx, aMerge, nMerge,
  124040. pTS->aaOutput[iOut], pTS->anOutput[iOut], &aNew, &nNew
  124041. );
  124042. if( rc!=SQLITE_OK ){
  124043. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  124044. return rc;
  124045. }
  124046. if( aMerge!=aDoclist ) sqlite3_free(aMerge);
  124047. sqlite3_free(pTS->aaOutput[iOut]);
  124048. pTS->aaOutput[iOut] = 0;
  124049. aMerge = aNew;
  124050. nMerge = nNew;
  124051. if( (iOut+1)==SizeofArray(pTS->aaOutput) ){
  124052. pTS->aaOutput[iOut] = aMerge;
  124053. pTS->anOutput[iOut] = nMerge;
  124054. }
  124055. }
  124056. }
  124057. }
  124058. return SQLITE_OK;
  124059. }
  124060. /*
  124061. ** Append SegReader object pNew to the end of the pCsr->apSegment[] array.
  124062. */
  124063. static int fts3SegReaderCursorAppend(
  124064. Fts3MultiSegReader *pCsr,
  124065. Fts3SegReader *pNew
  124066. ){
  124067. if( (pCsr->nSegment%16)==0 ){
  124068. Fts3SegReader **apNew;
  124069. int nByte = (pCsr->nSegment + 16)*sizeof(Fts3SegReader*);
  124070. apNew = (Fts3SegReader **)sqlite3_realloc(pCsr->apSegment, nByte);
  124071. if( !apNew ){
  124072. sqlite3Fts3SegReaderFree(pNew);
  124073. return SQLITE_NOMEM;
  124074. }
  124075. pCsr->apSegment = apNew;
  124076. }
  124077. pCsr->apSegment[pCsr->nSegment++] = pNew;
  124078. return SQLITE_OK;
  124079. }
  124080. /*
  124081. ** Add seg-reader objects to the Fts3MultiSegReader object passed as the
  124082. ** 8th argument.
  124083. **
  124084. ** This function returns SQLITE_OK if successful, or an SQLite error code
  124085. ** otherwise.
  124086. */
  124087. static int fts3SegReaderCursor(
  124088. Fts3Table *p, /* FTS3 table handle */
  124089. int iLangid, /* Language id */
  124090. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  124091. int iLevel, /* Level of segments to scan */
  124092. const char *zTerm, /* Term to query for */
  124093. int nTerm, /* Size of zTerm in bytes */
  124094. int isPrefix, /* True for a prefix search */
  124095. int isScan, /* True to scan from zTerm to EOF */
  124096. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  124097. ){
  124098. int rc = SQLITE_OK; /* Error code */
  124099. sqlite3_stmt *pStmt = 0; /* Statement to iterate through segments */
  124100. int rc2; /* Result of sqlite3_reset() */
  124101. /* If iLevel is less than 0 and this is not a scan, include a seg-reader
  124102. ** for the pending-terms. If this is a scan, then this call must be being
  124103. ** made by an fts4aux module, not an FTS table. In this case calling
  124104. ** Fts3SegReaderPending might segfault, as the data structures used by
  124105. ** fts4aux are not completely populated. So it's easiest to filter these
  124106. ** calls out here. */
  124107. if( iLevel<0 && p->aIndex ){
  124108. Fts3SegReader *pSeg = 0;
  124109. rc = sqlite3Fts3SegReaderPending(p, iIndex, zTerm, nTerm, isPrefix, &pSeg);
  124110. if( rc==SQLITE_OK && pSeg ){
  124111. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  124112. }
  124113. }
  124114. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  124115. if( rc==SQLITE_OK ){
  124116. rc = sqlite3Fts3AllSegdirs(p, iLangid, iIndex, iLevel, &pStmt);
  124117. }
  124118. while( rc==SQLITE_OK && SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
  124119. Fts3SegReader *pSeg = 0;
  124120. /* Read the values returned by the SELECT into local variables. */
  124121. sqlite3_int64 iStartBlock = sqlite3_column_int64(pStmt, 1);
  124122. sqlite3_int64 iLeavesEndBlock = sqlite3_column_int64(pStmt, 2);
  124123. sqlite3_int64 iEndBlock = sqlite3_column_int64(pStmt, 3);
  124124. int nRoot = sqlite3_column_bytes(pStmt, 4);
  124125. char const *zRoot = sqlite3_column_blob(pStmt, 4);
  124126. /* If zTerm is not NULL, and this segment is not stored entirely on its
  124127. ** root node, the range of leaves scanned can be reduced. Do this. */
  124128. if( iStartBlock && zTerm ){
  124129. sqlite3_int64 *pi = (isPrefix ? &iLeavesEndBlock : 0);
  124130. rc = fts3SelectLeaf(p, zTerm, nTerm, zRoot, nRoot, &iStartBlock, pi);
  124131. if( rc!=SQLITE_OK ) goto finished;
  124132. if( isPrefix==0 && isScan==0 ) iLeavesEndBlock = iStartBlock;
  124133. }
  124134. rc = sqlite3Fts3SegReaderNew(pCsr->nSegment+1,
  124135. (isPrefix==0 && isScan==0),
  124136. iStartBlock, iLeavesEndBlock,
  124137. iEndBlock, zRoot, nRoot, &pSeg
  124138. );
  124139. if( rc!=SQLITE_OK ) goto finished;
  124140. rc = fts3SegReaderCursorAppend(pCsr, pSeg);
  124141. }
  124142. }
  124143. finished:
  124144. rc2 = sqlite3_reset(pStmt);
  124145. if( rc==SQLITE_DONE ) rc = rc2;
  124146. return rc;
  124147. }
  124148. /*
  124149. ** Set up a cursor object for iterating through a full-text index or a
  124150. ** single level therein.
  124151. */
  124152. SQLITE_PRIVATE int sqlite3Fts3SegReaderCursor(
  124153. Fts3Table *p, /* FTS3 table handle */
  124154. int iLangid, /* Language-id to search */
  124155. int iIndex, /* Index to search (from 0 to p->nIndex-1) */
  124156. int iLevel, /* Level of segments to scan */
  124157. const char *zTerm, /* Term to query for */
  124158. int nTerm, /* Size of zTerm in bytes */
  124159. int isPrefix, /* True for a prefix search */
  124160. int isScan, /* True to scan from zTerm to EOF */
  124161. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  124162. ){
  124163. assert( iIndex>=0 && iIndex<p->nIndex );
  124164. assert( iLevel==FTS3_SEGCURSOR_ALL
  124165. || iLevel==FTS3_SEGCURSOR_PENDING
  124166. || iLevel>=0
  124167. );
  124168. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  124169. assert( FTS3_SEGCURSOR_ALL<0 && FTS3_SEGCURSOR_PENDING<0 );
  124170. assert( isPrefix==0 || isScan==0 );
  124171. memset(pCsr, 0, sizeof(Fts3MultiSegReader));
  124172. return fts3SegReaderCursor(
  124173. p, iLangid, iIndex, iLevel, zTerm, nTerm, isPrefix, isScan, pCsr
  124174. );
  124175. }
  124176. /*
  124177. ** In addition to its current configuration, have the Fts3MultiSegReader
  124178. ** passed as the 4th argument also scan the doclist for term zTerm/nTerm.
  124179. **
  124180. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  124181. */
  124182. static int fts3SegReaderCursorAddZero(
  124183. Fts3Table *p, /* FTS virtual table handle */
  124184. int iLangid,
  124185. const char *zTerm, /* Term to scan doclist of */
  124186. int nTerm, /* Number of bytes in zTerm */
  124187. Fts3MultiSegReader *pCsr /* Fts3MultiSegReader to modify */
  124188. ){
  124189. return fts3SegReaderCursor(p,
  124190. iLangid, 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0,pCsr
  124191. );
  124192. }
  124193. /*
  124194. ** Open an Fts3MultiSegReader to scan the doclist for term zTerm/nTerm. Or,
  124195. ** if isPrefix is true, to scan the doclist for all terms for which
  124196. ** zTerm/nTerm is a prefix. If successful, return SQLITE_OK and write
  124197. ** a pointer to the new Fts3MultiSegReader to *ppSegcsr. Otherwise, return
  124198. ** an SQLite error code.
  124199. **
  124200. ** It is the responsibility of the caller to free this object by eventually
  124201. ** passing it to fts3SegReaderCursorFree()
  124202. **
  124203. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  124204. ** Output parameter *ppSegcsr is set to 0 if an error occurs.
  124205. */
  124206. static int fts3TermSegReaderCursor(
  124207. Fts3Cursor *pCsr, /* Virtual table cursor handle */
  124208. const char *zTerm, /* Term to query for */
  124209. int nTerm, /* Size of zTerm in bytes */
  124210. int isPrefix, /* True for a prefix search */
  124211. Fts3MultiSegReader **ppSegcsr /* OUT: Allocated seg-reader cursor */
  124212. ){
  124213. Fts3MultiSegReader *pSegcsr; /* Object to allocate and return */
  124214. int rc = SQLITE_NOMEM; /* Return code */
  124215. pSegcsr = sqlite3_malloc(sizeof(Fts3MultiSegReader));
  124216. if( pSegcsr ){
  124217. int i;
  124218. int bFound = 0; /* True once an index has been found */
  124219. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  124220. if( isPrefix ){
  124221. for(i=1; bFound==0 && i<p->nIndex; i++){
  124222. if( p->aIndex[i].nPrefix==nTerm ){
  124223. bFound = 1;
  124224. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  124225. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 0, 0, pSegcsr
  124226. );
  124227. pSegcsr->bLookup = 1;
  124228. }
  124229. }
  124230. for(i=1; bFound==0 && i<p->nIndex; i++){
  124231. if( p->aIndex[i].nPrefix==nTerm+1 ){
  124232. bFound = 1;
  124233. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  124234. i, FTS3_SEGCURSOR_ALL, zTerm, nTerm, 1, 0, pSegcsr
  124235. );
  124236. if( rc==SQLITE_OK ){
  124237. rc = fts3SegReaderCursorAddZero(
  124238. p, pCsr->iLangid, zTerm, nTerm, pSegcsr
  124239. );
  124240. }
  124241. }
  124242. }
  124243. }
  124244. if( bFound==0 ){
  124245. rc = sqlite3Fts3SegReaderCursor(p, pCsr->iLangid,
  124246. 0, FTS3_SEGCURSOR_ALL, zTerm, nTerm, isPrefix, 0, pSegcsr
  124247. );
  124248. pSegcsr->bLookup = !isPrefix;
  124249. }
  124250. }
  124251. *ppSegcsr = pSegcsr;
  124252. return rc;
  124253. }
  124254. /*
  124255. ** Free an Fts3MultiSegReader allocated by fts3TermSegReaderCursor().
  124256. */
  124257. static void fts3SegReaderCursorFree(Fts3MultiSegReader *pSegcsr){
  124258. sqlite3Fts3SegReaderFinish(pSegcsr);
  124259. sqlite3_free(pSegcsr);
  124260. }
  124261. /*
  124262. ** This function retrieves the doclist for the specified term (or term
  124263. ** prefix) from the database.
  124264. */
  124265. static int fts3TermSelect(
  124266. Fts3Table *p, /* Virtual table handle */
  124267. Fts3PhraseToken *pTok, /* Token to query for */
  124268. int iColumn, /* Column to query (or -ve for all columns) */
  124269. int *pnOut, /* OUT: Size of buffer at *ppOut */
  124270. char **ppOut /* OUT: Malloced result buffer */
  124271. ){
  124272. int rc; /* Return code */
  124273. Fts3MultiSegReader *pSegcsr; /* Seg-reader cursor for this term */
  124274. TermSelect tsc; /* Object for pair-wise doclist merging */
  124275. Fts3SegFilter filter; /* Segment term filter configuration */
  124276. pSegcsr = pTok->pSegcsr;
  124277. memset(&tsc, 0, sizeof(TermSelect));
  124278. filter.flags = FTS3_SEGMENT_IGNORE_EMPTY | FTS3_SEGMENT_REQUIRE_POS
  124279. | (pTok->isPrefix ? FTS3_SEGMENT_PREFIX : 0)
  124280. | (pTok->bFirst ? FTS3_SEGMENT_FIRST : 0)
  124281. | (iColumn<p->nColumn ? FTS3_SEGMENT_COLUMN_FILTER : 0);
  124282. filter.iCol = iColumn;
  124283. filter.zTerm = pTok->z;
  124284. filter.nTerm = pTok->n;
  124285. rc = sqlite3Fts3SegReaderStart(p, pSegcsr, &filter);
  124286. while( SQLITE_OK==rc
  124287. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pSegcsr))
  124288. ){
  124289. rc = fts3TermSelectMerge(p, &tsc, pSegcsr->aDoclist, pSegcsr->nDoclist);
  124290. }
  124291. if( rc==SQLITE_OK ){
  124292. rc = fts3TermSelectFinishMerge(p, &tsc);
  124293. }
  124294. if( rc==SQLITE_OK ){
  124295. *ppOut = tsc.aaOutput[0];
  124296. *pnOut = tsc.anOutput[0];
  124297. }else{
  124298. int i;
  124299. for(i=0; i<SizeofArray(tsc.aaOutput); i++){
  124300. sqlite3_free(tsc.aaOutput[i]);
  124301. }
  124302. }
  124303. fts3SegReaderCursorFree(pSegcsr);
  124304. pTok->pSegcsr = 0;
  124305. return rc;
  124306. }
  124307. /*
  124308. ** This function counts the total number of docids in the doclist stored
  124309. ** in buffer aList[], size nList bytes.
  124310. **
  124311. ** If the isPoslist argument is true, then it is assumed that the doclist
  124312. ** contains a position-list following each docid. Otherwise, it is assumed
  124313. ** that the doclist is simply a list of docids stored as delta encoded
  124314. ** varints.
  124315. */
  124316. static int fts3DoclistCountDocids(char *aList, int nList){
  124317. int nDoc = 0; /* Return value */
  124318. if( aList ){
  124319. char *aEnd = &aList[nList]; /* Pointer to one byte after EOF */
  124320. char *p = aList; /* Cursor */
  124321. while( p<aEnd ){
  124322. nDoc++;
  124323. while( (*p++)&0x80 ); /* Skip docid varint */
  124324. fts3PoslistCopy(0, &p); /* Skip over position list */
  124325. }
  124326. }
  124327. return nDoc;
  124328. }
  124329. /*
  124330. ** Advance the cursor to the next row in the %_content table that
  124331. ** matches the search criteria. For a MATCH search, this will be
  124332. ** the next row that matches. For a full-table scan, this will be
  124333. ** simply the next row in the %_content table. For a docid lookup,
  124334. ** this routine simply sets the EOF flag.
  124335. **
  124336. ** Return SQLITE_OK if nothing goes wrong. SQLITE_OK is returned
  124337. ** even if we reach end-of-file. The fts3EofMethod() will be called
  124338. ** subsequently to determine whether or not an EOF was hit.
  124339. */
  124340. static int fts3NextMethod(sqlite3_vtab_cursor *pCursor){
  124341. int rc;
  124342. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  124343. if( pCsr->eSearch==FTS3_DOCID_SEARCH || pCsr->eSearch==FTS3_FULLSCAN_SEARCH ){
  124344. if( SQLITE_ROW!=sqlite3_step(pCsr->pStmt) ){
  124345. pCsr->isEof = 1;
  124346. rc = sqlite3_reset(pCsr->pStmt);
  124347. }else{
  124348. pCsr->iPrevId = sqlite3_column_int64(pCsr->pStmt, 0);
  124349. rc = SQLITE_OK;
  124350. }
  124351. }else{
  124352. rc = fts3EvalNext((Fts3Cursor *)pCursor);
  124353. }
  124354. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  124355. return rc;
  124356. }
  124357. /*
  124358. ** The following are copied from sqliteInt.h.
  124359. **
  124360. ** Constants for the largest and smallest possible 64-bit signed integers.
  124361. ** These macros are designed to work correctly on both 32-bit and 64-bit
  124362. ** compilers.
  124363. */
  124364. #ifndef SQLITE_AMALGAMATION
  124365. # define LARGEST_INT64 (0xffffffff|(((sqlite3_int64)0x7fffffff)<<32))
  124366. # define SMALLEST_INT64 (((sqlite3_int64)-1) - LARGEST_INT64)
  124367. #endif
  124368. /*
  124369. ** If the numeric type of argument pVal is "integer", then return it
  124370. ** converted to a 64-bit signed integer. Otherwise, return a copy of
  124371. ** the second parameter, iDefault.
  124372. */
  124373. static sqlite3_int64 fts3DocidRange(sqlite3_value *pVal, i64 iDefault){
  124374. if( pVal ){
  124375. int eType = sqlite3_value_numeric_type(pVal);
  124376. if( eType==SQLITE_INTEGER ){
  124377. return sqlite3_value_int64(pVal);
  124378. }
  124379. }
  124380. return iDefault;
  124381. }
  124382. /*
  124383. ** This is the xFilter interface for the virtual table. See
  124384. ** the virtual table xFilter method documentation for additional
  124385. ** information.
  124386. **
  124387. ** If idxNum==FTS3_FULLSCAN_SEARCH then do a full table scan against
  124388. ** the %_content table.
  124389. **
  124390. ** If idxNum==FTS3_DOCID_SEARCH then do a docid lookup for a single entry
  124391. ** in the %_content table.
  124392. **
  124393. ** If idxNum>=FTS3_FULLTEXT_SEARCH then use the full text index. The
  124394. ** column on the left-hand side of the MATCH operator is column
  124395. ** number idxNum-FTS3_FULLTEXT_SEARCH, 0 indexed. argv[0] is the right-hand
  124396. ** side of the MATCH operator.
  124397. */
  124398. static int fts3FilterMethod(
  124399. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  124400. int idxNum, /* Strategy index */
  124401. const char *idxStr, /* Unused */
  124402. int nVal, /* Number of elements in apVal */
  124403. sqlite3_value **apVal /* Arguments for the indexing scheme */
  124404. ){
  124405. int rc;
  124406. char *zSql; /* SQL statement used to access %_content */
  124407. int eSearch;
  124408. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  124409. Fts3Cursor *pCsr = (Fts3Cursor *)pCursor;
  124410. sqlite3_value *pCons = 0; /* The MATCH or rowid constraint, if any */
  124411. sqlite3_value *pLangid = 0; /* The "langid = ?" constraint, if any */
  124412. sqlite3_value *pDocidGe = 0; /* The "docid >= ?" constraint, if any */
  124413. sqlite3_value *pDocidLe = 0; /* The "docid <= ?" constraint, if any */
  124414. int iIdx;
  124415. UNUSED_PARAMETER(idxStr);
  124416. UNUSED_PARAMETER(nVal);
  124417. eSearch = (idxNum & 0x0000FFFF);
  124418. assert( eSearch>=0 && eSearch<=(FTS3_FULLTEXT_SEARCH+p->nColumn) );
  124419. assert( p->pSegments==0 );
  124420. /* Collect arguments into local variables */
  124421. iIdx = 0;
  124422. if( eSearch!=FTS3_FULLSCAN_SEARCH ) pCons = apVal[iIdx++];
  124423. if( idxNum & FTS3_HAVE_LANGID ) pLangid = apVal[iIdx++];
  124424. if( idxNum & FTS3_HAVE_DOCID_GE ) pDocidGe = apVal[iIdx++];
  124425. if( idxNum & FTS3_HAVE_DOCID_LE ) pDocidLe = apVal[iIdx++];
  124426. assert( iIdx==nVal );
  124427. /* In case the cursor has been used before, clear it now. */
  124428. sqlite3_finalize(pCsr->pStmt);
  124429. sqlite3_free(pCsr->aDoclist);
  124430. sqlite3_free(pCsr->aMatchinfo);
  124431. sqlite3Fts3ExprFree(pCsr->pExpr);
  124432. memset(&pCursor[1], 0, sizeof(Fts3Cursor)-sizeof(sqlite3_vtab_cursor));
  124433. /* Set the lower and upper bounds on docids to return */
  124434. pCsr->iMinDocid = fts3DocidRange(pDocidGe, SMALLEST_INT64);
  124435. pCsr->iMaxDocid = fts3DocidRange(pDocidLe, LARGEST_INT64);
  124436. if( idxStr ){
  124437. pCsr->bDesc = (idxStr[0]=='D');
  124438. }else{
  124439. pCsr->bDesc = p->bDescIdx;
  124440. }
  124441. pCsr->eSearch = (i16)eSearch;
  124442. if( eSearch!=FTS3_DOCID_SEARCH && eSearch!=FTS3_FULLSCAN_SEARCH ){
  124443. int iCol = eSearch-FTS3_FULLTEXT_SEARCH;
  124444. const char *zQuery = (const char *)sqlite3_value_text(pCons);
  124445. if( zQuery==0 && sqlite3_value_type(pCons)!=SQLITE_NULL ){
  124446. return SQLITE_NOMEM;
  124447. }
  124448. pCsr->iLangid = 0;
  124449. if( pLangid ) pCsr->iLangid = sqlite3_value_int(pLangid);
  124450. assert( p->base.zErrMsg==0 );
  124451. rc = sqlite3Fts3ExprParse(p->pTokenizer, pCsr->iLangid,
  124452. p->azColumn, p->bFts4, p->nColumn, iCol, zQuery, -1, &pCsr->pExpr,
  124453. &p->base.zErrMsg
  124454. );
  124455. if( rc!=SQLITE_OK ){
  124456. return rc;
  124457. }
  124458. rc = fts3EvalStart(pCsr);
  124459. sqlite3Fts3SegmentsClose(p);
  124460. if( rc!=SQLITE_OK ) return rc;
  124461. pCsr->pNextId = pCsr->aDoclist;
  124462. pCsr->iPrevId = 0;
  124463. }
  124464. /* Compile a SELECT statement for this cursor. For a full-table-scan, the
  124465. ** statement loops through all rows of the %_content table. For a
  124466. ** full-text query or docid lookup, the statement retrieves a single
  124467. ** row by docid.
  124468. */
  124469. if( eSearch==FTS3_FULLSCAN_SEARCH ){
  124470. zSql = sqlite3_mprintf(
  124471. "SELECT %s ORDER BY rowid %s",
  124472. p->zReadExprlist, (pCsr->bDesc ? "DESC" : "ASC")
  124473. );
  124474. if( zSql ){
  124475. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pCsr->pStmt, 0);
  124476. sqlite3_free(zSql);
  124477. }else{
  124478. rc = SQLITE_NOMEM;
  124479. }
  124480. }else if( eSearch==FTS3_DOCID_SEARCH ){
  124481. rc = fts3CursorSeekStmt(pCsr, &pCsr->pStmt);
  124482. if( rc==SQLITE_OK ){
  124483. rc = sqlite3_bind_value(pCsr->pStmt, 1, pCons);
  124484. }
  124485. }
  124486. if( rc!=SQLITE_OK ) return rc;
  124487. return fts3NextMethod(pCursor);
  124488. }
  124489. /*
  124490. ** This is the xEof method of the virtual table. SQLite calls this
  124491. ** routine to find out if it has reached the end of a result set.
  124492. */
  124493. static int fts3EofMethod(sqlite3_vtab_cursor *pCursor){
  124494. return ((Fts3Cursor *)pCursor)->isEof;
  124495. }
  124496. /*
  124497. ** This is the xRowid method. The SQLite core calls this routine to
  124498. ** retrieve the rowid for the current row of the result set. fts3
  124499. ** exposes %_content.docid as the rowid for the virtual table. The
  124500. ** rowid should be written to *pRowid.
  124501. */
  124502. static int fts3RowidMethod(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid){
  124503. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  124504. *pRowid = pCsr->iPrevId;
  124505. return SQLITE_OK;
  124506. }
  124507. /*
  124508. ** This is the xColumn method, called by SQLite to request a value from
  124509. ** the row that the supplied cursor currently points to.
  124510. **
  124511. ** If:
  124512. **
  124513. ** (iCol < p->nColumn) -> The value of the iCol'th user column.
  124514. ** (iCol == p->nColumn) -> Magic column with the same name as the table.
  124515. ** (iCol == p->nColumn+1) -> Docid column
  124516. ** (iCol == p->nColumn+2) -> Langid column
  124517. */
  124518. static int fts3ColumnMethod(
  124519. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  124520. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  124521. int iCol /* Index of column to read value from */
  124522. ){
  124523. int rc = SQLITE_OK; /* Return Code */
  124524. Fts3Cursor *pCsr = (Fts3Cursor *) pCursor;
  124525. Fts3Table *p = (Fts3Table *)pCursor->pVtab;
  124526. /* The column value supplied by SQLite must be in range. */
  124527. assert( iCol>=0 && iCol<=p->nColumn+2 );
  124528. if( iCol==p->nColumn+1 ){
  124529. /* This call is a request for the "docid" column. Since "docid" is an
  124530. ** alias for "rowid", use the xRowid() method to obtain the value.
  124531. */
  124532. sqlite3_result_int64(pCtx, pCsr->iPrevId);
  124533. }else if( iCol==p->nColumn ){
  124534. /* The extra column whose name is the same as the table.
  124535. ** Return a blob which is a pointer to the cursor. */
  124536. sqlite3_result_blob(pCtx, &pCsr, sizeof(pCsr), SQLITE_TRANSIENT);
  124537. }else if( iCol==p->nColumn+2 && pCsr->pExpr ){
  124538. sqlite3_result_int64(pCtx, pCsr->iLangid);
  124539. }else{
  124540. /* The requested column is either a user column (one that contains
  124541. ** indexed data), or the language-id column. */
  124542. rc = fts3CursorSeek(0, pCsr);
  124543. if( rc==SQLITE_OK ){
  124544. if( iCol==p->nColumn+2 ){
  124545. int iLangid = 0;
  124546. if( p->zLanguageid ){
  124547. iLangid = sqlite3_column_int(pCsr->pStmt, p->nColumn+1);
  124548. }
  124549. sqlite3_result_int(pCtx, iLangid);
  124550. }else if( sqlite3_data_count(pCsr->pStmt)>(iCol+1) ){
  124551. sqlite3_result_value(pCtx, sqlite3_column_value(pCsr->pStmt, iCol+1));
  124552. }
  124553. }
  124554. }
  124555. assert( ((Fts3Table *)pCsr->base.pVtab)->pSegments==0 );
  124556. return rc;
  124557. }
  124558. /*
  124559. ** This function is the implementation of the xUpdate callback used by
  124560. ** FTS3 virtual tables. It is invoked by SQLite each time a row is to be
  124561. ** inserted, updated or deleted.
  124562. */
  124563. static int fts3UpdateMethod(
  124564. sqlite3_vtab *pVtab, /* Virtual table handle */
  124565. int nArg, /* Size of argument array */
  124566. sqlite3_value **apVal, /* Array of arguments */
  124567. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  124568. ){
  124569. return sqlite3Fts3UpdateMethod(pVtab, nArg, apVal, pRowid);
  124570. }
  124571. /*
  124572. ** Implementation of xSync() method. Flush the contents of the pending-terms
  124573. ** hash-table to the database.
  124574. */
  124575. static int fts3SyncMethod(sqlite3_vtab *pVtab){
  124576. /* Following an incremental-merge operation, assuming that the input
  124577. ** segments are not completely consumed (the usual case), they are updated
  124578. ** in place to remove the entries that have already been merged. This
  124579. ** involves updating the leaf block that contains the smallest unmerged
  124580. ** entry and each block (if any) between the leaf and the root node. So
  124581. ** if the height of the input segment b-trees is N, and input segments
  124582. ** are merged eight at a time, updating the input segments at the end
  124583. ** of an incremental-merge requires writing (8*(1+N)) blocks. N is usually
  124584. ** small - often between 0 and 2. So the overhead of the incremental
  124585. ** merge is somewhere between 8 and 24 blocks. To avoid this overhead
  124586. ** dwarfing the actual productive work accomplished, the incremental merge
  124587. ** is only attempted if it will write at least 64 leaf blocks. Hence
  124588. ** nMinMerge.
  124589. **
  124590. ** Of course, updating the input segments also involves deleting a bunch
  124591. ** of blocks from the segments table. But this is not considered overhead
  124592. ** as it would also be required by a crisis-merge that used the same input
  124593. ** segments.
  124594. */
  124595. const u32 nMinMerge = 64; /* Minimum amount of incr-merge work to do */
  124596. Fts3Table *p = (Fts3Table*)pVtab;
  124597. int rc = sqlite3Fts3PendingTermsFlush(p);
  124598. if( rc==SQLITE_OK
  124599. && p->nLeafAdd>(nMinMerge/16)
  124600. && p->nAutoincrmerge && p->nAutoincrmerge!=0xff
  124601. ){
  124602. int mxLevel = 0; /* Maximum relative level value in db */
  124603. int A; /* Incr-merge parameter A */
  124604. rc = sqlite3Fts3MaxLevel(p, &mxLevel);
  124605. assert( rc==SQLITE_OK || mxLevel==0 );
  124606. A = p->nLeafAdd * mxLevel;
  124607. A += (A/2);
  124608. if( A>(int)nMinMerge ) rc = sqlite3Fts3Incrmerge(p, A, p->nAutoincrmerge);
  124609. }
  124610. sqlite3Fts3SegmentsClose(p);
  124611. return rc;
  124612. }
  124613. /*
  124614. ** If it is currently unknown whether or not the FTS table has an %_stat
  124615. ** table (if p->bHasStat==2), attempt to determine this (set p->bHasStat
  124616. ** to 0 or 1). Return SQLITE_OK if successful, or an SQLite error code
  124617. ** if an error occurs.
  124618. */
  124619. static int fts3SetHasStat(Fts3Table *p){
  124620. int rc = SQLITE_OK;
  124621. if( p->bHasStat==2 ){
  124622. const char *zFmt ="SELECT 1 FROM %Q.sqlite_master WHERE tbl_name='%q_stat'";
  124623. char *zSql = sqlite3_mprintf(zFmt, p->zDb, p->zName);
  124624. if( zSql ){
  124625. sqlite3_stmt *pStmt = 0;
  124626. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  124627. if( rc==SQLITE_OK ){
  124628. int bHasStat = (sqlite3_step(pStmt)==SQLITE_ROW);
  124629. rc = sqlite3_finalize(pStmt);
  124630. if( rc==SQLITE_OK ) p->bHasStat = bHasStat;
  124631. }
  124632. sqlite3_free(zSql);
  124633. }else{
  124634. rc = SQLITE_NOMEM;
  124635. }
  124636. }
  124637. return rc;
  124638. }
  124639. /*
  124640. ** Implementation of xBegin() method.
  124641. */
  124642. static int fts3BeginMethod(sqlite3_vtab *pVtab){
  124643. Fts3Table *p = (Fts3Table*)pVtab;
  124644. UNUSED_PARAMETER(pVtab);
  124645. assert( p->pSegments==0 );
  124646. assert( p->nPendingData==0 );
  124647. assert( p->inTransaction!=1 );
  124648. TESTONLY( p->inTransaction = 1 );
  124649. TESTONLY( p->mxSavepoint = -1; );
  124650. p->nLeafAdd = 0;
  124651. return fts3SetHasStat(p);
  124652. }
  124653. /*
  124654. ** Implementation of xCommit() method. This is a no-op. The contents of
  124655. ** the pending-terms hash-table have already been flushed into the database
  124656. ** by fts3SyncMethod().
  124657. */
  124658. static int fts3CommitMethod(sqlite3_vtab *pVtab){
  124659. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  124660. UNUSED_PARAMETER(pVtab);
  124661. assert( p->nPendingData==0 );
  124662. assert( p->inTransaction!=0 );
  124663. assert( p->pSegments==0 );
  124664. TESTONLY( p->inTransaction = 0 );
  124665. TESTONLY( p->mxSavepoint = -1; );
  124666. return SQLITE_OK;
  124667. }
  124668. /*
  124669. ** Implementation of xRollback(). Discard the contents of the pending-terms
  124670. ** hash-table. Any changes made to the database are reverted by SQLite.
  124671. */
  124672. static int fts3RollbackMethod(sqlite3_vtab *pVtab){
  124673. Fts3Table *p = (Fts3Table*)pVtab;
  124674. sqlite3Fts3PendingTermsClear(p);
  124675. assert( p->inTransaction!=0 );
  124676. TESTONLY( p->inTransaction = 0 );
  124677. TESTONLY( p->mxSavepoint = -1; );
  124678. return SQLITE_OK;
  124679. }
  124680. /*
  124681. ** When called, *ppPoslist must point to the byte immediately following the
  124682. ** end of a position-list. i.e. ( (*ppPoslist)[-1]==POS_END ). This function
  124683. ** moves *ppPoslist so that it instead points to the first byte of the
  124684. ** same position list.
  124685. */
  124686. static void fts3ReversePoslist(char *pStart, char **ppPoslist){
  124687. char *p = &(*ppPoslist)[-2];
  124688. char c = 0;
  124689. while( p>pStart && (c=*p--)==0 );
  124690. while( p>pStart && (*p & 0x80) | c ){
  124691. c = *p--;
  124692. }
  124693. if( p>pStart ){ p = &p[2]; }
  124694. while( *p++&0x80 );
  124695. *ppPoslist = p;
  124696. }
  124697. /*
  124698. ** Helper function used by the implementation of the overloaded snippet(),
  124699. ** offsets() and optimize() SQL functions.
  124700. **
  124701. ** If the value passed as the third argument is a blob of size
  124702. ** sizeof(Fts3Cursor*), then the blob contents are copied to the
  124703. ** output variable *ppCsr and SQLITE_OK is returned. Otherwise, an error
  124704. ** message is written to context pContext and SQLITE_ERROR returned. The
  124705. ** string passed via zFunc is used as part of the error message.
  124706. */
  124707. static int fts3FunctionArg(
  124708. sqlite3_context *pContext, /* SQL function call context */
  124709. const char *zFunc, /* Function name */
  124710. sqlite3_value *pVal, /* argv[0] passed to function */
  124711. Fts3Cursor **ppCsr /* OUT: Store cursor handle here */
  124712. ){
  124713. Fts3Cursor *pRet;
  124714. if( sqlite3_value_type(pVal)!=SQLITE_BLOB
  124715. || sqlite3_value_bytes(pVal)!=sizeof(Fts3Cursor *)
  124716. ){
  124717. char *zErr = sqlite3_mprintf("illegal first argument to %s", zFunc);
  124718. sqlite3_result_error(pContext, zErr, -1);
  124719. sqlite3_free(zErr);
  124720. return SQLITE_ERROR;
  124721. }
  124722. memcpy(&pRet, sqlite3_value_blob(pVal), sizeof(Fts3Cursor *));
  124723. *ppCsr = pRet;
  124724. return SQLITE_OK;
  124725. }
  124726. /*
  124727. ** Implementation of the snippet() function for FTS3
  124728. */
  124729. static void fts3SnippetFunc(
  124730. sqlite3_context *pContext, /* SQLite function call context */
  124731. int nVal, /* Size of apVal[] array */
  124732. sqlite3_value **apVal /* Array of arguments */
  124733. ){
  124734. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  124735. const char *zStart = "<b>";
  124736. const char *zEnd = "</b>";
  124737. const char *zEllipsis = "<b>...</b>";
  124738. int iCol = -1;
  124739. int nToken = 15; /* Default number of tokens in snippet */
  124740. /* There must be at least one argument passed to this function (otherwise
  124741. ** the non-overloaded version would have been called instead of this one).
  124742. */
  124743. assert( nVal>=1 );
  124744. if( nVal>6 ){
  124745. sqlite3_result_error(pContext,
  124746. "wrong number of arguments to function snippet()", -1);
  124747. return;
  124748. }
  124749. if( fts3FunctionArg(pContext, "snippet", apVal[0], &pCsr) ) return;
  124750. switch( nVal ){
  124751. case 6: nToken = sqlite3_value_int(apVal[5]);
  124752. case 5: iCol = sqlite3_value_int(apVal[4]);
  124753. case 4: zEllipsis = (const char*)sqlite3_value_text(apVal[3]);
  124754. case 3: zEnd = (const char*)sqlite3_value_text(apVal[2]);
  124755. case 2: zStart = (const char*)sqlite3_value_text(apVal[1]);
  124756. }
  124757. if( !zEllipsis || !zEnd || !zStart ){
  124758. sqlite3_result_error_nomem(pContext);
  124759. }else if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  124760. sqlite3Fts3Snippet(pContext, pCsr, zStart, zEnd, zEllipsis, iCol, nToken);
  124761. }
  124762. }
  124763. /*
  124764. ** Implementation of the offsets() function for FTS3
  124765. */
  124766. static void fts3OffsetsFunc(
  124767. sqlite3_context *pContext, /* SQLite function call context */
  124768. int nVal, /* Size of argument array */
  124769. sqlite3_value **apVal /* Array of arguments */
  124770. ){
  124771. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  124772. UNUSED_PARAMETER(nVal);
  124773. assert( nVal==1 );
  124774. if( fts3FunctionArg(pContext, "offsets", apVal[0], &pCsr) ) return;
  124775. assert( pCsr );
  124776. if( SQLITE_OK==fts3CursorSeek(pContext, pCsr) ){
  124777. sqlite3Fts3Offsets(pContext, pCsr);
  124778. }
  124779. }
  124780. /*
  124781. ** Implementation of the special optimize() function for FTS3. This
  124782. ** function merges all segments in the database to a single segment.
  124783. ** Example usage is:
  124784. **
  124785. ** SELECT optimize(t) FROM t LIMIT 1;
  124786. **
  124787. ** where 't' is the name of an FTS3 table.
  124788. */
  124789. static void fts3OptimizeFunc(
  124790. sqlite3_context *pContext, /* SQLite function call context */
  124791. int nVal, /* Size of argument array */
  124792. sqlite3_value **apVal /* Array of arguments */
  124793. ){
  124794. int rc; /* Return code */
  124795. Fts3Table *p; /* Virtual table handle */
  124796. Fts3Cursor *pCursor; /* Cursor handle passed through apVal[0] */
  124797. UNUSED_PARAMETER(nVal);
  124798. assert( nVal==1 );
  124799. if( fts3FunctionArg(pContext, "optimize", apVal[0], &pCursor) ) return;
  124800. p = (Fts3Table *)pCursor->base.pVtab;
  124801. assert( p );
  124802. rc = sqlite3Fts3Optimize(p);
  124803. switch( rc ){
  124804. case SQLITE_OK:
  124805. sqlite3_result_text(pContext, "Index optimized", -1, SQLITE_STATIC);
  124806. break;
  124807. case SQLITE_DONE:
  124808. sqlite3_result_text(pContext, "Index already optimal", -1, SQLITE_STATIC);
  124809. break;
  124810. default:
  124811. sqlite3_result_error_code(pContext, rc);
  124812. break;
  124813. }
  124814. }
  124815. /*
  124816. ** Implementation of the matchinfo() function for FTS3
  124817. */
  124818. static void fts3MatchinfoFunc(
  124819. sqlite3_context *pContext, /* SQLite function call context */
  124820. int nVal, /* Size of argument array */
  124821. sqlite3_value **apVal /* Array of arguments */
  124822. ){
  124823. Fts3Cursor *pCsr; /* Cursor handle passed through apVal[0] */
  124824. assert( nVal==1 || nVal==2 );
  124825. if( SQLITE_OK==fts3FunctionArg(pContext, "matchinfo", apVal[0], &pCsr) ){
  124826. const char *zArg = 0;
  124827. if( nVal>1 ){
  124828. zArg = (const char *)sqlite3_value_text(apVal[1]);
  124829. }
  124830. sqlite3Fts3Matchinfo(pContext, pCsr, zArg);
  124831. }
  124832. }
  124833. /*
  124834. ** This routine implements the xFindFunction method for the FTS3
  124835. ** virtual table.
  124836. */
  124837. static int fts3FindFunctionMethod(
  124838. sqlite3_vtab *pVtab, /* Virtual table handle */
  124839. int nArg, /* Number of SQL function arguments */
  124840. const char *zName, /* Name of SQL function */
  124841. void (**pxFunc)(sqlite3_context*,int,sqlite3_value**), /* OUT: Result */
  124842. void **ppArg /* Unused */
  124843. ){
  124844. struct Overloaded {
  124845. const char *zName;
  124846. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  124847. } aOverload[] = {
  124848. { "snippet", fts3SnippetFunc },
  124849. { "offsets", fts3OffsetsFunc },
  124850. { "optimize", fts3OptimizeFunc },
  124851. { "matchinfo", fts3MatchinfoFunc },
  124852. };
  124853. int i; /* Iterator variable */
  124854. UNUSED_PARAMETER(pVtab);
  124855. UNUSED_PARAMETER(nArg);
  124856. UNUSED_PARAMETER(ppArg);
  124857. for(i=0; i<SizeofArray(aOverload); i++){
  124858. if( strcmp(zName, aOverload[i].zName)==0 ){
  124859. *pxFunc = aOverload[i].xFunc;
  124860. return 1;
  124861. }
  124862. }
  124863. /* No function of the specified name was found. Return 0. */
  124864. return 0;
  124865. }
  124866. /*
  124867. ** Implementation of FTS3 xRename method. Rename an fts3 table.
  124868. */
  124869. static int fts3RenameMethod(
  124870. sqlite3_vtab *pVtab, /* Virtual table handle */
  124871. const char *zName /* New name of table */
  124872. ){
  124873. Fts3Table *p = (Fts3Table *)pVtab;
  124874. sqlite3 *db = p->db; /* Database connection */
  124875. int rc; /* Return Code */
  124876. /* At this point it must be known if the %_stat table exists or not.
  124877. ** So bHasStat may not be 2. */
  124878. rc = fts3SetHasStat(p);
  124879. /* As it happens, the pending terms table is always empty here. This is
  124880. ** because an "ALTER TABLE RENAME TABLE" statement inside a transaction
  124881. ** always opens a savepoint transaction. And the xSavepoint() method
  124882. ** flushes the pending terms table. But leave the (no-op) call to
  124883. ** PendingTermsFlush() in in case that changes.
  124884. */
  124885. assert( p->nPendingData==0 );
  124886. if( rc==SQLITE_OK ){
  124887. rc = sqlite3Fts3PendingTermsFlush(p);
  124888. }
  124889. if( p->zContentTbl==0 ){
  124890. fts3DbExec(&rc, db,
  124891. "ALTER TABLE %Q.'%q_content' RENAME TO '%q_content';",
  124892. p->zDb, p->zName, zName
  124893. );
  124894. }
  124895. if( p->bHasDocsize ){
  124896. fts3DbExec(&rc, db,
  124897. "ALTER TABLE %Q.'%q_docsize' RENAME TO '%q_docsize';",
  124898. p->zDb, p->zName, zName
  124899. );
  124900. }
  124901. if( p->bHasStat ){
  124902. fts3DbExec(&rc, db,
  124903. "ALTER TABLE %Q.'%q_stat' RENAME TO '%q_stat';",
  124904. p->zDb, p->zName, zName
  124905. );
  124906. }
  124907. fts3DbExec(&rc, db,
  124908. "ALTER TABLE %Q.'%q_segments' RENAME TO '%q_segments';",
  124909. p->zDb, p->zName, zName
  124910. );
  124911. fts3DbExec(&rc, db,
  124912. "ALTER TABLE %Q.'%q_segdir' RENAME TO '%q_segdir';",
  124913. p->zDb, p->zName, zName
  124914. );
  124915. return rc;
  124916. }
  124917. /*
  124918. ** The xSavepoint() method.
  124919. **
  124920. ** Flush the contents of the pending-terms table to disk.
  124921. */
  124922. static int fts3SavepointMethod(sqlite3_vtab *pVtab, int iSavepoint){
  124923. int rc = SQLITE_OK;
  124924. UNUSED_PARAMETER(iSavepoint);
  124925. assert( ((Fts3Table *)pVtab)->inTransaction );
  124926. assert( ((Fts3Table *)pVtab)->mxSavepoint < iSavepoint );
  124927. TESTONLY( ((Fts3Table *)pVtab)->mxSavepoint = iSavepoint );
  124928. if( ((Fts3Table *)pVtab)->bIgnoreSavepoint==0 ){
  124929. rc = fts3SyncMethod(pVtab);
  124930. }
  124931. return rc;
  124932. }
  124933. /*
  124934. ** The xRelease() method.
  124935. **
  124936. ** This is a no-op.
  124937. */
  124938. static int fts3ReleaseMethod(sqlite3_vtab *pVtab, int iSavepoint){
  124939. TESTONLY( Fts3Table *p = (Fts3Table*)pVtab );
  124940. UNUSED_PARAMETER(iSavepoint);
  124941. UNUSED_PARAMETER(pVtab);
  124942. assert( p->inTransaction );
  124943. assert( p->mxSavepoint >= iSavepoint );
  124944. TESTONLY( p->mxSavepoint = iSavepoint-1 );
  124945. return SQLITE_OK;
  124946. }
  124947. /*
  124948. ** The xRollbackTo() method.
  124949. **
  124950. ** Discard the contents of the pending terms table.
  124951. */
  124952. static int fts3RollbackToMethod(sqlite3_vtab *pVtab, int iSavepoint){
  124953. Fts3Table *p = (Fts3Table*)pVtab;
  124954. UNUSED_PARAMETER(iSavepoint);
  124955. assert( p->inTransaction );
  124956. assert( p->mxSavepoint >= iSavepoint );
  124957. TESTONLY( p->mxSavepoint = iSavepoint );
  124958. sqlite3Fts3PendingTermsClear(p);
  124959. return SQLITE_OK;
  124960. }
  124961. static const sqlite3_module fts3Module = {
  124962. /* iVersion */ 2,
  124963. /* xCreate */ fts3CreateMethod,
  124964. /* xConnect */ fts3ConnectMethod,
  124965. /* xBestIndex */ fts3BestIndexMethod,
  124966. /* xDisconnect */ fts3DisconnectMethod,
  124967. /* xDestroy */ fts3DestroyMethod,
  124968. /* xOpen */ fts3OpenMethod,
  124969. /* xClose */ fts3CloseMethod,
  124970. /* xFilter */ fts3FilterMethod,
  124971. /* xNext */ fts3NextMethod,
  124972. /* xEof */ fts3EofMethod,
  124973. /* xColumn */ fts3ColumnMethod,
  124974. /* xRowid */ fts3RowidMethod,
  124975. /* xUpdate */ fts3UpdateMethod,
  124976. /* xBegin */ fts3BeginMethod,
  124977. /* xSync */ fts3SyncMethod,
  124978. /* xCommit */ fts3CommitMethod,
  124979. /* xRollback */ fts3RollbackMethod,
  124980. /* xFindFunction */ fts3FindFunctionMethod,
  124981. /* xRename */ fts3RenameMethod,
  124982. /* xSavepoint */ fts3SavepointMethod,
  124983. /* xRelease */ fts3ReleaseMethod,
  124984. /* xRollbackTo */ fts3RollbackToMethod,
  124985. };
  124986. /*
  124987. ** This function is registered as the module destructor (called when an
  124988. ** FTS3 enabled database connection is closed). It frees the memory
  124989. ** allocated for the tokenizer hash table.
  124990. */
  124991. static void hashDestroy(void *p){
  124992. Fts3Hash *pHash = (Fts3Hash *)p;
  124993. sqlite3Fts3HashClear(pHash);
  124994. sqlite3_free(pHash);
  124995. }
  124996. /*
  124997. ** The fts3 built-in tokenizers - "simple", "porter" and "icu"- are
  124998. ** implemented in files fts3_tokenizer1.c, fts3_porter.c and fts3_icu.c
  124999. ** respectively. The following three forward declarations are for functions
  125000. ** declared in these files used to retrieve the respective implementations.
  125001. **
  125002. ** Calling sqlite3Fts3SimpleTokenizerModule() sets the value pointed
  125003. ** to by the argument to point to the "simple" tokenizer implementation.
  125004. ** And so on.
  125005. */
  125006. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  125007. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  125008. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125009. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const**ppModule);
  125010. #endif
  125011. #ifdef SQLITE_ENABLE_ICU
  125012. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  125013. #endif
  125014. /*
  125015. ** Initialize the fts3 extension. If this extension is built as part
  125016. ** of the sqlite library, then this function is called directly by
  125017. ** SQLite. If fts3 is built as a dynamically loadable extension, this
  125018. ** function is called by the sqlite3_extension_init() entry point.
  125019. */
  125020. SQLITE_PRIVATE int sqlite3Fts3Init(sqlite3 *db){
  125021. int rc = SQLITE_OK;
  125022. Fts3Hash *pHash = 0;
  125023. const sqlite3_tokenizer_module *pSimple = 0;
  125024. const sqlite3_tokenizer_module *pPorter = 0;
  125025. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125026. const sqlite3_tokenizer_module *pUnicode = 0;
  125027. #endif
  125028. #ifdef SQLITE_ENABLE_ICU
  125029. const sqlite3_tokenizer_module *pIcu = 0;
  125030. sqlite3Fts3IcuTokenizerModule(&pIcu);
  125031. #endif
  125032. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125033. sqlite3Fts3UnicodeTokenizer(&pUnicode);
  125034. #endif
  125035. #ifdef SQLITE_TEST
  125036. rc = sqlite3Fts3InitTerm(db);
  125037. if( rc!=SQLITE_OK ) return rc;
  125038. #endif
  125039. rc = sqlite3Fts3InitAux(db);
  125040. if( rc!=SQLITE_OK ) return rc;
  125041. sqlite3Fts3SimpleTokenizerModule(&pSimple);
  125042. sqlite3Fts3PorterTokenizerModule(&pPorter);
  125043. /* Allocate and initialize the hash-table used to store tokenizers. */
  125044. pHash = sqlite3_malloc(sizeof(Fts3Hash));
  125045. if( !pHash ){
  125046. rc = SQLITE_NOMEM;
  125047. }else{
  125048. sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  125049. }
  125050. /* Load the built-in tokenizers into the hash table */
  125051. if( rc==SQLITE_OK ){
  125052. if( sqlite3Fts3HashInsert(pHash, "simple", 7, (void *)pSimple)
  125053. || sqlite3Fts3HashInsert(pHash, "porter", 7, (void *)pPorter)
  125054. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  125055. || sqlite3Fts3HashInsert(pHash, "unicode61", 10, (void *)pUnicode)
  125056. #endif
  125057. #ifdef SQLITE_ENABLE_ICU
  125058. || (pIcu && sqlite3Fts3HashInsert(pHash, "icu", 4, (void *)pIcu))
  125059. #endif
  125060. ){
  125061. rc = SQLITE_NOMEM;
  125062. }
  125063. }
  125064. #ifdef SQLITE_TEST
  125065. if( rc==SQLITE_OK ){
  125066. rc = sqlite3Fts3ExprInitTestInterface(db);
  125067. }
  125068. #endif
  125069. /* Create the virtual table wrapper around the hash-table and overload
  125070. ** the two scalar functions. If this is successful, register the
  125071. ** module with sqlite.
  125072. */
  125073. if( SQLITE_OK==rc
  125074. && SQLITE_OK==(rc = sqlite3Fts3InitHashTable(db, pHash, "fts3_tokenizer"))
  125075. && SQLITE_OK==(rc = sqlite3_overload_function(db, "snippet", -1))
  125076. && SQLITE_OK==(rc = sqlite3_overload_function(db, "offsets", 1))
  125077. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 1))
  125078. && SQLITE_OK==(rc = sqlite3_overload_function(db, "matchinfo", 2))
  125079. && SQLITE_OK==(rc = sqlite3_overload_function(db, "optimize", 1))
  125080. ){
  125081. rc = sqlite3_create_module_v2(
  125082. db, "fts3", &fts3Module, (void *)pHash, hashDestroy
  125083. );
  125084. if( rc==SQLITE_OK ){
  125085. rc = sqlite3_create_module_v2(
  125086. db, "fts4", &fts3Module, (void *)pHash, 0
  125087. );
  125088. }
  125089. if( rc==SQLITE_OK ){
  125090. rc = sqlite3Fts3InitTok(db, (void *)pHash);
  125091. }
  125092. return rc;
  125093. }
  125094. /* An error has occurred. Delete the hash table and return the error code. */
  125095. assert( rc!=SQLITE_OK );
  125096. if( pHash ){
  125097. sqlite3Fts3HashClear(pHash);
  125098. sqlite3_free(pHash);
  125099. }
  125100. return rc;
  125101. }
  125102. /*
  125103. ** Allocate an Fts3MultiSegReader for each token in the expression headed
  125104. ** by pExpr.
  125105. **
  125106. ** An Fts3SegReader object is a cursor that can seek or scan a range of
  125107. ** entries within a single segment b-tree. An Fts3MultiSegReader uses multiple
  125108. ** Fts3SegReader objects internally to provide an interface to seek or scan
  125109. ** within the union of all segments of a b-tree. Hence the name.
  125110. **
  125111. ** If the allocated Fts3MultiSegReader just seeks to a single entry in a
  125112. ** segment b-tree (if the term is not a prefix or it is a prefix for which
  125113. ** there exists prefix b-tree of the right length) then it may be traversed
  125114. ** and merged incrementally. Otherwise, it has to be merged into an in-memory
  125115. ** doclist and then traversed.
  125116. */
  125117. static void fts3EvalAllocateReaders(
  125118. Fts3Cursor *pCsr, /* FTS cursor handle */
  125119. Fts3Expr *pExpr, /* Allocate readers for this expression */
  125120. int *pnToken, /* OUT: Total number of tokens in phrase. */
  125121. int *pnOr, /* OUT: Total number of OR nodes in expr. */
  125122. int *pRc /* IN/OUT: Error code */
  125123. ){
  125124. if( pExpr && SQLITE_OK==*pRc ){
  125125. if( pExpr->eType==FTSQUERY_PHRASE ){
  125126. int i;
  125127. int nToken = pExpr->pPhrase->nToken;
  125128. *pnToken += nToken;
  125129. for(i=0; i<nToken; i++){
  125130. Fts3PhraseToken *pToken = &pExpr->pPhrase->aToken[i];
  125131. int rc = fts3TermSegReaderCursor(pCsr,
  125132. pToken->z, pToken->n, pToken->isPrefix, &pToken->pSegcsr
  125133. );
  125134. if( rc!=SQLITE_OK ){
  125135. *pRc = rc;
  125136. return;
  125137. }
  125138. }
  125139. assert( pExpr->pPhrase->iDoclistToken==0 );
  125140. pExpr->pPhrase->iDoclistToken = -1;
  125141. }else{
  125142. *pnOr += (pExpr->eType==FTSQUERY_OR);
  125143. fts3EvalAllocateReaders(pCsr, pExpr->pLeft, pnToken, pnOr, pRc);
  125144. fts3EvalAllocateReaders(pCsr, pExpr->pRight, pnToken, pnOr, pRc);
  125145. }
  125146. }
  125147. }
  125148. /*
  125149. ** Arguments pList/nList contain the doclist for token iToken of phrase p.
  125150. ** It is merged into the main doclist stored in p->doclist.aAll/nAll.
  125151. **
  125152. ** This function assumes that pList points to a buffer allocated using
  125153. ** sqlite3_malloc(). This function takes responsibility for eventually
  125154. ** freeing the buffer.
  125155. */
  125156. static void fts3EvalPhraseMergeToken(
  125157. Fts3Table *pTab, /* FTS Table pointer */
  125158. Fts3Phrase *p, /* Phrase to merge pList/nList into */
  125159. int iToken, /* Token pList/nList corresponds to */
  125160. char *pList, /* Pointer to doclist */
  125161. int nList /* Number of bytes in pList */
  125162. ){
  125163. assert( iToken!=p->iDoclistToken );
  125164. if( pList==0 ){
  125165. sqlite3_free(p->doclist.aAll);
  125166. p->doclist.aAll = 0;
  125167. p->doclist.nAll = 0;
  125168. }
  125169. else if( p->iDoclistToken<0 ){
  125170. p->doclist.aAll = pList;
  125171. p->doclist.nAll = nList;
  125172. }
  125173. else if( p->doclist.aAll==0 ){
  125174. sqlite3_free(pList);
  125175. }
  125176. else {
  125177. char *pLeft;
  125178. char *pRight;
  125179. int nLeft;
  125180. int nRight;
  125181. int nDiff;
  125182. if( p->iDoclistToken<iToken ){
  125183. pLeft = p->doclist.aAll;
  125184. nLeft = p->doclist.nAll;
  125185. pRight = pList;
  125186. nRight = nList;
  125187. nDiff = iToken - p->iDoclistToken;
  125188. }else{
  125189. pRight = p->doclist.aAll;
  125190. nRight = p->doclist.nAll;
  125191. pLeft = pList;
  125192. nLeft = nList;
  125193. nDiff = p->iDoclistToken - iToken;
  125194. }
  125195. fts3DoclistPhraseMerge(pTab->bDescIdx, nDiff, pLeft, nLeft, pRight,&nRight);
  125196. sqlite3_free(pLeft);
  125197. p->doclist.aAll = pRight;
  125198. p->doclist.nAll = nRight;
  125199. }
  125200. if( iToken>p->iDoclistToken ) p->iDoclistToken = iToken;
  125201. }
  125202. /*
  125203. ** Load the doclist for phrase p into p->doclist.aAll/nAll. The loaded doclist
  125204. ** does not take deferred tokens into account.
  125205. **
  125206. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  125207. */
  125208. static int fts3EvalPhraseLoad(
  125209. Fts3Cursor *pCsr, /* FTS Cursor handle */
  125210. Fts3Phrase *p /* Phrase object */
  125211. ){
  125212. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125213. int iToken;
  125214. int rc = SQLITE_OK;
  125215. for(iToken=0; rc==SQLITE_OK && iToken<p->nToken; iToken++){
  125216. Fts3PhraseToken *pToken = &p->aToken[iToken];
  125217. assert( pToken->pDeferred==0 || pToken->pSegcsr==0 );
  125218. if( pToken->pSegcsr ){
  125219. int nThis = 0;
  125220. char *pThis = 0;
  125221. rc = fts3TermSelect(pTab, pToken, p->iColumn, &nThis, &pThis);
  125222. if( rc==SQLITE_OK ){
  125223. fts3EvalPhraseMergeToken(pTab, p, iToken, pThis, nThis);
  125224. }
  125225. }
  125226. assert( pToken->pSegcsr==0 );
  125227. }
  125228. return rc;
  125229. }
  125230. /*
  125231. ** This function is called on each phrase after the position lists for
  125232. ** any deferred tokens have been loaded into memory. It updates the phrases
  125233. ** current position list to include only those positions that are really
  125234. ** instances of the phrase (after considering deferred tokens). If this
  125235. ** means that the phrase does not appear in the current row, doclist.pList
  125236. ** and doclist.nList are both zeroed.
  125237. **
  125238. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  125239. */
  125240. static int fts3EvalDeferredPhrase(Fts3Cursor *pCsr, Fts3Phrase *pPhrase){
  125241. int iToken; /* Used to iterate through phrase tokens */
  125242. char *aPoslist = 0; /* Position list for deferred tokens */
  125243. int nPoslist = 0; /* Number of bytes in aPoslist */
  125244. int iPrev = -1; /* Token number of previous deferred token */
  125245. assert( pPhrase->doclist.bFreeList==0 );
  125246. for(iToken=0; iToken<pPhrase->nToken; iToken++){
  125247. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  125248. Fts3DeferredToken *pDeferred = pToken->pDeferred;
  125249. if( pDeferred ){
  125250. char *pList;
  125251. int nList;
  125252. int rc = sqlite3Fts3DeferredTokenList(pDeferred, &pList, &nList);
  125253. if( rc!=SQLITE_OK ) return rc;
  125254. if( pList==0 ){
  125255. sqlite3_free(aPoslist);
  125256. pPhrase->doclist.pList = 0;
  125257. pPhrase->doclist.nList = 0;
  125258. return SQLITE_OK;
  125259. }else if( aPoslist==0 ){
  125260. aPoslist = pList;
  125261. nPoslist = nList;
  125262. }else{
  125263. char *aOut = pList;
  125264. char *p1 = aPoslist;
  125265. char *p2 = aOut;
  125266. assert( iPrev>=0 );
  125267. fts3PoslistPhraseMerge(&aOut, iToken-iPrev, 0, 1, &p1, &p2);
  125268. sqlite3_free(aPoslist);
  125269. aPoslist = pList;
  125270. nPoslist = (int)(aOut - aPoslist);
  125271. if( nPoslist==0 ){
  125272. sqlite3_free(aPoslist);
  125273. pPhrase->doclist.pList = 0;
  125274. pPhrase->doclist.nList = 0;
  125275. return SQLITE_OK;
  125276. }
  125277. }
  125278. iPrev = iToken;
  125279. }
  125280. }
  125281. if( iPrev>=0 ){
  125282. int nMaxUndeferred = pPhrase->iDoclistToken;
  125283. if( nMaxUndeferred<0 ){
  125284. pPhrase->doclist.pList = aPoslist;
  125285. pPhrase->doclist.nList = nPoslist;
  125286. pPhrase->doclist.iDocid = pCsr->iPrevId;
  125287. pPhrase->doclist.bFreeList = 1;
  125288. }else{
  125289. int nDistance;
  125290. char *p1;
  125291. char *p2;
  125292. char *aOut;
  125293. if( nMaxUndeferred>iPrev ){
  125294. p1 = aPoslist;
  125295. p2 = pPhrase->doclist.pList;
  125296. nDistance = nMaxUndeferred - iPrev;
  125297. }else{
  125298. p1 = pPhrase->doclist.pList;
  125299. p2 = aPoslist;
  125300. nDistance = iPrev - nMaxUndeferred;
  125301. }
  125302. aOut = (char *)sqlite3_malloc(nPoslist+8);
  125303. if( !aOut ){
  125304. sqlite3_free(aPoslist);
  125305. return SQLITE_NOMEM;
  125306. }
  125307. pPhrase->doclist.pList = aOut;
  125308. if( fts3PoslistPhraseMerge(&aOut, nDistance, 0, 1, &p1, &p2) ){
  125309. pPhrase->doclist.bFreeList = 1;
  125310. pPhrase->doclist.nList = (int)(aOut - pPhrase->doclist.pList);
  125311. }else{
  125312. sqlite3_free(aOut);
  125313. pPhrase->doclist.pList = 0;
  125314. pPhrase->doclist.nList = 0;
  125315. }
  125316. sqlite3_free(aPoslist);
  125317. }
  125318. }
  125319. return SQLITE_OK;
  125320. }
  125321. /*
  125322. ** Maximum number of tokens a phrase may have to be considered for the
  125323. ** incremental doclists strategy.
  125324. */
  125325. #define MAX_INCR_PHRASE_TOKENS 4
  125326. /*
  125327. ** This function is called for each Fts3Phrase in a full-text query
  125328. ** expression to initialize the mechanism for returning rows. Once this
  125329. ** function has been called successfully on an Fts3Phrase, it may be
  125330. ** used with fts3EvalPhraseNext() to iterate through the matching docids.
  125331. **
  125332. ** If parameter bOptOk is true, then the phrase may (or may not) use the
  125333. ** incremental loading strategy. Otherwise, the entire doclist is loaded into
  125334. ** memory within this call.
  125335. **
  125336. ** SQLITE_OK is returned if no error occurs, otherwise an SQLite error code.
  125337. */
  125338. static int fts3EvalPhraseStart(Fts3Cursor *pCsr, int bOptOk, Fts3Phrase *p){
  125339. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125340. int rc = SQLITE_OK; /* Error code */
  125341. int i;
  125342. /* Determine if doclists may be loaded from disk incrementally. This is
  125343. ** possible if the bOptOk argument is true, the FTS doclists will be
  125344. ** scanned in forward order, and the phrase consists of
  125345. ** MAX_INCR_PHRASE_TOKENS or fewer tokens, none of which are are "^first"
  125346. ** tokens or prefix tokens that cannot use a prefix-index. */
  125347. int bHaveIncr = 0;
  125348. int bIncrOk = (bOptOk
  125349. && pCsr->bDesc==pTab->bDescIdx
  125350. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  125351. && p->nToken<=MAX_INCR_PHRASE_TOKENS && p->nToken>0
  125352. #ifdef SQLITE_TEST
  125353. && pTab->bNoIncrDoclist==0
  125354. #endif
  125355. );
  125356. for(i=0; bIncrOk==1 && i<p->nToken; i++){
  125357. Fts3PhraseToken *pToken = &p->aToken[i];
  125358. if( pToken->bFirst || (pToken->pSegcsr!=0 && !pToken->pSegcsr->bLookup) ){
  125359. bIncrOk = 0;
  125360. }
  125361. if( pToken->pSegcsr ) bHaveIncr = 1;
  125362. }
  125363. if( bIncrOk && bHaveIncr ){
  125364. /* Use the incremental approach. */
  125365. int iCol = (p->iColumn >= pTab->nColumn ? -1 : p->iColumn);
  125366. for(i=0; rc==SQLITE_OK && i<p->nToken; i++){
  125367. Fts3PhraseToken *pToken = &p->aToken[i];
  125368. Fts3MultiSegReader *pSegcsr = pToken->pSegcsr;
  125369. if( pSegcsr ){
  125370. rc = sqlite3Fts3MsrIncrStart(pTab, pSegcsr, iCol, pToken->z, pToken->n);
  125371. }
  125372. }
  125373. p->bIncr = 1;
  125374. }else{
  125375. /* Load the full doclist for the phrase into memory. */
  125376. rc = fts3EvalPhraseLoad(pCsr, p);
  125377. p->bIncr = 0;
  125378. }
  125379. assert( rc!=SQLITE_OK || p->nToken<1 || p->aToken[0].pSegcsr==0 || p->bIncr );
  125380. return rc;
  125381. }
  125382. /*
  125383. ** This function is used to iterate backwards (from the end to start)
  125384. ** through doclists. It is used by this module to iterate through phrase
  125385. ** doclists in reverse and by the fts3_write.c module to iterate through
  125386. ** pending-terms lists when writing to databases with "order=desc".
  125387. **
  125388. ** The doclist may be sorted in ascending (parameter bDescIdx==0) or
  125389. ** descending (parameter bDescIdx==1) order of docid. Regardless, this
  125390. ** function iterates from the end of the doclist to the beginning.
  125391. */
  125392. SQLITE_PRIVATE void sqlite3Fts3DoclistPrev(
  125393. int bDescIdx, /* True if the doclist is desc */
  125394. char *aDoclist, /* Pointer to entire doclist */
  125395. int nDoclist, /* Length of aDoclist in bytes */
  125396. char **ppIter, /* IN/OUT: Iterator pointer */
  125397. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  125398. int *pnList, /* OUT: List length pointer */
  125399. u8 *pbEof /* OUT: End-of-file flag */
  125400. ){
  125401. char *p = *ppIter;
  125402. assert( nDoclist>0 );
  125403. assert( *pbEof==0 );
  125404. assert( p || *piDocid==0 );
  125405. assert( !p || (p>aDoclist && p<&aDoclist[nDoclist]) );
  125406. if( p==0 ){
  125407. sqlite3_int64 iDocid = 0;
  125408. char *pNext = 0;
  125409. char *pDocid = aDoclist;
  125410. char *pEnd = &aDoclist[nDoclist];
  125411. int iMul = 1;
  125412. while( pDocid<pEnd ){
  125413. sqlite3_int64 iDelta;
  125414. pDocid += sqlite3Fts3GetVarint(pDocid, &iDelta);
  125415. iDocid += (iMul * iDelta);
  125416. pNext = pDocid;
  125417. fts3PoslistCopy(0, &pDocid);
  125418. while( pDocid<pEnd && *pDocid==0 ) pDocid++;
  125419. iMul = (bDescIdx ? -1 : 1);
  125420. }
  125421. *pnList = (int)(pEnd - pNext);
  125422. *ppIter = pNext;
  125423. *piDocid = iDocid;
  125424. }else{
  125425. int iMul = (bDescIdx ? -1 : 1);
  125426. sqlite3_int64 iDelta;
  125427. fts3GetReverseVarint(&p, aDoclist, &iDelta);
  125428. *piDocid -= (iMul * iDelta);
  125429. if( p==aDoclist ){
  125430. *pbEof = 1;
  125431. }else{
  125432. char *pSave = p;
  125433. fts3ReversePoslist(aDoclist, &p);
  125434. *pnList = (int)(pSave - p);
  125435. }
  125436. *ppIter = p;
  125437. }
  125438. }
  125439. /*
  125440. ** Iterate forwards through a doclist.
  125441. */
  125442. SQLITE_PRIVATE void sqlite3Fts3DoclistNext(
  125443. int bDescIdx, /* True if the doclist is desc */
  125444. char *aDoclist, /* Pointer to entire doclist */
  125445. int nDoclist, /* Length of aDoclist in bytes */
  125446. char **ppIter, /* IN/OUT: Iterator pointer */
  125447. sqlite3_int64 *piDocid, /* IN/OUT: Docid pointer */
  125448. u8 *pbEof /* OUT: End-of-file flag */
  125449. ){
  125450. char *p = *ppIter;
  125451. assert( nDoclist>0 );
  125452. assert( *pbEof==0 );
  125453. assert( p || *piDocid==0 );
  125454. assert( !p || (p>=aDoclist && p<=&aDoclist[nDoclist]) );
  125455. if( p==0 ){
  125456. p = aDoclist;
  125457. p += sqlite3Fts3GetVarint(p, piDocid);
  125458. }else{
  125459. fts3PoslistCopy(0, &p);
  125460. if( p>=&aDoclist[nDoclist] ){
  125461. *pbEof = 1;
  125462. }else{
  125463. sqlite3_int64 iVar;
  125464. p += sqlite3Fts3GetVarint(p, &iVar);
  125465. *piDocid += ((bDescIdx ? -1 : 1) * iVar);
  125466. }
  125467. }
  125468. *ppIter = p;
  125469. }
  125470. /*
  125471. ** Advance the iterator pDL to the next entry in pDL->aAll/nAll. Set *pbEof
  125472. ** to true if EOF is reached.
  125473. */
  125474. static void fts3EvalDlPhraseNext(
  125475. Fts3Table *pTab,
  125476. Fts3Doclist *pDL,
  125477. u8 *pbEof
  125478. ){
  125479. char *pIter; /* Used to iterate through aAll */
  125480. char *pEnd = &pDL->aAll[pDL->nAll]; /* 1 byte past end of aAll */
  125481. if( pDL->pNextDocid ){
  125482. pIter = pDL->pNextDocid;
  125483. }else{
  125484. pIter = pDL->aAll;
  125485. }
  125486. if( pIter>=pEnd ){
  125487. /* We have already reached the end of this doclist. EOF. */
  125488. *pbEof = 1;
  125489. }else{
  125490. sqlite3_int64 iDelta;
  125491. pIter += sqlite3Fts3GetVarint(pIter, &iDelta);
  125492. if( pTab->bDescIdx==0 || pDL->pNextDocid==0 ){
  125493. pDL->iDocid += iDelta;
  125494. }else{
  125495. pDL->iDocid -= iDelta;
  125496. }
  125497. pDL->pList = pIter;
  125498. fts3PoslistCopy(0, &pIter);
  125499. pDL->nList = (int)(pIter - pDL->pList);
  125500. /* pIter now points just past the 0x00 that terminates the position-
  125501. ** list for document pDL->iDocid. However, if this position-list was
  125502. ** edited in place by fts3EvalNearTrim(), then pIter may not actually
  125503. ** point to the start of the next docid value. The following line deals
  125504. ** with this case by advancing pIter past the zero-padding added by
  125505. ** fts3EvalNearTrim(). */
  125506. while( pIter<pEnd && *pIter==0 ) pIter++;
  125507. pDL->pNextDocid = pIter;
  125508. assert( pIter>=&pDL->aAll[pDL->nAll] || *pIter );
  125509. *pbEof = 0;
  125510. }
  125511. }
  125512. /*
  125513. ** Helper type used by fts3EvalIncrPhraseNext() and incrPhraseTokenNext().
  125514. */
  125515. typedef struct TokenDoclist TokenDoclist;
  125516. struct TokenDoclist {
  125517. int bIgnore;
  125518. sqlite3_int64 iDocid;
  125519. char *pList;
  125520. int nList;
  125521. };
  125522. /*
  125523. ** Token pToken is an incrementally loaded token that is part of a
  125524. ** multi-token phrase. Advance it to the next matching document in the
  125525. ** database and populate output variable *p with the details of the new
  125526. ** entry. Or, if the iterator has reached EOF, set *pbEof to true.
  125527. **
  125528. ** If an error occurs, return an SQLite error code. Otherwise, return
  125529. ** SQLITE_OK.
  125530. */
  125531. static int incrPhraseTokenNext(
  125532. Fts3Table *pTab, /* Virtual table handle */
  125533. Fts3Phrase *pPhrase, /* Phrase to advance token of */
  125534. int iToken, /* Specific token to advance */
  125535. TokenDoclist *p, /* OUT: Docid and doclist for new entry */
  125536. u8 *pbEof /* OUT: True if iterator is at EOF */
  125537. ){
  125538. int rc = SQLITE_OK;
  125539. if( pPhrase->iDoclistToken==iToken ){
  125540. assert( p->bIgnore==0 );
  125541. assert( pPhrase->aToken[iToken].pSegcsr==0 );
  125542. fts3EvalDlPhraseNext(pTab, &pPhrase->doclist, pbEof);
  125543. p->pList = pPhrase->doclist.pList;
  125544. p->nList = pPhrase->doclist.nList;
  125545. p->iDocid = pPhrase->doclist.iDocid;
  125546. }else{
  125547. Fts3PhraseToken *pToken = &pPhrase->aToken[iToken];
  125548. assert( pToken->pDeferred==0 );
  125549. assert( pToken->pSegcsr || pPhrase->iDoclistToken>=0 );
  125550. if( pToken->pSegcsr ){
  125551. assert( p->bIgnore==0 );
  125552. rc = sqlite3Fts3MsrIncrNext(
  125553. pTab, pToken->pSegcsr, &p->iDocid, &p->pList, &p->nList
  125554. );
  125555. if( p->pList==0 ) *pbEof = 1;
  125556. }else{
  125557. p->bIgnore = 1;
  125558. }
  125559. }
  125560. return rc;
  125561. }
  125562. /*
  125563. ** The phrase iterator passed as the second argument:
  125564. **
  125565. ** * features at least one token that uses an incremental doclist, and
  125566. **
  125567. ** * does not contain any deferred tokens.
  125568. **
  125569. ** Advance it to the next matching documnent in the database and populate
  125570. ** the Fts3Doclist.pList and nList fields.
  125571. **
  125572. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  125573. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  125574. ** successfully advanced, *pbEof is set to 0.
  125575. **
  125576. ** If an error occurs, return an SQLite error code. Otherwise, return
  125577. ** SQLITE_OK.
  125578. */
  125579. static int fts3EvalIncrPhraseNext(
  125580. Fts3Cursor *pCsr, /* FTS Cursor handle */
  125581. Fts3Phrase *p, /* Phrase object to advance to next docid */
  125582. u8 *pbEof /* OUT: Set to 1 if EOF */
  125583. ){
  125584. int rc = SQLITE_OK;
  125585. Fts3Doclist *pDL = &p->doclist;
  125586. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125587. u8 bEof = 0;
  125588. /* This is only called if it is guaranteed that the phrase has at least
  125589. ** one incremental token. In which case the bIncr flag is set. */
  125590. assert( p->bIncr==1 );
  125591. if( p->nToken==1 && p->bIncr ){
  125592. rc = sqlite3Fts3MsrIncrNext(pTab, p->aToken[0].pSegcsr,
  125593. &pDL->iDocid, &pDL->pList, &pDL->nList
  125594. );
  125595. if( pDL->pList==0 ) bEof = 1;
  125596. }else{
  125597. int bDescDoclist = pCsr->bDesc;
  125598. struct TokenDoclist a[MAX_INCR_PHRASE_TOKENS];
  125599. memset(a, 0, sizeof(a));
  125600. assert( p->nToken<=MAX_INCR_PHRASE_TOKENS );
  125601. assert( p->iDoclistToken<MAX_INCR_PHRASE_TOKENS );
  125602. while( bEof==0 ){
  125603. int bMaxSet = 0;
  125604. sqlite3_int64 iMax = 0; /* Largest docid for all iterators */
  125605. int i; /* Used to iterate through tokens */
  125606. /* Advance the iterator for each token in the phrase once. */
  125607. for(i=0; rc==SQLITE_OK && i<p->nToken && bEof==0; i++){
  125608. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  125609. if( a[i].bIgnore==0 && (bMaxSet==0 || DOCID_CMP(iMax, a[i].iDocid)<0) ){
  125610. iMax = a[i].iDocid;
  125611. bMaxSet = 1;
  125612. }
  125613. }
  125614. assert( rc!=SQLITE_OK || (p->nToken>=1 && a[p->nToken-1].bIgnore==0) );
  125615. assert( rc!=SQLITE_OK || bMaxSet );
  125616. /* Keep advancing iterators until they all point to the same document */
  125617. for(i=0; i<p->nToken; i++){
  125618. while( rc==SQLITE_OK && bEof==0
  125619. && a[i].bIgnore==0 && DOCID_CMP(a[i].iDocid, iMax)<0
  125620. ){
  125621. rc = incrPhraseTokenNext(pTab, p, i, &a[i], &bEof);
  125622. if( DOCID_CMP(a[i].iDocid, iMax)>0 ){
  125623. iMax = a[i].iDocid;
  125624. i = 0;
  125625. }
  125626. }
  125627. }
  125628. /* Check if the current entries really are a phrase match */
  125629. if( bEof==0 ){
  125630. int nList = 0;
  125631. int nByte = a[p->nToken-1].nList;
  125632. char *aDoclist = sqlite3_malloc(nByte+1);
  125633. if( !aDoclist ) return SQLITE_NOMEM;
  125634. memcpy(aDoclist, a[p->nToken-1].pList, nByte+1);
  125635. for(i=0; i<(p->nToken-1); i++){
  125636. if( a[i].bIgnore==0 ){
  125637. char *pL = a[i].pList;
  125638. char *pR = aDoclist;
  125639. char *pOut = aDoclist;
  125640. int nDist = p->nToken-1-i;
  125641. int res = fts3PoslistPhraseMerge(&pOut, nDist, 0, 1, &pL, &pR);
  125642. if( res==0 ) break;
  125643. nList = (int)(pOut - aDoclist);
  125644. }
  125645. }
  125646. if( i==(p->nToken-1) ){
  125647. pDL->iDocid = iMax;
  125648. pDL->pList = aDoclist;
  125649. pDL->nList = nList;
  125650. pDL->bFreeList = 1;
  125651. break;
  125652. }
  125653. sqlite3_free(aDoclist);
  125654. }
  125655. }
  125656. }
  125657. *pbEof = bEof;
  125658. return rc;
  125659. }
  125660. /*
  125661. ** Attempt to move the phrase iterator to point to the next matching docid.
  125662. ** If an error occurs, return an SQLite error code. Otherwise, return
  125663. ** SQLITE_OK.
  125664. **
  125665. ** If there is no "next" entry and no error occurs, then *pbEof is set to
  125666. ** 1 before returning. Otherwise, if no error occurs and the iterator is
  125667. ** successfully advanced, *pbEof is set to 0.
  125668. */
  125669. static int fts3EvalPhraseNext(
  125670. Fts3Cursor *pCsr, /* FTS Cursor handle */
  125671. Fts3Phrase *p, /* Phrase object to advance to next docid */
  125672. u8 *pbEof /* OUT: Set to 1 if EOF */
  125673. ){
  125674. int rc = SQLITE_OK;
  125675. Fts3Doclist *pDL = &p->doclist;
  125676. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125677. if( p->bIncr ){
  125678. rc = fts3EvalIncrPhraseNext(pCsr, p, pbEof);
  125679. }else if( pCsr->bDesc!=pTab->bDescIdx && pDL->nAll ){
  125680. sqlite3Fts3DoclistPrev(pTab->bDescIdx, pDL->aAll, pDL->nAll,
  125681. &pDL->pNextDocid, &pDL->iDocid, &pDL->nList, pbEof
  125682. );
  125683. pDL->pList = pDL->pNextDocid;
  125684. }else{
  125685. fts3EvalDlPhraseNext(pTab, pDL, pbEof);
  125686. }
  125687. return rc;
  125688. }
  125689. /*
  125690. **
  125691. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  125692. ** Otherwise, fts3EvalPhraseStart() is called on all phrases within the
  125693. ** expression. Also the Fts3Expr.bDeferred variable is set to true for any
  125694. ** expressions for which all descendent tokens are deferred.
  125695. **
  125696. ** If parameter bOptOk is zero, then it is guaranteed that the
  125697. ** Fts3Phrase.doclist.aAll/nAll variables contain the entire doclist for
  125698. ** each phrase in the expression (subject to deferred token processing).
  125699. ** Or, if bOptOk is non-zero, then one or more tokens within the expression
  125700. ** may be loaded incrementally, meaning doclist.aAll/nAll is not available.
  125701. **
  125702. ** If an error occurs within this function, *pRc is set to an SQLite error
  125703. ** code before returning.
  125704. */
  125705. static void fts3EvalStartReaders(
  125706. Fts3Cursor *pCsr, /* FTS Cursor handle */
  125707. Fts3Expr *pExpr, /* Expression to initialize phrases in */
  125708. int *pRc /* IN/OUT: Error code */
  125709. ){
  125710. if( pExpr && SQLITE_OK==*pRc ){
  125711. if( pExpr->eType==FTSQUERY_PHRASE ){
  125712. int i;
  125713. int nToken = pExpr->pPhrase->nToken;
  125714. for(i=0; i<nToken; i++){
  125715. if( pExpr->pPhrase->aToken[i].pDeferred==0 ) break;
  125716. }
  125717. pExpr->bDeferred = (i==nToken);
  125718. *pRc = fts3EvalPhraseStart(pCsr, 1, pExpr->pPhrase);
  125719. }else{
  125720. fts3EvalStartReaders(pCsr, pExpr->pLeft, pRc);
  125721. fts3EvalStartReaders(pCsr, pExpr->pRight, pRc);
  125722. pExpr->bDeferred = (pExpr->pLeft->bDeferred && pExpr->pRight->bDeferred);
  125723. }
  125724. }
  125725. }
  125726. /*
  125727. ** An array of the following structures is assembled as part of the process
  125728. ** of selecting tokens to defer before the query starts executing (as part
  125729. ** of the xFilter() method). There is one element in the array for each
  125730. ** token in the FTS expression.
  125731. **
  125732. ** Tokens are divided into AND/NEAR clusters. All tokens in a cluster belong
  125733. ** to phrases that are connected only by AND and NEAR operators (not OR or
  125734. ** NOT). When determining tokens to defer, each AND/NEAR cluster is considered
  125735. ** separately. The root of a tokens AND/NEAR cluster is stored in
  125736. ** Fts3TokenAndCost.pRoot.
  125737. */
  125738. typedef struct Fts3TokenAndCost Fts3TokenAndCost;
  125739. struct Fts3TokenAndCost {
  125740. Fts3Phrase *pPhrase; /* The phrase the token belongs to */
  125741. int iToken; /* Position of token in phrase */
  125742. Fts3PhraseToken *pToken; /* The token itself */
  125743. Fts3Expr *pRoot; /* Root of NEAR/AND cluster */
  125744. int nOvfl; /* Number of overflow pages to load doclist */
  125745. int iCol; /* The column the token must match */
  125746. };
  125747. /*
  125748. ** This function is used to populate an allocated Fts3TokenAndCost array.
  125749. **
  125750. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  125751. ** Otherwise, if an error occurs during execution, *pRc is set to an
  125752. ** SQLite error code.
  125753. */
  125754. static void fts3EvalTokenCosts(
  125755. Fts3Cursor *pCsr, /* FTS Cursor handle */
  125756. Fts3Expr *pRoot, /* Root of current AND/NEAR cluster */
  125757. Fts3Expr *pExpr, /* Expression to consider */
  125758. Fts3TokenAndCost **ppTC, /* Write new entries to *(*ppTC)++ */
  125759. Fts3Expr ***ppOr, /* Write new OR root to *(*ppOr)++ */
  125760. int *pRc /* IN/OUT: Error code */
  125761. ){
  125762. if( *pRc==SQLITE_OK ){
  125763. if( pExpr->eType==FTSQUERY_PHRASE ){
  125764. Fts3Phrase *pPhrase = pExpr->pPhrase;
  125765. int i;
  125766. for(i=0; *pRc==SQLITE_OK && i<pPhrase->nToken; i++){
  125767. Fts3TokenAndCost *pTC = (*ppTC)++;
  125768. pTC->pPhrase = pPhrase;
  125769. pTC->iToken = i;
  125770. pTC->pRoot = pRoot;
  125771. pTC->pToken = &pPhrase->aToken[i];
  125772. pTC->iCol = pPhrase->iColumn;
  125773. *pRc = sqlite3Fts3MsrOvfl(pCsr, pTC->pToken->pSegcsr, &pTC->nOvfl);
  125774. }
  125775. }else if( pExpr->eType!=FTSQUERY_NOT ){
  125776. assert( pExpr->eType==FTSQUERY_OR
  125777. || pExpr->eType==FTSQUERY_AND
  125778. || pExpr->eType==FTSQUERY_NEAR
  125779. );
  125780. assert( pExpr->pLeft && pExpr->pRight );
  125781. if( pExpr->eType==FTSQUERY_OR ){
  125782. pRoot = pExpr->pLeft;
  125783. **ppOr = pRoot;
  125784. (*ppOr)++;
  125785. }
  125786. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pLeft, ppTC, ppOr, pRc);
  125787. if( pExpr->eType==FTSQUERY_OR ){
  125788. pRoot = pExpr->pRight;
  125789. **ppOr = pRoot;
  125790. (*ppOr)++;
  125791. }
  125792. fts3EvalTokenCosts(pCsr, pRoot, pExpr->pRight, ppTC, ppOr, pRc);
  125793. }
  125794. }
  125795. }
  125796. /*
  125797. ** Determine the average document (row) size in pages. If successful,
  125798. ** write this value to *pnPage and return SQLITE_OK. Otherwise, return
  125799. ** an SQLite error code.
  125800. **
  125801. ** The average document size in pages is calculated by first calculating
  125802. ** determining the average size in bytes, B. If B is less than the amount
  125803. ** of data that will fit on a single leaf page of an intkey table in
  125804. ** this database, then the average docsize is 1. Otherwise, it is 1 plus
  125805. ** the number of overflow pages consumed by a record B bytes in size.
  125806. */
  125807. static int fts3EvalAverageDocsize(Fts3Cursor *pCsr, int *pnPage){
  125808. if( pCsr->nRowAvg==0 ){
  125809. /* The average document size, which is required to calculate the cost
  125810. ** of each doclist, has not yet been determined. Read the required
  125811. ** data from the %_stat table to calculate it.
  125812. **
  125813. ** Entry 0 of the %_stat table is a blob containing (nCol+1) FTS3
  125814. ** varints, where nCol is the number of columns in the FTS3 table.
  125815. ** The first varint is the number of documents currently stored in
  125816. ** the table. The following nCol varints contain the total amount of
  125817. ** data stored in all rows of each column of the table, from left
  125818. ** to right.
  125819. */
  125820. int rc;
  125821. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  125822. sqlite3_stmt *pStmt;
  125823. sqlite3_int64 nDoc = 0;
  125824. sqlite3_int64 nByte = 0;
  125825. const char *pEnd;
  125826. const char *a;
  125827. rc = sqlite3Fts3SelectDoctotal(p, &pStmt);
  125828. if( rc!=SQLITE_OK ) return rc;
  125829. a = sqlite3_column_blob(pStmt, 0);
  125830. assert( a );
  125831. pEnd = &a[sqlite3_column_bytes(pStmt, 0)];
  125832. a += sqlite3Fts3GetVarint(a, &nDoc);
  125833. while( a<pEnd ){
  125834. a += sqlite3Fts3GetVarint(a, &nByte);
  125835. }
  125836. if( nDoc==0 || nByte==0 ){
  125837. sqlite3_reset(pStmt);
  125838. return FTS_CORRUPT_VTAB;
  125839. }
  125840. pCsr->nDoc = nDoc;
  125841. pCsr->nRowAvg = (int)(((nByte / nDoc) + p->nPgsz) / p->nPgsz);
  125842. assert( pCsr->nRowAvg>0 );
  125843. rc = sqlite3_reset(pStmt);
  125844. if( rc!=SQLITE_OK ) return rc;
  125845. }
  125846. *pnPage = pCsr->nRowAvg;
  125847. return SQLITE_OK;
  125848. }
  125849. /*
  125850. ** This function is called to select the tokens (if any) that will be
  125851. ** deferred. The array aTC[] has already been populated when this is
  125852. ** called.
  125853. **
  125854. ** This function is called once for each AND/NEAR cluster in the
  125855. ** expression. Each invocation determines which tokens to defer within
  125856. ** the cluster with root node pRoot. See comments above the definition
  125857. ** of struct Fts3TokenAndCost for more details.
  125858. **
  125859. ** If no error occurs, SQLITE_OK is returned and sqlite3Fts3DeferToken()
  125860. ** called on each token to defer. Otherwise, an SQLite error code is
  125861. ** returned.
  125862. */
  125863. static int fts3EvalSelectDeferred(
  125864. Fts3Cursor *pCsr, /* FTS Cursor handle */
  125865. Fts3Expr *pRoot, /* Consider tokens with this root node */
  125866. Fts3TokenAndCost *aTC, /* Array of expression tokens and costs */
  125867. int nTC /* Number of entries in aTC[] */
  125868. ){
  125869. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125870. int nDocSize = 0; /* Number of pages per doc loaded */
  125871. int rc = SQLITE_OK; /* Return code */
  125872. int ii; /* Iterator variable for various purposes */
  125873. int nOvfl = 0; /* Total overflow pages used by doclists */
  125874. int nToken = 0; /* Total number of tokens in cluster */
  125875. int nMinEst = 0; /* The minimum count for any phrase so far. */
  125876. int nLoad4 = 1; /* (Phrases that will be loaded)^4. */
  125877. /* Tokens are never deferred for FTS tables created using the content=xxx
  125878. ** option. The reason being that it is not guaranteed that the content
  125879. ** table actually contains the same data as the index. To prevent this from
  125880. ** causing any problems, the deferred token optimization is completely
  125881. ** disabled for content=xxx tables. */
  125882. if( pTab->zContentTbl ){
  125883. return SQLITE_OK;
  125884. }
  125885. /* Count the tokens in this AND/NEAR cluster. If none of the doclists
  125886. ** associated with the tokens spill onto overflow pages, or if there is
  125887. ** only 1 token, exit early. No tokens to defer in this case. */
  125888. for(ii=0; ii<nTC; ii++){
  125889. if( aTC[ii].pRoot==pRoot ){
  125890. nOvfl += aTC[ii].nOvfl;
  125891. nToken++;
  125892. }
  125893. }
  125894. if( nOvfl==0 || nToken<2 ) return SQLITE_OK;
  125895. /* Obtain the average docsize (in pages). */
  125896. rc = fts3EvalAverageDocsize(pCsr, &nDocSize);
  125897. assert( rc!=SQLITE_OK || nDocSize>0 );
  125898. /* Iterate through all tokens in this AND/NEAR cluster, in ascending order
  125899. ** of the number of overflow pages that will be loaded by the pager layer
  125900. ** to retrieve the entire doclist for the token from the full-text index.
  125901. ** Load the doclists for tokens that are either:
  125902. **
  125903. ** a. The cheapest token in the entire query (i.e. the one visited by the
  125904. ** first iteration of this loop), or
  125905. **
  125906. ** b. Part of a multi-token phrase.
  125907. **
  125908. ** After each token doclist is loaded, merge it with the others from the
  125909. ** same phrase and count the number of documents that the merged doclist
  125910. ** contains. Set variable "nMinEst" to the smallest number of documents in
  125911. ** any phrase doclist for which 1 or more token doclists have been loaded.
  125912. ** Let nOther be the number of other phrases for which it is certain that
  125913. ** one or more tokens will not be deferred.
  125914. **
  125915. ** Then, for each token, defer it if loading the doclist would result in
  125916. ** loading N or more overflow pages into memory, where N is computed as:
  125917. **
  125918. ** (nMinEst + 4^nOther - 1) / (4^nOther)
  125919. */
  125920. for(ii=0; ii<nToken && rc==SQLITE_OK; ii++){
  125921. int iTC; /* Used to iterate through aTC[] array. */
  125922. Fts3TokenAndCost *pTC = 0; /* Set to cheapest remaining token. */
  125923. /* Set pTC to point to the cheapest remaining token. */
  125924. for(iTC=0; iTC<nTC; iTC++){
  125925. if( aTC[iTC].pToken && aTC[iTC].pRoot==pRoot
  125926. && (!pTC || aTC[iTC].nOvfl<pTC->nOvfl)
  125927. ){
  125928. pTC = &aTC[iTC];
  125929. }
  125930. }
  125931. assert( pTC );
  125932. if( ii && pTC->nOvfl>=((nMinEst+(nLoad4/4)-1)/(nLoad4/4))*nDocSize ){
  125933. /* The number of overflow pages to load for this (and therefore all
  125934. ** subsequent) tokens is greater than the estimated number of pages
  125935. ** that will be loaded if all subsequent tokens are deferred.
  125936. */
  125937. Fts3PhraseToken *pToken = pTC->pToken;
  125938. rc = sqlite3Fts3DeferToken(pCsr, pToken, pTC->iCol);
  125939. fts3SegReaderCursorFree(pToken->pSegcsr);
  125940. pToken->pSegcsr = 0;
  125941. }else{
  125942. /* Set nLoad4 to the value of (4^nOther) for the next iteration of the
  125943. ** for-loop. Except, limit the value to 2^24 to prevent it from
  125944. ** overflowing the 32-bit integer it is stored in. */
  125945. if( ii<12 ) nLoad4 = nLoad4*4;
  125946. if( ii==0 || (pTC->pPhrase->nToken>1 && ii!=nToken-1) ){
  125947. /* Either this is the cheapest token in the entire query, or it is
  125948. ** part of a multi-token phrase. Either way, the entire doclist will
  125949. ** (eventually) be loaded into memory. It may as well be now. */
  125950. Fts3PhraseToken *pToken = pTC->pToken;
  125951. int nList = 0;
  125952. char *pList = 0;
  125953. rc = fts3TermSelect(pTab, pToken, pTC->iCol, &nList, &pList);
  125954. assert( rc==SQLITE_OK || pList==0 );
  125955. if( rc==SQLITE_OK ){
  125956. int nCount;
  125957. fts3EvalPhraseMergeToken(pTab, pTC->pPhrase, pTC->iToken,pList,nList);
  125958. nCount = fts3DoclistCountDocids(
  125959. pTC->pPhrase->doclist.aAll, pTC->pPhrase->doclist.nAll
  125960. );
  125961. if( ii==0 || nCount<nMinEst ) nMinEst = nCount;
  125962. }
  125963. }
  125964. }
  125965. pTC->pToken = 0;
  125966. }
  125967. return rc;
  125968. }
  125969. /*
  125970. ** This function is called from within the xFilter method. It initializes
  125971. ** the full-text query currently stored in pCsr->pExpr. To iterate through
  125972. ** the results of a query, the caller does:
  125973. **
  125974. ** fts3EvalStart(pCsr);
  125975. ** while( 1 ){
  125976. ** fts3EvalNext(pCsr);
  125977. ** if( pCsr->bEof ) break;
  125978. ** ... return row pCsr->iPrevId to the caller ...
  125979. ** }
  125980. */
  125981. static int fts3EvalStart(Fts3Cursor *pCsr){
  125982. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  125983. int rc = SQLITE_OK;
  125984. int nToken = 0;
  125985. int nOr = 0;
  125986. /* Allocate a MultiSegReader for each token in the expression. */
  125987. fts3EvalAllocateReaders(pCsr, pCsr->pExpr, &nToken, &nOr, &rc);
  125988. /* Determine which, if any, tokens in the expression should be deferred. */
  125989. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  125990. if( rc==SQLITE_OK && nToken>1 && pTab->bFts4 ){
  125991. Fts3TokenAndCost *aTC;
  125992. Fts3Expr **apOr;
  125993. aTC = (Fts3TokenAndCost *)sqlite3_malloc(
  125994. sizeof(Fts3TokenAndCost) * nToken
  125995. + sizeof(Fts3Expr *) * nOr * 2
  125996. );
  125997. apOr = (Fts3Expr **)&aTC[nToken];
  125998. if( !aTC ){
  125999. rc = SQLITE_NOMEM;
  126000. }else{
  126001. int ii;
  126002. Fts3TokenAndCost *pTC = aTC;
  126003. Fts3Expr **ppOr = apOr;
  126004. fts3EvalTokenCosts(pCsr, 0, pCsr->pExpr, &pTC, &ppOr, &rc);
  126005. nToken = (int)(pTC-aTC);
  126006. nOr = (int)(ppOr-apOr);
  126007. if( rc==SQLITE_OK ){
  126008. rc = fts3EvalSelectDeferred(pCsr, 0, aTC, nToken);
  126009. for(ii=0; rc==SQLITE_OK && ii<nOr; ii++){
  126010. rc = fts3EvalSelectDeferred(pCsr, apOr[ii], aTC, nToken);
  126011. }
  126012. }
  126013. sqlite3_free(aTC);
  126014. }
  126015. }
  126016. #endif
  126017. fts3EvalStartReaders(pCsr, pCsr->pExpr, &rc);
  126018. return rc;
  126019. }
  126020. /*
  126021. ** Invalidate the current position list for phrase pPhrase.
  126022. */
  126023. static void fts3EvalInvalidatePoslist(Fts3Phrase *pPhrase){
  126024. if( pPhrase->doclist.bFreeList ){
  126025. sqlite3_free(pPhrase->doclist.pList);
  126026. }
  126027. pPhrase->doclist.pList = 0;
  126028. pPhrase->doclist.nList = 0;
  126029. pPhrase->doclist.bFreeList = 0;
  126030. }
  126031. /*
  126032. ** This function is called to edit the position list associated with
  126033. ** the phrase object passed as the fifth argument according to a NEAR
  126034. ** condition. For example:
  126035. **
  126036. ** abc NEAR/5 "def ghi"
  126037. **
  126038. ** Parameter nNear is passed the NEAR distance of the expression (5 in
  126039. ** the example above). When this function is called, *paPoslist points to
  126040. ** the position list, and *pnToken is the number of phrase tokens in, the
  126041. ** phrase on the other side of the NEAR operator to pPhrase. For example,
  126042. ** if pPhrase refers to the "def ghi" phrase, then *paPoslist points to
  126043. ** the position list associated with phrase "abc".
  126044. **
  126045. ** All positions in the pPhrase position list that are not sufficiently
  126046. ** close to a position in the *paPoslist position list are removed. If this
  126047. ** leaves 0 positions, zero is returned. Otherwise, non-zero.
  126048. **
  126049. ** Before returning, *paPoslist is set to point to the position lsit
  126050. ** associated with pPhrase. And *pnToken is set to the number of tokens in
  126051. ** pPhrase.
  126052. */
  126053. static int fts3EvalNearTrim(
  126054. int nNear, /* NEAR distance. As in "NEAR/nNear". */
  126055. char *aTmp, /* Temporary space to use */
  126056. char **paPoslist, /* IN/OUT: Position list */
  126057. int *pnToken, /* IN/OUT: Tokens in phrase of *paPoslist */
  126058. Fts3Phrase *pPhrase /* The phrase object to trim the doclist of */
  126059. ){
  126060. int nParam1 = nNear + pPhrase->nToken;
  126061. int nParam2 = nNear + *pnToken;
  126062. int nNew;
  126063. char *p2;
  126064. char *pOut;
  126065. int res;
  126066. assert( pPhrase->doclist.pList );
  126067. p2 = pOut = pPhrase->doclist.pList;
  126068. res = fts3PoslistNearMerge(
  126069. &pOut, aTmp, nParam1, nParam2, paPoslist, &p2
  126070. );
  126071. if( res ){
  126072. nNew = (int)(pOut - pPhrase->doclist.pList) - 1;
  126073. assert( pPhrase->doclist.pList[nNew]=='\0' );
  126074. assert( nNew<=pPhrase->doclist.nList && nNew>0 );
  126075. memset(&pPhrase->doclist.pList[nNew], 0, pPhrase->doclist.nList - nNew);
  126076. pPhrase->doclist.nList = nNew;
  126077. *paPoslist = pPhrase->doclist.pList;
  126078. *pnToken = pPhrase->nToken;
  126079. }
  126080. return res;
  126081. }
  126082. /*
  126083. ** This function is a no-op if *pRc is other than SQLITE_OK when it is called.
  126084. ** Otherwise, it advances the expression passed as the second argument to
  126085. ** point to the next matching row in the database. Expressions iterate through
  126086. ** matching rows in docid order. Ascending order if Fts3Cursor.bDesc is zero,
  126087. ** or descending if it is non-zero.
  126088. **
  126089. ** If an error occurs, *pRc is set to an SQLite error code. Otherwise, if
  126090. ** successful, the following variables in pExpr are set:
  126091. **
  126092. ** Fts3Expr.bEof (non-zero if EOF - there is no next row)
  126093. ** Fts3Expr.iDocid (valid if bEof==0. The docid of the next row)
  126094. **
  126095. ** If the expression is of type FTSQUERY_PHRASE, and the expression is not
  126096. ** at EOF, then the following variables are populated with the position list
  126097. ** for the phrase for the visited row:
  126098. **
  126099. ** FTs3Expr.pPhrase->doclist.nList (length of pList in bytes)
  126100. ** FTs3Expr.pPhrase->doclist.pList (pointer to position list)
  126101. **
  126102. ** It says above that this function advances the expression to the next
  126103. ** matching row. This is usually true, but there are the following exceptions:
  126104. **
  126105. ** 1. Deferred tokens are not taken into account. If a phrase consists
  126106. ** entirely of deferred tokens, it is assumed to match every row in
  126107. ** the db. In this case the position-list is not populated at all.
  126108. **
  126109. ** Or, if a phrase contains one or more deferred tokens and one or
  126110. ** more non-deferred tokens, then the expression is advanced to the
  126111. ** next possible match, considering only non-deferred tokens. In other
  126112. ** words, if the phrase is "A B C", and "B" is deferred, the expression
  126113. ** is advanced to the next row that contains an instance of "A * C",
  126114. ** where "*" may match any single token. The position list in this case
  126115. ** is populated as for "A * C" before returning.
  126116. **
  126117. ** 2. NEAR is treated as AND. If the expression is "x NEAR y", it is
  126118. ** advanced to point to the next row that matches "x AND y".
  126119. **
  126120. ** See fts3EvalTestDeferredAndNear() for details on testing if a row is
  126121. ** really a match, taking into account deferred tokens and NEAR operators.
  126122. */
  126123. static void fts3EvalNextRow(
  126124. Fts3Cursor *pCsr, /* FTS Cursor handle */
  126125. Fts3Expr *pExpr, /* Expr. to advance to next matching row */
  126126. int *pRc /* IN/OUT: Error code */
  126127. ){
  126128. if( *pRc==SQLITE_OK ){
  126129. int bDescDoclist = pCsr->bDesc; /* Used by DOCID_CMP() macro */
  126130. assert( pExpr->bEof==0 );
  126131. pExpr->bStart = 1;
  126132. switch( pExpr->eType ){
  126133. case FTSQUERY_NEAR:
  126134. case FTSQUERY_AND: {
  126135. Fts3Expr *pLeft = pExpr->pLeft;
  126136. Fts3Expr *pRight = pExpr->pRight;
  126137. assert( !pLeft->bDeferred || !pRight->bDeferred );
  126138. if( pLeft->bDeferred ){
  126139. /* LHS is entirely deferred. So we assume it matches every row.
  126140. ** Advance the RHS iterator to find the next row visited. */
  126141. fts3EvalNextRow(pCsr, pRight, pRc);
  126142. pExpr->iDocid = pRight->iDocid;
  126143. pExpr->bEof = pRight->bEof;
  126144. }else if( pRight->bDeferred ){
  126145. /* RHS is entirely deferred. So we assume it matches every row.
  126146. ** Advance the LHS iterator to find the next row visited. */
  126147. fts3EvalNextRow(pCsr, pLeft, pRc);
  126148. pExpr->iDocid = pLeft->iDocid;
  126149. pExpr->bEof = pLeft->bEof;
  126150. }else{
  126151. /* Neither the RHS or LHS are deferred. */
  126152. fts3EvalNextRow(pCsr, pLeft, pRc);
  126153. fts3EvalNextRow(pCsr, pRight, pRc);
  126154. while( !pLeft->bEof && !pRight->bEof && *pRc==SQLITE_OK ){
  126155. sqlite3_int64 iDiff = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  126156. if( iDiff==0 ) break;
  126157. if( iDiff<0 ){
  126158. fts3EvalNextRow(pCsr, pLeft, pRc);
  126159. }else{
  126160. fts3EvalNextRow(pCsr, pRight, pRc);
  126161. }
  126162. }
  126163. pExpr->iDocid = pLeft->iDocid;
  126164. pExpr->bEof = (pLeft->bEof || pRight->bEof);
  126165. }
  126166. break;
  126167. }
  126168. case FTSQUERY_OR: {
  126169. Fts3Expr *pLeft = pExpr->pLeft;
  126170. Fts3Expr *pRight = pExpr->pRight;
  126171. sqlite3_int64 iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  126172. assert( pLeft->bStart || pLeft->iDocid==pRight->iDocid );
  126173. assert( pRight->bStart || pLeft->iDocid==pRight->iDocid );
  126174. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  126175. fts3EvalNextRow(pCsr, pLeft, pRc);
  126176. }else if( pLeft->bEof || (pRight->bEof==0 && iCmp>0) ){
  126177. fts3EvalNextRow(pCsr, pRight, pRc);
  126178. }else{
  126179. fts3EvalNextRow(pCsr, pLeft, pRc);
  126180. fts3EvalNextRow(pCsr, pRight, pRc);
  126181. }
  126182. pExpr->bEof = (pLeft->bEof && pRight->bEof);
  126183. iCmp = DOCID_CMP(pLeft->iDocid, pRight->iDocid);
  126184. if( pRight->bEof || (pLeft->bEof==0 && iCmp<0) ){
  126185. pExpr->iDocid = pLeft->iDocid;
  126186. }else{
  126187. pExpr->iDocid = pRight->iDocid;
  126188. }
  126189. break;
  126190. }
  126191. case FTSQUERY_NOT: {
  126192. Fts3Expr *pLeft = pExpr->pLeft;
  126193. Fts3Expr *pRight = pExpr->pRight;
  126194. if( pRight->bStart==0 ){
  126195. fts3EvalNextRow(pCsr, pRight, pRc);
  126196. assert( *pRc!=SQLITE_OK || pRight->bStart );
  126197. }
  126198. fts3EvalNextRow(pCsr, pLeft, pRc);
  126199. if( pLeft->bEof==0 ){
  126200. while( !*pRc
  126201. && !pRight->bEof
  126202. && DOCID_CMP(pLeft->iDocid, pRight->iDocid)>0
  126203. ){
  126204. fts3EvalNextRow(pCsr, pRight, pRc);
  126205. }
  126206. }
  126207. pExpr->iDocid = pLeft->iDocid;
  126208. pExpr->bEof = pLeft->bEof;
  126209. break;
  126210. }
  126211. default: {
  126212. Fts3Phrase *pPhrase = pExpr->pPhrase;
  126213. fts3EvalInvalidatePoslist(pPhrase);
  126214. *pRc = fts3EvalPhraseNext(pCsr, pPhrase, &pExpr->bEof);
  126215. pExpr->iDocid = pPhrase->doclist.iDocid;
  126216. break;
  126217. }
  126218. }
  126219. }
  126220. }
  126221. /*
  126222. ** If *pRc is not SQLITE_OK, or if pExpr is not the root node of a NEAR
  126223. ** cluster, then this function returns 1 immediately.
  126224. **
  126225. ** Otherwise, it checks if the current row really does match the NEAR
  126226. ** expression, using the data currently stored in the position lists
  126227. ** (Fts3Expr->pPhrase.doclist.pList/nList) for each phrase in the expression.
  126228. **
  126229. ** If the current row is a match, the position list associated with each
  126230. ** phrase in the NEAR expression is edited in place to contain only those
  126231. ** phrase instances sufficiently close to their peers to satisfy all NEAR
  126232. ** constraints. In this case it returns 1. If the NEAR expression does not
  126233. ** match the current row, 0 is returned. The position lists may or may not
  126234. ** be edited if 0 is returned.
  126235. */
  126236. static int fts3EvalNearTest(Fts3Expr *pExpr, int *pRc){
  126237. int res = 1;
  126238. /* The following block runs if pExpr is the root of a NEAR query.
  126239. ** For example, the query:
  126240. **
  126241. ** "w" NEAR "x" NEAR "y" NEAR "z"
  126242. **
  126243. ** which is represented in tree form as:
  126244. **
  126245. ** |
  126246. ** +--NEAR--+ <-- root of NEAR query
  126247. ** | |
  126248. ** +--NEAR--+ "z"
  126249. ** | |
  126250. ** +--NEAR--+ "y"
  126251. ** | |
  126252. ** "w" "x"
  126253. **
  126254. ** The right-hand child of a NEAR node is always a phrase. The
  126255. ** left-hand child may be either a phrase or a NEAR node. There are
  126256. ** no exceptions to this - it's the way the parser in fts3_expr.c works.
  126257. */
  126258. if( *pRc==SQLITE_OK
  126259. && pExpr->eType==FTSQUERY_NEAR
  126260. && pExpr->bEof==0
  126261. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  126262. ){
  126263. Fts3Expr *p;
  126264. int nTmp = 0; /* Bytes of temp space */
  126265. char *aTmp; /* Temp space for PoslistNearMerge() */
  126266. /* Allocate temporary working space. */
  126267. for(p=pExpr; p->pLeft; p=p->pLeft){
  126268. nTmp += p->pRight->pPhrase->doclist.nList;
  126269. }
  126270. nTmp += p->pPhrase->doclist.nList;
  126271. if( nTmp==0 ){
  126272. res = 0;
  126273. }else{
  126274. aTmp = sqlite3_malloc(nTmp*2);
  126275. if( !aTmp ){
  126276. *pRc = SQLITE_NOMEM;
  126277. res = 0;
  126278. }else{
  126279. char *aPoslist = p->pPhrase->doclist.pList;
  126280. int nToken = p->pPhrase->nToken;
  126281. for(p=p->pParent;res && p && p->eType==FTSQUERY_NEAR; p=p->pParent){
  126282. Fts3Phrase *pPhrase = p->pRight->pPhrase;
  126283. int nNear = p->nNear;
  126284. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  126285. }
  126286. aPoslist = pExpr->pRight->pPhrase->doclist.pList;
  126287. nToken = pExpr->pRight->pPhrase->nToken;
  126288. for(p=pExpr->pLeft; p && res; p=p->pLeft){
  126289. int nNear;
  126290. Fts3Phrase *pPhrase;
  126291. assert( p->pParent && p->pParent->pLeft==p );
  126292. nNear = p->pParent->nNear;
  126293. pPhrase = (
  126294. p->eType==FTSQUERY_NEAR ? p->pRight->pPhrase : p->pPhrase
  126295. );
  126296. res = fts3EvalNearTrim(nNear, aTmp, &aPoslist, &nToken, pPhrase);
  126297. }
  126298. }
  126299. sqlite3_free(aTmp);
  126300. }
  126301. }
  126302. return res;
  126303. }
  126304. /*
  126305. ** This function is a helper function for fts3EvalTestDeferredAndNear().
  126306. ** Assuming no error occurs or has occurred, It returns non-zero if the
  126307. ** expression passed as the second argument matches the row that pCsr
  126308. ** currently points to, or zero if it does not.
  126309. **
  126310. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  126311. ** If an error occurs during execution of this function, *pRc is set to
  126312. ** the appropriate SQLite error code. In this case the returned value is
  126313. ** undefined.
  126314. */
  126315. static int fts3EvalTestExpr(
  126316. Fts3Cursor *pCsr, /* FTS cursor handle */
  126317. Fts3Expr *pExpr, /* Expr to test. May or may not be root. */
  126318. int *pRc /* IN/OUT: Error code */
  126319. ){
  126320. int bHit = 1; /* Return value */
  126321. if( *pRc==SQLITE_OK ){
  126322. switch( pExpr->eType ){
  126323. case FTSQUERY_NEAR:
  126324. case FTSQUERY_AND:
  126325. bHit = (
  126326. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  126327. && fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  126328. && fts3EvalNearTest(pExpr, pRc)
  126329. );
  126330. /* If the NEAR expression does not match any rows, zero the doclist for
  126331. ** all phrases involved in the NEAR. This is because the snippet(),
  126332. ** offsets() and matchinfo() functions are not supposed to recognize
  126333. ** any instances of phrases that are part of unmatched NEAR queries.
  126334. ** For example if this expression:
  126335. **
  126336. ** ... MATCH 'a OR (b NEAR c)'
  126337. **
  126338. ** is matched against a row containing:
  126339. **
  126340. ** 'a b d e'
  126341. **
  126342. ** then any snippet() should ony highlight the "a" term, not the "b"
  126343. ** (as "b" is part of a non-matching NEAR clause).
  126344. */
  126345. if( bHit==0
  126346. && pExpr->eType==FTSQUERY_NEAR
  126347. && (pExpr->pParent==0 || pExpr->pParent->eType!=FTSQUERY_NEAR)
  126348. ){
  126349. Fts3Expr *p;
  126350. for(p=pExpr; p->pPhrase==0; p=p->pLeft){
  126351. if( p->pRight->iDocid==pCsr->iPrevId ){
  126352. fts3EvalInvalidatePoslist(p->pRight->pPhrase);
  126353. }
  126354. }
  126355. if( p->iDocid==pCsr->iPrevId ){
  126356. fts3EvalInvalidatePoslist(p->pPhrase);
  126357. }
  126358. }
  126359. break;
  126360. case FTSQUERY_OR: {
  126361. int bHit1 = fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc);
  126362. int bHit2 = fts3EvalTestExpr(pCsr, pExpr->pRight, pRc);
  126363. bHit = bHit1 || bHit2;
  126364. break;
  126365. }
  126366. case FTSQUERY_NOT:
  126367. bHit = (
  126368. fts3EvalTestExpr(pCsr, pExpr->pLeft, pRc)
  126369. && !fts3EvalTestExpr(pCsr, pExpr->pRight, pRc)
  126370. );
  126371. break;
  126372. default: {
  126373. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  126374. if( pCsr->pDeferred
  126375. && (pExpr->iDocid==pCsr->iPrevId || pExpr->bDeferred)
  126376. ){
  126377. Fts3Phrase *pPhrase = pExpr->pPhrase;
  126378. assert( pExpr->bDeferred || pPhrase->doclist.bFreeList==0 );
  126379. if( pExpr->bDeferred ){
  126380. fts3EvalInvalidatePoslist(pPhrase);
  126381. }
  126382. *pRc = fts3EvalDeferredPhrase(pCsr, pPhrase);
  126383. bHit = (pPhrase->doclist.pList!=0);
  126384. pExpr->iDocid = pCsr->iPrevId;
  126385. }else
  126386. #endif
  126387. {
  126388. bHit = (pExpr->bEof==0 && pExpr->iDocid==pCsr->iPrevId);
  126389. }
  126390. break;
  126391. }
  126392. }
  126393. }
  126394. return bHit;
  126395. }
  126396. /*
  126397. ** This function is called as the second part of each xNext operation when
  126398. ** iterating through the results of a full-text query. At this point the
  126399. ** cursor points to a row that matches the query expression, with the
  126400. ** following caveats:
  126401. **
  126402. ** * Up until this point, "NEAR" operators in the expression have been
  126403. ** treated as "AND".
  126404. **
  126405. ** * Deferred tokens have not yet been considered.
  126406. **
  126407. ** If *pRc is not SQLITE_OK when this function is called, it immediately
  126408. ** returns 0. Otherwise, it tests whether or not after considering NEAR
  126409. ** operators and deferred tokens the current row is still a match for the
  126410. ** expression. It returns 1 if both of the following are true:
  126411. **
  126412. ** 1. *pRc is SQLITE_OK when this function returns, and
  126413. **
  126414. ** 2. After scanning the current FTS table row for the deferred tokens,
  126415. ** it is determined that the row does *not* match the query.
  126416. **
  126417. ** Or, if no error occurs and it seems the current row does match the FTS
  126418. ** query, return 0.
  126419. */
  126420. static int fts3EvalTestDeferredAndNear(Fts3Cursor *pCsr, int *pRc){
  126421. int rc = *pRc;
  126422. int bMiss = 0;
  126423. if( rc==SQLITE_OK ){
  126424. /* If there are one or more deferred tokens, load the current row into
  126425. ** memory and scan it to determine the position list for each deferred
  126426. ** token. Then, see if this row is really a match, considering deferred
  126427. ** tokens and NEAR operators (neither of which were taken into account
  126428. ** earlier, by fts3EvalNextRow()).
  126429. */
  126430. if( pCsr->pDeferred ){
  126431. rc = fts3CursorSeek(0, pCsr);
  126432. if( rc==SQLITE_OK ){
  126433. rc = sqlite3Fts3CacheDeferredDoclists(pCsr);
  126434. }
  126435. }
  126436. bMiss = (0==fts3EvalTestExpr(pCsr, pCsr->pExpr, &rc));
  126437. /* Free the position-lists accumulated for each deferred token above. */
  126438. sqlite3Fts3FreeDeferredDoclists(pCsr);
  126439. *pRc = rc;
  126440. }
  126441. return (rc==SQLITE_OK && bMiss);
  126442. }
  126443. /*
  126444. ** Advance to the next document that matches the FTS expression in
  126445. ** Fts3Cursor.pExpr.
  126446. */
  126447. static int fts3EvalNext(Fts3Cursor *pCsr){
  126448. int rc = SQLITE_OK; /* Return Code */
  126449. Fts3Expr *pExpr = pCsr->pExpr;
  126450. assert( pCsr->isEof==0 );
  126451. if( pExpr==0 ){
  126452. pCsr->isEof = 1;
  126453. }else{
  126454. do {
  126455. if( pCsr->isRequireSeek==0 ){
  126456. sqlite3_reset(pCsr->pStmt);
  126457. }
  126458. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  126459. fts3EvalNextRow(pCsr, pExpr, &rc);
  126460. pCsr->isEof = pExpr->bEof;
  126461. pCsr->isRequireSeek = 1;
  126462. pCsr->isMatchinfoNeeded = 1;
  126463. pCsr->iPrevId = pExpr->iDocid;
  126464. }while( pCsr->isEof==0 && fts3EvalTestDeferredAndNear(pCsr, &rc) );
  126465. }
  126466. /* Check if the cursor is past the end of the docid range specified
  126467. ** by Fts3Cursor.iMinDocid/iMaxDocid. If so, set the EOF flag. */
  126468. if( rc==SQLITE_OK && (
  126469. (pCsr->bDesc==0 && pCsr->iPrevId>pCsr->iMaxDocid)
  126470. || (pCsr->bDesc!=0 && pCsr->iPrevId<pCsr->iMinDocid)
  126471. )){
  126472. pCsr->isEof = 1;
  126473. }
  126474. return rc;
  126475. }
  126476. /*
  126477. ** Restart interation for expression pExpr so that the next call to
  126478. ** fts3EvalNext() visits the first row. Do not allow incremental
  126479. ** loading or merging of phrase doclists for this iteration.
  126480. **
  126481. ** If *pRc is other than SQLITE_OK when this function is called, it is
  126482. ** a no-op. If an error occurs within this function, *pRc is set to an
  126483. ** SQLite error code before returning.
  126484. */
  126485. static void fts3EvalRestart(
  126486. Fts3Cursor *pCsr,
  126487. Fts3Expr *pExpr,
  126488. int *pRc
  126489. ){
  126490. if( pExpr && *pRc==SQLITE_OK ){
  126491. Fts3Phrase *pPhrase = pExpr->pPhrase;
  126492. if( pPhrase ){
  126493. fts3EvalInvalidatePoslist(pPhrase);
  126494. if( pPhrase->bIncr ){
  126495. int i;
  126496. for(i=0; i<pPhrase->nToken; i++){
  126497. Fts3PhraseToken *pToken = &pPhrase->aToken[i];
  126498. assert( pToken->pDeferred==0 );
  126499. if( pToken->pSegcsr ){
  126500. sqlite3Fts3MsrIncrRestart(pToken->pSegcsr);
  126501. }
  126502. }
  126503. *pRc = fts3EvalPhraseStart(pCsr, 0, pPhrase);
  126504. }
  126505. pPhrase->doclist.pNextDocid = 0;
  126506. pPhrase->doclist.iDocid = 0;
  126507. }
  126508. pExpr->iDocid = 0;
  126509. pExpr->bEof = 0;
  126510. pExpr->bStart = 0;
  126511. fts3EvalRestart(pCsr, pExpr->pLeft, pRc);
  126512. fts3EvalRestart(pCsr, pExpr->pRight, pRc);
  126513. }
  126514. }
  126515. /*
  126516. ** After allocating the Fts3Expr.aMI[] array for each phrase in the
  126517. ** expression rooted at pExpr, the cursor iterates through all rows matched
  126518. ** by pExpr, calling this function for each row. This function increments
  126519. ** the values in Fts3Expr.aMI[] according to the position-list currently
  126520. ** found in Fts3Expr.pPhrase->doclist.pList for each of the phrase
  126521. ** expression nodes.
  126522. */
  126523. static void fts3EvalUpdateCounts(Fts3Expr *pExpr){
  126524. if( pExpr ){
  126525. Fts3Phrase *pPhrase = pExpr->pPhrase;
  126526. if( pPhrase && pPhrase->doclist.pList ){
  126527. int iCol = 0;
  126528. char *p = pPhrase->doclist.pList;
  126529. assert( *p );
  126530. while( 1 ){
  126531. u8 c = 0;
  126532. int iCnt = 0;
  126533. while( 0xFE & (*p | c) ){
  126534. if( (c&0x80)==0 ) iCnt++;
  126535. c = *p++ & 0x80;
  126536. }
  126537. /* aMI[iCol*3 + 1] = Number of occurrences
  126538. ** aMI[iCol*3 + 2] = Number of rows containing at least one instance
  126539. */
  126540. pExpr->aMI[iCol*3 + 1] += iCnt;
  126541. pExpr->aMI[iCol*3 + 2] += (iCnt>0);
  126542. if( *p==0x00 ) break;
  126543. p++;
  126544. p += fts3GetVarint32(p, &iCol);
  126545. }
  126546. }
  126547. fts3EvalUpdateCounts(pExpr->pLeft);
  126548. fts3EvalUpdateCounts(pExpr->pRight);
  126549. }
  126550. }
  126551. /*
  126552. ** Expression pExpr must be of type FTSQUERY_PHRASE.
  126553. **
  126554. ** If it is not already allocated and populated, this function allocates and
  126555. ** populates the Fts3Expr.aMI[] array for expression pExpr. If pExpr is part
  126556. ** of a NEAR expression, then it also allocates and populates the same array
  126557. ** for all other phrases that are part of the NEAR expression.
  126558. **
  126559. ** SQLITE_OK is returned if the aMI[] array is successfully allocated and
  126560. ** populated. Otherwise, if an error occurs, an SQLite error code is returned.
  126561. */
  126562. static int fts3EvalGatherStats(
  126563. Fts3Cursor *pCsr, /* Cursor object */
  126564. Fts3Expr *pExpr /* FTSQUERY_PHRASE expression */
  126565. ){
  126566. int rc = SQLITE_OK; /* Return code */
  126567. assert( pExpr->eType==FTSQUERY_PHRASE );
  126568. if( pExpr->aMI==0 ){
  126569. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126570. Fts3Expr *pRoot; /* Root of NEAR expression */
  126571. Fts3Expr *p; /* Iterator used for several purposes */
  126572. sqlite3_int64 iPrevId = pCsr->iPrevId;
  126573. sqlite3_int64 iDocid;
  126574. u8 bEof;
  126575. /* Find the root of the NEAR expression */
  126576. pRoot = pExpr;
  126577. while( pRoot->pParent && pRoot->pParent->eType==FTSQUERY_NEAR ){
  126578. pRoot = pRoot->pParent;
  126579. }
  126580. iDocid = pRoot->iDocid;
  126581. bEof = pRoot->bEof;
  126582. assert( pRoot->bStart );
  126583. /* Allocate space for the aMSI[] array of each FTSQUERY_PHRASE node */
  126584. for(p=pRoot; p; p=p->pLeft){
  126585. Fts3Expr *pE = (p->eType==FTSQUERY_PHRASE?p:p->pRight);
  126586. assert( pE->aMI==0 );
  126587. pE->aMI = (u32 *)sqlite3_malloc(pTab->nColumn * 3 * sizeof(u32));
  126588. if( !pE->aMI ) return SQLITE_NOMEM;
  126589. memset(pE->aMI, 0, pTab->nColumn * 3 * sizeof(u32));
  126590. }
  126591. fts3EvalRestart(pCsr, pRoot, &rc);
  126592. while( pCsr->isEof==0 && rc==SQLITE_OK ){
  126593. do {
  126594. /* Ensure the %_content statement is reset. */
  126595. if( pCsr->isRequireSeek==0 ) sqlite3_reset(pCsr->pStmt);
  126596. assert( sqlite3_data_count(pCsr->pStmt)==0 );
  126597. /* Advance to the next document */
  126598. fts3EvalNextRow(pCsr, pRoot, &rc);
  126599. pCsr->isEof = pRoot->bEof;
  126600. pCsr->isRequireSeek = 1;
  126601. pCsr->isMatchinfoNeeded = 1;
  126602. pCsr->iPrevId = pRoot->iDocid;
  126603. }while( pCsr->isEof==0
  126604. && pRoot->eType==FTSQUERY_NEAR
  126605. && fts3EvalTestDeferredAndNear(pCsr, &rc)
  126606. );
  126607. if( rc==SQLITE_OK && pCsr->isEof==0 ){
  126608. fts3EvalUpdateCounts(pRoot);
  126609. }
  126610. }
  126611. pCsr->isEof = 0;
  126612. pCsr->iPrevId = iPrevId;
  126613. if( bEof ){
  126614. pRoot->bEof = bEof;
  126615. }else{
  126616. /* Caution: pRoot may iterate through docids in ascending or descending
  126617. ** order. For this reason, even though it seems more defensive, the
  126618. ** do loop can not be written:
  126619. **
  126620. ** do {...} while( pRoot->iDocid<iDocid && rc==SQLITE_OK );
  126621. */
  126622. fts3EvalRestart(pCsr, pRoot, &rc);
  126623. do {
  126624. fts3EvalNextRow(pCsr, pRoot, &rc);
  126625. assert( pRoot->bEof==0 );
  126626. }while( pRoot->iDocid!=iDocid && rc==SQLITE_OK );
  126627. fts3EvalTestDeferredAndNear(pCsr, &rc);
  126628. }
  126629. }
  126630. return rc;
  126631. }
  126632. /*
  126633. ** This function is used by the matchinfo() module to query a phrase
  126634. ** expression node for the following information:
  126635. **
  126636. ** 1. The total number of occurrences of the phrase in each column of
  126637. ** the FTS table (considering all rows), and
  126638. **
  126639. ** 2. For each column, the number of rows in the table for which the
  126640. ** column contains at least one instance of the phrase.
  126641. **
  126642. ** If no error occurs, SQLITE_OK is returned and the values for each column
  126643. ** written into the array aiOut as follows:
  126644. **
  126645. ** aiOut[iCol*3 + 1] = Number of occurrences
  126646. ** aiOut[iCol*3 + 2] = Number of rows containing at least one instance
  126647. **
  126648. ** Caveats:
  126649. **
  126650. ** * If a phrase consists entirely of deferred tokens, then all output
  126651. ** values are set to the number of documents in the table. In other
  126652. ** words we assume that very common tokens occur exactly once in each
  126653. ** column of each row of the table.
  126654. **
  126655. ** * If a phrase contains some deferred tokens (and some non-deferred
  126656. ** tokens), count the potential occurrence identified by considering
  126657. ** the non-deferred tokens instead of actual phrase occurrences.
  126658. **
  126659. ** * If the phrase is part of a NEAR expression, then only phrase instances
  126660. ** that meet the NEAR constraint are included in the counts.
  126661. */
  126662. SQLITE_PRIVATE int sqlite3Fts3EvalPhraseStats(
  126663. Fts3Cursor *pCsr, /* FTS cursor handle */
  126664. Fts3Expr *pExpr, /* Phrase expression */
  126665. u32 *aiOut /* Array to write results into (see above) */
  126666. ){
  126667. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126668. int rc = SQLITE_OK;
  126669. int iCol;
  126670. if( pExpr->bDeferred && pExpr->pParent->eType!=FTSQUERY_NEAR ){
  126671. assert( pCsr->nDoc>0 );
  126672. for(iCol=0; iCol<pTab->nColumn; iCol++){
  126673. aiOut[iCol*3 + 1] = (u32)pCsr->nDoc;
  126674. aiOut[iCol*3 + 2] = (u32)pCsr->nDoc;
  126675. }
  126676. }else{
  126677. rc = fts3EvalGatherStats(pCsr, pExpr);
  126678. if( rc==SQLITE_OK ){
  126679. assert( pExpr->aMI );
  126680. for(iCol=0; iCol<pTab->nColumn; iCol++){
  126681. aiOut[iCol*3 + 1] = pExpr->aMI[iCol*3 + 1];
  126682. aiOut[iCol*3 + 2] = pExpr->aMI[iCol*3 + 2];
  126683. }
  126684. }
  126685. }
  126686. return rc;
  126687. }
  126688. /*
  126689. ** The expression pExpr passed as the second argument to this function
  126690. ** must be of type FTSQUERY_PHRASE.
  126691. **
  126692. ** The returned value is either NULL or a pointer to a buffer containing
  126693. ** a position-list indicating the occurrences of the phrase in column iCol
  126694. ** of the current row.
  126695. **
  126696. ** More specifically, the returned buffer contains 1 varint for each
  126697. ** occurrence of the phrase in the column, stored using the normal (delta+2)
  126698. ** compression and is terminated by either an 0x01 or 0x00 byte. For example,
  126699. ** if the requested column contains "a b X c d X X" and the position-list
  126700. ** for 'X' is requested, the buffer returned may contain:
  126701. **
  126702. ** 0x04 0x05 0x03 0x01 or 0x04 0x05 0x03 0x00
  126703. **
  126704. ** This function works regardless of whether or not the phrase is deferred,
  126705. ** incremental, or neither.
  126706. */
  126707. SQLITE_PRIVATE int sqlite3Fts3EvalPhrasePoslist(
  126708. Fts3Cursor *pCsr, /* FTS3 cursor object */
  126709. Fts3Expr *pExpr, /* Phrase to return doclist for */
  126710. int iCol, /* Column to return position list for */
  126711. char **ppOut /* OUT: Pointer to position list */
  126712. ){
  126713. Fts3Phrase *pPhrase = pExpr->pPhrase;
  126714. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  126715. char *pIter;
  126716. int iThis;
  126717. sqlite3_int64 iDocid;
  126718. /* If this phrase is applies specifically to some column other than
  126719. ** column iCol, return a NULL pointer. */
  126720. *ppOut = 0;
  126721. assert( iCol>=0 && iCol<pTab->nColumn );
  126722. if( (pPhrase->iColumn<pTab->nColumn && pPhrase->iColumn!=iCol) ){
  126723. return SQLITE_OK;
  126724. }
  126725. iDocid = pExpr->iDocid;
  126726. pIter = pPhrase->doclist.pList;
  126727. if( iDocid!=pCsr->iPrevId || pExpr->bEof ){
  126728. int bDescDoclist = pTab->bDescIdx; /* For DOCID_CMP macro */
  126729. int iMul; /* +1 if csr dir matches index dir, else -1 */
  126730. int bOr = 0;
  126731. u8 bEof = 0;
  126732. u8 bTreeEof = 0;
  126733. Fts3Expr *p; /* Used to iterate from pExpr to root */
  126734. Fts3Expr *pNear; /* Most senior NEAR ancestor (or pExpr) */
  126735. /* Check if this phrase descends from an OR expression node. If not,
  126736. ** return NULL. Otherwise, the entry that corresponds to docid
  126737. ** pCsr->iPrevId may lie earlier in the doclist buffer. Or, if the
  126738. ** tree that the node is part of has been marked as EOF, but the node
  126739. ** itself is not EOF, then it may point to an earlier entry. */
  126740. pNear = pExpr;
  126741. for(p=pExpr->pParent; p; p=p->pParent){
  126742. if( p->eType==FTSQUERY_OR ) bOr = 1;
  126743. if( p->eType==FTSQUERY_NEAR ) pNear = p;
  126744. if( p->bEof ) bTreeEof = 1;
  126745. }
  126746. if( bOr==0 ) return SQLITE_OK;
  126747. /* This is the descendent of an OR node. In this case we cannot use
  126748. ** an incremental phrase. Load the entire doclist for the phrase
  126749. ** into memory in this case. */
  126750. if( pPhrase->bIncr ){
  126751. int rc = SQLITE_OK;
  126752. int bEofSave = pExpr->bEof;
  126753. fts3EvalRestart(pCsr, pExpr, &rc);
  126754. while( rc==SQLITE_OK && !pExpr->bEof ){
  126755. fts3EvalNextRow(pCsr, pExpr, &rc);
  126756. if( bEofSave==0 && pExpr->iDocid==iDocid ) break;
  126757. }
  126758. pIter = pPhrase->doclist.pList;
  126759. assert( rc!=SQLITE_OK || pPhrase->bIncr==0 );
  126760. if( rc!=SQLITE_OK ) return rc;
  126761. }
  126762. iMul = ((pCsr->bDesc==bDescDoclist) ? 1 : -1);
  126763. while( bTreeEof==1
  126764. && pNear->bEof==0
  126765. && (DOCID_CMP(pNear->iDocid, pCsr->iPrevId) * iMul)<0
  126766. ){
  126767. int rc = SQLITE_OK;
  126768. fts3EvalNextRow(pCsr, pExpr, &rc);
  126769. if( rc!=SQLITE_OK ) return rc;
  126770. iDocid = pExpr->iDocid;
  126771. pIter = pPhrase->doclist.pList;
  126772. }
  126773. bEof = (pPhrase->doclist.nAll==0);
  126774. assert( bDescDoclist==0 || bDescDoclist==1 );
  126775. assert( pCsr->bDesc==0 || pCsr->bDesc==1 );
  126776. if( bEof==0 ){
  126777. if( pCsr->bDesc==bDescDoclist ){
  126778. int dummy;
  126779. if( pNear->bEof ){
  126780. /* This expression is already at EOF. So position it to point to the
  126781. ** last entry in the doclist at pPhrase->doclist.aAll[]. Variable
  126782. ** iDocid is already set for this entry, so all that is required is
  126783. ** to set pIter to point to the first byte of the last position-list
  126784. ** in the doclist.
  126785. **
  126786. ** It would also be correct to set pIter and iDocid to zero. In
  126787. ** this case, the first call to sqltie3Fts4DoclistPrev() below
  126788. ** would also move the iterator to point to the last entry in the
  126789. ** doclist. However, this is expensive, as to do so it has to
  126790. ** iterate through the entire doclist from start to finish (since
  126791. ** it does not know the docid for the last entry). */
  126792. pIter = &pPhrase->doclist.aAll[pPhrase->doclist.nAll-1];
  126793. fts3ReversePoslist(pPhrase->doclist.aAll, &pIter);
  126794. }
  126795. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)>0 ) && bEof==0 ){
  126796. sqlite3Fts3DoclistPrev(
  126797. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  126798. &pIter, &iDocid, &dummy, &bEof
  126799. );
  126800. }
  126801. }else{
  126802. if( pNear->bEof ){
  126803. pIter = 0;
  126804. iDocid = 0;
  126805. }
  126806. while( (pIter==0 || DOCID_CMP(iDocid, pCsr->iPrevId)<0 ) && bEof==0 ){
  126807. sqlite3Fts3DoclistNext(
  126808. bDescDoclist, pPhrase->doclist.aAll, pPhrase->doclist.nAll,
  126809. &pIter, &iDocid, &bEof
  126810. );
  126811. }
  126812. }
  126813. }
  126814. if( bEof || iDocid!=pCsr->iPrevId ) pIter = 0;
  126815. }
  126816. if( pIter==0 ) return SQLITE_OK;
  126817. if( *pIter==0x01 ){
  126818. pIter++;
  126819. pIter += fts3GetVarint32(pIter, &iThis);
  126820. }else{
  126821. iThis = 0;
  126822. }
  126823. while( iThis<iCol ){
  126824. fts3ColumnlistCopy(0, &pIter);
  126825. if( *pIter==0x00 ) return 0;
  126826. pIter++;
  126827. pIter += fts3GetVarint32(pIter, &iThis);
  126828. }
  126829. *ppOut = ((iCol==iThis)?pIter:0);
  126830. return SQLITE_OK;
  126831. }
  126832. /*
  126833. ** Free all components of the Fts3Phrase structure that were allocated by
  126834. ** the eval module. Specifically, this means to free:
  126835. **
  126836. ** * the contents of pPhrase->doclist, and
  126837. ** * any Fts3MultiSegReader objects held by phrase tokens.
  126838. */
  126839. SQLITE_PRIVATE void sqlite3Fts3EvalPhraseCleanup(Fts3Phrase *pPhrase){
  126840. if( pPhrase ){
  126841. int i;
  126842. sqlite3_free(pPhrase->doclist.aAll);
  126843. fts3EvalInvalidatePoslist(pPhrase);
  126844. memset(&pPhrase->doclist, 0, sizeof(Fts3Doclist));
  126845. for(i=0; i<pPhrase->nToken; i++){
  126846. fts3SegReaderCursorFree(pPhrase->aToken[i].pSegcsr);
  126847. pPhrase->aToken[i].pSegcsr = 0;
  126848. }
  126849. }
  126850. }
  126851. /*
  126852. ** Return SQLITE_CORRUPT_VTAB.
  126853. */
  126854. #ifdef SQLITE_DEBUG
  126855. SQLITE_PRIVATE int sqlite3Fts3Corrupt(){
  126856. return SQLITE_CORRUPT_VTAB;
  126857. }
  126858. #endif
  126859. #if !SQLITE_CORE
  126860. /*
  126861. ** Initialize API pointer table, if required.
  126862. */
  126863. #ifdef _WIN32
  126864. __declspec(dllexport)
  126865. #endif
  126866. SQLITE_API int sqlite3_fts3_init(
  126867. sqlite3 *db,
  126868. char **pzErrMsg,
  126869. const sqlite3_api_routines *pApi
  126870. ){
  126871. SQLITE_EXTENSION_INIT2(pApi)
  126872. return sqlite3Fts3Init(db);
  126873. }
  126874. #endif
  126875. #endif
  126876. /************** End of fts3.c ************************************************/
  126877. /************** Begin file fts3_aux.c ****************************************/
  126878. /*
  126879. ** 2011 Jan 27
  126880. **
  126881. ** The author disclaims copyright to this source code. In place of
  126882. ** a legal notice, here is a blessing:
  126883. **
  126884. ** May you do good and not evil.
  126885. ** May you find forgiveness for yourself and forgive others.
  126886. ** May you share freely, never taking more than you give.
  126887. **
  126888. ******************************************************************************
  126889. **
  126890. */
  126891. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  126892. /* #include <string.h> */
  126893. /* #include <assert.h> */
  126894. typedef struct Fts3auxTable Fts3auxTable;
  126895. typedef struct Fts3auxCursor Fts3auxCursor;
  126896. struct Fts3auxTable {
  126897. sqlite3_vtab base; /* Base class used by SQLite core */
  126898. Fts3Table *pFts3Tab;
  126899. };
  126900. struct Fts3auxCursor {
  126901. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  126902. Fts3MultiSegReader csr; /* Must be right after "base" */
  126903. Fts3SegFilter filter;
  126904. char *zStop;
  126905. int nStop; /* Byte-length of string zStop */
  126906. int iLangid; /* Language id to query */
  126907. int isEof; /* True if cursor is at EOF */
  126908. sqlite3_int64 iRowid; /* Current rowid */
  126909. int iCol; /* Current value of 'col' column */
  126910. int nStat; /* Size of aStat[] array */
  126911. struct Fts3auxColstats {
  126912. sqlite3_int64 nDoc; /* 'documents' values for current csr row */
  126913. sqlite3_int64 nOcc; /* 'occurrences' values for current csr row */
  126914. } *aStat;
  126915. };
  126916. /*
  126917. ** Schema of the terms table.
  126918. */
  126919. #define FTS3_AUX_SCHEMA \
  126920. "CREATE TABLE x(term, col, documents, occurrences, languageid HIDDEN)"
  126921. /*
  126922. ** This function does all the work for both the xConnect and xCreate methods.
  126923. ** These tables have no persistent representation of their own, so xConnect
  126924. ** and xCreate are identical operations.
  126925. */
  126926. static int fts3auxConnectMethod(
  126927. sqlite3 *db, /* Database connection */
  126928. void *pUnused, /* Unused */
  126929. int argc, /* Number of elements in argv array */
  126930. const char * const *argv, /* xCreate/xConnect argument array */
  126931. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  126932. char **pzErr /* OUT: sqlite3_malloc'd error message */
  126933. ){
  126934. char const *zDb; /* Name of database (e.g. "main") */
  126935. char const *zFts3; /* Name of fts3 table */
  126936. int nDb; /* Result of strlen(zDb) */
  126937. int nFts3; /* Result of strlen(zFts3) */
  126938. int nByte; /* Bytes of space to allocate here */
  126939. int rc; /* value returned by declare_vtab() */
  126940. Fts3auxTable *p; /* Virtual table object to return */
  126941. UNUSED_PARAMETER(pUnused);
  126942. /* The user should invoke this in one of two forms:
  126943. **
  126944. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table);
  126945. ** CREATE VIRTUAL TABLE xxx USING fts4aux(fts4-table-db, fts4-table);
  126946. */
  126947. if( argc!=4 && argc!=5 ) goto bad_args;
  126948. zDb = argv[1];
  126949. nDb = (int)strlen(zDb);
  126950. if( argc==5 ){
  126951. if( nDb==4 && 0==sqlite3_strnicmp("temp", zDb, 4) ){
  126952. zDb = argv[3];
  126953. nDb = (int)strlen(zDb);
  126954. zFts3 = argv[4];
  126955. }else{
  126956. goto bad_args;
  126957. }
  126958. }else{
  126959. zFts3 = argv[3];
  126960. }
  126961. nFts3 = (int)strlen(zFts3);
  126962. rc = sqlite3_declare_vtab(db, FTS3_AUX_SCHEMA);
  126963. if( rc!=SQLITE_OK ) return rc;
  126964. nByte = sizeof(Fts3auxTable) + sizeof(Fts3Table) + nDb + nFts3 + 2;
  126965. p = (Fts3auxTable *)sqlite3_malloc(nByte);
  126966. if( !p ) return SQLITE_NOMEM;
  126967. memset(p, 0, nByte);
  126968. p->pFts3Tab = (Fts3Table *)&p[1];
  126969. p->pFts3Tab->zDb = (char *)&p->pFts3Tab[1];
  126970. p->pFts3Tab->zName = &p->pFts3Tab->zDb[nDb+1];
  126971. p->pFts3Tab->db = db;
  126972. p->pFts3Tab->nIndex = 1;
  126973. memcpy((char *)p->pFts3Tab->zDb, zDb, nDb);
  126974. memcpy((char *)p->pFts3Tab->zName, zFts3, nFts3);
  126975. sqlite3Fts3Dequote((char *)p->pFts3Tab->zName);
  126976. *ppVtab = (sqlite3_vtab *)p;
  126977. return SQLITE_OK;
  126978. bad_args:
  126979. *pzErr = sqlite3_mprintf("invalid arguments to fts4aux constructor");
  126980. return SQLITE_ERROR;
  126981. }
  126982. /*
  126983. ** This function does the work for both the xDisconnect and xDestroy methods.
  126984. ** These tables have no persistent representation of their own, so xDisconnect
  126985. ** and xDestroy are identical operations.
  126986. */
  126987. static int fts3auxDisconnectMethod(sqlite3_vtab *pVtab){
  126988. Fts3auxTable *p = (Fts3auxTable *)pVtab;
  126989. Fts3Table *pFts3 = p->pFts3Tab;
  126990. int i;
  126991. /* Free any prepared statements held */
  126992. for(i=0; i<SizeofArray(pFts3->aStmt); i++){
  126993. sqlite3_finalize(pFts3->aStmt[i]);
  126994. }
  126995. sqlite3_free(pFts3->zSegmentsTbl);
  126996. sqlite3_free(p);
  126997. return SQLITE_OK;
  126998. }
  126999. #define FTS4AUX_EQ_CONSTRAINT 1
  127000. #define FTS4AUX_GE_CONSTRAINT 2
  127001. #define FTS4AUX_LE_CONSTRAINT 4
  127002. /*
  127003. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  127004. */
  127005. static int fts3auxBestIndexMethod(
  127006. sqlite3_vtab *pVTab,
  127007. sqlite3_index_info *pInfo
  127008. ){
  127009. int i;
  127010. int iEq = -1;
  127011. int iGe = -1;
  127012. int iLe = -1;
  127013. int iLangid = -1;
  127014. int iNext = 1; /* Next free argvIndex value */
  127015. UNUSED_PARAMETER(pVTab);
  127016. /* This vtab delivers always results in "ORDER BY term ASC" order. */
  127017. if( pInfo->nOrderBy==1
  127018. && pInfo->aOrderBy[0].iColumn==0
  127019. && pInfo->aOrderBy[0].desc==0
  127020. ){
  127021. pInfo->orderByConsumed = 1;
  127022. }
  127023. /* Search for equality and range constraints on the "term" column.
  127024. ** And equality constraints on the hidden "languageid" column. */
  127025. for(i=0; i<pInfo->nConstraint; i++){
  127026. if( pInfo->aConstraint[i].usable ){
  127027. int op = pInfo->aConstraint[i].op;
  127028. int iCol = pInfo->aConstraint[i].iColumn;
  127029. if( iCol==0 ){
  127030. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iEq = i;
  127031. if( op==SQLITE_INDEX_CONSTRAINT_LT ) iLe = i;
  127032. if( op==SQLITE_INDEX_CONSTRAINT_LE ) iLe = i;
  127033. if( op==SQLITE_INDEX_CONSTRAINT_GT ) iGe = i;
  127034. if( op==SQLITE_INDEX_CONSTRAINT_GE ) iGe = i;
  127035. }
  127036. if( iCol==4 ){
  127037. if( op==SQLITE_INDEX_CONSTRAINT_EQ ) iLangid = i;
  127038. }
  127039. }
  127040. }
  127041. if( iEq>=0 ){
  127042. pInfo->idxNum = FTS4AUX_EQ_CONSTRAINT;
  127043. pInfo->aConstraintUsage[iEq].argvIndex = iNext++;
  127044. pInfo->estimatedCost = 5;
  127045. }else{
  127046. pInfo->idxNum = 0;
  127047. pInfo->estimatedCost = 20000;
  127048. if( iGe>=0 ){
  127049. pInfo->idxNum += FTS4AUX_GE_CONSTRAINT;
  127050. pInfo->aConstraintUsage[iGe].argvIndex = iNext++;
  127051. pInfo->estimatedCost /= 2;
  127052. }
  127053. if( iLe>=0 ){
  127054. pInfo->idxNum += FTS4AUX_LE_CONSTRAINT;
  127055. pInfo->aConstraintUsage[iLe].argvIndex = iNext++;
  127056. pInfo->estimatedCost /= 2;
  127057. }
  127058. }
  127059. if( iLangid>=0 ){
  127060. pInfo->aConstraintUsage[iLangid].argvIndex = iNext++;
  127061. pInfo->estimatedCost--;
  127062. }
  127063. return SQLITE_OK;
  127064. }
  127065. /*
  127066. ** xOpen - Open a cursor.
  127067. */
  127068. static int fts3auxOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  127069. Fts3auxCursor *pCsr; /* Pointer to cursor object to return */
  127070. UNUSED_PARAMETER(pVTab);
  127071. pCsr = (Fts3auxCursor *)sqlite3_malloc(sizeof(Fts3auxCursor));
  127072. if( !pCsr ) return SQLITE_NOMEM;
  127073. memset(pCsr, 0, sizeof(Fts3auxCursor));
  127074. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  127075. return SQLITE_OK;
  127076. }
  127077. /*
  127078. ** xClose - Close a cursor.
  127079. */
  127080. static int fts3auxCloseMethod(sqlite3_vtab_cursor *pCursor){
  127081. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  127082. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127083. sqlite3Fts3SegmentsClose(pFts3);
  127084. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  127085. sqlite3_free((void *)pCsr->filter.zTerm);
  127086. sqlite3_free(pCsr->zStop);
  127087. sqlite3_free(pCsr->aStat);
  127088. sqlite3_free(pCsr);
  127089. return SQLITE_OK;
  127090. }
  127091. static int fts3auxGrowStatArray(Fts3auxCursor *pCsr, int nSize){
  127092. if( nSize>pCsr->nStat ){
  127093. struct Fts3auxColstats *aNew;
  127094. aNew = (struct Fts3auxColstats *)sqlite3_realloc(pCsr->aStat,
  127095. sizeof(struct Fts3auxColstats) * nSize
  127096. );
  127097. if( aNew==0 ) return SQLITE_NOMEM;
  127098. memset(&aNew[pCsr->nStat], 0,
  127099. sizeof(struct Fts3auxColstats) * (nSize - pCsr->nStat)
  127100. );
  127101. pCsr->aStat = aNew;
  127102. pCsr->nStat = nSize;
  127103. }
  127104. return SQLITE_OK;
  127105. }
  127106. /*
  127107. ** xNext - Advance the cursor to the next row, if any.
  127108. */
  127109. static int fts3auxNextMethod(sqlite3_vtab_cursor *pCursor){
  127110. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127111. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  127112. int rc;
  127113. /* Increment our pretend rowid value. */
  127114. pCsr->iRowid++;
  127115. for(pCsr->iCol++; pCsr->iCol<pCsr->nStat; pCsr->iCol++){
  127116. if( pCsr->aStat[pCsr->iCol].nDoc>0 ) return SQLITE_OK;
  127117. }
  127118. rc = sqlite3Fts3SegReaderStep(pFts3, &pCsr->csr);
  127119. if( rc==SQLITE_ROW ){
  127120. int i = 0;
  127121. int nDoclist = pCsr->csr.nDoclist;
  127122. char *aDoclist = pCsr->csr.aDoclist;
  127123. int iCol;
  127124. int eState = 0;
  127125. if( pCsr->zStop ){
  127126. int n = (pCsr->nStop<pCsr->csr.nTerm) ? pCsr->nStop : pCsr->csr.nTerm;
  127127. int mc = memcmp(pCsr->zStop, pCsr->csr.zTerm, n);
  127128. if( mc<0 || (mc==0 && pCsr->csr.nTerm>pCsr->nStop) ){
  127129. pCsr->isEof = 1;
  127130. return SQLITE_OK;
  127131. }
  127132. }
  127133. if( fts3auxGrowStatArray(pCsr, 2) ) return SQLITE_NOMEM;
  127134. memset(pCsr->aStat, 0, sizeof(struct Fts3auxColstats) * pCsr->nStat);
  127135. iCol = 0;
  127136. while( i<nDoclist ){
  127137. sqlite3_int64 v = 0;
  127138. i += sqlite3Fts3GetVarint(&aDoclist[i], &v);
  127139. switch( eState ){
  127140. /* State 0. In this state the integer just read was a docid. */
  127141. case 0:
  127142. pCsr->aStat[0].nDoc++;
  127143. eState = 1;
  127144. iCol = 0;
  127145. break;
  127146. /* State 1. In this state we are expecting either a 1, indicating
  127147. ** that the following integer will be a column number, or the
  127148. ** start of a position list for column 0.
  127149. **
  127150. ** The only difference between state 1 and state 2 is that if the
  127151. ** integer encountered in state 1 is not 0 or 1, then we need to
  127152. ** increment the column 0 "nDoc" count for this term.
  127153. */
  127154. case 1:
  127155. assert( iCol==0 );
  127156. if( v>1 ){
  127157. pCsr->aStat[1].nDoc++;
  127158. }
  127159. eState = 2;
  127160. /* fall through */
  127161. case 2:
  127162. if( v==0 ){ /* 0x00. Next integer will be a docid. */
  127163. eState = 0;
  127164. }else if( v==1 ){ /* 0x01. Next integer will be a column number. */
  127165. eState = 3;
  127166. }else{ /* 2 or greater. A position. */
  127167. pCsr->aStat[iCol+1].nOcc++;
  127168. pCsr->aStat[0].nOcc++;
  127169. }
  127170. break;
  127171. /* State 3. The integer just read is a column number. */
  127172. default: assert( eState==3 );
  127173. iCol = (int)v;
  127174. if( fts3auxGrowStatArray(pCsr, iCol+2) ) return SQLITE_NOMEM;
  127175. pCsr->aStat[iCol+1].nDoc++;
  127176. eState = 2;
  127177. break;
  127178. }
  127179. }
  127180. pCsr->iCol = 0;
  127181. rc = SQLITE_OK;
  127182. }else{
  127183. pCsr->isEof = 1;
  127184. }
  127185. return rc;
  127186. }
  127187. /*
  127188. ** xFilter - Initialize a cursor to point at the start of its data.
  127189. */
  127190. static int fts3auxFilterMethod(
  127191. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  127192. int idxNum, /* Strategy index */
  127193. const char *idxStr, /* Unused */
  127194. int nVal, /* Number of elements in apVal */
  127195. sqlite3_value **apVal /* Arguments for the indexing scheme */
  127196. ){
  127197. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127198. Fts3Table *pFts3 = ((Fts3auxTable *)pCursor->pVtab)->pFts3Tab;
  127199. int rc;
  127200. int isScan = 0;
  127201. int iLangVal = 0; /* Language id to query */
  127202. int iEq = -1; /* Index of term=? value in apVal */
  127203. int iGe = -1; /* Index of term>=? value in apVal */
  127204. int iLe = -1; /* Index of term<=? value in apVal */
  127205. int iLangid = -1; /* Index of languageid=? value in apVal */
  127206. int iNext = 0;
  127207. UNUSED_PARAMETER(nVal);
  127208. UNUSED_PARAMETER(idxStr);
  127209. assert( idxStr==0 );
  127210. assert( idxNum==FTS4AUX_EQ_CONSTRAINT || idxNum==0
  127211. || idxNum==FTS4AUX_LE_CONSTRAINT || idxNum==FTS4AUX_GE_CONSTRAINT
  127212. || idxNum==(FTS4AUX_LE_CONSTRAINT|FTS4AUX_GE_CONSTRAINT)
  127213. );
  127214. if( idxNum==FTS4AUX_EQ_CONSTRAINT ){
  127215. iEq = iNext++;
  127216. }else{
  127217. isScan = 1;
  127218. if( idxNum & FTS4AUX_GE_CONSTRAINT ){
  127219. iGe = iNext++;
  127220. }
  127221. if( idxNum & FTS4AUX_LE_CONSTRAINT ){
  127222. iLe = iNext++;
  127223. }
  127224. }
  127225. if( iNext<nVal ){
  127226. iLangid = iNext++;
  127227. }
  127228. /* In case this cursor is being reused, close and zero it. */
  127229. testcase(pCsr->filter.zTerm);
  127230. sqlite3Fts3SegReaderFinish(&pCsr->csr);
  127231. sqlite3_free((void *)pCsr->filter.zTerm);
  127232. sqlite3_free(pCsr->aStat);
  127233. memset(&pCsr->csr, 0, ((u8*)&pCsr[1]) - (u8*)&pCsr->csr);
  127234. pCsr->filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  127235. if( isScan ) pCsr->filter.flags |= FTS3_SEGMENT_SCAN;
  127236. if( iEq>=0 || iGe>=0 ){
  127237. const unsigned char *zStr = sqlite3_value_text(apVal[0]);
  127238. assert( (iEq==0 && iGe==-1) || (iEq==-1 && iGe==0) );
  127239. if( zStr ){
  127240. pCsr->filter.zTerm = sqlite3_mprintf("%s", zStr);
  127241. pCsr->filter.nTerm = sqlite3_value_bytes(apVal[0]);
  127242. if( pCsr->filter.zTerm==0 ) return SQLITE_NOMEM;
  127243. }
  127244. }
  127245. if( iLe>=0 ){
  127246. pCsr->zStop = sqlite3_mprintf("%s", sqlite3_value_text(apVal[iLe]));
  127247. pCsr->nStop = sqlite3_value_bytes(apVal[iLe]);
  127248. if( pCsr->zStop==0 ) return SQLITE_NOMEM;
  127249. }
  127250. if( iLangid>=0 ){
  127251. iLangVal = sqlite3_value_int(apVal[iLangid]);
  127252. /* If the user specified a negative value for the languageid, use zero
  127253. ** instead. This works, as the "languageid=?" constraint will also
  127254. ** be tested by the VDBE layer. The test will always be false (since
  127255. ** this module will not return a row with a negative languageid), and
  127256. ** so the overall query will return zero rows. */
  127257. if( iLangVal<0 ) iLangVal = 0;
  127258. }
  127259. pCsr->iLangid = iLangVal;
  127260. rc = sqlite3Fts3SegReaderCursor(pFts3, iLangVal, 0, FTS3_SEGCURSOR_ALL,
  127261. pCsr->filter.zTerm, pCsr->filter.nTerm, 0, isScan, &pCsr->csr
  127262. );
  127263. if( rc==SQLITE_OK ){
  127264. rc = sqlite3Fts3SegReaderStart(pFts3, &pCsr->csr, &pCsr->filter);
  127265. }
  127266. if( rc==SQLITE_OK ) rc = fts3auxNextMethod(pCursor);
  127267. return rc;
  127268. }
  127269. /*
  127270. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  127271. */
  127272. static int fts3auxEofMethod(sqlite3_vtab_cursor *pCursor){
  127273. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127274. return pCsr->isEof;
  127275. }
  127276. /*
  127277. ** xColumn - Return a column value.
  127278. */
  127279. static int fts3auxColumnMethod(
  127280. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  127281. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  127282. int iCol /* Index of column to read value from */
  127283. ){
  127284. Fts3auxCursor *p = (Fts3auxCursor *)pCursor;
  127285. assert( p->isEof==0 );
  127286. switch( iCol ){
  127287. case 0: /* term */
  127288. sqlite3_result_text(pCtx, p->csr.zTerm, p->csr.nTerm, SQLITE_TRANSIENT);
  127289. break;
  127290. case 1: /* col */
  127291. if( p->iCol ){
  127292. sqlite3_result_int(pCtx, p->iCol-1);
  127293. }else{
  127294. sqlite3_result_text(pCtx, "*", -1, SQLITE_STATIC);
  127295. }
  127296. break;
  127297. case 2: /* documents */
  127298. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nDoc);
  127299. break;
  127300. case 3: /* occurrences */
  127301. sqlite3_result_int64(pCtx, p->aStat[p->iCol].nOcc);
  127302. break;
  127303. default: /* languageid */
  127304. assert( iCol==4 );
  127305. sqlite3_result_int(pCtx, p->iLangid);
  127306. break;
  127307. }
  127308. return SQLITE_OK;
  127309. }
  127310. /*
  127311. ** xRowid - Return the current rowid for the cursor.
  127312. */
  127313. static int fts3auxRowidMethod(
  127314. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  127315. sqlite_int64 *pRowid /* OUT: Rowid value */
  127316. ){
  127317. Fts3auxCursor *pCsr = (Fts3auxCursor *)pCursor;
  127318. *pRowid = pCsr->iRowid;
  127319. return SQLITE_OK;
  127320. }
  127321. /*
  127322. ** Register the fts3aux module with database connection db. Return SQLITE_OK
  127323. ** if successful or an error code if sqlite3_create_module() fails.
  127324. */
  127325. SQLITE_PRIVATE int sqlite3Fts3InitAux(sqlite3 *db){
  127326. static const sqlite3_module fts3aux_module = {
  127327. 0, /* iVersion */
  127328. fts3auxConnectMethod, /* xCreate */
  127329. fts3auxConnectMethod, /* xConnect */
  127330. fts3auxBestIndexMethod, /* xBestIndex */
  127331. fts3auxDisconnectMethod, /* xDisconnect */
  127332. fts3auxDisconnectMethod, /* xDestroy */
  127333. fts3auxOpenMethod, /* xOpen */
  127334. fts3auxCloseMethod, /* xClose */
  127335. fts3auxFilterMethod, /* xFilter */
  127336. fts3auxNextMethod, /* xNext */
  127337. fts3auxEofMethod, /* xEof */
  127338. fts3auxColumnMethod, /* xColumn */
  127339. fts3auxRowidMethod, /* xRowid */
  127340. 0, /* xUpdate */
  127341. 0, /* xBegin */
  127342. 0, /* xSync */
  127343. 0, /* xCommit */
  127344. 0, /* xRollback */
  127345. 0, /* xFindFunction */
  127346. 0, /* xRename */
  127347. 0, /* xSavepoint */
  127348. 0, /* xRelease */
  127349. 0 /* xRollbackTo */
  127350. };
  127351. int rc; /* Return code */
  127352. rc = sqlite3_create_module(db, "fts4aux", &fts3aux_module, 0);
  127353. return rc;
  127354. }
  127355. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  127356. /************** End of fts3_aux.c ********************************************/
  127357. /************** Begin file fts3_expr.c ***************************************/
  127358. /*
  127359. ** 2008 Nov 28
  127360. **
  127361. ** The author disclaims copyright to this source code. In place of
  127362. ** a legal notice, here is a blessing:
  127363. **
  127364. ** May you do good and not evil.
  127365. ** May you find forgiveness for yourself and forgive others.
  127366. ** May you share freely, never taking more than you give.
  127367. **
  127368. ******************************************************************************
  127369. **
  127370. ** This module contains code that implements a parser for fts3 query strings
  127371. ** (the right-hand argument to the MATCH operator). Because the supported
  127372. ** syntax is relatively simple, the whole tokenizer/parser system is
  127373. ** hand-coded.
  127374. */
  127375. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  127376. /*
  127377. ** By default, this module parses the legacy syntax that has been
  127378. ** traditionally used by fts3. Or, if SQLITE_ENABLE_FTS3_PARENTHESIS
  127379. ** is defined, then it uses the new syntax. The differences between
  127380. ** the new and the old syntaxes are:
  127381. **
  127382. ** a) The new syntax supports parenthesis. The old does not.
  127383. **
  127384. ** b) The new syntax supports the AND and NOT operators. The old does not.
  127385. **
  127386. ** c) The old syntax supports the "-" token qualifier. This is not
  127387. ** supported by the new syntax (it is replaced by the NOT operator).
  127388. **
  127389. ** d) When using the old syntax, the OR operator has a greater precedence
  127390. ** than an implicit AND. When using the new, both implicity and explicit
  127391. ** AND operators have a higher precedence than OR.
  127392. **
  127393. ** If compiled with SQLITE_TEST defined, then this module exports the
  127394. ** symbol "int sqlite3_fts3_enable_parentheses". Setting this variable
  127395. ** to zero causes the module to use the old syntax. If it is set to
  127396. ** non-zero the new syntax is activated. This is so both syntaxes can
  127397. ** be tested using a single build of testfixture.
  127398. **
  127399. ** The following describes the syntax supported by the fts3 MATCH
  127400. ** operator in a similar format to that used by the lemon parser
  127401. ** generator. This module does not use actually lemon, it uses a
  127402. ** custom parser.
  127403. **
  127404. ** query ::= andexpr (OR andexpr)*.
  127405. **
  127406. ** andexpr ::= notexpr (AND? notexpr)*.
  127407. **
  127408. ** notexpr ::= nearexpr (NOT nearexpr|-TOKEN)*.
  127409. ** notexpr ::= LP query RP.
  127410. **
  127411. ** nearexpr ::= phrase (NEAR distance_opt nearexpr)*.
  127412. **
  127413. ** distance_opt ::= .
  127414. ** distance_opt ::= / INTEGER.
  127415. **
  127416. ** phrase ::= TOKEN.
  127417. ** phrase ::= COLUMN:TOKEN.
  127418. ** phrase ::= "TOKEN TOKEN TOKEN...".
  127419. */
  127420. #ifdef SQLITE_TEST
  127421. SQLITE_API int sqlite3_fts3_enable_parentheses = 0;
  127422. #else
  127423. # ifdef SQLITE_ENABLE_FTS3_PARENTHESIS
  127424. # define sqlite3_fts3_enable_parentheses 1
  127425. # else
  127426. # define sqlite3_fts3_enable_parentheses 0
  127427. # endif
  127428. #endif
  127429. /*
  127430. ** Default span for NEAR operators.
  127431. */
  127432. #define SQLITE_FTS3_DEFAULT_NEAR_PARAM 10
  127433. /* #include <string.h> */
  127434. /* #include <assert.h> */
  127435. /*
  127436. ** isNot:
  127437. ** This variable is used by function getNextNode(). When getNextNode() is
  127438. ** called, it sets ParseContext.isNot to true if the 'next node' is a
  127439. ** FTSQUERY_PHRASE with a unary "-" attached to it. i.e. "mysql" in the
  127440. ** FTS3 query "sqlite -mysql". Otherwise, ParseContext.isNot is set to
  127441. ** zero.
  127442. */
  127443. typedef struct ParseContext ParseContext;
  127444. struct ParseContext {
  127445. sqlite3_tokenizer *pTokenizer; /* Tokenizer module */
  127446. int iLangid; /* Language id used with tokenizer */
  127447. const char **azCol; /* Array of column names for fts3 table */
  127448. int bFts4; /* True to allow FTS4-only syntax */
  127449. int nCol; /* Number of entries in azCol[] */
  127450. int iDefaultCol; /* Default column to query */
  127451. int isNot; /* True if getNextNode() sees a unary - */
  127452. sqlite3_context *pCtx; /* Write error message here */
  127453. int nNest; /* Number of nested brackets */
  127454. };
  127455. /*
  127456. ** This function is equivalent to the standard isspace() function.
  127457. **
  127458. ** The standard isspace() can be awkward to use safely, because although it
  127459. ** is defined to accept an argument of type int, its behavior when passed
  127460. ** an integer that falls outside of the range of the unsigned char type
  127461. ** is undefined (and sometimes, "undefined" means segfault). This wrapper
  127462. ** is defined to accept an argument of type char, and always returns 0 for
  127463. ** any values that fall outside of the range of the unsigned char type (i.e.
  127464. ** negative values).
  127465. */
  127466. static int fts3isspace(char c){
  127467. return c==' ' || c=='\t' || c=='\n' || c=='\r' || c=='\v' || c=='\f';
  127468. }
  127469. /*
  127470. ** Allocate nByte bytes of memory using sqlite3_malloc(). If successful,
  127471. ** zero the memory before returning a pointer to it. If unsuccessful,
  127472. ** return NULL.
  127473. */
  127474. static void *fts3MallocZero(int nByte){
  127475. void *pRet = sqlite3_malloc(nByte);
  127476. if( pRet ) memset(pRet, 0, nByte);
  127477. return pRet;
  127478. }
  127479. SQLITE_PRIVATE int sqlite3Fts3OpenTokenizer(
  127480. sqlite3_tokenizer *pTokenizer,
  127481. int iLangid,
  127482. const char *z,
  127483. int n,
  127484. sqlite3_tokenizer_cursor **ppCsr
  127485. ){
  127486. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  127487. sqlite3_tokenizer_cursor *pCsr = 0;
  127488. int rc;
  127489. rc = pModule->xOpen(pTokenizer, z, n, &pCsr);
  127490. assert( rc==SQLITE_OK || pCsr==0 );
  127491. if( rc==SQLITE_OK ){
  127492. pCsr->pTokenizer = pTokenizer;
  127493. if( pModule->iVersion>=1 ){
  127494. rc = pModule->xLanguageid(pCsr, iLangid);
  127495. if( rc!=SQLITE_OK ){
  127496. pModule->xClose(pCsr);
  127497. pCsr = 0;
  127498. }
  127499. }
  127500. }
  127501. *ppCsr = pCsr;
  127502. return rc;
  127503. }
  127504. /*
  127505. ** Function getNextNode(), which is called by fts3ExprParse(), may itself
  127506. ** call fts3ExprParse(). So this forward declaration is required.
  127507. */
  127508. static int fts3ExprParse(ParseContext *, const char *, int, Fts3Expr **, int *);
  127509. /*
  127510. ** Extract the next token from buffer z (length n) using the tokenizer
  127511. ** and other information (column names etc.) in pParse. Create an Fts3Expr
  127512. ** structure of type FTSQUERY_PHRASE containing a phrase consisting of this
  127513. ** single token and set *ppExpr to point to it. If the end of the buffer is
  127514. ** reached before a token is found, set *ppExpr to zero. It is the
  127515. ** responsibility of the caller to eventually deallocate the allocated
  127516. ** Fts3Expr structure (if any) by passing it to sqlite3_free().
  127517. **
  127518. ** Return SQLITE_OK if successful, or SQLITE_NOMEM if a memory allocation
  127519. ** fails.
  127520. */
  127521. static int getNextToken(
  127522. ParseContext *pParse, /* fts3 query parse context */
  127523. int iCol, /* Value for Fts3Phrase.iColumn */
  127524. const char *z, int n, /* Input string */
  127525. Fts3Expr **ppExpr, /* OUT: expression */
  127526. int *pnConsumed /* OUT: Number of bytes consumed */
  127527. ){
  127528. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  127529. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  127530. int rc;
  127531. sqlite3_tokenizer_cursor *pCursor;
  127532. Fts3Expr *pRet = 0;
  127533. int i = 0;
  127534. /* Set variable i to the maximum number of bytes of input to tokenize. */
  127535. for(i=0; i<n; i++){
  127536. if( sqlite3_fts3_enable_parentheses && (z[i]=='(' || z[i]==')') ) break;
  127537. if( z[i]=='"' ) break;
  127538. }
  127539. *pnConsumed = i;
  127540. rc = sqlite3Fts3OpenTokenizer(pTokenizer, pParse->iLangid, z, i, &pCursor);
  127541. if( rc==SQLITE_OK ){
  127542. const char *zToken;
  127543. int nToken = 0, iStart = 0, iEnd = 0, iPosition = 0;
  127544. int nByte; /* total space to allocate */
  127545. rc = pModule->xNext(pCursor, &zToken, &nToken, &iStart, &iEnd, &iPosition);
  127546. if( rc==SQLITE_OK ){
  127547. nByte = sizeof(Fts3Expr) + sizeof(Fts3Phrase) + nToken;
  127548. pRet = (Fts3Expr *)fts3MallocZero(nByte);
  127549. if( !pRet ){
  127550. rc = SQLITE_NOMEM;
  127551. }else{
  127552. pRet->eType = FTSQUERY_PHRASE;
  127553. pRet->pPhrase = (Fts3Phrase *)&pRet[1];
  127554. pRet->pPhrase->nToken = 1;
  127555. pRet->pPhrase->iColumn = iCol;
  127556. pRet->pPhrase->aToken[0].n = nToken;
  127557. pRet->pPhrase->aToken[0].z = (char *)&pRet->pPhrase[1];
  127558. memcpy(pRet->pPhrase->aToken[0].z, zToken, nToken);
  127559. if( iEnd<n && z[iEnd]=='*' ){
  127560. pRet->pPhrase->aToken[0].isPrefix = 1;
  127561. iEnd++;
  127562. }
  127563. while( 1 ){
  127564. if( !sqlite3_fts3_enable_parentheses
  127565. && iStart>0 && z[iStart-1]=='-'
  127566. ){
  127567. pParse->isNot = 1;
  127568. iStart--;
  127569. }else if( pParse->bFts4 && iStart>0 && z[iStart-1]=='^' ){
  127570. pRet->pPhrase->aToken[0].bFirst = 1;
  127571. iStart--;
  127572. }else{
  127573. break;
  127574. }
  127575. }
  127576. }
  127577. *pnConsumed = iEnd;
  127578. }else if( i && rc==SQLITE_DONE ){
  127579. rc = SQLITE_OK;
  127580. }
  127581. pModule->xClose(pCursor);
  127582. }
  127583. *ppExpr = pRet;
  127584. return rc;
  127585. }
  127586. /*
  127587. ** Enlarge a memory allocation. If an out-of-memory allocation occurs,
  127588. ** then free the old allocation.
  127589. */
  127590. static void *fts3ReallocOrFree(void *pOrig, int nNew){
  127591. void *pRet = sqlite3_realloc(pOrig, nNew);
  127592. if( !pRet ){
  127593. sqlite3_free(pOrig);
  127594. }
  127595. return pRet;
  127596. }
  127597. /*
  127598. ** Buffer zInput, length nInput, contains the contents of a quoted string
  127599. ** that appeared as part of an fts3 query expression. Neither quote character
  127600. ** is included in the buffer. This function attempts to tokenize the entire
  127601. ** input buffer and create an Fts3Expr structure of type FTSQUERY_PHRASE
  127602. ** containing the results.
  127603. **
  127604. ** If successful, SQLITE_OK is returned and *ppExpr set to point at the
  127605. ** allocated Fts3Expr structure. Otherwise, either SQLITE_NOMEM (out of memory
  127606. ** error) or SQLITE_ERROR (tokenization error) is returned and *ppExpr set
  127607. ** to 0.
  127608. */
  127609. static int getNextString(
  127610. ParseContext *pParse, /* fts3 query parse context */
  127611. const char *zInput, int nInput, /* Input string */
  127612. Fts3Expr **ppExpr /* OUT: expression */
  127613. ){
  127614. sqlite3_tokenizer *pTokenizer = pParse->pTokenizer;
  127615. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  127616. int rc;
  127617. Fts3Expr *p = 0;
  127618. sqlite3_tokenizer_cursor *pCursor = 0;
  127619. char *zTemp = 0;
  127620. int nTemp = 0;
  127621. const int nSpace = sizeof(Fts3Expr) + sizeof(Fts3Phrase);
  127622. int nToken = 0;
  127623. /* The final Fts3Expr data structure, including the Fts3Phrase,
  127624. ** Fts3PhraseToken structures token buffers are all stored as a single
  127625. ** allocation so that the expression can be freed with a single call to
  127626. ** sqlite3_free(). Setting this up requires a two pass approach.
  127627. **
  127628. ** The first pass, in the block below, uses a tokenizer cursor to iterate
  127629. ** through the tokens in the expression. This pass uses fts3ReallocOrFree()
  127630. ** to assemble data in two dynamic buffers:
  127631. **
  127632. ** Buffer p: Points to the Fts3Expr structure, followed by the Fts3Phrase
  127633. ** structure, followed by the array of Fts3PhraseToken
  127634. ** structures. This pass only populates the Fts3PhraseToken array.
  127635. **
  127636. ** Buffer zTemp: Contains copies of all tokens.
  127637. **
  127638. ** The second pass, in the block that begins "if( rc==SQLITE_DONE )" below,
  127639. ** appends buffer zTemp to buffer p, and fills in the Fts3Expr and Fts3Phrase
  127640. ** structures.
  127641. */
  127642. rc = sqlite3Fts3OpenTokenizer(
  127643. pTokenizer, pParse->iLangid, zInput, nInput, &pCursor);
  127644. if( rc==SQLITE_OK ){
  127645. int ii;
  127646. for(ii=0; rc==SQLITE_OK; ii++){
  127647. const char *zByte;
  127648. int nByte = 0, iBegin = 0, iEnd = 0, iPos = 0;
  127649. rc = pModule->xNext(pCursor, &zByte, &nByte, &iBegin, &iEnd, &iPos);
  127650. if( rc==SQLITE_OK ){
  127651. Fts3PhraseToken *pToken;
  127652. p = fts3ReallocOrFree(p, nSpace + ii*sizeof(Fts3PhraseToken));
  127653. if( !p ) goto no_mem;
  127654. zTemp = fts3ReallocOrFree(zTemp, nTemp + nByte);
  127655. if( !zTemp ) goto no_mem;
  127656. assert( nToken==ii );
  127657. pToken = &((Fts3Phrase *)(&p[1]))->aToken[ii];
  127658. memset(pToken, 0, sizeof(Fts3PhraseToken));
  127659. memcpy(&zTemp[nTemp], zByte, nByte);
  127660. nTemp += nByte;
  127661. pToken->n = nByte;
  127662. pToken->isPrefix = (iEnd<nInput && zInput[iEnd]=='*');
  127663. pToken->bFirst = (iBegin>0 && zInput[iBegin-1]=='^');
  127664. nToken = ii+1;
  127665. }
  127666. }
  127667. pModule->xClose(pCursor);
  127668. pCursor = 0;
  127669. }
  127670. if( rc==SQLITE_DONE ){
  127671. int jj;
  127672. char *zBuf = 0;
  127673. p = fts3ReallocOrFree(p, nSpace + nToken*sizeof(Fts3PhraseToken) + nTemp);
  127674. if( !p ) goto no_mem;
  127675. memset(p, 0, (char *)&(((Fts3Phrase *)&p[1])->aToken[0])-(char *)p);
  127676. p->eType = FTSQUERY_PHRASE;
  127677. p->pPhrase = (Fts3Phrase *)&p[1];
  127678. p->pPhrase->iColumn = pParse->iDefaultCol;
  127679. p->pPhrase->nToken = nToken;
  127680. zBuf = (char *)&p->pPhrase->aToken[nToken];
  127681. if( zTemp ){
  127682. memcpy(zBuf, zTemp, nTemp);
  127683. sqlite3_free(zTemp);
  127684. }else{
  127685. assert( nTemp==0 );
  127686. }
  127687. for(jj=0; jj<p->pPhrase->nToken; jj++){
  127688. p->pPhrase->aToken[jj].z = zBuf;
  127689. zBuf += p->pPhrase->aToken[jj].n;
  127690. }
  127691. rc = SQLITE_OK;
  127692. }
  127693. *ppExpr = p;
  127694. return rc;
  127695. no_mem:
  127696. if( pCursor ){
  127697. pModule->xClose(pCursor);
  127698. }
  127699. sqlite3_free(zTemp);
  127700. sqlite3_free(p);
  127701. *ppExpr = 0;
  127702. return SQLITE_NOMEM;
  127703. }
  127704. /*
  127705. ** The output variable *ppExpr is populated with an allocated Fts3Expr
  127706. ** structure, or set to 0 if the end of the input buffer is reached.
  127707. **
  127708. ** Returns an SQLite error code. SQLITE_OK if everything works, SQLITE_NOMEM
  127709. ** if a malloc failure occurs, or SQLITE_ERROR if a parse error is encountered.
  127710. ** If SQLITE_ERROR is returned, pContext is populated with an error message.
  127711. */
  127712. static int getNextNode(
  127713. ParseContext *pParse, /* fts3 query parse context */
  127714. const char *z, int n, /* Input string */
  127715. Fts3Expr **ppExpr, /* OUT: expression */
  127716. int *pnConsumed /* OUT: Number of bytes consumed */
  127717. ){
  127718. static const struct Fts3Keyword {
  127719. char *z; /* Keyword text */
  127720. unsigned char n; /* Length of the keyword */
  127721. unsigned char parenOnly; /* Only valid in paren mode */
  127722. unsigned char eType; /* Keyword code */
  127723. } aKeyword[] = {
  127724. { "OR" , 2, 0, FTSQUERY_OR },
  127725. { "AND", 3, 1, FTSQUERY_AND },
  127726. { "NOT", 3, 1, FTSQUERY_NOT },
  127727. { "NEAR", 4, 0, FTSQUERY_NEAR }
  127728. };
  127729. int ii;
  127730. int iCol;
  127731. int iColLen;
  127732. int rc;
  127733. Fts3Expr *pRet = 0;
  127734. const char *zInput = z;
  127735. int nInput = n;
  127736. pParse->isNot = 0;
  127737. /* Skip over any whitespace before checking for a keyword, an open or
  127738. ** close bracket, or a quoted string.
  127739. */
  127740. while( nInput>0 && fts3isspace(*zInput) ){
  127741. nInput--;
  127742. zInput++;
  127743. }
  127744. if( nInput==0 ){
  127745. return SQLITE_DONE;
  127746. }
  127747. /* See if we are dealing with a keyword. */
  127748. for(ii=0; ii<(int)(sizeof(aKeyword)/sizeof(struct Fts3Keyword)); ii++){
  127749. const struct Fts3Keyword *pKey = &aKeyword[ii];
  127750. if( (pKey->parenOnly & ~sqlite3_fts3_enable_parentheses)!=0 ){
  127751. continue;
  127752. }
  127753. if( nInput>=pKey->n && 0==memcmp(zInput, pKey->z, pKey->n) ){
  127754. int nNear = SQLITE_FTS3_DEFAULT_NEAR_PARAM;
  127755. int nKey = pKey->n;
  127756. char cNext;
  127757. /* If this is a "NEAR" keyword, check for an explicit nearness. */
  127758. if( pKey->eType==FTSQUERY_NEAR ){
  127759. assert( nKey==4 );
  127760. if( zInput[4]=='/' && zInput[5]>='0' && zInput[5]<='9' ){
  127761. nNear = 0;
  127762. for(nKey=5; zInput[nKey]>='0' && zInput[nKey]<='9'; nKey++){
  127763. nNear = nNear * 10 + (zInput[nKey] - '0');
  127764. }
  127765. }
  127766. }
  127767. /* At this point this is probably a keyword. But for that to be true,
  127768. ** the next byte must contain either whitespace, an open or close
  127769. ** parenthesis, a quote character, or EOF.
  127770. */
  127771. cNext = zInput[nKey];
  127772. if( fts3isspace(cNext)
  127773. || cNext=='"' || cNext=='(' || cNext==')' || cNext==0
  127774. ){
  127775. pRet = (Fts3Expr *)fts3MallocZero(sizeof(Fts3Expr));
  127776. if( !pRet ){
  127777. return SQLITE_NOMEM;
  127778. }
  127779. pRet->eType = pKey->eType;
  127780. pRet->nNear = nNear;
  127781. *ppExpr = pRet;
  127782. *pnConsumed = (int)((zInput - z) + nKey);
  127783. return SQLITE_OK;
  127784. }
  127785. /* Turns out that wasn't a keyword after all. This happens if the
  127786. ** user has supplied a token such as "ORacle". Continue.
  127787. */
  127788. }
  127789. }
  127790. /* See if we are dealing with a quoted phrase. If this is the case, then
  127791. ** search for the closing quote and pass the whole string to getNextString()
  127792. ** for processing. This is easy to do, as fts3 has no syntax for escaping
  127793. ** a quote character embedded in a string.
  127794. */
  127795. if( *zInput=='"' ){
  127796. for(ii=1; ii<nInput && zInput[ii]!='"'; ii++);
  127797. *pnConsumed = (int)((zInput - z) + ii + 1);
  127798. if( ii==nInput ){
  127799. return SQLITE_ERROR;
  127800. }
  127801. return getNextString(pParse, &zInput[1], ii-1, ppExpr);
  127802. }
  127803. if( sqlite3_fts3_enable_parentheses ){
  127804. if( *zInput=='(' ){
  127805. int nConsumed = 0;
  127806. pParse->nNest++;
  127807. rc = fts3ExprParse(pParse, zInput+1, nInput-1, ppExpr, &nConsumed);
  127808. if( rc==SQLITE_OK && !*ppExpr ){ rc = SQLITE_DONE; }
  127809. *pnConsumed = (int)(zInput - z) + 1 + nConsumed;
  127810. return rc;
  127811. }else if( *zInput==')' ){
  127812. pParse->nNest--;
  127813. *pnConsumed = (int)((zInput - z) + 1);
  127814. *ppExpr = 0;
  127815. return SQLITE_DONE;
  127816. }
  127817. }
  127818. /* If control flows to this point, this must be a regular token, or
  127819. ** the end of the input. Read a regular token using the sqlite3_tokenizer
  127820. ** interface. Before doing so, figure out if there is an explicit
  127821. ** column specifier for the token.
  127822. **
  127823. ** TODO: Strangely, it is not possible to associate a column specifier
  127824. ** with a quoted phrase, only with a single token. Not sure if this was
  127825. ** an implementation artifact or an intentional decision when fts3 was
  127826. ** first implemented. Whichever it was, this module duplicates the
  127827. ** limitation.
  127828. */
  127829. iCol = pParse->iDefaultCol;
  127830. iColLen = 0;
  127831. for(ii=0; ii<pParse->nCol; ii++){
  127832. const char *zStr = pParse->azCol[ii];
  127833. int nStr = (int)strlen(zStr);
  127834. if( nInput>nStr && zInput[nStr]==':'
  127835. && sqlite3_strnicmp(zStr, zInput, nStr)==0
  127836. ){
  127837. iCol = ii;
  127838. iColLen = (int)((zInput - z) + nStr + 1);
  127839. break;
  127840. }
  127841. }
  127842. rc = getNextToken(pParse, iCol, &z[iColLen], n-iColLen, ppExpr, pnConsumed);
  127843. *pnConsumed += iColLen;
  127844. return rc;
  127845. }
  127846. /*
  127847. ** The argument is an Fts3Expr structure for a binary operator (any type
  127848. ** except an FTSQUERY_PHRASE). Return an integer value representing the
  127849. ** precedence of the operator. Lower values have a higher precedence (i.e.
  127850. ** group more tightly). For example, in the C language, the == operator
  127851. ** groups more tightly than ||, and would therefore have a higher precedence.
  127852. **
  127853. ** When using the new fts3 query syntax (when SQLITE_ENABLE_FTS3_PARENTHESIS
  127854. ** is defined), the order of the operators in precedence from highest to
  127855. ** lowest is:
  127856. **
  127857. ** NEAR
  127858. ** NOT
  127859. ** AND (including implicit ANDs)
  127860. ** OR
  127861. **
  127862. ** Note that when using the old query syntax, the OR operator has a higher
  127863. ** precedence than the AND operator.
  127864. */
  127865. static int opPrecedence(Fts3Expr *p){
  127866. assert( p->eType!=FTSQUERY_PHRASE );
  127867. if( sqlite3_fts3_enable_parentheses ){
  127868. return p->eType;
  127869. }else if( p->eType==FTSQUERY_NEAR ){
  127870. return 1;
  127871. }else if( p->eType==FTSQUERY_OR ){
  127872. return 2;
  127873. }
  127874. assert( p->eType==FTSQUERY_AND );
  127875. return 3;
  127876. }
  127877. /*
  127878. ** Argument ppHead contains a pointer to the current head of a query
  127879. ** expression tree being parsed. pPrev is the expression node most recently
  127880. ** inserted into the tree. This function adds pNew, which is always a binary
  127881. ** operator node, into the expression tree based on the relative precedence
  127882. ** of pNew and the existing nodes of the tree. This may result in the head
  127883. ** of the tree changing, in which case *ppHead is set to the new root node.
  127884. */
  127885. static void insertBinaryOperator(
  127886. Fts3Expr **ppHead, /* Pointer to the root node of a tree */
  127887. Fts3Expr *pPrev, /* Node most recently inserted into the tree */
  127888. Fts3Expr *pNew /* New binary node to insert into expression tree */
  127889. ){
  127890. Fts3Expr *pSplit = pPrev;
  127891. while( pSplit->pParent && opPrecedence(pSplit->pParent)<=opPrecedence(pNew) ){
  127892. pSplit = pSplit->pParent;
  127893. }
  127894. if( pSplit->pParent ){
  127895. assert( pSplit->pParent->pRight==pSplit );
  127896. pSplit->pParent->pRight = pNew;
  127897. pNew->pParent = pSplit->pParent;
  127898. }else{
  127899. *ppHead = pNew;
  127900. }
  127901. pNew->pLeft = pSplit;
  127902. pSplit->pParent = pNew;
  127903. }
  127904. /*
  127905. ** Parse the fts3 query expression found in buffer z, length n. This function
  127906. ** returns either when the end of the buffer is reached or an unmatched
  127907. ** closing bracket - ')' - is encountered.
  127908. **
  127909. ** If successful, SQLITE_OK is returned, *ppExpr is set to point to the
  127910. ** parsed form of the expression and *pnConsumed is set to the number of
  127911. ** bytes read from buffer z. Otherwise, *ppExpr is set to 0 and SQLITE_NOMEM
  127912. ** (out of memory error) or SQLITE_ERROR (parse error) is returned.
  127913. */
  127914. static int fts3ExprParse(
  127915. ParseContext *pParse, /* fts3 query parse context */
  127916. const char *z, int n, /* Text of MATCH query */
  127917. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  127918. int *pnConsumed /* OUT: Number of bytes consumed */
  127919. ){
  127920. Fts3Expr *pRet = 0;
  127921. Fts3Expr *pPrev = 0;
  127922. Fts3Expr *pNotBranch = 0; /* Only used in legacy parse mode */
  127923. int nIn = n;
  127924. const char *zIn = z;
  127925. int rc = SQLITE_OK;
  127926. int isRequirePhrase = 1;
  127927. while( rc==SQLITE_OK ){
  127928. Fts3Expr *p = 0;
  127929. int nByte = 0;
  127930. rc = getNextNode(pParse, zIn, nIn, &p, &nByte);
  127931. assert( nByte>0 || (rc!=SQLITE_OK && p==0) );
  127932. if( rc==SQLITE_OK ){
  127933. if( p ){
  127934. int isPhrase;
  127935. if( !sqlite3_fts3_enable_parentheses
  127936. && p->eType==FTSQUERY_PHRASE && pParse->isNot
  127937. ){
  127938. /* Create an implicit NOT operator. */
  127939. Fts3Expr *pNot = fts3MallocZero(sizeof(Fts3Expr));
  127940. if( !pNot ){
  127941. sqlite3Fts3ExprFree(p);
  127942. rc = SQLITE_NOMEM;
  127943. goto exprparse_out;
  127944. }
  127945. pNot->eType = FTSQUERY_NOT;
  127946. pNot->pRight = p;
  127947. p->pParent = pNot;
  127948. if( pNotBranch ){
  127949. pNot->pLeft = pNotBranch;
  127950. pNotBranch->pParent = pNot;
  127951. }
  127952. pNotBranch = pNot;
  127953. p = pPrev;
  127954. }else{
  127955. int eType = p->eType;
  127956. isPhrase = (eType==FTSQUERY_PHRASE || p->pLeft);
  127957. /* The isRequirePhrase variable is set to true if a phrase or
  127958. ** an expression contained in parenthesis is required. If a
  127959. ** binary operator (AND, OR, NOT or NEAR) is encounted when
  127960. ** isRequirePhrase is set, this is a syntax error.
  127961. */
  127962. if( !isPhrase && isRequirePhrase ){
  127963. sqlite3Fts3ExprFree(p);
  127964. rc = SQLITE_ERROR;
  127965. goto exprparse_out;
  127966. }
  127967. if( isPhrase && !isRequirePhrase ){
  127968. /* Insert an implicit AND operator. */
  127969. Fts3Expr *pAnd;
  127970. assert( pRet && pPrev );
  127971. pAnd = fts3MallocZero(sizeof(Fts3Expr));
  127972. if( !pAnd ){
  127973. sqlite3Fts3ExprFree(p);
  127974. rc = SQLITE_NOMEM;
  127975. goto exprparse_out;
  127976. }
  127977. pAnd->eType = FTSQUERY_AND;
  127978. insertBinaryOperator(&pRet, pPrev, pAnd);
  127979. pPrev = pAnd;
  127980. }
  127981. /* This test catches attempts to make either operand of a NEAR
  127982. ** operator something other than a phrase. For example, either of
  127983. ** the following:
  127984. **
  127985. ** (bracketed expression) NEAR phrase
  127986. ** phrase NEAR (bracketed expression)
  127987. **
  127988. ** Return an error in either case.
  127989. */
  127990. if( pPrev && (
  127991. (eType==FTSQUERY_NEAR && !isPhrase && pPrev->eType!=FTSQUERY_PHRASE)
  127992. || (eType!=FTSQUERY_PHRASE && isPhrase && pPrev->eType==FTSQUERY_NEAR)
  127993. )){
  127994. sqlite3Fts3ExprFree(p);
  127995. rc = SQLITE_ERROR;
  127996. goto exprparse_out;
  127997. }
  127998. if( isPhrase ){
  127999. if( pRet ){
  128000. assert( pPrev && pPrev->pLeft && pPrev->pRight==0 );
  128001. pPrev->pRight = p;
  128002. p->pParent = pPrev;
  128003. }else{
  128004. pRet = p;
  128005. }
  128006. }else{
  128007. insertBinaryOperator(&pRet, pPrev, p);
  128008. }
  128009. isRequirePhrase = !isPhrase;
  128010. }
  128011. pPrev = p;
  128012. }
  128013. assert( nByte>0 );
  128014. }
  128015. assert( rc!=SQLITE_OK || (nByte>0 && nByte<=nIn) );
  128016. nIn -= nByte;
  128017. zIn += nByte;
  128018. }
  128019. if( rc==SQLITE_DONE && pRet && isRequirePhrase ){
  128020. rc = SQLITE_ERROR;
  128021. }
  128022. if( rc==SQLITE_DONE ){
  128023. rc = SQLITE_OK;
  128024. if( !sqlite3_fts3_enable_parentheses && pNotBranch ){
  128025. if( !pRet ){
  128026. rc = SQLITE_ERROR;
  128027. }else{
  128028. Fts3Expr *pIter = pNotBranch;
  128029. while( pIter->pLeft ){
  128030. pIter = pIter->pLeft;
  128031. }
  128032. pIter->pLeft = pRet;
  128033. pRet->pParent = pIter;
  128034. pRet = pNotBranch;
  128035. }
  128036. }
  128037. }
  128038. *pnConsumed = n - nIn;
  128039. exprparse_out:
  128040. if( rc!=SQLITE_OK ){
  128041. sqlite3Fts3ExprFree(pRet);
  128042. sqlite3Fts3ExprFree(pNotBranch);
  128043. pRet = 0;
  128044. }
  128045. *ppExpr = pRet;
  128046. return rc;
  128047. }
  128048. /*
  128049. ** Return SQLITE_ERROR if the maximum depth of the expression tree passed
  128050. ** as the only argument is more than nMaxDepth.
  128051. */
  128052. static int fts3ExprCheckDepth(Fts3Expr *p, int nMaxDepth){
  128053. int rc = SQLITE_OK;
  128054. if( p ){
  128055. if( nMaxDepth<0 ){
  128056. rc = SQLITE_TOOBIG;
  128057. }else{
  128058. rc = fts3ExprCheckDepth(p->pLeft, nMaxDepth-1);
  128059. if( rc==SQLITE_OK ){
  128060. rc = fts3ExprCheckDepth(p->pRight, nMaxDepth-1);
  128061. }
  128062. }
  128063. }
  128064. return rc;
  128065. }
  128066. /*
  128067. ** This function attempts to transform the expression tree at (*pp) to
  128068. ** an equivalent but more balanced form. The tree is modified in place.
  128069. ** If successful, SQLITE_OK is returned and (*pp) set to point to the
  128070. ** new root expression node.
  128071. **
  128072. ** nMaxDepth is the maximum allowable depth of the balanced sub-tree.
  128073. **
  128074. ** Otherwise, if an error occurs, an SQLite error code is returned and
  128075. ** expression (*pp) freed.
  128076. */
  128077. static int fts3ExprBalance(Fts3Expr **pp, int nMaxDepth){
  128078. int rc = SQLITE_OK; /* Return code */
  128079. Fts3Expr *pRoot = *pp; /* Initial root node */
  128080. Fts3Expr *pFree = 0; /* List of free nodes. Linked by pParent. */
  128081. int eType = pRoot->eType; /* Type of node in this tree */
  128082. if( nMaxDepth==0 ){
  128083. rc = SQLITE_ERROR;
  128084. }
  128085. if( rc==SQLITE_OK && (eType==FTSQUERY_AND || eType==FTSQUERY_OR) ){
  128086. Fts3Expr **apLeaf;
  128087. apLeaf = (Fts3Expr **)sqlite3_malloc(sizeof(Fts3Expr *) * nMaxDepth);
  128088. if( 0==apLeaf ){
  128089. rc = SQLITE_NOMEM;
  128090. }else{
  128091. memset(apLeaf, 0, sizeof(Fts3Expr *) * nMaxDepth);
  128092. }
  128093. if( rc==SQLITE_OK ){
  128094. int i;
  128095. Fts3Expr *p;
  128096. /* Set $p to point to the left-most leaf in the tree of eType nodes. */
  128097. for(p=pRoot; p->eType==eType; p=p->pLeft){
  128098. assert( p->pParent==0 || p->pParent->pLeft==p );
  128099. assert( p->pLeft && p->pRight );
  128100. }
  128101. /* This loop runs once for each leaf in the tree of eType nodes. */
  128102. while( 1 ){
  128103. int iLvl;
  128104. Fts3Expr *pParent = p->pParent; /* Current parent of p */
  128105. assert( pParent==0 || pParent->pLeft==p );
  128106. p->pParent = 0;
  128107. if( pParent ){
  128108. pParent->pLeft = 0;
  128109. }else{
  128110. pRoot = 0;
  128111. }
  128112. rc = fts3ExprBalance(&p, nMaxDepth-1);
  128113. if( rc!=SQLITE_OK ) break;
  128114. for(iLvl=0; p && iLvl<nMaxDepth; iLvl++){
  128115. if( apLeaf[iLvl]==0 ){
  128116. apLeaf[iLvl] = p;
  128117. p = 0;
  128118. }else{
  128119. assert( pFree );
  128120. pFree->pLeft = apLeaf[iLvl];
  128121. pFree->pRight = p;
  128122. pFree->pLeft->pParent = pFree;
  128123. pFree->pRight->pParent = pFree;
  128124. p = pFree;
  128125. pFree = pFree->pParent;
  128126. p->pParent = 0;
  128127. apLeaf[iLvl] = 0;
  128128. }
  128129. }
  128130. if( p ){
  128131. sqlite3Fts3ExprFree(p);
  128132. rc = SQLITE_TOOBIG;
  128133. break;
  128134. }
  128135. /* If that was the last leaf node, break out of the loop */
  128136. if( pParent==0 ) break;
  128137. /* Set $p to point to the next leaf in the tree of eType nodes */
  128138. for(p=pParent->pRight; p->eType==eType; p=p->pLeft);
  128139. /* Remove pParent from the original tree. */
  128140. assert( pParent->pParent==0 || pParent->pParent->pLeft==pParent );
  128141. pParent->pRight->pParent = pParent->pParent;
  128142. if( pParent->pParent ){
  128143. pParent->pParent->pLeft = pParent->pRight;
  128144. }else{
  128145. assert( pParent==pRoot );
  128146. pRoot = pParent->pRight;
  128147. }
  128148. /* Link pParent into the free node list. It will be used as an
  128149. ** internal node of the new tree. */
  128150. pParent->pParent = pFree;
  128151. pFree = pParent;
  128152. }
  128153. if( rc==SQLITE_OK ){
  128154. p = 0;
  128155. for(i=0; i<nMaxDepth; i++){
  128156. if( apLeaf[i] ){
  128157. if( p==0 ){
  128158. p = apLeaf[i];
  128159. p->pParent = 0;
  128160. }else{
  128161. assert( pFree!=0 );
  128162. pFree->pRight = p;
  128163. pFree->pLeft = apLeaf[i];
  128164. pFree->pLeft->pParent = pFree;
  128165. pFree->pRight->pParent = pFree;
  128166. p = pFree;
  128167. pFree = pFree->pParent;
  128168. p->pParent = 0;
  128169. }
  128170. }
  128171. }
  128172. pRoot = p;
  128173. }else{
  128174. /* An error occurred. Delete the contents of the apLeaf[] array
  128175. ** and pFree list. Everything else is cleaned up by the call to
  128176. ** sqlite3Fts3ExprFree(pRoot) below. */
  128177. Fts3Expr *pDel;
  128178. for(i=0; i<nMaxDepth; i++){
  128179. sqlite3Fts3ExprFree(apLeaf[i]);
  128180. }
  128181. while( (pDel=pFree)!=0 ){
  128182. pFree = pDel->pParent;
  128183. sqlite3_free(pDel);
  128184. }
  128185. }
  128186. assert( pFree==0 );
  128187. sqlite3_free( apLeaf );
  128188. }
  128189. }
  128190. if( rc!=SQLITE_OK ){
  128191. sqlite3Fts3ExprFree(pRoot);
  128192. pRoot = 0;
  128193. }
  128194. *pp = pRoot;
  128195. return rc;
  128196. }
  128197. /*
  128198. ** This function is similar to sqlite3Fts3ExprParse(), with the following
  128199. ** differences:
  128200. **
  128201. ** 1. It does not do expression rebalancing.
  128202. ** 2. It does not check that the expression does not exceed the
  128203. ** maximum allowable depth.
  128204. ** 3. Even if it fails, *ppExpr may still be set to point to an
  128205. ** expression tree. It should be deleted using sqlite3Fts3ExprFree()
  128206. ** in this case.
  128207. */
  128208. static int fts3ExprParseUnbalanced(
  128209. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  128210. int iLangid, /* Language id for tokenizer */
  128211. char **azCol, /* Array of column names for fts3 table */
  128212. int bFts4, /* True to allow FTS4-only syntax */
  128213. int nCol, /* Number of entries in azCol[] */
  128214. int iDefaultCol, /* Default column to query */
  128215. const char *z, int n, /* Text of MATCH query */
  128216. Fts3Expr **ppExpr /* OUT: Parsed query structure */
  128217. ){
  128218. int nParsed;
  128219. int rc;
  128220. ParseContext sParse;
  128221. memset(&sParse, 0, sizeof(ParseContext));
  128222. sParse.pTokenizer = pTokenizer;
  128223. sParse.iLangid = iLangid;
  128224. sParse.azCol = (const char **)azCol;
  128225. sParse.nCol = nCol;
  128226. sParse.iDefaultCol = iDefaultCol;
  128227. sParse.bFts4 = bFts4;
  128228. if( z==0 ){
  128229. *ppExpr = 0;
  128230. return SQLITE_OK;
  128231. }
  128232. if( n<0 ){
  128233. n = (int)strlen(z);
  128234. }
  128235. rc = fts3ExprParse(&sParse, z, n, ppExpr, &nParsed);
  128236. assert( rc==SQLITE_OK || *ppExpr==0 );
  128237. /* Check for mismatched parenthesis */
  128238. if( rc==SQLITE_OK && sParse.nNest ){
  128239. rc = SQLITE_ERROR;
  128240. }
  128241. return rc;
  128242. }
  128243. /*
  128244. ** Parameters z and n contain a pointer to and length of a buffer containing
  128245. ** an fts3 query expression, respectively. This function attempts to parse the
  128246. ** query expression and create a tree of Fts3Expr structures representing the
  128247. ** parsed expression. If successful, *ppExpr is set to point to the head
  128248. ** of the parsed expression tree and SQLITE_OK is returned. If an error
  128249. ** occurs, either SQLITE_NOMEM (out-of-memory error) or SQLITE_ERROR (parse
  128250. ** error) is returned and *ppExpr is set to 0.
  128251. **
  128252. ** If parameter n is a negative number, then z is assumed to point to a
  128253. ** nul-terminated string and the length is determined using strlen().
  128254. **
  128255. ** The first parameter, pTokenizer, is passed the fts3 tokenizer module to
  128256. ** use to normalize query tokens while parsing the expression. The azCol[]
  128257. ** array, which is assumed to contain nCol entries, should contain the names
  128258. ** of each column in the target fts3 table, in order from left to right.
  128259. ** Column names must be nul-terminated strings.
  128260. **
  128261. ** The iDefaultCol parameter should be passed the index of the table column
  128262. ** that appears on the left-hand-side of the MATCH operator (the default
  128263. ** column to match against for tokens for which a column name is not explicitly
  128264. ** specified as part of the query string), or -1 if tokens may by default
  128265. ** match any table column.
  128266. */
  128267. SQLITE_PRIVATE int sqlite3Fts3ExprParse(
  128268. sqlite3_tokenizer *pTokenizer, /* Tokenizer module */
  128269. int iLangid, /* Language id for tokenizer */
  128270. char **azCol, /* Array of column names for fts3 table */
  128271. int bFts4, /* True to allow FTS4-only syntax */
  128272. int nCol, /* Number of entries in azCol[] */
  128273. int iDefaultCol, /* Default column to query */
  128274. const char *z, int n, /* Text of MATCH query */
  128275. Fts3Expr **ppExpr, /* OUT: Parsed query structure */
  128276. char **pzErr /* OUT: Error message (sqlite3_malloc) */
  128277. ){
  128278. int rc = fts3ExprParseUnbalanced(
  128279. pTokenizer, iLangid, azCol, bFts4, nCol, iDefaultCol, z, n, ppExpr
  128280. );
  128281. /* Rebalance the expression. And check that its depth does not exceed
  128282. ** SQLITE_FTS3_MAX_EXPR_DEPTH. */
  128283. if( rc==SQLITE_OK && *ppExpr ){
  128284. rc = fts3ExprBalance(ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  128285. if( rc==SQLITE_OK ){
  128286. rc = fts3ExprCheckDepth(*ppExpr, SQLITE_FTS3_MAX_EXPR_DEPTH);
  128287. }
  128288. }
  128289. if( rc!=SQLITE_OK ){
  128290. sqlite3Fts3ExprFree(*ppExpr);
  128291. *ppExpr = 0;
  128292. if( rc==SQLITE_TOOBIG ){
  128293. *pzErr = sqlite3_mprintf(
  128294. "FTS expression tree is too large (maximum depth %d)",
  128295. SQLITE_FTS3_MAX_EXPR_DEPTH
  128296. );
  128297. rc = SQLITE_ERROR;
  128298. }else if( rc==SQLITE_ERROR ){
  128299. *pzErr = sqlite3_mprintf("malformed MATCH expression: [%s]", z);
  128300. }
  128301. }
  128302. return rc;
  128303. }
  128304. /*
  128305. ** Free a single node of an expression tree.
  128306. */
  128307. static void fts3FreeExprNode(Fts3Expr *p){
  128308. assert( p->eType==FTSQUERY_PHRASE || p->pPhrase==0 );
  128309. sqlite3Fts3EvalPhraseCleanup(p->pPhrase);
  128310. sqlite3_free(p->aMI);
  128311. sqlite3_free(p);
  128312. }
  128313. /*
  128314. ** Free a parsed fts3 query expression allocated by sqlite3Fts3ExprParse().
  128315. **
  128316. ** This function would be simpler if it recursively called itself. But
  128317. ** that would mean passing a sufficiently large expression to ExprParse()
  128318. ** could cause a stack overflow.
  128319. */
  128320. SQLITE_PRIVATE void sqlite3Fts3ExprFree(Fts3Expr *pDel){
  128321. Fts3Expr *p;
  128322. assert( pDel==0 || pDel->pParent==0 );
  128323. for(p=pDel; p && (p->pLeft||p->pRight); p=(p->pLeft ? p->pLeft : p->pRight)){
  128324. assert( p->pParent==0 || p==p->pParent->pRight || p==p->pParent->pLeft );
  128325. }
  128326. while( p ){
  128327. Fts3Expr *pParent = p->pParent;
  128328. fts3FreeExprNode(p);
  128329. if( pParent && p==pParent->pLeft && pParent->pRight ){
  128330. p = pParent->pRight;
  128331. while( p && (p->pLeft || p->pRight) ){
  128332. assert( p==p->pParent->pRight || p==p->pParent->pLeft );
  128333. p = (p->pLeft ? p->pLeft : p->pRight);
  128334. }
  128335. }else{
  128336. p = pParent;
  128337. }
  128338. }
  128339. }
  128340. /****************************************************************************
  128341. *****************************************************************************
  128342. ** Everything after this point is just test code.
  128343. */
  128344. #ifdef SQLITE_TEST
  128345. /* #include <stdio.h> */
  128346. /*
  128347. ** Function to query the hash-table of tokenizers (see README.tokenizers).
  128348. */
  128349. static int queryTestTokenizer(
  128350. sqlite3 *db,
  128351. const char *zName,
  128352. const sqlite3_tokenizer_module **pp
  128353. ){
  128354. int rc;
  128355. sqlite3_stmt *pStmt;
  128356. const char zSql[] = "SELECT fts3_tokenizer(?)";
  128357. *pp = 0;
  128358. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  128359. if( rc!=SQLITE_OK ){
  128360. return rc;
  128361. }
  128362. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  128363. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  128364. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  128365. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  128366. }
  128367. }
  128368. return sqlite3_finalize(pStmt);
  128369. }
  128370. /*
  128371. ** Return a pointer to a buffer containing a text representation of the
  128372. ** expression passed as the first argument. The buffer is obtained from
  128373. ** sqlite3_malloc(). It is the responsibility of the caller to use
  128374. ** sqlite3_free() to release the memory. If an OOM condition is encountered,
  128375. ** NULL is returned.
  128376. **
  128377. ** If the second argument is not NULL, then its contents are prepended to
  128378. ** the returned expression text and then freed using sqlite3_free().
  128379. */
  128380. static char *exprToString(Fts3Expr *pExpr, char *zBuf){
  128381. if( pExpr==0 ){
  128382. return sqlite3_mprintf("");
  128383. }
  128384. switch( pExpr->eType ){
  128385. case FTSQUERY_PHRASE: {
  128386. Fts3Phrase *pPhrase = pExpr->pPhrase;
  128387. int i;
  128388. zBuf = sqlite3_mprintf(
  128389. "%zPHRASE %d 0", zBuf, pPhrase->iColumn);
  128390. for(i=0; zBuf && i<pPhrase->nToken; i++){
  128391. zBuf = sqlite3_mprintf("%z %.*s%s", zBuf,
  128392. pPhrase->aToken[i].n, pPhrase->aToken[i].z,
  128393. (pPhrase->aToken[i].isPrefix?"+":"")
  128394. );
  128395. }
  128396. return zBuf;
  128397. }
  128398. case FTSQUERY_NEAR:
  128399. zBuf = sqlite3_mprintf("%zNEAR/%d ", zBuf, pExpr->nNear);
  128400. break;
  128401. case FTSQUERY_NOT:
  128402. zBuf = sqlite3_mprintf("%zNOT ", zBuf);
  128403. break;
  128404. case FTSQUERY_AND:
  128405. zBuf = sqlite3_mprintf("%zAND ", zBuf);
  128406. break;
  128407. case FTSQUERY_OR:
  128408. zBuf = sqlite3_mprintf("%zOR ", zBuf);
  128409. break;
  128410. }
  128411. if( zBuf ) zBuf = sqlite3_mprintf("%z{", zBuf);
  128412. if( zBuf ) zBuf = exprToString(pExpr->pLeft, zBuf);
  128413. if( zBuf ) zBuf = sqlite3_mprintf("%z} {", zBuf);
  128414. if( zBuf ) zBuf = exprToString(pExpr->pRight, zBuf);
  128415. if( zBuf ) zBuf = sqlite3_mprintf("%z}", zBuf);
  128416. return zBuf;
  128417. }
  128418. /*
  128419. ** This is the implementation of a scalar SQL function used to test the
  128420. ** expression parser. It should be called as follows:
  128421. **
  128422. ** fts3_exprtest(<tokenizer>, <expr>, <column 1>, ...);
  128423. **
  128424. ** The first argument, <tokenizer>, is the name of the fts3 tokenizer used
  128425. ** to parse the query expression (see README.tokenizers). The second argument
  128426. ** is the query expression to parse. Each subsequent argument is the name
  128427. ** of a column of the fts3 table that the query expression may refer to.
  128428. ** For example:
  128429. **
  128430. ** SELECT fts3_exprtest('simple', 'Bill col2:Bloggs', 'col1', 'col2');
  128431. */
  128432. static void fts3ExprTest(
  128433. sqlite3_context *context,
  128434. int argc,
  128435. sqlite3_value **argv
  128436. ){
  128437. sqlite3_tokenizer_module const *pModule = 0;
  128438. sqlite3_tokenizer *pTokenizer = 0;
  128439. int rc;
  128440. char **azCol = 0;
  128441. const char *zExpr;
  128442. int nExpr;
  128443. int nCol;
  128444. int ii;
  128445. Fts3Expr *pExpr;
  128446. char *zBuf = 0;
  128447. sqlite3 *db = sqlite3_context_db_handle(context);
  128448. if( argc<3 ){
  128449. sqlite3_result_error(context,
  128450. "Usage: fts3_exprtest(tokenizer, expr, col1, ...", -1
  128451. );
  128452. return;
  128453. }
  128454. rc = queryTestTokenizer(db,
  128455. (const char *)sqlite3_value_text(argv[0]), &pModule);
  128456. if( rc==SQLITE_NOMEM ){
  128457. sqlite3_result_error_nomem(context);
  128458. goto exprtest_out;
  128459. }else if( !pModule ){
  128460. sqlite3_result_error(context, "No such tokenizer module", -1);
  128461. goto exprtest_out;
  128462. }
  128463. rc = pModule->xCreate(0, 0, &pTokenizer);
  128464. assert( rc==SQLITE_NOMEM || rc==SQLITE_OK );
  128465. if( rc==SQLITE_NOMEM ){
  128466. sqlite3_result_error_nomem(context);
  128467. goto exprtest_out;
  128468. }
  128469. pTokenizer->pModule = pModule;
  128470. zExpr = (const char *)sqlite3_value_text(argv[1]);
  128471. nExpr = sqlite3_value_bytes(argv[1]);
  128472. nCol = argc-2;
  128473. azCol = (char **)sqlite3_malloc(nCol*sizeof(char *));
  128474. if( !azCol ){
  128475. sqlite3_result_error_nomem(context);
  128476. goto exprtest_out;
  128477. }
  128478. for(ii=0; ii<nCol; ii++){
  128479. azCol[ii] = (char *)sqlite3_value_text(argv[ii+2]);
  128480. }
  128481. if( sqlite3_user_data(context) ){
  128482. char *zDummy = 0;
  128483. rc = sqlite3Fts3ExprParse(
  128484. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr, &zDummy
  128485. );
  128486. assert( rc==SQLITE_OK || pExpr==0 );
  128487. sqlite3_free(zDummy);
  128488. }else{
  128489. rc = fts3ExprParseUnbalanced(
  128490. pTokenizer, 0, azCol, 0, nCol, nCol, zExpr, nExpr, &pExpr
  128491. );
  128492. }
  128493. if( rc!=SQLITE_OK && rc!=SQLITE_NOMEM ){
  128494. sqlite3Fts3ExprFree(pExpr);
  128495. sqlite3_result_error(context, "Error parsing expression", -1);
  128496. }else if( rc==SQLITE_NOMEM || !(zBuf = exprToString(pExpr, 0)) ){
  128497. sqlite3_result_error_nomem(context);
  128498. }else{
  128499. sqlite3_result_text(context, zBuf, -1, SQLITE_TRANSIENT);
  128500. sqlite3_free(zBuf);
  128501. }
  128502. sqlite3Fts3ExprFree(pExpr);
  128503. exprtest_out:
  128504. if( pModule && pTokenizer ){
  128505. rc = pModule->xDestroy(pTokenizer);
  128506. }
  128507. sqlite3_free(azCol);
  128508. }
  128509. /*
  128510. ** Register the query expression parser test function fts3_exprtest()
  128511. ** with database connection db.
  128512. */
  128513. SQLITE_PRIVATE int sqlite3Fts3ExprInitTestInterface(sqlite3* db){
  128514. int rc = sqlite3_create_function(
  128515. db, "fts3_exprtest", -1, SQLITE_UTF8, 0, fts3ExprTest, 0, 0
  128516. );
  128517. if( rc==SQLITE_OK ){
  128518. rc = sqlite3_create_function(db, "fts3_exprtest_rebalance",
  128519. -1, SQLITE_UTF8, (void *)1, fts3ExprTest, 0, 0
  128520. );
  128521. }
  128522. return rc;
  128523. }
  128524. #endif
  128525. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  128526. /************** End of fts3_expr.c *******************************************/
  128527. /************** Begin file fts3_hash.c ***************************************/
  128528. /*
  128529. ** 2001 September 22
  128530. **
  128531. ** The author disclaims copyright to this source code. In place of
  128532. ** a legal notice, here is a blessing:
  128533. **
  128534. ** May you do good and not evil.
  128535. ** May you find forgiveness for yourself and forgive others.
  128536. ** May you share freely, never taking more than you give.
  128537. **
  128538. *************************************************************************
  128539. ** This is the implementation of generic hash-tables used in SQLite.
  128540. ** We've modified it slightly to serve as a standalone hash table
  128541. ** implementation for the full-text indexing module.
  128542. */
  128543. /*
  128544. ** The code in this file is only compiled if:
  128545. **
  128546. ** * The FTS3 module is being built as an extension
  128547. ** (in which case SQLITE_CORE is not defined), or
  128548. **
  128549. ** * The FTS3 module is being built into the core of
  128550. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  128551. */
  128552. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  128553. /* #include <assert.h> */
  128554. /* #include <stdlib.h> */
  128555. /* #include <string.h> */
  128556. /*
  128557. ** Malloc and Free functions
  128558. */
  128559. static void *fts3HashMalloc(int n){
  128560. void *p = sqlite3_malloc(n);
  128561. if( p ){
  128562. memset(p, 0, n);
  128563. }
  128564. return p;
  128565. }
  128566. static void fts3HashFree(void *p){
  128567. sqlite3_free(p);
  128568. }
  128569. /* Turn bulk memory into a hash table object by initializing the
  128570. ** fields of the Hash structure.
  128571. **
  128572. ** "pNew" is a pointer to the hash table that is to be initialized.
  128573. ** keyClass is one of the constants
  128574. ** FTS3_HASH_BINARY or FTS3_HASH_STRING. The value of keyClass
  128575. ** determines what kind of key the hash table will use. "copyKey" is
  128576. ** true if the hash table should make its own private copy of keys and
  128577. ** false if it should just use the supplied pointer.
  128578. */
  128579. SQLITE_PRIVATE void sqlite3Fts3HashInit(Fts3Hash *pNew, char keyClass, char copyKey){
  128580. assert( pNew!=0 );
  128581. assert( keyClass>=FTS3_HASH_STRING && keyClass<=FTS3_HASH_BINARY );
  128582. pNew->keyClass = keyClass;
  128583. pNew->copyKey = copyKey;
  128584. pNew->first = 0;
  128585. pNew->count = 0;
  128586. pNew->htsize = 0;
  128587. pNew->ht = 0;
  128588. }
  128589. /* Remove all entries from a hash table. Reclaim all memory.
  128590. ** Call this routine to delete a hash table or to reset a hash table
  128591. ** to the empty state.
  128592. */
  128593. SQLITE_PRIVATE void sqlite3Fts3HashClear(Fts3Hash *pH){
  128594. Fts3HashElem *elem; /* For looping over all elements of the table */
  128595. assert( pH!=0 );
  128596. elem = pH->first;
  128597. pH->first = 0;
  128598. fts3HashFree(pH->ht);
  128599. pH->ht = 0;
  128600. pH->htsize = 0;
  128601. while( elem ){
  128602. Fts3HashElem *next_elem = elem->next;
  128603. if( pH->copyKey && elem->pKey ){
  128604. fts3HashFree(elem->pKey);
  128605. }
  128606. fts3HashFree(elem);
  128607. elem = next_elem;
  128608. }
  128609. pH->count = 0;
  128610. }
  128611. /*
  128612. ** Hash and comparison functions when the mode is FTS3_HASH_STRING
  128613. */
  128614. static int fts3StrHash(const void *pKey, int nKey){
  128615. const char *z = (const char *)pKey;
  128616. unsigned h = 0;
  128617. if( nKey<=0 ) nKey = (int) strlen(z);
  128618. while( nKey > 0 ){
  128619. h = (h<<3) ^ h ^ *z++;
  128620. nKey--;
  128621. }
  128622. return (int)(h & 0x7fffffff);
  128623. }
  128624. static int fts3StrCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  128625. if( n1!=n2 ) return 1;
  128626. return strncmp((const char*)pKey1,(const char*)pKey2,n1);
  128627. }
  128628. /*
  128629. ** Hash and comparison functions when the mode is FTS3_HASH_BINARY
  128630. */
  128631. static int fts3BinHash(const void *pKey, int nKey){
  128632. int h = 0;
  128633. const char *z = (const char *)pKey;
  128634. while( nKey-- > 0 ){
  128635. h = (h<<3) ^ h ^ *(z++);
  128636. }
  128637. return h & 0x7fffffff;
  128638. }
  128639. static int fts3BinCompare(const void *pKey1, int n1, const void *pKey2, int n2){
  128640. if( n1!=n2 ) return 1;
  128641. return memcmp(pKey1,pKey2,n1);
  128642. }
  128643. /*
  128644. ** Return a pointer to the appropriate hash function given the key class.
  128645. **
  128646. ** The C syntax in this function definition may be unfamilar to some
  128647. ** programmers, so we provide the following additional explanation:
  128648. **
  128649. ** The name of the function is "ftsHashFunction". The function takes a
  128650. ** single parameter "keyClass". The return value of ftsHashFunction()
  128651. ** is a pointer to another function. Specifically, the return value
  128652. ** of ftsHashFunction() is a pointer to a function that takes two parameters
  128653. ** with types "const void*" and "int" and returns an "int".
  128654. */
  128655. static int (*ftsHashFunction(int keyClass))(const void*,int){
  128656. if( keyClass==FTS3_HASH_STRING ){
  128657. return &fts3StrHash;
  128658. }else{
  128659. assert( keyClass==FTS3_HASH_BINARY );
  128660. return &fts3BinHash;
  128661. }
  128662. }
  128663. /*
  128664. ** Return a pointer to the appropriate hash function given the key class.
  128665. **
  128666. ** For help in interpreted the obscure C code in the function definition,
  128667. ** see the header comment on the previous function.
  128668. */
  128669. static int (*ftsCompareFunction(int keyClass))(const void*,int,const void*,int){
  128670. if( keyClass==FTS3_HASH_STRING ){
  128671. return &fts3StrCompare;
  128672. }else{
  128673. assert( keyClass==FTS3_HASH_BINARY );
  128674. return &fts3BinCompare;
  128675. }
  128676. }
  128677. /* Link an element into the hash table
  128678. */
  128679. static void fts3HashInsertElement(
  128680. Fts3Hash *pH, /* The complete hash table */
  128681. struct _fts3ht *pEntry, /* The entry into which pNew is inserted */
  128682. Fts3HashElem *pNew /* The element to be inserted */
  128683. ){
  128684. Fts3HashElem *pHead; /* First element already in pEntry */
  128685. pHead = pEntry->chain;
  128686. if( pHead ){
  128687. pNew->next = pHead;
  128688. pNew->prev = pHead->prev;
  128689. if( pHead->prev ){ pHead->prev->next = pNew; }
  128690. else { pH->first = pNew; }
  128691. pHead->prev = pNew;
  128692. }else{
  128693. pNew->next = pH->first;
  128694. if( pH->first ){ pH->first->prev = pNew; }
  128695. pNew->prev = 0;
  128696. pH->first = pNew;
  128697. }
  128698. pEntry->count++;
  128699. pEntry->chain = pNew;
  128700. }
  128701. /* Resize the hash table so that it cantains "new_size" buckets.
  128702. ** "new_size" must be a power of 2. The hash table might fail
  128703. ** to resize if sqliteMalloc() fails.
  128704. **
  128705. ** Return non-zero if a memory allocation error occurs.
  128706. */
  128707. static int fts3Rehash(Fts3Hash *pH, int new_size){
  128708. struct _fts3ht *new_ht; /* The new hash table */
  128709. Fts3HashElem *elem, *next_elem; /* For looping over existing elements */
  128710. int (*xHash)(const void*,int); /* The hash function */
  128711. assert( (new_size & (new_size-1))==0 );
  128712. new_ht = (struct _fts3ht *)fts3HashMalloc( new_size*sizeof(struct _fts3ht) );
  128713. if( new_ht==0 ) return 1;
  128714. fts3HashFree(pH->ht);
  128715. pH->ht = new_ht;
  128716. pH->htsize = new_size;
  128717. xHash = ftsHashFunction(pH->keyClass);
  128718. for(elem=pH->first, pH->first=0; elem; elem = next_elem){
  128719. int h = (*xHash)(elem->pKey, elem->nKey) & (new_size-1);
  128720. next_elem = elem->next;
  128721. fts3HashInsertElement(pH, &new_ht[h], elem);
  128722. }
  128723. return 0;
  128724. }
  128725. /* This function (for internal use only) locates an element in an
  128726. ** hash table that matches the given key. The hash for this key has
  128727. ** already been computed and is passed as the 4th parameter.
  128728. */
  128729. static Fts3HashElem *fts3FindElementByHash(
  128730. const Fts3Hash *pH, /* The pH to be searched */
  128731. const void *pKey, /* The key we are searching for */
  128732. int nKey,
  128733. int h /* The hash for this key. */
  128734. ){
  128735. Fts3HashElem *elem; /* Used to loop thru the element list */
  128736. int count; /* Number of elements left to test */
  128737. int (*xCompare)(const void*,int,const void*,int); /* comparison function */
  128738. if( pH->ht ){
  128739. struct _fts3ht *pEntry = &pH->ht[h];
  128740. elem = pEntry->chain;
  128741. count = pEntry->count;
  128742. xCompare = ftsCompareFunction(pH->keyClass);
  128743. while( count-- && elem ){
  128744. if( (*xCompare)(elem->pKey,elem->nKey,pKey,nKey)==0 ){
  128745. return elem;
  128746. }
  128747. elem = elem->next;
  128748. }
  128749. }
  128750. return 0;
  128751. }
  128752. /* Remove a single entry from the hash table given a pointer to that
  128753. ** element and a hash on the element's key.
  128754. */
  128755. static void fts3RemoveElementByHash(
  128756. Fts3Hash *pH, /* The pH containing "elem" */
  128757. Fts3HashElem* elem, /* The element to be removed from the pH */
  128758. int h /* Hash value for the element */
  128759. ){
  128760. struct _fts3ht *pEntry;
  128761. if( elem->prev ){
  128762. elem->prev->next = elem->next;
  128763. }else{
  128764. pH->first = elem->next;
  128765. }
  128766. if( elem->next ){
  128767. elem->next->prev = elem->prev;
  128768. }
  128769. pEntry = &pH->ht[h];
  128770. if( pEntry->chain==elem ){
  128771. pEntry->chain = elem->next;
  128772. }
  128773. pEntry->count--;
  128774. if( pEntry->count<=0 ){
  128775. pEntry->chain = 0;
  128776. }
  128777. if( pH->copyKey && elem->pKey ){
  128778. fts3HashFree(elem->pKey);
  128779. }
  128780. fts3HashFree( elem );
  128781. pH->count--;
  128782. if( pH->count<=0 ){
  128783. assert( pH->first==0 );
  128784. assert( pH->count==0 );
  128785. fts3HashClear(pH);
  128786. }
  128787. }
  128788. SQLITE_PRIVATE Fts3HashElem *sqlite3Fts3HashFindElem(
  128789. const Fts3Hash *pH,
  128790. const void *pKey,
  128791. int nKey
  128792. ){
  128793. int h; /* A hash on key */
  128794. int (*xHash)(const void*,int); /* The hash function */
  128795. if( pH==0 || pH->ht==0 ) return 0;
  128796. xHash = ftsHashFunction(pH->keyClass);
  128797. assert( xHash!=0 );
  128798. h = (*xHash)(pKey,nKey);
  128799. assert( (pH->htsize & (pH->htsize-1))==0 );
  128800. return fts3FindElementByHash(pH,pKey,nKey, h & (pH->htsize-1));
  128801. }
  128802. /*
  128803. ** Attempt to locate an element of the hash table pH with a key
  128804. ** that matches pKey,nKey. Return the data for this element if it is
  128805. ** found, or NULL if there is no match.
  128806. */
  128807. SQLITE_PRIVATE void *sqlite3Fts3HashFind(const Fts3Hash *pH, const void *pKey, int nKey){
  128808. Fts3HashElem *pElem; /* The element that matches key (if any) */
  128809. pElem = sqlite3Fts3HashFindElem(pH, pKey, nKey);
  128810. return pElem ? pElem->data : 0;
  128811. }
  128812. /* Insert an element into the hash table pH. The key is pKey,nKey
  128813. ** and the data is "data".
  128814. **
  128815. ** If no element exists with a matching key, then a new
  128816. ** element is created. A copy of the key is made if the copyKey
  128817. ** flag is set. NULL is returned.
  128818. **
  128819. ** If another element already exists with the same key, then the
  128820. ** new data replaces the old data and the old data is returned.
  128821. ** The key is not copied in this instance. If a malloc fails, then
  128822. ** the new data is returned and the hash table is unchanged.
  128823. **
  128824. ** If the "data" parameter to this function is NULL, then the
  128825. ** element corresponding to "key" is removed from the hash table.
  128826. */
  128827. SQLITE_PRIVATE void *sqlite3Fts3HashInsert(
  128828. Fts3Hash *pH, /* The hash table to insert into */
  128829. const void *pKey, /* The key */
  128830. int nKey, /* Number of bytes in the key */
  128831. void *data /* The data */
  128832. ){
  128833. int hraw; /* Raw hash value of the key */
  128834. int h; /* the hash of the key modulo hash table size */
  128835. Fts3HashElem *elem; /* Used to loop thru the element list */
  128836. Fts3HashElem *new_elem; /* New element added to the pH */
  128837. int (*xHash)(const void*,int); /* The hash function */
  128838. assert( pH!=0 );
  128839. xHash = ftsHashFunction(pH->keyClass);
  128840. assert( xHash!=0 );
  128841. hraw = (*xHash)(pKey, nKey);
  128842. assert( (pH->htsize & (pH->htsize-1))==0 );
  128843. h = hraw & (pH->htsize-1);
  128844. elem = fts3FindElementByHash(pH,pKey,nKey,h);
  128845. if( elem ){
  128846. void *old_data = elem->data;
  128847. if( data==0 ){
  128848. fts3RemoveElementByHash(pH,elem,h);
  128849. }else{
  128850. elem->data = data;
  128851. }
  128852. return old_data;
  128853. }
  128854. if( data==0 ) return 0;
  128855. if( (pH->htsize==0 && fts3Rehash(pH,8))
  128856. || (pH->count>=pH->htsize && fts3Rehash(pH, pH->htsize*2))
  128857. ){
  128858. pH->count = 0;
  128859. return data;
  128860. }
  128861. assert( pH->htsize>0 );
  128862. new_elem = (Fts3HashElem*)fts3HashMalloc( sizeof(Fts3HashElem) );
  128863. if( new_elem==0 ) return data;
  128864. if( pH->copyKey && pKey!=0 ){
  128865. new_elem->pKey = fts3HashMalloc( nKey );
  128866. if( new_elem->pKey==0 ){
  128867. fts3HashFree(new_elem);
  128868. return data;
  128869. }
  128870. memcpy((void*)new_elem->pKey, pKey, nKey);
  128871. }else{
  128872. new_elem->pKey = (void*)pKey;
  128873. }
  128874. new_elem->nKey = nKey;
  128875. pH->count++;
  128876. assert( pH->htsize>0 );
  128877. assert( (pH->htsize & (pH->htsize-1))==0 );
  128878. h = hraw & (pH->htsize-1);
  128879. fts3HashInsertElement(pH, &pH->ht[h], new_elem);
  128880. new_elem->data = data;
  128881. return 0;
  128882. }
  128883. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  128884. /************** End of fts3_hash.c *******************************************/
  128885. /************** Begin file fts3_porter.c *************************************/
  128886. /*
  128887. ** 2006 September 30
  128888. **
  128889. ** The author disclaims copyright to this source code. In place of
  128890. ** a legal notice, here is a blessing:
  128891. **
  128892. ** May you do good and not evil.
  128893. ** May you find forgiveness for yourself and forgive others.
  128894. ** May you share freely, never taking more than you give.
  128895. **
  128896. *************************************************************************
  128897. ** Implementation of the full-text-search tokenizer that implements
  128898. ** a Porter stemmer.
  128899. */
  128900. /*
  128901. ** The code in this file is only compiled if:
  128902. **
  128903. ** * The FTS3 module is being built as an extension
  128904. ** (in which case SQLITE_CORE is not defined), or
  128905. **
  128906. ** * The FTS3 module is being built into the core of
  128907. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  128908. */
  128909. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  128910. /* #include <assert.h> */
  128911. /* #include <stdlib.h> */
  128912. /* #include <stdio.h> */
  128913. /* #include <string.h> */
  128914. /*
  128915. ** Class derived from sqlite3_tokenizer
  128916. */
  128917. typedef struct porter_tokenizer {
  128918. sqlite3_tokenizer base; /* Base class */
  128919. } porter_tokenizer;
  128920. /*
  128921. ** Class derived from sqlite3_tokenizer_cursor
  128922. */
  128923. typedef struct porter_tokenizer_cursor {
  128924. sqlite3_tokenizer_cursor base;
  128925. const char *zInput; /* input we are tokenizing */
  128926. int nInput; /* size of the input */
  128927. int iOffset; /* current position in zInput */
  128928. int iToken; /* index of next token to be returned */
  128929. char *zToken; /* storage for current token */
  128930. int nAllocated; /* space allocated to zToken buffer */
  128931. } porter_tokenizer_cursor;
  128932. /*
  128933. ** Create a new tokenizer instance.
  128934. */
  128935. static int porterCreate(
  128936. int argc, const char * const *argv,
  128937. sqlite3_tokenizer **ppTokenizer
  128938. ){
  128939. porter_tokenizer *t;
  128940. UNUSED_PARAMETER(argc);
  128941. UNUSED_PARAMETER(argv);
  128942. t = (porter_tokenizer *) sqlite3_malloc(sizeof(*t));
  128943. if( t==NULL ) return SQLITE_NOMEM;
  128944. memset(t, 0, sizeof(*t));
  128945. *ppTokenizer = &t->base;
  128946. return SQLITE_OK;
  128947. }
  128948. /*
  128949. ** Destroy a tokenizer
  128950. */
  128951. static int porterDestroy(sqlite3_tokenizer *pTokenizer){
  128952. sqlite3_free(pTokenizer);
  128953. return SQLITE_OK;
  128954. }
  128955. /*
  128956. ** Prepare to begin tokenizing a particular string. The input
  128957. ** string to be tokenized is zInput[0..nInput-1]. A cursor
  128958. ** used to incrementally tokenize this string is returned in
  128959. ** *ppCursor.
  128960. */
  128961. static int porterOpen(
  128962. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  128963. const char *zInput, int nInput, /* String to be tokenized */
  128964. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  128965. ){
  128966. porter_tokenizer_cursor *c;
  128967. UNUSED_PARAMETER(pTokenizer);
  128968. c = (porter_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  128969. if( c==NULL ) return SQLITE_NOMEM;
  128970. c->zInput = zInput;
  128971. if( zInput==0 ){
  128972. c->nInput = 0;
  128973. }else if( nInput<0 ){
  128974. c->nInput = (int)strlen(zInput);
  128975. }else{
  128976. c->nInput = nInput;
  128977. }
  128978. c->iOffset = 0; /* start tokenizing at the beginning */
  128979. c->iToken = 0;
  128980. c->zToken = NULL; /* no space allocated, yet. */
  128981. c->nAllocated = 0;
  128982. *ppCursor = &c->base;
  128983. return SQLITE_OK;
  128984. }
  128985. /*
  128986. ** Close a tokenization cursor previously opened by a call to
  128987. ** porterOpen() above.
  128988. */
  128989. static int porterClose(sqlite3_tokenizer_cursor *pCursor){
  128990. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  128991. sqlite3_free(c->zToken);
  128992. sqlite3_free(c);
  128993. return SQLITE_OK;
  128994. }
  128995. /*
  128996. ** Vowel or consonant
  128997. */
  128998. static const char cType[] = {
  128999. 0, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0,
  129000. 1, 1, 1, 2, 1
  129001. };
  129002. /*
  129003. ** isConsonant() and isVowel() determine if their first character in
  129004. ** the string they point to is a consonant or a vowel, according
  129005. ** to Porter ruls.
  129006. **
  129007. ** A consonate is any letter other than 'a', 'e', 'i', 'o', or 'u'.
  129008. ** 'Y' is a consonant unless it follows another consonant,
  129009. ** in which case it is a vowel.
  129010. **
  129011. ** In these routine, the letters are in reverse order. So the 'y' rule
  129012. ** is that 'y' is a consonant unless it is followed by another
  129013. ** consonent.
  129014. */
  129015. static int isVowel(const char*);
  129016. static int isConsonant(const char *z){
  129017. int j;
  129018. char x = *z;
  129019. if( x==0 ) return 0;
  129020. assert( x>='a' && x<='z' );
  129021. j = cType[x-'a'];
  129022. if( j<2 ) return j;
  129023. return z[1]==0 || isVowel(z + 1);
  129024. }
  129025. static int isVowel(const char *z){
  129026. int j;
  129027. char x = *z;
  129028. if( x==0 ) return 0;
  129029. assert( x>='a' && x<='z' );
  129030. j = cType[x-'a'];
  129031. if( j<2 ) return 1-j;
  129032. return isConsonant(z + 1);
  129033. }
  129034. /*
  129035. ** Let any sequence of one or more vowels be represented by V and let
  129036. ** C be sequence of one or more consonants. Then every word can be
  129037. ** represented as:
  129038. **
  129039. ** [C] (VC){m} [V]
  129040. **
  129041. ** In prose: A word is an optional consonant followed by zero or
  129042. ** vowel-consonant pairs followed by an optional vowel. "m" is the
  129043. ** number of vowel consonant pairs. This routine computes the value
  129044. ** of m for the first i bytes of a word.
  129045. **
  129046. ** Return true if the m-value for z is 1 or more. In other words,
  129047. ** return true if z contains at least one vowel that is followed
  129048. ** by a consonant.
  129049. **
  129050. ** In this routine z[] is in reverse order. So we are really looking
  129051. ** for an instance of of a consonant followed by a vowel.
  129052. */
  129053. static int m_gt_0(const char *z){
  129054. while( isVowel(z) ){ z++; }
  129055. if( *z==0 ) return 0;
  129056. while( isConsonant(z) ){ z++; }
  129057. return *z!=0;
  129058. }
  129059. /* Like mgt0 above except we are looking for a value of m which is
  129060. ** exactly 1
  129061. */
  129062. static int m_eq_1(const char *z){
  129063. while( isVowel(z) ){ z++; }
  129064. if( *z==0 ) return 0;
  129065. while( isConsonant(z) ){ z++; }
  129066. if( *z==0 ) return 0;
  129067. while( isVowel(z) ){ z++; }
  129068. if( *z==0 ) return 1;
  129069. while( isConsonant(z) ){ z++; }
  129070. return *z==0;
  129071. }
  129072. /* Like mgt0 above except we are looking for a value of m>1 instead
  129073. ** or m>0
  129074. */
  129075. static int m_gt_1(const char *z){
  129076. while( isVowel(z) ){ z++; }
  129077. if( *z==0 ) return 0;
  129078. while( isConsonant(z) ){ z++; }
  129079. if( *z==0 ) return 0;
  129080. while( isVowel(z) ){ z++; }
  129081. if( *z==0 ) return 0;
  129082. while( isConsonant(z) ){ z++; }
  129083. return *z!=0;
  129084. }
  129085. /*
  129086. ** Return TRUE if there is a vowel anywhere within z[0..n-1]
  129087. */
  129088. static int hasVowel(const char *z){
  129089. while( isConsonant(z) ){ z++; }
  129090. return *z!=0;
  129091. }
  129092. /*
  129093. ** Return TRUE if the word ends in a double consonant.
  129094. **
  129095. ** The text is reversed here. So we are really looking at
  129096. ** the first two characters of z[].
  129097. */
  129098. static int doubleConsonant(const char *z){
  129099. return isConsonant(z) && z[0]==z[1];
  129100. }
  129101. /*
  129102. ** Return TRUE if the word ends with three letters which
  129103. ** are consonant-vowel-consonent and where the final consonant
  129104. ** is not 'w', 'x', or 'y'.
  129105. **
  129106. ** The word is reversed here. So we are really checking the
  129107. ** first three letters and the first one cannot be in [wxy].
  129108. */
  129109. static int star_oh(const char *z){
  129110. return
  129111. isConsonant(z) &&
  129112. z[0]!='w' && z[0]!='x' && z[0]!='y' &&
  129113. isVowel(z+1) &&
  129114. isConsonant(z+2);
  129115. }
  129116. /*
  129117. ** If the word ends with zFrom and xCond() is true for the stem
  129118. ** of the word that preceeds the zFrom ending, then change the
  129119. ** ending to zTo.
  129120. **
  129121. ** The input word *pz and zFrom are both in reverse order. zTo
  129122. ** is in normal order.
  129123. **
  129124. ** Return TRUE if zFrom matches. Return FALSE if zFrom does not
  129125. ** match. Not that TRUE is returned even if xCond() fails and
  129126. ** no substitution occurs.
  129127. */
  129128. static int stem(
  129129. char **pz, /* The word being stemmed (Reversed) */
  129130. const char *zFrom, /* If the ending matches this... (Reversed) */
  129131. const char *zTo, /* ... change the ending to this (not reversed) */
  129132. int (*xCond)(const char*) /* Condition that must be true */
  129133. ){
  129134. char *z = *pz;
  129135. while( *zFrom && *zFrom==*z ){ z++; zFrom++; }
  129136. if( *zFrom!=0 ) return 0;
  129137. if( xCond && !xCond(z) ) return 1;
  129138. while( *zTo ){
  129139. *(--z) = *(zTo++);
  129140. }
  129141. *pz = z;
  129142. return 1;
  129143. }
  129144. /*
  129145. ** This is the fallback stemmer used when the porter stemmer is
  129146. ** inappropriate. The input word is copied into the output with
  129147. ** US-ASCII case folding. If the input word is too long (more
  129148. ** than 20 bytes if it contains no digits or more than 6 bytes if
  129149. ** it contains digits) then word is truncated to 20 or 6 bytes
  129150. ** by taking 10 or 3 bytes from the beginning and end.
  129151. */
  129152. static void copy_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  129153. int i, mx, j;
  129154. int hasDigit = 0;
  129155. for(i=0; i<nIn; i++){
  129156. char c = zIn[i];
  129157. if( c>='A' && c<='Z' ){
  129158. zOut[i] = c - 'A' + 'a';
  129159. }else{
  129160. if( c>='0' && c<='9' ) hasDigit = 1;
  129161. zOut[i] = c;
  129162. }
  129163. }
  129164. mx = hasDigit ? 3 : 10;
  129165. if( nIn>mx*2 ){
  129166. for(j=mx, i=nIn-mx; i<nIn; i++, j++){
  129167. zOut[j] = zOut[i];
  129168. }
  129169. i = j;
  129170. }
  129171. zOut[i] = 0;
  129172. *pnOut = i;
  129173. }
  129174. /*
  129175. ** Stem the input word zIn[0..nIn-1]. Store the output in zOut.
  129176. ** zOut is at least big enough to hold nIn bytes. Write the actual
  129177. ** size of the output word (exclusive of the '\0' terminator) into *pnOut.
  129178. **
  129179. ** Any upper-case characters in the US-ASCII character set ([A-Z])
  129180. ** are converted to lower case. Upper-case UTF characters are
  129181. ** unchanged.
  129182. **
  129183. ** Words that are longer than about 20 bytes are stemmed by retaining
  129184. ** a few bytes from the beginning and the end of the word. If the
  129185. ** word contains digits, 3 bytes are taken from the beginning and
  129186. ** 3 bytes from the end. For long words without digits, 10 bytes
  129187. ** are taken from each end. US-ASCII case folding still applies.
  129188. **
  129189. ** If the input word contains not digits but does characters not
  129190. ** in [a-zA-Z] then no stemming is attempted and this routine just
  129191. ** copies the input into the input into the output with US-ASCII
  129192. ** case folding.
  129193. **
  129194. ** Stemming never increases the length of the word. So there is
  129195. ** no chance of overflowing the zOut buffer.
  129196. */
  129197. static void porter_stemmer(const char *zIn, int nIn, char *zOut, int *pnOut){
  129198. int i, j;
  129199. char zReverse[28];
  129200. char *z, *z2;
  129201. if( nIn<3 || nIn>=(int)sizeof(zReverse)-7 ){
  129202. /* The word is too big or too small for the porter stemmer.
  129203. ** Fallback to the copy stemmer */
  129204. copy_stemmer(zIn, nIn, zOut, pnOut);
  129205. return;
  129206. }
  129207. for(i=0, j=sizeof(zReverse)-6; i<nIn; i++, j--){
  129208. char c = zIn[i];
  129209. if( c>='A' && c<='Z' ){
  129210. zReverse[j] = c + 'a' - 'A';
  129211. }else if( c>='a' && c<='z' ){
  129212. zReverse[j] = c;
  129213. }else{
  129214. /* The use of a character not in [a-zA-Z] means that we fallback
  129215. ** to the copy stemmer */
  129216. copy_stemmer(zIn, nIn, zOut, pnOut);
  129217. return;
  129218. }
  129219. }
  129220. memset(&zReverse[sizeof(zReverse)-5], 0, 5);
  129221. z = &zReverse[j+1];
  129222. /* Step 1a */
  129223. if( z[0]=='s' ){
  129224. if(
  129225. !stem(&z, "sess", "ss", 0) &&
  129226. !stem(&z, "sei", "i", 0) &&
  129227. !stem(&z, "ss", "ss", 0)
  129228. ){
  129229. z++;
  129230. }
  129231. }
  129232. /* Step 1b */
  129233. z2 = z;
  129234. if( stem(&z, "dee", "ee", m_gt_0) ){
  129235. /* Do nothing. The work was all in the test */
  129236. }else if(
  129237. (stem(&z, "gni", "", hasVowel) || stem(&z, "de", "", hasVowel))
  129238. && z!=z2
  129239. ){
  129240. if( stem(&z, "ta", "ate", 0) ||
  129241. stem(&z, "lb", "ble", 0) ||
  129242. stem(&z, "zi", "ize", 0) ){
  129243. /* Do nothing. The work was all in the test */
  129244. }else if( doubleConsonant(z) && (*z!='l' && *z!='s' && *z!='z') ){
  129245. z++;
  129246. }else if( m_eq_1(z) && star_oh(z) ){
  129247. *(--z) = 'e';
  129248. }
  129249. }
  129250. /* Step 1c */
  129251. if( z[0]=='y' && hasVowel(z+1) ){
  129252. z[0] = 'i';
  129253. }
  129254. /* Step 2 */
  129255. switch( z[1] ){
  129256. case 'a':
  129257. if( !stem(&z, "lanoita", "ate", m_gt_0) ){
  129258. stem(&z, "lanoit", "tion", m_gt_0);
  129259. }
  129260. break;
  129261. case 'c':
  129262. if( !stem(&z, "icne", "ence", m_gt_0) ){
  129263. stem(&z, "icna", "ance", m_gt_0);
  129264. }
  129265. break;
  129266. case 'e':
  129267. stem(&z, "rezi", "ize", m_gt_0);
  129268. break;
  129269. case 'g':
  129270. stem(&z, "igol", "log", m_gt_0);
  129271. break;
  129272. case 'l':
  129273. if( !stem(&z, "ilb", "ble", m_gt_0)
  129274. && !stem(&z, "illa", "al", m_gt_0)
  129275. && !stem(&z, "iltne", "ent", m_gt_0)
  129276. && !stem(&z, "ile", "e", m_gt_0)
  129277. ){
  129278. stem(&z, "ilsuo", "ous", m_gt_0);
  129279. }
  129280. break;
  129281. case 'o':
  129282. if( !stem(&z, "noitazi", "ize", m_gt_0)
  129283. && !stem(&z, "noita", "ate", m_gt_0)
  129284. ){
  129285. stem(&z, "rota", "ate", m_gt_0);
  129286. }
  129287. break;
  129288. case 's':
  129289. if( !stem(&z, "msila", "al", m_gt_0)
  129290. && !stem(&z, "ssenevi", "ive", m_gt_0)
  129291. && !stem(&z, "ssenluf", "ful", m_gt_0)
  129292. ){
  129293. stem(&z, "ssensuo", "ous", m_gt_0);
  129294. }
  129295. break;
  129296. case 't':
  129297. if( !stem(&z, "itila", "al", m_gt_0)
  129298. && !stem(&z, "itivi", "ive", m_gt_0)
  129299. ){
  129300. stem(&z, "itilib", "ble", m_gt_0);
  129301. }
  129302. break;
  129303. }
  129304. /* Step 3 */
  129305. switch( z[0] ){
  129306. case 'e':
  129307. if( !stem(&z, "etaci", "ic", m_gt_0)
  129308. && !stem(&z, "evita", "", m_gt_0)
  129309. ){
  129310. stem(&z, "ezila", "al", m_gt_0);
  129311. }
  129312. break;
  129313. case 'i':
  129314. stem(&z, "itici", "ic", m_gt_0);
  129315. break;
  129316. case 'l':
  129317. if( !stem(&z, "laci", "ic", m_gt_0) ){
  129318. stem(&z, "luf", "", m_gt_0);
  129319. }
  129320. break;
  129321. case 's':
  129322. stem(&z, "ssen", "", m_gt_0);
  129323. break;
  129324. }
  129325. /* Step 4 */
  129326. switch( z[1] ){
  129327. case 'a':
  129328. if( z[0]=='l' && m_gt_1(z+2) ){
  129329. z += 2;
  129330. }
  129331. break;
  129332. case 'c':
  129333. if( z[0]=='e' && z[2]=='n' && (z[3]=='a' || z[3]=='e') && m_gt_1(z+4) ){
  129334. z += 4;
  129335. }
  129336. break;
  129337. case 'e':
  129338. if( z[0]=='r' && m_gt_1(z+2) ){
  129339. z += 2;
  129340. }
  129341. break;
  129342. case 'i':
  129343. if( z[0]=='c' && m_gt_1(z+2) ){
  129344. z += 2;
  129345. }
  129346. break;
  129347. case 'l':
  129348. if( z[0]=='e' && z[2]=='b' && (z[3]=='a' || z[3]=='i') && m_gt_1(z+4) ){
  129349. z += 4;
  129350. }
  129351. break;
  129352. case 'n':
  129353. if( z[0]=='t' ){
  129354. if( z[2]=='a' ){
  129355. if( m_gt_1(z+3) ){
  129356. z += 3;
  129357. }
  129358. }else if( z[2]=='e' ){
  129359. if( !stem(&z, "tneme", "", m_gt_1)
  129360. && !stem(&z, "tnem", "", m_gt_1)
  129361. ){
  129362. stem(&z, "tne", "", m_gt_1);
  129363. }
  129364. }
  129365. }
  129366. break;
  129367. case 'o':
  129368. if( z[0]=='u' ){
  129369. if( m_gt_1(z+2) ){
  129370. z += 2;
  129371. }
  129372. }else if( z[3]=='s' || z[3]=='t' ){
  129373. stem(&z, "noi", "", m_gt_1);
  129374. }
  129375. break;
  129376. case 's':
  129377. if( z[0]=='m' && z[2]=='i' && m_gt_1(z+3) ){
  129378. z += 3;
  129379. }
  129380. break;
  129381. case 't':
  129382. if( !stem(&z, "eta", "", m_gt_1) ){
  129383. stem(&z, "iti", "", m_gt_1);
  129384. }
  129385. break;
  129386. case 'u':
  129387. if( z[0]=='s' && z[2]=='o' && m_gt_1(z+3) ){
  129388. z += 3;
  129389. }
  129390. break;
  129391. case 'v':
  129392. case 'z':
  129393. if( z[0]=='e' && z[2]=='i' && m_gt_1(z+3) ){
  129394. z += 3;
  129395. }
  129396. break;
  129397. }
  129398. /* Step 5a */
  129399. if( z[0]=='e' ){
  129400. if( m_gt_1(z+1) ){
  129401. z++;
  129402. }else if( m_eq_1(z+1) && !star_oh(z+1) ){
  129403. z++;
  129404. }
  129405. }
  129406. /* Step 5b */
  129407. if( m_gt_1(z) && z[0]=='l' && z[1]=='l' ){
  129408. z++;
  129409. }
  129410. /* z[] is now the stemmed word in reverse order. Flip it back
  129411. ** around into forward order and return.
  129412. */
  129413. *pnOut = i = (int)strlen(z);
  129414. zOut[i] = 0;
  129415. while( *z ){
  129416. zOut[--i] = *(z++);
  129417. }
  129418. }
  129419. /*
  129420. ** Characters that can be part of a token. We assume any character
  129421. ** whose value is greater than 0x80 (any UTF character) can be
  129422. ** part of a token. In other words, delimiters all must have
  129423. ** values of 0x7f or lower.
  129424. */
  129425. static const char porterIdChar[] = {
  129426. /* x0 x1 x2 x3 x4 x5 x6 x7 x8 x9 xA xB xC xD xE xF */
  129427. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  129428. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  129429. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  129430. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  129431. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  129432. };
  129433. #define isDelim(C) (((ch=C)&0x80)==0 && (ch<0x30 || !porterIdChar[ch-0x30]))
  129434. /*
  129435. ** Extract the next token from a tokenization cursor. The cursor must
  129436. ** have been opened by a prior call to porterOpen().
  129437. */
  129438. static int porterNext(
  129439. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by porterOpen */
  129440. const char **pzToken, /* OUT: *pzToken is the token text */
  129441. int *pnBytes, /* OUT: Number of bytes in token */
  129442. int *piStartOffset, /* OUT: Starting offset of token */
  129443. int *piEndOffset, /* OUT: Ending offset of token */
  129444. int *piPosition /* OUT: Position integer of token */
  129445. ){
  129446. porter_tokenizer_cursor *c = (porter_tokenizer_cursor *) pCursor;
  129447. const char *z = c->zInput;
  129448. while( c->iOffset<c->nInput ){
  129449. int iStartOffset, ch;
  129450. /* Scan past delimiter characters */
  129451. while( c->iOffset<c->nInput && isDelim(z[c->iOffset]) ){
  129452. c->iOffset++;
  129453. }
  129454. /* Count non-delimiter characters. */
  129455. iStartOffset = c->iOffset;
  129456. while( c->iOffset<c->nInput && !isDelim(z[c->iOffset]) ){
  129457. c->iOffset++;
  129458. }
  129459. if( c->iOffset>iStartOffset ){
  129460. int n = c->iOffset-iStartOffset;
  129461. if( n>c->nAllocated ){
  129462. char *pNew;
  129463. c->nAllocated = n+20;
  129464. pNew = sqlite3_realloc(c->zToken, c->nAllocated);
  129465. if( !pNew ) return SQLITE_NOMEM;
  129466. c->zToken = pNew;
  129467. }
  129468. porter_stemmer(&z[iStartOffset], n, c->zToken, pnBytes);
  129469. *pzToken = c->zToken;
  129470. *piStartOffset = iStartOffset;
  129471. *piEndOffset = c->iOffset;
  129472. *piPosition = c->iToken++;
  129473. return SQLITE_OK;
  129474. }
  129475. }
  129476. return SQLITE_DONE;
  129477. }
  129478. /*
  129479. ** The set of routines that implement the porter-stemmer tokenizer
  129480. */
  129481. static const sqlite3_tokenizer_module porterTokenizerModule = {
  129482. 0,
  129483. porterCreate,
  129484. porterDestroy,
  129485. porterOpen,
  129486. porterClose,
  129487. porterNext,
  129488. 0
  129489. };
  129490. /*
  129491. ** Allocate a new porter tokenizer. Return a pointer to the new
  129492. ** tokenizer in *ppModule
  129493. */
  129494. SQLITE_PRIVATE void sqlite3Fts3PorterTokenizerModule(
  129495. sqlite3_tokenizer_module const**ppModule
  129496. ){
  129497. *ppModule = &porterTokenizerModule;
  129498. }
  129499. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  129500. /************** End of fts3_porter.c *****************************************/
  129501. /************** Begin file fts3_tokenizer.c **********************************/
  129502. /*
  129503. ** 2007 June 22
  129504. **
  129505. ** The author disclaims copyright to this source code. In place of
  129506. ** a legal notice, here is a blessing:
  129507. **
  129508. ** May you do good and not evil.
  129509. ** May you find forgiveness for yourself and forgive others.
  129510. ** May you share freely, never taking more than you give.
  129511. **
  129512. ******************************************************************************
  129513. **
  129514. ** This is part of an SQLite module implementing full-text search.
  129515. ** This particular file implements the generic tokenizer interface.
  129516. */
  129517. /*
  129518. ** The code in this file is only compiled if:
  129519. **
  129520. ** * The FTS3 module is being built as an extension
  129521. ** (in which case SQLITE_CORE is not defined), or
  129522. **
  129523. ** * The FTS3 module is being built into the core of
  129524. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  129525. */
  129526. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  129527. /* #include <assert.h> */
  129528. /* #include <string.h> */
  129529. /*
  129530. ** Implementation of the SQL scalar function for accessing the underlying
  129531. ** hash table. This function may be called as follows:
  129532. **
  129533. ** SELECT <function-name>(<key-name>);
  129534. ** SELECT <function-name>(<key-name>, <pointer>);
  129535. **
  129536. ** where <function-name> is the name passed as the second argument
  129537. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer').
  129538. **
  129539. ** If the <pointer> argument is specified, it must be a blob value
  129540. ** containing a pointer to be stored as the hash data corresponding
  129541. ** to the string <key-name>. If <pointer> is not specified, then
  129542. ** the string <key-name> must already exist in the has table. Otherwise,
  129543. ** an error is returned.
  129544. **
  129545. ** Whether or not the <pointer> argument is specified, the value returned
  129546. ** is a blob containing the pointer stored as the hash data corresponding
  129547. ** to string <key-name> (after the hash-table is updated, if applicable).
  129548. */
  129549. static void scalarFunc(
  129550. sqlite3_context *context,
  129551. int argc,
  129552. sqlite3_value **argv
  129553. ){
  129554. Fts3Hash *pHash;
  129555. void *pPtr = 0;
  129556. const unsigned char *zName;
  129557. int nName;
  129558. assert( argc==1 || argc==2 );
  129559. pHash = (Fts3Hash *)sqlite3_user_data(context);
  129560. zName = sqlite3_value_text(argv[0]);
  129561. nName = sqlite3_value_bytes(argv[0])+1;
  129562. if( argc==2 ){
  129563. void *pOld;
  129564. int n = sqlite3_value_bytes(argv[1]);
  129565. if( n!=sizeof(pPtr) ){
  129566. sqlite3_result_error(context, "argument type mismatch", -1);
  129567. return;
  129568. }
  129569. pPtr = *(void **)sqlite3_value_blob(argv[1]);
  129570. pOld = sqlite3Fts3HashInsert(pHash, (void *)zName, nName, pPtr);
  129571. if( pOld==pPtr ){
  129572. sqlite3_result_error(context, "out of memory", -1);
  129573. return;
  129574. }
  129575. }else{
  129576. pPtr = sqlite3Fts3HashFind(pHash, zName, nName);
  129577. if( !pPtr ){
  129578. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  129579. sqlite3_result_error(context, zErr, -1);
  129580. sqlite3_free(zErr);
  129581. return;
  129582. }
  129583. }
  129584. sqlite3_result_blob(context, (void *)&pPtr, sizeof(pPtr), SQLITE_TRANSIENT);
  129585. }
  129586. SQLITE_PRIVATE int sqlite3Fts3IsIdChar(char c){
  129587. static const char isFtsIdChar[] = {
  129588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 0x */
  129589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 1x */
  129590. 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* 2x */
  129591. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, /* 3x */
  129592. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 4x */
  129593. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, /* 5x */
  129594. 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, /* 6x */
  129595. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, /* 7x */
  129596. };
  129597. return (c&0x80 || isFtsIdChar[(int)(c)]);
  129598. }
  129599. SQLITE_PRIVATE const char *sqlite3Fts3NextToken(const char *zStr, int *pn){
  129600. const char *z1;
  129601. const char *z2 = 0;
  129602. /* Find the start of the next token. */
  129603. z1 = zStr;
  129604. while( z2==0 ){
  129605. char c = *z1;
  129606. switch( c ){
  129607. case '\0': return 0; /* No more tokens here */
  129608. case '\'':
  129609. case '"':
  129610. case '`': {
  129611. z2 = z1;
  129612. while( *++z2 && (*z2!=c || *++z2==c) );
  129613. break;
  129614. }
  129615. case '[':
  129616. z2 = &z1[1];
  129617. while( *z2 && z2[0]!=']' ) z2++;
  129618. if( *z2 ) z2++;
  129619. break;
  129620. default:
  129621. if( sqlite3Fts3IsIdChar(*z1) ){
  129622. z2 = &z1[1];
  129623. while( sqlite3Fts3IsIdChar(*z2) ) z2++;
  129624. }else{
  129625. z1++;
  129626. }
  129627. }
  129628. }
  129629. *pn = (int)(z2-z1);
  129630. return z1;
  129631. }
  129632. SQLITE_PRIVATE int sqlite3Fts3InitTokenizer(
  129633. Fts3Hash *pHash, /* Tokenizer hash table */
  129634. const char *zArg, /* Tokenizer name */
  129635. sqlite3_tokenizer **ppTok, /* OUT: Tokenizer (if applicable) */
  129636. char **pzErr /* OUT: Set to malloced error message */
  129637. ){
  129638. int rc;
  129639. char *z = (char *)zArg;
  129640. int n = 0;
  129641. char *zCopy;
  129642. char *zEnd; /* Pointer to nul-term of zCopy */
  129643. sqlite3_tokenizer_module *m;
  129644. zCopy = sqlite3_mprintf("%s", zArg);
  129645. if( !zCopy ) return SQLITE_NOMEM;
  129646. zEnd = &zCopy[strlen(zCopy)];
  129647. z = (char *)sqlite3Fts3NextToken(zCopy, &n);
  129648. z[n] = '\0';
  129649. sqlite3Fts3Dequote(z);
  129650. m = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash,z,(int)strlen(z)+1);
  129651. if( !m ){
  129652. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", z);
  129653. rc = SQLITE_ERROR;
  129654. }else{
  129655. char const **aArg = 0;
  129656. int iArg = 0;
  129657. z = &z[n+1];
  129658. while( z<zEnd && (NULL!=(z = (char *)sqlite3Fts3NextToken(z, &n))) ){
  129659. int nNew = sizeof(char *)*(iArg+1);
  129660. char const **aNew = (const char **)sqlite3_realloc((void *)aArg, nNew);
  129661. if( !aNew ){
  129662. sqlite3_free(zCopy);
  129663. sqlite3_free((void *)aArg);
  129664. return SQLITE_NOMEM;
  129665. }
  129666. aArg = aNew;
  129667. aArg[iArg++] = z;
  129668. z[n] = '\0';
  129669. sqlite3Fts3Dequote(z);
  129670. z = &z[n+1];
  129671. }
  129672. rc = m->xCreate(iArg, aArg, ppTok);
  129673. assert( rc!=SQLITE_OK || *ppTok );
  129674. if( rc!=SQLITE_OK ){
  129675. *pzErr = sqlite3_mprintf("unknown tokenizer");
  129676. }else{
  129677. (*ppTok)->pModule = m;
  129678. }
  129679. sqlite3_free((void *)aArg);
  129680. }
  129681. sqlite3_free(zCopy);
  129682. return rc;
  129683. }
  129684. #ifdef SQLITE_TEST
  129685. #include <tcl.h>
  129686. /* #include <string.h> */
  129687. /*
  129688. ** Implementation of a special SQL scalar function for testing tokenizers
  129689. ** designed to be used in concert with the Tcl testing framework. This
  129690. ** function must be called with two or more arguments:
  129691. **
  129692. ** SELECT <function-name>(<key-name>, ..., <input-string>);
  129693. **
  129694. ** where <function-name> is the name passed as the second argument
  129695. ** to the sqlite3Fts3InitHashTable() function (e.g. 'fts3_tokenizer')
  129696. ** concatenated with the string '_test' (e.g. 'fts3_tokenizer_test').
  129697. **
  129698. ** The return value is a string that may be interpreted as a Tcl
  129699. ** list. For each token in the <input-string>, three elements are
  129700. ** added to the returned list. The first is the token position, the
  129701. ** second is the token text (folded, stemmed, etc.) and the third is the
  129702. ** substring of <input-string> associated with the token. For example,
  129703. ** using the built-in "simple" tokenizer:
  129704. **
  129705. ** SELECT fts_tokenizer_test('simple', 'I don't see how');
  129706. **
  129707. ** will return the string:
  129708. **
  129709. ** "{0 i I 1 dont don't 2 see see 3 how how}"
  129710. **
  129711. */
  129712. static void testFunc(
  129713. sqlite3_context *context,
  129714. int argc,
  129715. sqlite3_value **argv
  129716. ){
  129717. Fts3Hash *pHash;
  129718. sqlite3_tokenizer_module *p;
  129719. sqlite3_tokenizer *pTokenizer = 0;
  129720. sqlite3_tokenizer_cursor *pCsr = 0;
  129721. const char *zErr = 0;
  129722. const char *zName;
  129723. int nName;
  129724. const char *zInput;
  129725. int nInput;
  129726. const char *azArg[64];
  129727. const char *zToken;
  129728. int nToken = 0;
  129729. int iStart = 0;
  129730. int iEnd = 0;
  129731. int iPos = 0;
  129732. int i;
  129733. Tcl_Obj *pRet;
  129734. if( argc<2 ){
  129735. sqlite3_result_error(context, "insufficient arguments", -1);
  129736. return;
  129737. }
  129738. nName = sqlite3_value_bytes(argv[0]);
  129739. zName = (const char *)sqlite3_value_text(argv[0]);
  129740. nInput = sqlite3_value_bytes(argv[argc-1]);
  129741. zInput = (const char *)sqlite3_value_text(argv[argc-1]);
  129742. pHash = (Fts3Hash *)sqlite3_user_data(context);
  129743. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  129744. if( !p ){
  129745. char *zErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  129746. sqlite3_result_error(context, zErr, -1);
  129747. sqlite3_free(zErr);
  129748. return;
  129749. }
  129750. pRet = Tcl_NewObj();
  129751. Tcl_IncrRefCount(pRet);
  129752. for(i=1; i<argc-1; i++){
  129753. azArg[i-1] = (const char *)sqlite3_value_text(argv[i]);
  129754. }
  129755. if( SQLITE_OK!=p->xCreate(argc-2, azArg, &pTokenizer) ){
  129756. zErr = "error in xCreate()";
  129757. goto finish;
  129758. }
  129759. pTokenizer->pModule = p;
  129760. if( sqlite3Fts3OpenTokenizer(pTokenizer, 0, zInput, nInput, &pCsr) ){
  129761. zErr = "error in xOpen()";
  129762. goto finish;
  129763. }
  129764. while( SQLITE_OK==p->xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos) ){
  129765. Tcl_ListObjAppendElement(0, pRet, Tcl_NewIntObj(iPos));
  129766. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  129767. zToken = &zInput[iStart];
  129768. nToken = iEnd-iStart;
  129769. Tcl_ListObjAppendElement(0, pRet, Tcl_NewStringObj(zToken, nToken));
  129770. }
  129771. if( SQLITE_OK!=p->xClose(pCsr) ){
  129772. zErr = "error in xClose()";
  129773. goto finish;
  129774. }
  129775. if( SQLITE_OK!=p->xDestroy(pTokenizer) ){
  129776. zErr = "error in xDestroy()";
  129777. goto finish;
  129778. }
  129779. finish:
  129780. if( zErr ){
  129781. sqlite3_result_error(context, zErr, -1);
  129782. }else{
  129783. sqlite3_result_text(context, Tcl_GetString(pRet), -1, SQLITE_TRANSIENT);
  129784. }
  129785. Tcl_DecrRefCount(pRet);
  129786. }
  129787. static
  129788. int registerTokenizer(
  129789. sqlite3 *db,
  129790. char *zName,
  129791. const sqlite3_tokenizer_module *p
  129792. ){
  129793. int rc;
  129794. sqlite3_stmt *pStmt;
  129795. const char zSql[] = "SELECT fts3_tokenizer(?, ?)";
  129796. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  129797. if( rc!=SQLITE_OK ){
  129798. return rc;
  129799. }
  129800. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  129801. sqlite3_bind_blob(pStmt, 2, &p, sizeof(p), SQLITE_STATIC);
  129802. sqlite3_step(pStmt);
  129803. return sqlite3_finalize(pStmt);
  129804. }
  129805. static
  129806. int queryTokenizer(
  129807. sqlite3 *db,
  129808. char *zName,
  129809. const sqlite3_tokenizer_module **pp
  129810. ){
  129811. int rc;
  129812. sqlite3_stmt *pStmt;
  129813. const char zSql[] = "SELECT fts3_tokenizer(?)";
  129814. *pp = 0;
  129815. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  129816. if( rc!=SQLITE_OK ){
  129817. return rc;
  129818. }
  129819. sqlite3_bind_text(pStmt, 1, zName, -1, SQLITE_STATIC);
  129820. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  129821. if( sqlite3_column_type(pStmt, 0)==SQLITE_BLOB ){
  129822. memcpy((void *)pp, sqlite3_column_blob(pStmt, 0), sizeof(*pp));
  129823. }
  129824. }
  129825. return sqlite3_finalize(pStmt);
  129826. }
  129827. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(sqlite3_tokenizer_module const**ppModule);
  129828. /*
  129829. ** Implementation of the scalar function fts3_tokenizer_internal_test().
  129830. ** This function is used for testing only, it is not included in the
  129831. ** build unless SQLITE_TEST is defined.
  129832. **
  129833. ** The purpose of this is to test that the fts3_tokenizer() function
  129834. ** can be used as designed by the C-code in the queryTokenizer and
  129835. ** registerTokenizer() functions above. These two functions are repeated
  129836. ** in the README.tokenizer file as an example, so it is important to
  129837. ** test them.
  129838. **
  129839. ** To run the tests, evaluate the fts3_tokenizer_internal_test() scalar
  129840. ** function with no arguments. An assert() will fail if a problem is
  129841. ** detected. i.e.:
  129842. **
  129843. ** SELECT fts3_tokenizer_internal_test();
  129844. **
  129845. */
  129846. static void intTestFunc(
  129847. sqlite3_context *context,
  129848. int argc,
  129849. sqlite3_value **argv
  129850. ){
  129851. int rc;
  129852. const sqlite3_tokenizer_module *p1;
  129853. const sqlite3_tokenizer_module *p2;
  129854. sqlite3 *db = (sqlite3 *)sqlite3_user_data(context);
  129855. UNUSED_PARAMETER(argc);
  129856. UNUSED_PARAMETER(argv);
  129857. /* Test the query function */
  129858. sqlite3Fts3SimpleTokenizerModule(&p1);
  129859. rc = queryTokenizer(db, "simple", &p2);
  129860. assert( rc==SQLITE_OK );
  129861. assert( p1==p2 );
  129862. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  129863. assert( rc==SQLITE_ERROR );
  129864. assert( p2==0 );
  129865. assert( 0==strcmp(sqlite3_errmsg(db), "unknown tokenizer: nosuchtokenizer") );
  129866. /* Test the storage function */
  129867. rc = registerTokenizer(db, "nosuchtokenizer", p1);
  129868. assert( rc==SQLITE_OK );
  129869. rc = queryTokenizer(db, "nosuchtokenizer", &p2);
  129870. assert( rc==SQLITE_OK );
  129871. assert( p2==p1 );
  129872. sqlite3_result_text(context, "ok", -1, SQLITE_STATIC);
  129873. }
  129874. #endif
  129875. /*
  129876. ** Set up SQL objects in database db used to access the contents of
  129877. ** the hash table pointed to by argument pHash. The hash table must
  129878. ** been initialized to use string keys, and to take a private copy
  129879. ** of the key when a value is inserted. i.e. by a call similar to:
  129880. **
  129881. ** sqlite3Fts3HashInit(pHash, FTS3_HASH_STRING, 1);
  129882. **
  129883. ** This function adds a scalar function (see header comment above
  129884. ** scalarFunc() in this file for details) and, if ENABLE_TABLE is
  129885. ** defined at compilation time, a temporary virtual table (see header
  129886. ** comment above struct HashTableVtab) to the database schema. Both
  129887. ** provide read/write access to the contents of *pHash.
  129888. **
  129889. ** The third argument to this function, zName, is used as the name
  129890. ** of both the scalar and, if created, the virtual table.
  129891. */
  129892. SQLITE_PRIVATE int sqlite3Fts3InitHashTable(
  129893. sqlite3 *db,
  129894. Fts3Hash *pHash,
  129895. const char *zName
  129896. ){
  129897. int rc = SQLITE_OK;
  129898. void *p = (void *)pHash;
  129899. const int any = SQLITE_ANY;
  129900. #ifdef SQLITE_TEST
  129901. char *zTest = 0;
  129902. char *zTest2 = 0;
  129903. void *pdb = (void *)db;
  129904. zTest = sqlite3_mprintf("%s_test", zName);
  129905. zTest2 = sqlite3_mprintf("%s_internal_test", zName);
  129906. if( !zTest || !zTest2 ){
  129907. rc = SQLITE_NOMEM;
  129908. }
  129909. #endif
  129910. if( SQLITE_OK==rc ){
  129911. rc = sqlite3_create_function(db, zName, 1, any, p, scalarFunc, 0, 0);
  129912. }
  129913. if( SQLITE_OK==rc ){
  129914. rc = sqlite3_create_function(db, zName, 2, any, p, scalarFunc, 0, 0);
  129915. }
  129916. #ifdef SQLITE_TEST
  129917. if( SQLITE_OK==rc ){
  129918. rc = sqlite3_create_function(db, zTest, -1, any, p, testFunc, 0, 0);
  129919. }
  129920. if( SQLITE_OK==rc ){
  129921. rc = sqlite3_create_function(db, zTest2, 0, any, pdb, intTestFunc, 0, 0);
  129922. }
  129923. #endif
  129924. #ifdef SQLITE_TEST
  129925. sqlite3_free(zTest);
  129926. sqlite3_free(zTest2);
  129927. #endif
  129928. return rc;
  129929. }
  129930. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  129931. /************** End of fts3_tokenizer.c **************************************/
  129932. /************** Begin file fts3_tokenizer1.c *********************************/
  129933. /*
  129934. ** 2006 Oct 10
  129935. **
  129936. ** The author disclaims copyright to this source code. In place of
  129937. ** a legal notice, here is a blessing:
  129938. **
  129939. ** May you do good and not evil.
  129940. ** May you find forgiveness for yourself and forgive others.
  129941. ** May you share freely, never taking more than you give.
  129942. **
  129943. ******************************************************************************
  129944. **
  129945. ** Implementation of the "simple" full-text-search tokenizer.
  129946. */
  129947. /*
  129948. ** The code in this file is only compiled if:
  129949. **
  129950. ** * The FTS3 module is being built as an extension
  129951. ** (in which case SQLITE_CORE is not defined), or
  129952. **
  129953. ** * The FTS3 module is being built into the core of
  129954. ** SQLite (in which case SQLITE_ENABLE_FTS3 is defined).
  129955. */
  129956. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  129957. /* #include <assert.h> */
  129958. /* #include <stdlib.h> */
  129959. /* #include <stdio.h> */
  129960. /* #include <string.h> */
  129961. typedef struct simple_tokenizer {
  129962. sqlite3_tokenizer base;
  129963. char delim[128]; /* flag ASCII delimiters */
  129964. } simple_tokenizer;
  129965. typedef struct simple_tokenizer_cursor {
  129966. sqlite3_tokenizer_cursor base;
  129967. const char *pInput; /* input we are tokenizing */
  129968. int nBytes; /* size of the input */
  129969. int iOffset; /* current position in pInput */
  129970. int iToken; /* index of next token to be returned */
  129971. char *pToken; /* storage for current token */
  129972. int nTokenAllocated; /* space allocated to zToken buffer */
  129973. } simple_tokenizer_cursor;
  129974. static int simpleDelim(simple_tokenizer *t, unsigned char c){
  129975. return c<0x80 && t->delim[c];
  129976. }
  129977. static int fts3_isalnum(int x){
  129978. return (x>='0' && x<='9') || (x>='A' && x<='Z') || (x>='a' && x<='z');
  129979. }
  129980. /*
  129981. ** Create a new tokenizer instance.
  129982. */
  129983. static int simpleCreate(
  129984. int argc, const char * const *argv,
  129985. sqlite3_tokenizer **ppTokenizer
  129986. ){
  129987. simple_tokenizer *t;
  129988. t = (simple_tokenizer *) sqlite3_malloc(sizeof(*t));
  129989. if( t==NULL ) return SQLITE_NOMEM;
  129990. memset(t, 0, sizeof(*t));
  129991. /* TODO(shess) Delimiters need to remain the same from run to run,
  129992. ** else we need to reindex. One solution would be a meta-table to
  129993. ** track such information in the database, then we'd only want this
  129994. ** information on the initial create.
  129995. */
  129996. if( argc>1 ){
  129997. int i, n = (int)strlen(argv[1]);
  129998. for(i=0; i<n; i++){
  129999. unsigned char ch = argv[1][i];
  130000. /* We explicitly don't support UTF-8 delimiters for now. */
  130001. if( ch>=0x80 ){
  130002. sqlite3_free(t);
  130003. return SQLITE_ERROR;
  130004. }
  130005. t->delim[ch] = 1;
  130006. }
  130007. } else {
  130008. /* Mark non-alphanumeric ASCII characters as delimiters */
  130009. int i;
  130010. for(i=1; i<0x80; i++){
  130011. t->delim[i] = !fts3_isalnum(i) ? -1 : 0;
  130012. }
  130013. }
  130014. *ppTokenizer = &t->base;
  130015. return SQLITE_OK;
  130016. }
  130017. /*
  130018. ** Destroy a tokenizer
  130019. */
  130020. static int simpleDestroy(sqlite3_tokenizer *pTokenizer){
  130021. sqlite3_free(pTokenizer);
  130022. return SQLITE_OK;
  130023. }
  130024. /*
  130025. ** Prepare to begin tokenizing a particular string. The input
  130026. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  130027. ** used to incrementally tokenize this string is returned in
  130028. ** *ppCursor.
  130029. */
  130030. static int simpleOpen(
  130031. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  130032. const char *pInput, int nBytes, /* String to be tokenized */
  130033. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  130034. ){
  130035. simple_tokenizer_cursor *c;
  130036. UNUSED_PARAMETER(pTokenizer);
  130037. c = (simple_tokenizer_cursor *) sqlite3_malloc(sizeof(*c));
  130038. if( c==NULL ) return SQLITE_NOMEM;
  130039. c->pInput = pInput;
  130040. if( pInput==0 ){
  130041. c->nBytes = 0;
  130042. }else if( nBytes<0 ){
  130043. c->nBytes = (int)strlen(pInput);
  130044. }else{
  130045. c->nBytes = nBytes;
  130046. }
  130047. c->iOffset = 0; /* start tokenizing at the beginning */
  130048. c->iToken = 0;
  130049. c->pToken = NULL; /* no space allocated, yet. */
  130050. c->nTokenAllocated = 0;
  130051. *ppCursor = &c->base;
  130052. return SQLITE_OK;
  130053. }
  130054. /*
  130055. ** Close a tokenization cursor previously opened by a call to
  130056. ** simpleOpen() above.
  130057. */
  130058. static int simpleClose(sqlite3_tokenizer_cursor *pCursor){
  130059. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  130060. sqlite3_free(c->pToken);
  130061. sqlite3_free(c);
  130062. return SQLITE_OK;
  130063. }
  130064. /*
  130065. ** Extract the next token from a tokenization cursor. The cursor must
  130066. ** have been opened by a prior call to simpleOpen().
  130067. */
  130068. static int simpleNext(
  130069. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  130070. const char **ppToken, /* OUT: *ppToken is the token text */
  130071. int *pnBytes, /* OUT: Number of bytes in token */
  130072. int *piStartOffset, /* OUT: Starting offset of token */
  130073. int *piEndOffset, /* OUT: Ending offset of token */
  130074. int *piPosition /* OUT: Position integer of token */
  130075. ){
  130076. simple_tokenizer_cursor *c = (simple_tokenizer_cursor *) pCursor;
  130077. simple_tokenizer *t = (simple_tokenizer *) pCursor->pTokenizer;
  130078. unsigned char *p = (unsigned char *)c->pInput;
  130079. while( c->iOffset<c->nBytes ){
  130080. int iStartOffset;
  130081. /* Scan past delimiter characters */
  130082. while( c->iOffset<c->nBytes && simpleDelim(t, p[c->iOffset]) ){
  130083. c->iOffset++;
  130084. }
  130085. /* Count non-delimiter characters. */
  130086. iStartOffset = c->iOffset;
  130087. while( c->iOffset<c->nBytes && !simpleDelim(t, p[c->iOffset]) ){
  130088. c->iOffset++;
  130089. }
  130090. if( c->iOffset>iStartOffset ){
  130091. int i, n = c->iOffset-iStartOffset;
  130092. if( n>c->nTokenAllocated ){
  130093. char *pNew;
  130094. c->nTokenAllocated = n+20;
  130095. pNew = sqlite3_realloc(c->pToken, c->nTokenAllocated);
  130096. if( !pNew ) return SQLITE_NOMEM;
  130097. c->pToken = pNew;
  130098. }
  130099. for(i=0; i<n; i++){
  130100. /* TODO(shess) This needs expansion to handle UTF-8
  130101. ** case-insensitivity.
  130102. */
  130103. unsigned char ch = p[iStartOffset+i];
  130104. c->pToken[i] = (char)((ch>='A' && ch<='Z') ? ch-'A'+'a' : ch);
  130105. }
  130106. *ppToken = c->pToken;
  130107. *pnBytes = n;
  130108. *piStartOffset = iStartOffset;
  130109. *piEndOffset = c->iOffset;
  130110. *piPosition = c->iToken++;
  130111. return SQLITE_OK;
  130112. }
  130113. }
  130114. return SQLITE_DONE;
  130115. }
  130116. /*
  130117. ** The set of routines that implement the simple tokenizer
  130118. */
  130119. static const sqlite3_tokenizer_module simpleTokenizerModule = {
  130120. 0,
  130121. simpleCreate,
  130122. simpleDestroy,
  130123. simpleOpen,
  130124. simpleClose,
  130125. simpleNext,
  130126. 0,
  130127. };
  130128. /*
  130129. ** Allocate a new simple tokenizer. Return a pointer to the new
  130130. ** tokenizer in *ppModule
  130131. */
  130132. SQLITE_PRIVATE void sqlite3Fts3SimpleTokenizerModule(
  130133. sqlite3_tokenizer_module const**ppModule
  130134. ){
  130135. *ppModule = &simpleTokenizerModule;
  130136. }
  130137. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  130138. /************** End of fts3_tokenizer1.c *************************************/
  130139. /************** Begin file fts3_tokenize_vtab.c ******************************/
  130140. /*
  130141. ** 2013 Apr 22
  130142. **
  130143. ** The author disclaims copyright to this source code. In place of
  130144. ** a legal notice, here is a blessing:
  130145. **
  130146. ** May you do good and not evil.
  130147. ** May you find forgiveness for yourself and forgive others.
  130148. ** May you share freely, never taking more than you give.
  130149. **
  130150. ******************************************************************************
  130151. **
  130152. ** This file contains code for the "fts3tokenize" virtual table module.
  130153. ** An fts3tokenize virtual table is created as follows:
  130154. **
  130155. ** CREATE VIRTUAL TABLE <tbl> USING fts3tokenize(
  130156. ** <tokenizer-name>, <arg-1>, ...
  130157. ** );
  130158. **
  130159. ** The table created has the following schema:
  130160. **
  130161. ** CREATE TABLE <tbl>(input, token, start, end, position)
  130162. **
  130163. ** When queried, the query must include a WHERE clause of type:
  130164. **
  130165. ** input = <string>
  130166. **
  130167. ** The virtual table module tokenizes this <string>, using the FTS3
  130168. ** tokenizer specified by the arguments to the CREATE VIRTUAL TABLE
  130169. ** statement and returns one row for each token in the result. With
  130170. ** fields set as follows:
  130171. **
  130172. ** input: Always set to a copy of <string>
  130173. ** token: A token from the input.
  130174. ** start: Byte offset of the token within the input <string>.
  130175. ** end: Byte offset of the byte immediately following the end of the
  130176. ** token within the input string.
  130177. ** pos: Token offset of token within input.
  130178. **
  130179. */
  130180. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130181. /* #include <string.h> */
  130182. /* #include <assert.h> */
  130183. typedef struct Fts3tokTable Fts3tokTable;
  130184. typedef struct Fts3tokCursor Fts3tokCursor;
  130185. /*
  130186. ** Virtual table structure.
  130187. */
  130188. struct Fts3tokTable {
  130189. sqlite3_vtab base; /* Base class used by SQLite core */
  130190. const sqlite3_tokenizer_module *pMod;
  130191. sqlite3_tokenizer *pTok;
  130192. };
  130193. /*
  130194. ** Virtual table cursor structure.
  130195. */
  130196. struct Fts3tokCursor {
  130197. sqlite3_vtab_cursor base; /* Base class used by SQLite core */
  130198. char *zInput; /* Input string */
  130199. sqlite3_tokenizer_cursor *pCsr; /* Cursor to iterate through zInput */
  130200. int iRowid; /* Current 'rowid' value */
  130201. const char *zToken; /* Current 'token' value */
  130202. int nToken; /* Size of zToken in bytes */
  130203. int iStart; /* Current 'start' value */
  130204. int iEnd; /* Current 'end' value */
  130205. int iPos; /* Current 'pos' value */
  130206. };
  130207. /*
  130208. ** Query FTS for the tokenizer implementation named zName.
  130209. */
  130210. static int fts3tokQueryTokenizer(
  130211. Fts3Hash *pHash,
  130212. const char *zName,
  130213. const sqlite3_tokenizer_module **pp,
  130214. char **pzErr
  130215. ){
  130216. sqlite3_tokenizer_module *p;
  130217. int nName = (int)strlen(zName);
  130218. p = (sqlite3_tokenizer_module *)sqlite3Fts3HashFind(pHash, zName, nName+1);
  130219. if( !p ){
  130220. *pzErr = sqlite3_mprintf("unknown tokenizer: %s", zName);
  130221. return SQLITE_ERROR;
  130222. }
  130223. *pp = p;
  130224. return SQLITE_OK;
  130225. }
  130226. /*
  130227. ** The second argument, argv[], is an array of pointers to nul-terminated
  130228. ** strings. This function makes a copy of the array and strings into a
  130229. ** single block of memory. It then dequotes any of the strings that appear
  130230. ** to be quoted.
  130231. **
  130232. ** If successful, output parameter *pazDequote is set to point at the
  130233. ** array of dequoted strings and SQLITE_OK is returned. The caller is
  130234. ** responsible for eventually calling sqlite3_free() to free the array
  130235. ** in this case. Or, if an error occurs, an SQLite error code is returned.
  130236. ** The final value of *pazDequote is undefined in this case.
  130237. */
  130238. static int fts3tokDequoteArray(
  130239. int argc, /* Number of elements in argv[] */
  130240. const char * const *argv, /* Input array */
  130241. char ***pazDequote /* Output array */
  130242. ){
  130243. int rc = SQLITE_OK; /* Return code */
  130244. if( argc==0 ){
  130245. *pazDequote = 0;
  130246. }else{
  130247. int i;
  130248. int nByte = 0;
  130249. char **azDequote;
  130250. for(i=0; i<argc; i++){
  130251. nByte += (int)(strlen(argv[i]) + 1);
  130252. }
  130253. *pazDequote = azDequote = sqlite3_malloc(sizeof(char *)*argc + nByte);
  130254. if( azDequote==0 ){
  130255. rc = SQLITE_NOMEM;
  130256. }else{
  130257. char *pSpace = (char *)&azDequote[argc];
  130258. for(i=0; i<argc; i++){
  130259. int n = (int)strlen(argv[i]);
  130260. azDequote[i] = pSpace;
  130261. memcpy(pSpace, argv[i], n+1);
  130262. sqlite3Fts3Dequote(pSpace);
  130263. pSpace += (n+1);
  130264. }
  130265. }
  130266. }
  130267. return rc;
  130268. }
  130269. /*
  130270. ** Schema of the tokenizer table.
  130271. */
  130272. #define FTS3_TOK_SCHEMA "CREATE TABLE x(input, token, start, end, position)"
  130273. /*
  130274. ** This function does all the work for both the xConnect and xCreate methods.
  130275. ** These tables have no persistent representation of their own, so xConnect
  130276. ** and xCreate are identical operations.
  130277. **
  130278. ** argv[0]: module name
  130279. ** argv[1]: database name
  130280. ** argv[2]: table name
  130281. ** argv[3]: first argument (tokenizer name)
  130282. */
  130283. static int fts3tokConnectMethod(
  130284. sqlite3 *db, /* Database connection */
  130285. void *pHash, /* Hash table of tokenizers */
  130286. int argc, /* Number of elements in argv array */
  130287. const char * const *argv, /* xCreate/xConnect argument array */
  130288. sqlite3_vtab **ppVtab, /* OUT: New sqlite3_vtab object */
  130289. char **pzErr /* OUT: sqlite3_malloc'd error message */
  130290. ){
  130291. Fts3tokTable *pTab;
  130292. const sqlite3_tokenizer_module *pMod = 0;
  130293. sqlite3_tokenizer *pTok = 0;
  130294. int rc;
  130295. char **azDequote = 0;
  130296. int nDequote;
  130297. rc = sqlite3_declare_vtab(db, FTS3_TOK_SCHEMA);
  130298. if( rc!=SQLITE_OK ) return rc;
  130299. nDequote = argc-3;
  130300. rc = fts3tokDequoteArray(nDequote, &argv[3], &azDequote);
  130301. if( rc==SQLITE_OK ){
  130302. const char *zModule;
  130303. if( nDequote<1 ){
  130304. zModule = "simple";
  130305. }else{
  130306. zModule = azDequote[0];
  130307. }
  130308. rc = fts3tokQueryTokenizer((Fts3Hash*)pHash, zModule, &pMod, pzErr);
  130309. }
  130310. assert( (rc==SQLITE_OK)==(pMod!=0) );
  130311. if( rc==SQLITE_OK ){
  130312. const char * const *azArg = (const char * const *)&azDequote[1];
  130313. rc = pMod->xCreate((nDequote>1 ? nDequote-1 : 0), azArg, &pTok);
  130314. }
  130315. if( rc==SQLITE_OK ){
  130316. pTab = (Fts3tokTable *)sqlite3_malloc(sizeof(Fts3tokTable));
  130317. if( pTab==0 ){
  130318. rc = SQLITE_NOMEM;
  130319. }
  130320. }
  130321. if( rc==SQLITE_OK ){
  130322. memset(pTab, 0, sizeof(Fts3tokTable));
  130323. pTab->pMod = pMod;
  130324. pTab->pTok = pTok;
  130325. *ppVtab = &pTab->base;
  130326. }else{
  130327. if( pTok ){
  130328. pMod->xDestroy(pTok);
  130329. }
  130330. }
  130331. sqlite3_free(azDequote);
  130332. return rc;
  130333. }
  130334. /*
  130335. ** This function does the work for both the xDisconnect and xDestroy methods.
  130336. ** These tables have no persistent representation of their own, so xDisconnect
  130337. ** and xDestroy are identical operations.
  130338. */
  130339. static int fts3tokDisconnectMethod(sqlite3_vtab *pVtab){
  130340. Fts3tokTable *pTab = (Fts3tokTable *)pVtab;
  130341. pTab->pMod->xDestroy(pTab->pTok);
  130342. sqlite3_free(pTab);
  130343. return SQLITE_OK;
  130344. }
  130345. /*
  130346. ** xBestIndex - Analyze a WHERE and ORDER BY clause.
  130347. */
  130348. static int fts3tokBestIndexMethod(
  130349. sqlite3_vtab *pVTab,
  130350. sqlite3_index_info *pInfo
  130351. ){
  130352. int i;
  130353. UNUSED_PARAMETER(pVTab);
  130354. for(i=0; i<pInfo->nConstraint; i++){
  130355. if( pInfo->aConstraint[i].usable
  130356. && pInfo->aConstraint[i].iColumn==0
  130357. && pInfo->aConstraint[i].op==SQLITE_INDEX_CONSTRAINT_EQ
  130358. ){
  130359. pInfo->idxNum = 1;
  130360. pInfo->aConstraintUsage[i].argvIndex = 1;
  130361. pInfo->aConstraintUsage[i].omit = 1;
  130362. pInfo->estimatedCost = 1;
  130363. return SQLITE_OK;
  130364. }
  130365. }
  130366. pInfo->idxNum = 0;
  130367. assert( pInfo->estimatedCost>1000000.0 );
  130368. return SQLITE_OK;
  130369. }
  130370. /*
  130371. ** xOpen - Open a cursor.
  130372. */
  130373. static int fts3tokOpenMethod(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCsr){
  130374. Fts3tokCursor *pCsr;
  130375. UNUSED_PARAMETER(pVTab);
  130376. pCsr = (Fts3tokCursor *)sqlite3_malloc(sizeof(Fts3tokCursor));
  130377. if( pCsr==0 ){
  130378. return SQLITE_NOMEM;
  130379. }
  130380. memset(pCsr, 0, sizeof(Fts3tokCursor));
  130381. *ppCsr = (sqlite3_vtab_cursor *)pCsr;
  130382. return SQLITE_OK;
  130383. }
  130384. /*
  130385. ** Reset the tokenizer cursor passed as the only argument. As if it had
  130386. ** just been returned by fts3tokOpenMethod().
  130387. */
  130388. static void fts3tokResetCursor(Fts3tokCursor *pCsr){
  130389. if( pCsr->pCsr ){
  130390. Fts3tokTable *pTab = (Fts3tokTable *)(pCsr->base.pVtab);
  130391. pTab->pMod->xClose(pCsr->pCsr);
  130392. pCsr->pCsr = 0;
  130393. }
  130394. sqlite3_free(pCsr->zInput);
  130395. pCsr->zInput = 0;
  130396. pCsr->zToken = 0;
  130397. pCsr->nToken = 0;
  130398. pCsr->iStart = 0;
  130399. pCsr->iEnd = 0;
  130400. pCsr->iPos = 0;
  130401. pCsr->iRowid = 0;
  130402. }
  130403. /*
  130404. ** xClose - Close a cursor.
  130405. */
  130406. static int fts3tokCloseMethod(sqlite3_vtab_cursor *pCursor){
  130407. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130408. fts3tokResetCursor(pCsr);
  130409. sqlite3_free(pCsr);
  130410. return SQLITE_OK;
  130411. }
  130412. /*
  130413. ** xNext - Advance the cursor to the next row, if any.
  130414. */
  130415. static int fts3tokNextMethod(sqlite3_vtab_cursor *pCursor){
  130416. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130417. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  130418. int rc; /* Return code */
  130419. pCsr->iRowid++;
  130420. rc = pTab->pMod->xNext(pCsr->pCsr,
  130421. &pCsr->zToken, &pCsr->nToken,
  130422. &pCsr->iStart, &pCsr->iEnd, &pCsr->iPos
  130423. );
  130424. if( rc!=SQLITE_OK ){
  130425. fts3tokResetCursor(pCsr);
  130426. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  130427. }
  130428. return rc;
  130429. }
  130430. /*
  130431. ** xFilter - Initialize a cursor to point at the start of its data.
  130432. */
  130433. static int fts3tokFilterMethod(
  130434. sqlite3_vtab_cursor *pCursor, /* The cursor used for this query */
  130435. int idxNum, /* Strategy index */
  130436. const char *idxStr, /* Unused */
  130437. int nVal, /* Number of elements in apVal */
  130438. sqlite3_value **apVal /* Arguments for the indexing scheme */
  130439. ){
  130440. int rc = SQLITE_ERROR;
  130441. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130442. Fts3tokTable *pTab = (Fts3tokTable *)(pCursor->pVtab);
  130443. UNUSED_PARAMETER(idxStr);
  130444. UNUSED_PARAMETER(nVal);
  130445. fts3tokResetCursor(pCsr);
  130446. if( idxNum==1 ){
  130447. const char *zByte = (const char *)sqlite3_value_text(apVal[0]);
  130448. int nByte = sqlite3_value_bytes(apVal[0]);
  130449. pCsr->zInput = sqlite3_malloc(nByte+1);
  130450. if( pCsr->zInput==0 ){
  130451. rc = SQLITE_NOMEM;
  130452. }else{
  130453. memcpy(pCsr->zInput, zByte, nByte);
  130454. pCsr->zInput[nByte] = 0;
  130455. rc = pTab->pMod->xOpen(pTab->pTok, pCsr->zInput, nByte, &pCsr->pCsr);
  130456. if( rc==SQLITE_OK ){
  130457. pCsr->pCsr->pTokenizer = pTab->pTok;
  130458. }
  130459. }
  130460. }
  130461. if( rc!=SQLITE_OK ) return rc;
  130462. return fts3tokNextMethod(pCursor);
  130463. }
  130464. /*
  130465. ** xEof - Return true if the cursor is at EOF, or false otherwise.
  130466. */
  130467. static int fts3tokEofMethod(sqlite3_vtab_cursor *pCursor){
  130468. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130469. return (pCsr->zToken==0);
  130470. }
  130471. /*
  130472. ** xColumn - Return a column value.
  130473. */
  130474. static int fts3tokColumnMethod(
  130475. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  130476. sqlite3_context *pCtx, /* Context for sqlite3_result_xxx() calls */
  130477. int iCol /* Index of column to read value from */
  130478. ){
  130479. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130480. /* CREATE TABLE x(input, token, start, end, position) */
  130481. switch( iCol ){
  130482. case 0:
  130483. sqlite3_result_text(pCtx, pCsr->zInput, -1, SQLITE_TRANSIENT);
  130484. break;
  130485. case 1:
  130486. sqlite3_result_text(pCtx, pCsr->zToken, pCsr->nToken, SQLITE_TRANSIENT);
  130487. break;
  130488. case 2:
  130489. sqlite3_result_int(pCtx, pCsr->iStart);
  130490. break;
  130491. case 3:
  130492. sqlite3_result_int(pCtx, pCsr->iEnd);
  130493. break;
  130494. default:
  130495. assert( iCol==4 );
  130496. sqlite3_result_int(pCtx, pCsr->iPos);
  130497. break;
  130498. }
  130499. return SQLITE_OK;
  130500. }
  130501. /*
  130502. ** xRowid - Return the current rowid for the cursor.
  130503. */
  130504. static int fts3tokRowidMethod(
  130505. sqlite3_vtab_cursor *pCursor, /* Cursor to retrieve value from */
  130506. sqlite_int64 *pRowid /* OUT: Rowid value */
  130507. ){
  130508. Fts3tokCursor *pCsr = (Fts3tokCursor *)pCursor;
  130509. *pRowid = (sqlite3_int64)pCsr->iRowid;
  130510. return SQLITE_OK;
  130511. }
  130512. /*
  130513. ** Register the fts3tok module with database connection db. Return SQLITE_OK
  130514. ** if successful or an error code if sqlite3_create_module() fails.
  130515. */
  130516. SQLITE_PRIVATE int sqlite3Fts3InitTok(sqlite3 *db, Fts3Hash *pHash){
  130517. static const sqlite3_module fts3tok_module = {
  130518. 0, /* iVersion */
  130519. fts3tokConnectMethod, /* xCreate */
  130520. fts3tokConnectMethod, /* xConnect */
  130521. fts3tokBestIndexMethod, /* xBestIndex */
  130522. fts3tokDisconnectMethod, /* xDisconnect */
  130523. fts3tokDisconnectMethod, /* xDestroy */
  130524. fts3tokOpenMethod, /* xOpen */
  130525. fts3tokCloseMethod, /* xClose */
  130526. fts3tokFilterMethod, /* xFilter */
  130527. fts3tokNextMethod, /* xNext */
  130528. fts3tokEofMethod, /* xEof */
  130529. fts3tokColumnMethod, /* xColumn */
  130530. fts3tokRowidMethod, /* xRowid */
  130531. 0, /* xUpdate */
  130532. 0, /* xBegin */
  130533. 0, /* xSync */
  130534. 0, /* xCommit */
  130535. 0, /* xRollback */
  130536. 0, /* xFindFunction */
  130537. 0, /* xRename */
  130538. 0, /* xSavepoint */
  130539. 0, /* xRelease */
  130540. 0 /* xRollbackTo */
  130541. };
  130542. int rc; /* Return code */
  130543. rc = sqlite3_create_module(db, "fts3tokenize", &fts3tok_module, (void*)pHash);
  130544. return rc;
  130545. }
  130546. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  130547. /************** End of fts3_tokenize_vtab.c **********************************/
  130548. /************** Begin file fts3_write.c **************************************/
  130549. /*
  130550. ** 2009 Oct 23
  130551. **
  130552. ** The author disclaims copyright to this source code. In place of
  130553. ** a legal notice, here is a blessing:
  130554. **
  130555. ** May you do good and not evil.
  130556. ** May you find forgiveness for yourself and forgive others.
  130557. ** May you share freely, never taking more than you give.
  130558. **
  130559. ******************************************************************************
  130560. **
  130561. ** This file is part of the SQLite FTS3 extension module. Specifically,
  130562. ** this file contains code to insert, update and delete rows from FTS3
  130563. ** tables. It also contains code to merge FTS3 b-tree segments. Some
  130564. ** of the sub-routines used to merge segments are also used by the query
  130565. ** code in fts3.c.
  130566. */
  130567. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  130568. /* #include <string.h> */
  130569. /* #include <assert.h> */
  130570. /* #include <stdlib.h> */
  130571. #define FTS_MAX_APPENDABLE_HEIGHT 16
  130572. /*
  130573. ** When full-text index nodes are loaded from disk, the buffer that they
  130574. ** are loaded into has the following number of bytes of padding at the end
  130575. ** of it. i.e. if a full-text index node is 900 bytes in size, then a buffer
  130576. ** of 920 bytes is allocated for it.
  130577. **
  130578. ** This means that if we have a pointer into a buffer containing node data,
  130579. ** it is always safe to read up to two varints from it without risking an
  130580. ** overread, even if the node data is corrupted.
  130581. */
  130582. #define FTS3_NODE_PADDING (FTS3_VARINT_MAX*2)
  130583. /*
  130584. ** Under certain circumstances, b-tree nodes (doclists) can be loaded into
  130585. ** memory incrementally instead of all at once. This can be a big performance
  130586. ** win (reduced IO and CPU) if SQLite stops calling the virtual table xNext()
  130587. ** method before retrieving all query results (as may happen, for example,
  130588. ** if a query has a LIMIT clause).
  130589. **
  130590. ** Incremental loading is used for b-tree nodes FTS3_NODE_CHUNK_THRESHOLD
  130591. ** bytes and larger. Nodes are loaded in chunks of FTS3_NODE_CHUNKSIZE bytes.
  130592. ** The code is written so that the hard lower-limit for each of these values
  130593. ** is 1. Clearly such small values would be inefficient, but can be useful
  130594. ** for testing purposes.
  130595. **
  130596. ** If this module is built with SQLITE_TEST defined, these constants may
  130597. ** be overridden at runtime for testing purposes. File fts3_test.c contains
  130598. ** a Tcl interface to read and write the values.
  130599. */
  130600. #ifdef SQLITE_TEST
  130601. int test_fts3_node_chunksize = (4*1024);
  130602. int test_fts3_node_chunk_threshold = (4*1024)*4;
  130603. # define FTS3_NODE_CHUNKSIZE test_fts3_node_chunksize
  130604. # define FTS3_NODE_CHUNK_THRESHOLD test_fts3_node_chunk_threshold
  130605. #else
  130606. # define FTS3_NODE_CHUNKSIZE (4*1024)
  130607. # define FTS3_NODE_CHUNK_THRESHOLD (FTS3_NODE_CHUNKSIZE*4)
  130608. #endif
  130609. /*
  130610. ** The two values that may be meaningfully bound to the :1 parameter in
  130611. ** statements SQL_REPLACE_STAT and SQL_SELECT_STAT.
  130612. */
  130613. #define FTS_STAT_DOCTOTAL 0
  130614. #define FTS_STAT_INCRMERGEHINT 1
  130615. #define FTS_STAT_AUTOINCRMERGE 2
  130616. /*
  130617. ** If FTS_LOG_MERGES is defined, call sqlite3_log() to report each automatic
  130618. ** and incremental merge operation that takes place. This is used for
  130619. ** debugging FTS only, it should not usually be turned on in production
  130620. ** systems.
  130621. */
  130622. #ifdef FTS3_LOG_MERGES
  130623. static void fts3LogMerge(int nMerge, sqlite3_int64 iAbsLevel){
  130624. sqlite3_log(SQLITE_OK, "%d-way merge from level %d", nMerge, (int)iAbsLevel);
  130625. }
  130626. #else
  130627. #define fts3LogMerge(x, y)
  130628. #endif
  130629. typedef struct PendingList PendingList;
  130630. typedef struct SegmentNode SegmentNode;
  130631. typedef struct SegmentWriter SegmentWriter;
  130632. /*
  130633. ** An instance of the following data structure is used to build doclists
  130634. ** incrementally. See function fts3PendingListAppend() for details.
  130635. */
  130636. struct PendingList {
  130637. int nData;
  130638. char *aData;
  130639. int nSpace;
  130640. sqlite3_int64 iLastDocid;
  130641. sqlite3_int64 iLastCol;
  130642. sqlite3_int64 iLastPos;
  130643. };
  130644. /*
  130645. ** Each cursor has a (possibly empty) linked list of the following objects.
  130646. */
  130647. struct Fts3DeferredToken {
  130648. Fts3PhraseToken *pToken; /* Pointer to corresponding expr token */
  130649. int iCol; /* Column token must occur in */
  130650. Fts3DeferredToken *pNext; /* Next in list of deferred tokens */
  130651. PendingList *pList; /* Doclist is assembled here */
  130652. };
  130653. /*
  130654. ** An instance of this structure is used to iterate through the terms on
  130655. ** a contiguous set of segment b-tree leaf nodes. Although the details of
  130656. ** this structure are only manipulated by code in this file, opaque handles
  130657. ** of type Fts3SegReader* are also used by code in fts3.c to iterate through
  130658. ** terms when querying the full-text index. See functions:
  130659. **
  130660. ** sqlite3Fts3SegReaderNew()
  130661. ** sqlite3Fts3SegReaderFree()
  130662. ** sqlite3Fts3SegReaderIterate()
  130663. **
  130664. ** Methods used to manipulate Fts3SegReader structures:
  130665. **
  130666. ** fts3SegReaderNext()
  130667. ** fts3SegReaderFirstDocid()
  130668. ** fts3SegReaderNextDocid()
  130669. */
  130670. struct Fts3SegReader {
  130671. int iIdx; /* Index within level, or 0x7FFFFFFF for PT */
  130672. u8 bLookup; /* True for a lookup only */
  130673. u8 rootOnly; /* True for a root-only reader */
  130674. sqlite3_int64 iStartBlock; /* Rowid of first leaf block to traverse */
  130675. sqlite3_int64 iLeafEndBlock; /* Rowid of final leaf block to traverse */
  130676. sqlite3_int64 iEndBlock; /* Rowid of final block in segment (or 0) */
  130677. sqlite3_int64 iCurrentBlock; /* Current leaf block (or 0) */
  130678. char *aNode; /* Pointer to node data (or NULL) */
  130679. int nNode; /* Size of buffer at aNode (or 0) */
  130680. int nPopulate; /* If >0, bytes of buffer aNode[] loaded */
  130681. sqlite3_blob *pBlob; /* If not NULL, blob handle to read node */
  130682. Fts3HashElem **ppNextElem;
  130683. /* Variables set by fts3SegReaderNext(). These may be read directly
  130684. ** by the caller. They are valid from the time SegmentReaderNew() returns
  130685. ** until SegmentReaderNext() returns something other than SQLITE_OK
  130686. ** (i.e. SQLITE_DONE).
  130687. */
  130688. int nTerm; /* Number of bytes in current term */
  130689. char *zTerm; /* Pointer to current term */
  130690. int nTermAlloc; /* Allocated size of zTerm buffer */
  130691. char *aDoclist; /* Pointer to doclist of current entry */
  130692. int nDoclist; /* Size of doclist in current entry */
  130693. /* The following variables are used by fts3SegReaderNextDocid() to iterate
  130694. ** through the current doclist (aDoclist/nDoclist).
  130695. */
  130696. char *pOffsetList;
  130697. int nOffsetList; /* For descending pending seg-readers only */
  130698. sqlite3_int64 iDocid;
  130699. };
  130700. #define fts3SegReaderIsPending(p) ((p)->ppNextElem!=0)
  130701. #define fts3SegReaderIsRootOnly(p) ((p)->rootOnly!=0)
  130702. /*
  130703. ** An instance of this structure is used to create a segment b-tree in the
  130704. ** database. The internal details of this type are only accessed by the
  130705. ** following functions:
  130706. **
  130707. ** fts3SegWriterAdd()
  130708. ** fts3SegWriterFlush()
  130709. ** fts3SegWriterFree()
  130710. */
  130711. struct SegmentWriter {
  130712. SegmentNode *pTree; /* Pointer to interior tree structure */
  130713. sqlite3_int64 iFirst; /* First slot in %_segments written */
  130714. sqlite3_int64 iFree; /* Next free slot in %_segments */
  130715. char *zTerm; /* Pointer to previous term buffer */
  130716. int nTerm; /* Number of bytes in zTerm */
  130717. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  130718. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  130719. int nSize; /* Size of allocation at aData */
  130720. int nData; /* Bytes of data in aData */
  130721. char *aData; /* Pointer to block from malloc() */
  130722. i64 nLeafData; /* Number of bytes of leaf data written */
  130723. };
  130724. /*
  130725. ** Type SegmentNode is used by the following three functions to create
  130726. ** the interior part of the segment b+-tree structures (everything except
  130727. ** the leaf nodes). These functions and type are only ever used by code
  130728. ** within the fts3SegWriterXXX() family of functions described above.
  130729. **
  130730. ** fts3NodeAddTerm()
  130731. ** fts3NodeWrite()
  130732. ** fts3NodeFree()
  130733. **
  130734. ** When a b+tree is written to the database (either as a result of a merge
  130735. ** or the pending-terms table being flushed), leaves are written into the
  130736. ** database file as soon as they are completely populated. The interior of
  130737. ** the tree is assembled in memory and written out only once all leaves have
  130738. ** been populated and stored. This is Ok, as the b+-tree fanout is usually
  130739. ** very large, meaning that the interior of the tree consumes relatively
  130740. ** little memory.
  130741. */
  130742. struct SegmentNode {
  130743. SegmentNode *pParent; /* Parent node (or NULL for root node) */
  130744. SegmentNode *pRight; /* Pointer to right-sibling */
  130745. SegmentNode *pLeftmost; /* Pointer to left-most node of this depth */
  130746. int nEntry; /* Number of terms written to node so far */
  130747. char *zTerm; /* Pointer to previous term buffer */
  130748. int nTerm; /* Number of bytes in zTerm */
  130749. int nMalloc; /* Size of malloc'd buffer at zMalloc */
  130750. char *zMalloc; /* Malloc'd space (possibly) used for zTerm */
  130751. int nData; /* Bytes of valid data so far */
  130752. char *aData; /* Node data */
  130753. };
  130754. /*
  130755. ** Valid values for the second argument to fts3SqlStmt().
  130756. */
  130757. #define SQL_DELETE_CONTENT 0
  130758. #define SQL_IS_EMPTY 1
  130759. #define SQL_DELETE_ALL_CONTENT 2
  130760. #define SQL_DELETE_ALL_SEGMENTS 3
  130761. #define SQL_DELETE_ALL_SEGDIR 4
  130762. #define SQL_DELETE_ALL_DOCSIZE 5
  130763. #define SQL_DELETE_ALL_STAT 6
  130764. #define SQL_SELECT_CONTENT_BY_ROWID 7
  130765. #define SQL_NEXT_SEGMENT_INDEX 8
  130766. #define SQL_INSERT_SEGMENTS 9
  130767. #define SQL_NEXT_SEGMENTS_ID 10
  130768. #define SQL_INSERT_SEGDIR 11
  130769. #define SQL_SELECT_LEVEL 12
  130770. #define SQL_SELECT_LEVEL_RANGE 13
  130771. #define SQL_SELECT_LEVEL_COUNT 14
  130772. #define SQL_SELECT_SEGDIR_MAX_LEVEL 15
  130773. #define SQL_DELETE_SEGDIR_LEVEL 16
  130774. #define SQL_DELETE_SEGMENTS_RANGE 17
  130775. #define SQL_CONTENT_INSERT 18
  130776. #define SQL_DELETE_DOCSIZE 19
  130777. #define SQL_REPLACE_DOCSIZE 20
  130778. #define SQL_SELECT_DOCSIZE 21
  130779. #define SQL_SELECT_STAT 22
  130780. #define SQL_REPLACE_STAT 23
  130781. #define SQL_SELECT_ALL_PREFIX_LEVEL 24
  130782. #define SQL_DELETE_ALL_TERMS_SEGDIR 25
  130783. #define SQL_DELETE_SEGDIR_RANGE 26
  130784. #define SQL_SELECT_ALL_LANGID 27
  130785. #define SQL_FIND_MERGE_LEVEL 28
  130786. #define SQL_MAX_LEAF_NODE_ESTIMATE 29
  130787. #define SQL_DELETE_SEGDIR_ENTRY 30
  130788. #define SQL_SHIFT_SEGDIR_ENTRY 31
  130789. #define SQL_SELECT_SEGDIR 32
  130790. #define SQL_CHOMP_SEGDIR 33
  130791. #define SQL_SEGMENT_IS_APPENDABLE 34
  130792. #define SQL_SELECT_INDEXES 35
  130793. #define SQL_SELECT_MXLEVEL 36
  130794. #define SQL_SELECT_LEVEL_RANGE2 37
  130795. #define SQL_UPDATE_LEVEL_IDX 38
  130796. #define SQL_UPDATE_LEVEL 39
  130797. /*
  130798. ** This function is used to obtain an SQLite prepared statement handle
  130799. ** for the statement identified by the second argument. If successful,
  130800. ** *pp is set to the requested statement handle and SQLITE_OK returned.
  130801. ** Otherwise, an SQLite error code is returned and *pp is set to 0.
  130802. **
  130803. ** If argument apVal is not NULL, then it must point to an array with
  130804. ** at least as many entries as the requested statement has bound
  130805. ** parameters. The values are bound to the statements parameters before
  130806. ** returning.
  130807. */
  130808. static int fts3SqlStmt(
  130809. Fts3Table *p, /* Virtual table handle */
  130810. int eStmt, /* One of the SQL_XXX constants above */
  130811. sqlite3_stmt **pp, /* OUT: Statement handle */
  130812. sqlite3_value **apVal /* Values to bind to statement */
  130813. ){
  130814. const char *azSql[] = {
  130815. /* 0 */ "DELETE FROM %Q.'%q_content' WHERE rowid = ?",
  130816. /* 1 */ "SELECT NOT EXISTS(SELECT docid FROM %Q.'%q_content' WHERE rowid!=?)",
  130817. /* 2 */ "DELETE FROM %Q.'%q_content'",
  130818. /* 3 */ "DELETE FROM %Q.'%q_segments'",
  130819. /* 4 */ "DELETE FROM %Q.'%q_segdir'",
  130820. /* 5 */ "DELETE FROM %Q.'%q_docsize'",
  130821. /* 6 */ "DELETE FROM %Q.'%q_stat'",
  130822. /* 7 */ "SELECT %s WHERE rowid=?",
  130823. /* 8 */ "SELECT (SELECT max(idx) FROM %Q.'%q_segdir' WHERE level = ?) + 1",
  130824. /* 9 */ "REPLACE INTO %Q.'%q_segments'(blockid, block) VALUES(?, ?)",
  130825. /* 10 */ "SELECT coalesce((SELECT max(blockid) FROM %Q.'%q_segments') + 1, 1)",
  130826. /* 11 */ "REPLACE INTO %Q.'%q_segdir' VALUES(?,?,?,?,?,?)",
  130827. /* Return segments in order from oldest to newest.*/
  130828. /* 12 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  130829. "FROM %Q.'%q_segdir' WHERE level = ? ORDER BY idx ASC",
  130830. /* 13 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  130831. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?"
  130832. "ORDER BY level DESC, idx ASC",
  130833. /* 14 */ "SELECT count(*) FROM %Q.'%q_segdir' WHERE level = ?",
  130834. /* 15 */ "SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  130835. /* 16 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ?",
  130836. /* 17 */ "DELETE FROM %Q.'%q_segments' WHERE blockid BETWEEN ? AND ?",
  130837. /* 18 */ "INSERT INTO %Q.'%q_content' VALUES(%s)",
  130838. /* 19 */ "DELETE FROM %Q.'%q_docsize' WHERE docid = ?",
  130839. /* 20 */ "REPLACE INTO %Q.'%q_docsize' VALUES(?,?)",
  130840. /* 21 */ "SELECT size FROM %Q.'%q_docsize' WHERE docid=?",
  130841. /* 22 */ "SELECT value FROM %Q.'%q_stat' WHERE id=?",
  130842. /* 23 */ "REPLACE INTO %Q.'%q_stat' VALUES(?,?)",
  130843. /* 24 */ "",
  130844. /* 25 */ "",
  130845. /* 26 */ "DELETE FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?",
  130846. /* 27 */ "SELECT DISTINCT level / (1024 * ?) FROM %Q.'%q_segdir'",
  130847. /* This statement is used to determine which level to read the input from
  130848. ** when performing an incremental merge. It returns the absolute level number
  130849. ** of the oldest level in the db that contains at least ? segments. Or,
  130850. ** if no level in the FTS index contains more than ? segments, the statement
  130851. ** returns zero rows. */
  130852. /* 28 */ "SELECT level FROM %Q.'%q_segdir' GROUP BY level HAVING count(*)>=?"
  130853. " ORDER BY (level %% 1024) ASC LIMIT 1",
  130854. /* Estimate the upper limit on the number of leaf nodes in a new segment
  130855. ** created by merging the oldest :2 segments from absolute level :1. See
  130856. ** function sqlite3Fts3Incrmerge() for details. */
  130857. /* 29 */ "SELECT 2 * total(1 + leaves_end_block - start_block) "
  130858. " FROM %Q.'%q_segdir' WHERE level = ? AND idx < ?",
  130859. /* SQL_DELETE_SEGDIR_ENTRY
  130860. ** Delete the %_segdir entry on absolute level :1 with index :2. */
  130861. /* 30 */ "DELETE FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  130862. /* SQL_SHIFT_SEGDIR_ENTRY
  130863. ** Modify the idx value for the segment with idx=:3 on absolute level :2
  130864. ** to :1. */
  130865. /* 31 */ "UPDATE %Q.'%q_segdir' SET idx = ? WHERE level=? AND idx=?",
  130866. /* SQL_SELECT_SEGDIR
  130867. ** Read a single entry from the %_segdir table. The entry from absolute
  130868. ** level :1 with index value :2. */
  130869. /* 32 */ "SELECT idx, start_block, leaves_end_block, end_block, root "
  130870. "FROM %Q.'%q_segdir' WHERE level = ? AND idx = ?",
  130871. /* SQL_CHOMP_SEGDIR
  130872. ** Update the start_block (:1) and root (:2) fields of the %_segdir
  130873. ** entry located on absolute level :3 with index :4. */
  130874. /* 33 */ "UPDATE %Q.'%q_segdir' SET start_block = ?, root = ?"
  130875. "WHERE level = ? AND idx = ?",
  130876. /* SQL_SEGMENT_IS_APPENDABLE
  130877. ** Return a single row if the segment with end_block=? is appendable. Or
  130878. ** no rows otherwise. */
  130879. /* 34 */ "SELECT 1 FROM %Q.'%q_segments' WHERE blockid=? AND block IS NULL",
  130880. /* SQL_SELECT_INDEXES
  130881. ** Return the list of valid segment indexes for absolute level ? */
  130882. /* 35 */ "SELECT idx FROM %Q.'%q_segdir' WHERE level=? ORDER BY 1 ASC",
  130883. /* SQL_SELECT_MXLEVEL
  130884. ** Return the largest relative level in the FTS index or indexes. */
  130885. /* 36 */ "SELECT max( level %% 1024 ) FROM %Q.'%q_segdir'",
  130886. /* Return segments in order from oldest to newest.*/
  130887. /* 37 */ "SELECT level, idx, end_block "
  130888. "FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ? "
  130889. "ORDER BY level DESC, idx ASC",
  130890. /* Update statements used while promoting segments */
  130891. /* 38 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=-1,idx=? "
  130892. "WHERE level=? AND idx=?",
  130893. /* 39 */ "UPDATE OR FAIL %Q.'%q_segdir' SET level=? WHERE level=-1"
  130894. };
  130895. int rc = SQLITE_OK;
  130896. sqlite3_stmt *pStmt;
  130897. assert( SizeofArray(azSql)==SizeofArray(p->aStmt) );
  130898. assert( eStmt<SizeofArray(azSql) && eStmt>=0 );
  130899. pStmt = p->aStmt[eStmt];
  130900. if( !pStmt ){
  130901. char *zSql;
  130902. if( eStmt==SQL_CONTENT_INSERT ){
  130903. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName, p->zWriteExprlist);
  130904. }else if( eStmt==SQL_SELECT_CONTENT_BY_ROWID ){
  130905. zSql = sqlite3_mprintf(azSql[eStmt], p->zReadExprlist);
  130906. }else{
  130907. zSql = sqlite3_mprintf(azSql[eStmt], p->zDb, p->zName);
  130908. }
  130909. if( !zSql ){
  130910. rc = SQLITE_NOMEM;
  130911. }else{
  130912. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, NULL);
  130913. sqlite3_free(zSql);
  130914. assert( rc==SQLITE_OK || pStmt==0 );
  130915. p->aStmt[eStmt] = pStmt;
  130916. }
  130917. }
  130918. if( apVal ){
  130919. int i;
  130920. int nParam = sqlite3_bind_parameter_count(pStmt);
  130921. for(i=0; rc==SQLITE_OK && i<nParam; i++){
  130922. rc = sqlite3_bind_value(pStmt, i+1, apVal[i]);
  130923. }
  130924. }
  130925. *pp = pStmt;
  130926. return rc;
  130927. }
  130928. static int fts3SelectDocsize(
  130929. Fts3Table *pTab, /* FTS3 table handle */
  130930. sqlite3_int64 iDocid, /* Docid to bind for SQL_SELECT_DOCSIZE */
  130931. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  130932. ){
  130933. sqlite3_stmt *pStmt = 0; /* Statement requested from fts3SqlStmt() */
  130934. int rc; /* Return code */
  130935. rc = fts3SqlStmt(pTab, SQL_SELECT_DOCSIZE, &pStmt, 0);
  130936. if( rc==SQLITE_OK ){
  130937. sqlite3_bind_int64(pStmt, 1, iDocid);
  130938. rc = sqlite3_step(pStmt);
  130939. if( rc!=SQLITE_ROW || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB ){
  130940. rc = sqlite3_reset(pStmt);
  130941. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  130942. pStmt = 0;
  130943. }else{
  130944. rc = SQLITE_OK;
  130945. }
  130946. }
  130947. *ppStmt = pStmt;
  130948. return rc;
  130949. }
  130950. SQLITE_PRIVATE int sqlite3Fts3SelectDoctotal(
  130951. Fts3Table *pTab, /* Fts3 table handle */
  130952. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  130953. ){
  130954. sqlite3_stmt *pStmt = 0;
  130955. int rc;
  130956. rc = fts3SqlStmt(pTab, SQL_SELECT_STAT, &pStmt, 0);
  130957. if( rc==SQLITE_OK ){
  130958. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  130959. if( sqlite3_step(pStmt)!=SQLITE_ROW
  130960. || sqlite3_column_type(pStmt, 0)!=SQLITE_BLOB
  130961. ){
  130962. rc = sqlite3_reset(pStmt);
  130963. if( rc==SQLITE_OK ) rc = FTS_CORRUPT_VTAB;
  130964. pStmt = 0;
  130965. }
  130966. }
  130967. *ppStmt = pStmt;
  130968. return rc;
  130969. }
  130970. SQLITE_PRIVATE int sqlite3Fts3SelectDocsize(
  130971. Fts3Table *pTab, /* Fts3 table handle */
  130972. sqlite3_int64 iDocid, /* Docid to read size data for */
  130973. sqlite3_stmt **ppStmt /* OUT: Statement handle */
  130974. ){
  130975. return fts3SelectDocsize(pTab, iDocid, ppStmt);
  130976. }
  130977. /*
  130978. ** Similar to fts3SqlStmt(). Except, after binding the parameters in
  130979. ** array apVal[] to the SQL statement identified by eStmt, the statement
  130980. ** is executed.
  130981. **
  130982. ** Returns SQLITE_OK if the statement is successfully executed, or an
  130983. ** SQLite error code otherwise.
  130984. */
  130985. static void fts3SqlExec(
  130986. int *pRC, /* Result code */
  130987. Fts3Table *p, /* The FTS3 table */
  130988. int eStmt, /* Index of statement to evaluate */
  130989. sqlite3_value **apVal /* Parameters to bind */
  130990. ){
  130991. sqlite3_stmt *pStmt;
  130992. int rc;
  130993. if( *pRC ) return;
  130994. rc = fts3SqlStmt(p, eStmt, &pStmt, apVal);
  130995. if( rc==SQLITE_OK ){
  130996. sqlite3_step(pStmt);
  130997. rc = sqlite3_reset(pStmt);
  130998. }
  130999. *pRC = rc;
  131000. }
  131001. /*
  131002. ** This function ensures that the caller has obtained an exclusive
  131003. ** shared-cache table-lock on the %_segdir table. This is required before
  131004. ** writing data to the fts3 table. If this lock is not acquired first, then
  131005. ** the caller may end up attempting to take this lock as part of committing
  131006. ** a transaction, causing SQLite to return SQLITE_LOCKED or
  131007. ** LOCKED_SHAREDCACHEto a COMMIT command.
  131008. **
  131009. ** It is best to avoid this because if FTS3 returns any error when
  131010. ** committing a transaction, the whole transaction will be rolled back.
  131011. ** And this is not what users expect when they get SQLITE_LOCKED_SHAREDCACHE.
  131012. ** It can still happen if the user locks the underlying tables directly
  131013. ** instead of accessing them via FTS.
  131014. */
  131015. static int fts3Writelock(Fts3Table *p){
  131016. int rc = SQLITE_OK;
  131017. if( p->nPendingData==0 ){
  131018. sqlite3_stmt *pStmt;
  131019. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pStmt, 0);
  131020. if( rc==SQLITE_OK ){
  131021. sqlite3_bind_null(pStmt, 1);
  131022. sqlite3_step(pStmt);
  131023. rc = sqlite3_reset(pStmt);
  131024. }
  131025. }
  131026. return rc;
  131027. }
  131028. /*
  131029. ** FTS maintains a separate indexes for each language-id (a 32-bit integer).
  131030. ** Within each language id, a separate index is maintained to store the
  131031. ** document terms, and each configured prefix size (configured the FTS
  131032. ** "prefix=" option). And each index consists of multiple levels ("relative
  131033. ** levels").
  131034. **
  131035. ** All three of these values (the language id, the specific index and the
  131036. ** level within the index) are encoded in 64-bit integer values stored
  131037. ** in the %_segdir table on disk. This function is used to convert three
  131038. ** separate component values into the single 64-bit integer value that
  131039. ** can be used to query the %_segdir table.
  131040. **
  131041. ** Specifically, each language-id/index combination is allocated 1024
  131042. ** 64-bit integer level values ("absolute levels"). The main terms index
  131043. ** for language-id 0 is allocate values 0-1023. The first prefix index
  131044. ** (if any) for language-id 0 is allocated values 1024-2047. And so on.
  131045. ** Language 1 indexes are allocated immediately following language 0.
  131046. **
  131047. ** So, for a system with nPrefix prefix indexes configured, the block of
  131048. ** absolute levels that corresponds to language-id iLangid and index
  131049. ** iIndex starts at absolute level ((iLangid * (nPrefix+1) + iIndex) * 1024).
  131050. */
  131051. static sqlite3_int64 getAbsoluteLevel(
  131052. Fts3Table *p, /* FTS3 table handle */
  131053. int iLangid, /* Language id */
  131054. int iIndex, /* Index in p->aIndex[] */
  131055. int iLevel /* Level of segments */
  131056. ){
  131057. sqlite3_int64 iBase; /* First absolute level for iLangid/iIndex */
  131058. assert( iLangid>=0 );
  131059. assert( p->nIndex>0 );
  131060. assert( iIndex>=0 && iIndex<p->nIndex );
  131061. iBase = ((sqlite3_int64)iLangid * p->nIndex + iIndex) * FTS3_SEGDIR_MAXLEVEL;
  131062. return iBase + iLevel;
  131063. }
  131064. /*
  131065. ** Set *ppStmt to a statement handle that may be used to iterate through
  131066. ** all rows in the %_segdir table, from oldest to newest. If successful,
  131067. ** return SQLITE_OK. If an error occurs while preparing the statement,
  131068. ** return an SQLite error code.
  131069. **
  131070. ** There is only ever one instance of this SQL statement compiled for
  131071. ** each FTS3 table.
  131072. **
  131073. ** The statement returns the following columns from the %_segdir table:
  131074. **
  131075. ** 0: idx
  131076. ** 1: start_block
  131077. ** 2: leaves_end_block
  131078. ** 3: end_block
  131079. ** 4: root
  131080. */
  131081. SQLITE_PRIVATE int sqlite3Fts3AllSegdirs(
  131082. Fts3Table *p, /* FTS3 table */
  131083. int iLangid, /* Language being queried */
  131084. int iIndex, /* Index for p->aIndex[] */
  131085. int iLevel, /* Level to select (relative level) */
  131086. sqlite3_stmt **ppStmt /* OUT: Compiled statement */
  131087. ){
  131088. int rc;
  131089. sqlite3_stmt *pStmt = 0;
  131090. assert( iLevel==FTS3_SEGCURSOR_ALL || iLevel>=0 );
  131091. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  131092. assert( iIndex>=0 && iIndex<p->nIndex );
  131093. if( iLevel<0 ){
  131094. /* "SELECT * FROM %_segdir WHERE level BETWEEN ? AND ? ORDER BY ..." */
  131095. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE, &pStmt, 0);
  131096. if( rc==SQLITE_OK ){
  131097. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  131098. sqlite3_bind_int64(pStmt, 2,
  131099. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  131100. );
  131101. }
  131102. }else{
  131103. /* "SELECT * FROM %_segdir WHERE level = ? ORDER BY ..." */
  131104. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  131105. if( rc==SQLITE_OK ){
  131106. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex,iLevel));
  131107. }
  131108. }
  131109. *ppStmt = pStmt;
  131110. return rc;
  131111. }
  131112. /*
  131113. ** Append a single varint to a PendingList buffer. SQLITE_OK is returned
  131114. ** if successful, or an SQLite error code otherwise.
  131115. **
  131116. ** This function also serves to allocate the PendingList structure itself.
  131117. ** For example, to create a new PendingList structure containing two
  131118. ** varints:
  131119. **
  131120. ** PendingList *p = 0;
  131121. ** fts3PendingListAppendVarint(&p, 1);
  131122. ** fts3PendingListAppendVarint(&p, 2);
  131123. */
  131124. static int fts3PendingListAppendVarint(
  131125. PendingList **pp, /* IN/OUT: Pointer to PendingList struct */
  131126. sqlite3_int64 i /* Value to append to data */
  131127. ){
  131128. PendingList *p = *pp;
  131129. /* Allocate or grow the PendingList as required. */
  131130. if( !p ){
  131131. p = sqlite3_malloc(sizeof(*p) + 100);
  131132. if( !p ){
  131133. return SQLITE_NOMEM;
  131134. }
  131135. p->nSpace = 100;
  131136. p->aData = (char *)&p[1];
  131137. p->nData = 0;
  131138. }
  131139. else if( p->nData+FTS3_VARINT_MAX+1>p->nSpace ){
  131140. int nNew = p->nSpace * 2;
  131141. p = sqlite3_realloc(p, sizeof(*p) + nNew);
  131142. if( !p ){
  131143. sqlite3_free(*pp);
  131144. *pp = 0;
  131145. return SQLITE_NOMEM;
  131146. }
  131147. p->nSpace = nNew;
  131148. p->aData = (char *)&p[1];
  131149. }
  131150. /* Append the new serialized varint to the end of the list. */
  131151. p->nData += sqlite3Fts3PutVarint(&p->aData[p->nData], i);
  131152. p->aData[p->nData] = '\0';
  131153. *pp = p;
  131154. return SQLITE_OK;
  131155. }
  131156. /*
  131157. ** Add a docid/column/position entry to a PendingList structure. Non-zero
  131158. ** is returned if the structure is sqlite3_realloced as part of adding
  131159. ** the entry. Otherwise, zero.
  131160. **
  131161. ** If an OOM error occurs, *pRc is set to SQLITE_NOMEM before returning.
  131162. ** Zero is always returned in this case. Otherwise, if no OOM error occurs,
  131163. ** it is set to SQLITE_OK.
  131164. */
  131165. static int fts3PendingListAppend(
  131166. PendingList **pp, /* IN/OUT: PendingList structure */
  131167. sqlite3_int64 iDocid, /* Docid for entry to add */
  131168. sqlite3_int64 iCol, /* Column for entry to add */
  131169. sqlite3_int64 iPos, /* Position of term for entry to add */
  131170. int *pRc /* OUT: Return code */
  131171. ){
  131172. PendingList *p = *pp;
  131173. int rc = SQLITE_OK;
  131174. assert( !p || p->iLastDocid<=iDocid );
  131175. if( !p || p->iLastDocid!=iDocid ){
  131176. sqlite3_int64 iDelta = iDocid - (p ? p->iLastDocid : 0);
  131177. if( p ){
  131178. assert( p->nData<p->nSpace );
  131179. assert( p->aData[p->nData]==0 );
  131180. p->nData++;
  131181. }
  131182. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iDelta)) ){
  131183. goto pendinglistappend_out;
  131184. }
  131185. p->iLastCol = -1;
  131186. p->iLastPos = 0;
  131187. p->iLastDocid = iDocid;
  131188. }
  131189. if( iCol>0 && p->iLastCol!=iCol ){
  131190. if( SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, 1))
  131191. || SQLITE_OK!=(rc = fts3PendingListAppendVarint(&p, iCol))
  131192. ){
  131193. goto pendinglistappend_out;
  131194. }
  131195. p->iLastCol = iCol;
  131196. p->iLastPos = 0;
  131197. }
  131198. if( iCol>=0 ){
  131199. assert( iPos>p->iLastPos || (iPos==0 && p->iLastPos==0) );
  131200. rc = fts3PendingListAppendVarint(&p, 2+iPos-p->iLastPos);
  131201. if( rc==SQLITE_OK ){
  131202. p->iLastPos = iPos;
  131203. }
  131204. }
  131205. pendinglistappend_out:
  131206. *pRc = rc;
  131207. if( p!=*pp ){
  131208. *pp = p;
  131209. return 1;
  131210. }
  131211. return 0;
  131212. }
  131213. /*
  131214. ** Free a PendingList object allocated by fts3PendingListAppend().
  131215. */
  131216. static void fts3PendingListDelete(PendingList *pList){
  131217. sqlite3_free(pList);
  131218. }
  131219. /*
  131220. ** Add an entry to one of the pending-terms hash tables.
  131221. */
  131222. static int fts3PendingTermsAddOne(
  131223. Fts3Table *p,
  131224. int iCol,
  131225. int iPos,
  131226. Fts3Hash *pHash, /* Pending terms hash table to add entry to */
  131227. const char *zToken,
  131228. int nToken
  131229. ){
  131230. PendingList *pList;
  131231. int rc = SQLITE_OK;
  131232. pList = (PendingList *)fts3HashFind(pHash, zToken, nToken);
  131233. if( pList ){
  131234. p->nPendingData -= (pList->nData + nToken + sizeof(Fts3HashElem));
  131235. }
  131236. if( fts3PendingListAppend(&pList, p->iPrevDocid, iCol, iPos, &rc) ){
  131237. if( pList==fts3HashInsert(pHash, zToken, nToken, pList) ){
  131238. /* Malloc failed while inserting the new entry. This can only
  131239. ** happen if there was no previous entry for this token.
  131240. */
  131241. assert( 0==fts3HashFind(pHash, zToken, nToken) );
  131242. sqlite3_free(pList);
  131243. rc = SQLITE_NOMEM;
  131244. }
  131245. }
  131246. if( rc==SQLITE_OK ){
  131247. p->nPendingData += (pList->nData + nToken + sizeof(Fts3HashElem));
  131248. }
  131249. return rc;
  131250. }
  131251. /*
  131252. ** Tokenize the nul-terminated string zText and add all tokens to the
  131253. ** pending-terms hash-table. The docid used is that currently stored in
  131254. ** p->iPrevDocid, and the column is specified by argument iCol.
  131255. **
  131256. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  131257. */
  131258. static int fts3PendingTermsAdd(
  131259. Fts3Table *p, /* Table into which text will be inserted */
  131260. int iLangid, /* Language id to use */
  131261. const char *zText, /* Text of document to be inserted */
  131262. int iCol, /* Column into which text is being inserted */
  131263. u32 *pnWord /* IN/OUT: Incr. by number tokens inserted */
  131264. ){
  131265. int rc;
  131266. int iStart = 0;
  131267. int iEnd = 0;
  131268. int iPos = 0;
  131269. int nWord = 0;
  131270. char const *zToken;
  131271. int nToken = 0;
  131272. sqlite3_tokenizer *pTokenizer = p->pTokenizer;
  131273. sqlite3_tokenizer_module const *pModule = pTokenizer->pModule;
  131274. sqlite3_tokenizer_cursor *pCsr;
  131275. int (*xNext)(sqlite3_tokenizer_cursor *pCursor,
  131276. const char**,int*,int*,int*,int*);
  131277. assert( pTokenizer && pModule );
  131278. /* If the user has inserted a NULL value, this function may be called with
  131279. ** zText==0. In this case, add zero token entries to the hash table and
  131280. ** return early. */
  131281. if( zText==0 ){
  131282. *pnWord = 0;
  131283. return SQLITE_OK;
  131284. }
  131285. rc = sqlite3Fts3OpenTokenizer(pTokenizer, iLangid, zText, -1, &pCsr);
  131286. if( rc!=SQLITE_OK ){
  131287. return rc;
  131288. }
  131289. xNext = pModule->xNext;
  131290. while( SQLITE_OK==rc
  131291. && SQLITE_OK==(rc = xNext(pCsr, &zToken, &nToken, &iStart, &iEnd, &iPos))
  131292. ){
  131293. int i;
  131294. if( iPos>=nWord ) nWord = iPos+1;
  131295. /* Positions cannot be negative; we use -1 as a terminator internally.
  131296. ** Tokens must have a non-zero length.
  131297. */
  131298. if( iPos<0 || !zToken || nToken<=0 ){
  131299. rc = SQLITE_ERROR;
  131300. break;
  131301. }
  131302. /* Add the term to the terms index */
  131303. rc = fts3PendingTermsAddOne(
  131304. p, iCol, iPos, &p->aIndex[0].hPending, zToken, nToken
  131305. );
  131306. /* Add the term to each of the prefix indexes that it is not too
  131307. ** short for. */
  131308. for(i=1; rc==SQLITE_OK && i<p->nIndex; i++){
  131309. struct Fts3Index *pIndex = &p->aIndex[i];
  131310. if( nToken<pIndex->nPrefix ) continue;
  131311. rc = fts3PendingTermsAddOne(
  131312. p, iCol, iPos, &pIndex->hPending, zToken, pIndex->nPrefix
  131313. );
  131314. }
  131315. }
  131316. pModule->xClose(pCsr);
  131317. *pnWord += nWord;
  131318. return (rc==SQLITE_DONE ? SQLITE_OK : rc);
  131319. }
  131320. /*
  131321. ** Calling this function indicates that subsequent calls to
  131322. ** fts3PendingTermsAdd() are to add term/position-list pairs for the
  131323. ** contents of the document with docid iDocid.
  131324. */
  131325. static int fts3PendingTermsDocid(
  131326. Fts3Table *p, /* Full-text table handle */
  131327. int iLangid, /* Language id of row being written */
  131328. sqlite_int64 iDocid /* Docid of row being written */
  131329. ){
  131330. assert( iLangid>=0 );
  131331. /* TODO(shess) Explore whether partially flushing the buffer on
  131332. ** forced-flush would provide better performance. I suspect that if
  131333. ** we ordered the doclists by size and flushed the largest until the
  131334. ** buffer was half empty, that would let the less frequent terms
  131335. ** generate longer doclists.
  131336. */
  131337. if( iDocid<=p->iPrevDocid
  131338. || p->iPrevLangid!=iLangid
  131339. || p->nPendingData>p->nMaxPendingData
  131340. ){
  131341. int rc = sqlite3Fts3PendingTermsFlush(p);
  131342. if( rc!=SQLITE_OK ) return rc;
  131343. }
  131344. p->iPrevDocid = iDocid;
  131345. p->iPrevLangid = iLangid;
  131346. return SQLITE_OK;
  131347. }
  131348. /*
  131349. ** Discard the contents of the pending-terms hash tables.
  131350. */
  131351. SQLITE_PRIVATE void sqlite3Fts3PendingTermsClear(Fts3Table *p){
  131352. int i;
  131353. for(i=0; i<p->nIndex; i++){
  131354. Fts3HashElem *pElem;
  131355. Fts3Hash *pHash = &p->aIndex[i].hPending;
  131356. for(pElem=fts3HashFirst(pHash); pElem; pElem=fts3HashNext(pElem)){
  131357. PendingList *pList = (PendingList *)fts3HashData(pElem);
  131358. fts3PendingListDelete(pList);
  131359. }
  131360. fts3HashClear(pHash);
  131361. }
  131362. p->nPendingData = 0;
  131363. }
  131364. /*
  131365. ** This function is called by the xUpdate() method as part of an INSERT
  131366. ** operation. It adds entries for each term in the new record to the
  131367. ** pendingTerms hash table.
  131368. **
  131369. ** Argument apVal is the same as the similarly named argument passed to
  131370. ** fts3InsertData(). Parameter iDocid is the docid of the new row.
  131371. */
  131372. static int fts3InsertTerms(
  131373. Fts3Table *p,
  131374. int iLangid,
  131375. sqlite3_value **apVal,
  131376. u32 *aSz
  131377. ){
  131378. int i; /* Iterator variable */
  131379. for(i=2; i<p->nColumn+2; i++){
  131380. int iCol = i-2;
  131381. if( p->abNotindexed[iCol]==0 ){
  131382. const char *zText = (const char *)sqlite3_value_text(apVal[i]);
  131383. int rc = fts3PendingTermsAdd(p, iLangid, zText, iCol, &aSz[iCol]);
  131384. if( rc!=SQLITE_OK ){
  131385. return rc;
  131386. }
  131387. aSz[p->nColumn] += sqlite3_value_bytes(apVal[i]);
  131388. }
  131389. }
  131390. return SQLITE_OK;
  131391. }
  131392. /*
  131393. ** This function is called by the xUpdate() method for an INSERT operation.
  131394. ** The apVal parameter is passed a copy of the apVal argument passed by
  131395. ** SQLite to the xUpdate() method. i.e:
  131396. **
  131397. ** apVal[0] Not used for INSERT.
  131398. ** apVal[1] rowid
  131399. ** apVal[2] Left-most user-defined column
  131400. ** ...
  131401. ** apVal[p->nColumn+1] Right-most user-defined column
  131402. ** apVal[p->nColumn+2] Hidden column with same name as table
  131403. ** apVal[p->nColumn+3] Hidden "docid" column (alias for rowid)
  131404. ** apVal[p->nColumn+4] Hidden languageid column
  131405. */
  131406. static int fts3InsertData(
  131407. Fts3Table *p, /* Full-text table */
  131408. sqlite3_value **apVal, /* Array of values to insert */
  131409. sqlite3_int64 *piDocid /* OUT: Docid for row just inserted */
  131410. ){
  131411. int rc; /* Return code */
  131412. sqlite3_stmt *pContentInsert; /* INSERT INTO %_content VALUES(...) */
  131413. if( p->zContentTbl ){
  131414. sqlite3_value *pRowid = apVal[p->nColumn+3];
  131415. if( sqlite3_value_type(pRowid)==SQLITE_NULL ){
  131416. pRowid = apVal[1];
  131417. }
  131418. if( sqlite3_value_type(pRowid)!=SQLITE_INTEGER ){
  131419. return SQLITE_CONSTRAINT;
  131420. }
  131421. *piDocid = sqlite3_value_int64(pRowid);
  131422. return SQLITE_OK;
  131423. }
  131424. /* Locate the statement handle used to insert data into the %_content
  131425. ** table. The SQL for this statement is:
  131426. **
  131427. ** INSERT INTO %_content VALUES(?, ?, ?, ...)
  131428. **
  131429. ** The statement features N '?' variables, where N is the number of user
  131430. ** defined columns in the FTS3 table, plus one for the docid field.
  131431. */
  131432. rc = fts3SqlStmt(p, SQL_CONTENT_INSERT, &pContentInsert, &apVal[1]);
  131433. if( rc==SQLITE_OK && p->zLanguageid ){
  131434. rc = sqlite3_bind_int(
  131435. pContentInsert, p->nColumn+2,
  131436. sqlite3_value_int(apVal[p->nColumn+4])
  131437. );
  131438. }
  131439. if( rc!=SQLITE_OK ) return rc;
  131440. /* There is a quirk here. The users INSERT statement may have specified
  131441. ** a value for the "rowid" field, for the "docid" field, or for both.
  131442. ** Which is a problem, since "rowid" and "docid" are aliases for the
  131443. ** same value. For example:
  131444. **
  131445. ** INSERT INTO fts3tbl(rowid, docid) VALUES(1, 2);
  131446. **
  131447. ** In FTS3, this is an error. It is an error to specify non-NULL values
  131448. ** for both docid and some other rowid alias.
  131449. */
  131450. if( SQLITE_NULL!=sqlite3_value_type(apVal[3+p->nColumn]) ){
  131451. if( SQLITE_NULL==sqlite3_value_type(apVal[0])
  131452. && SQLITE_NULL!=sqlite3_value_type(apVal[1])
  131453. ){
  131454. /* A rowid/docid conflict. */
  131455. return SQLITE_ERROR;
  131456. }
  131457. rc = sqlite3_bind_value(pContentInsert, 1, apVal[3+p->nColumn]);
  131458. if( rc!=SQLITE_OK ) return rc;
  131459. }
  131460. /* Execute the statement to insert the record. Set *piDocid to the
  131461. ** new docid value.
  131462. */
  131463. sqlite3_step(pContentInsert);
  131464. rc = sqlite3_reset(pContentInsert);
  131465. *piDocid = sqlite3_last_insert_rowid(p->db);
  131466. return rc;
  131467. }
  131468. /*
  131469. ** Remove all data from the FTS3 table. Clear the hash table containing
  131470. ** pending terms.
  131471. */
  131472. static int fts3DeleteAll(Fts3Table *p, int bContent){
  131473. int rc = SQLITE_OK; /* Return code */
  131474. /* Discard the contents of the pending-terms hash table. */
  131475. sqlite3Fts3PendingTermsClear(p);
  131476. /* Delete everything from the shadow tables. Except, leave %_content as
  131477. ** is if bContent is false. */
  131478. assert( p->zContentTbl==0 || bContent==0 );
  131479. if( bContent ) fts3SqlExec(&rc, p, SQL_DELETE_ALL_CONTENT, 0);
  131480. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGMENTS, 0);
  131481. fts3SqlExec(&rc, p, SQL_DELETE_ALL_SEGDIR, 0);
  131482. if( p->bHasDocsize ){
  131483. fts3SqlExec(&rc, p, SQL_DELETE_ALL_DOCSIZE, 0);
  131484. }
  131485. if( p->bHasStat ){
  131486. fts3SqlExec(&rc, p, SQL_DELETE_ALL_STAT, 0);
  131487. }
  131488. return rc;
  131489. }
  131490. /*
  131491. **
  131492. */
  131493. static int langidFromSelect(Fts3Table *p, sqlite3_stmt *pSelect){
  131494. int iLangid = 0;
  131495. if( p->zLanguageid ) iLangid = sqlite3_column_int(pSelect, p->nColumn+1);
  131496. return iLangid;
  131497. }
  131498. /*
  131499. ** The first element in the apVal[] array is assumed to contain the docid
  131500. ** (an integer) of a row about to be deleted. Remove all terms from the
  131501. ** full-text index.
  131502. */
  131503. static void fts3DeleteTerms(
  131504. int *pRC, /* Result code */
  131505. Fts3Table *p, /* The FTS table to delete from */
  131506. sqlite3_value *pRowid, /* The docid to be deleted */
  131507. u32 *aSz, /* Sizes of deleted document written here */
  131508. int *pbFound /* OUT: Set to true if row really does exist */
  131509. ){
  131510. int rc;
  131511. sqlite3_stmt *pSelect;
  131512. assert( *pbFound==0 );
  131513. if( *pRC ) return;
  131514. rc = fts3SqlStmt(p, SQL_SELECT_CONTENT_BY_ROWID, &pSelect, &pRowid);
  131515. if( rc==SQLITE_OK ){
  131516. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  131517. int i;
  131518. int iLangid = langidFromSelect(p, pSelect);
  131519. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pSelect, 0));
  131520. for(i=1; rc==SQLITE_OK && i<=p->nColumn; i++){
  131521. int iCol = i-1;
  131522. if( p->abNotindexed[iCol]==0 ){
  131523. const char *zText = (const char *)sqlite3_column_text(pSelect, i);
  131524. rc = fts3PendingTermsAdd(p, iLangid, zText, -1, &aSz[iCol]);
  131525. aSz[p->nColumn] += sqlite3_column_bytes(pSelect, i);
  131526. }
  131527. }
  131528. if( rc!=SQLITE_OK ){
  131529. sqlite3_reset(pSelect);
  131530. *pRC = rc;
  131531. return;
  131532. }
  131533. *pbFound = 1;
  131534. }
  131535. rc = sqlite3_reset(pSelect);
  131536. }else{
  131537. sqlite3_reset(pSelect);
  131538. }
  131539. *pRC = rc;
  131540. }
  131541. /*
  131542. ** Forward declaration to account for the circular dependency between
  131543. ** functions fts3SegmentMerge() and fts3AllocateSegdirIdx().
  131544. */
  131545. static int fts3SegmentMerge(Fts3Table *, int, int, int);
  131546. /*
  131547. ** This function allocates a new level iLevel index in the segdir table.
  131548. ** Usually, indexes are allocated within a level sequentially starting
  131549. ** with 0, so the allocated index is one greater than the value returned
  131550. ** by:
  131551. **
  131552. ** SELECT max(idx) FROM %_segdir WHERE level = :iLevel
  131553. **
  131554. ** However, if there are already FTS3_MERGE_COUNT indexes at the requested
  131555. ** level, they are merged into a single level (iLevel+1) segment and the
  131556. ** allocated index is 0.
  131557. **
  131558. ** If successful, *piIdx is set to the allocated index slot and SQLITE_OK
  131559. ** returned. Otherwise, an SQLite error code is returned.
  131560. */
  131561. static int fts3AllocateSegdirIdx(
  131562. Fts3Table *p,
  131563. int iLangid, /* Language id */
  131564. int iIndex, /* Index for p->aIndex */
  131565. int iLevel,
  131566. int *piIdx
  131567. ){
  131568. int rc; /* Return Code */
  131569. sqlite3_stmt *pNextIdx; /* Query for next idx at level iLevel */
  131570. int iNext = 0; /* Result of query pNextIdx */
  131571. assert( iLangid>=0 );
  131572. assert( p->nIndex>=1 );
  131573. /* Set variable iNext to the next available segdir index at level iLevel. */
  131574. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pNextIdx, 0);
  131575. if( rc==SQLITE_OK ){
  131576. sqlite3_bind_int64(
  131577. pNextIdx, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  131578. );
  131579. if( SQLITE_ROW==sqlite3_step(pNextIdx) ){
  131580. iNext = sqlite3_column_int(pNextIdx, 0);
  131581. }
  131582. rc = sqlite3_reset(pNextIdx);
  131583. }
  131584. if( rc==SQLITE_OK ){
  131585. /* If iNext is FTS3_MERGE_COUNT, indicating that level iLevel is already
  131586. ** full, merge all segments in level iLevel into a single iLevel+1
  131587. ** segment and allocate (newly freed) index 0 at level iLevel. Otherwise,
  131588. ** if iNext is less than FTS3_MERGE_COUNT, allocate index iNext.
  131589. */
  131590. if( iNext>=FTS3_MERGE_COUNT ){
  131591. fts3LogMerge(16, getAbsoluteLevel(p, iLangid, iIndex, iLevel));
  131592. rc = fts3SegmentMerge(p, iLangid, iIndex, iLevel);
  131593. *piIdx = 0;
  131594. }else{
  131595. *piIdx = iNext;
  131596. }
  131597. }
  131598. return rc;
  131599. }
  131600. /*
  131601. ** The %_segments table is declared as follows:
  131602. **
  131603. ** CREATE TABLE %_segments(blockid INTEGER PRIMARY KEY, block BLOB)
  131604. **
  131605. ** This function reads data from a single row of the %_segments table. The
  131606. ** specific row is identified by the iBlockid parameter. If paBlob is not
  131607. ** NULL, then a buffer is allocated using sqlite3_malloc() and populated
  131608. ** with the contents of the blob stored in the "block" column of the
  131609. ** identified table row is. Whether or not paBlob is NULL, *pnBlob is set
  131610. ** to the size of the blob in bytes before returning.
  131611. **
  131612. ** If an error occurs, or the table does not contain the specified row,
  131613. ** an SQLite error code is returned. Otherwise, SQLITE_OK is returned. If
  131614. ** paBlob is non-NULL, then it is the responsibility of the caller to
  131615. ** eventually free the returned buffer.
  131616. **
  131617. ** This function may leave an open sqlite3_blob* handle in the
  131618. ** Fts3Table.pSegments variable. This handle is reused by subsequent calls
  131619. ** to this function. The handle may be closed by calling the
  131620. ** sqlite3Fts3SegmentsClose() function. Reusing a blob handle is a handy
  131621. ** performance improvement, but the blob handle should always be closed
  131622. ** before control is returned to the user (to prevent a lock being held
  131623. ** on the database file for longer than necessary). Thus, any virtual table
  131624. ** method (xFilter etc.) that may directly or indirectly call this function
  131625. ** must call sqlite3Fts3SegmentsClose() before returning.
  131626. */
  131627. SQLITE_PRIVATE int sqlite3Fts3ReadBlock(
  131628. Fts3Table *p, /* FTS3 table handle */
  131629. sqlite3_int64 iBlockid, /* Access the row with blockid=$iBlockid */
  131630. char **paBlob, /* OUT: Blob data in malloc'd buffer */
  131631. int *pnBlob, /* OUT: Size of blob data */
  131632. int *pnLoad /* OUT: Bytes actually loaded */
  131633. ){
  131634. int rc; /* Return code */
  131635. /* pnBlob must be non-NULL. paBlob may be NULL or non-NULL. */
  131636. assert( pnBlob );
  131637. if( p->pSegments ){
  131638. rc = sqlite3_blob_reopen(p->pSegments, iBlockid);
  131639. }else{
  131640. if( 0==p->zSegmentsTbl ){
  131641. p->zSegmentsTbl = sqlite3_mprintf("%s_segments", p->zName);
  131642. if( 0==p->zSegmentsTbl ) return SQLITE_NOMEM;
  131643. }
  131644. rc = sqlite3_blob_open(
  131645. p->db, p->zDb, p->zSegmentsTbl, "block", iBlockid, 0, &p->pSegments
  131646. );
  131647. }
  131648. if( rc==SQLITE_OK ){
  131649. int nByte = sqlite3_blob_bytes(p->pSegments);
  131650. *pnBlob = nByte;
  131651. if( paBlob ){
  131652. char *aByte = sqlite3_malloc(nByte + FTS3_NODE_PADDING);
  131653. if( !aByte ){
  131654. rc = SQLITE_NOMEM;
  131655. }else{
  131656. if( pnLoad && nByte>(FTS3_NODE_CHUNK_THRESHOLD) ){
  131657. nByte = FTS3_NODE_CHUNKSIZE;
  131658. *pnLoad = nByte;
  131659. }
  131660. rc = sqlite3_blob_read(p->pSegments, aByte, nByte, 0);
  131661. memset(&aByte[nByte], 0, FTS3_NODE_PADDING);
  131662. if( rc!=SQLITE_OK ){
  131663. sqlite3_free(aByte);
  131664. aByte = 0;
  131665. }
  131666. }
  131667. *paBlob = aByte;
  131668. }
  131669. }
  131670. return rc;
  131671. }
  131672. /*
  131673. ** Close the blob handle at p->pSegments, if it is open. See comments above
  131674. ** the sqlite3Fts3ReadBlock() function for details.
  131675. */
  131676. SQLITE_PRIVATE void sqlite3Fts3SegmentsClose(Fts3Table *p){
  131677. sqlite3_blob_close(p->pSegments);
  131678. p->pSegments = 0;
  131679. }
  131680. static int fts3SegReaderIncrRead(Fts3SegReader *pReader){
  131681. int nRead; /* Number of bytes to read */
  131682. int rc; /* Return code */
  131683. nRead = MIN(pReader->nNode - pReader->nPopulate, FTS3_NODE_CHUNKSIZE);
  131684. rc = sqlite3_blob_read(
  131685. pReader->pBlob,
  131686. &pReader->aNode[pReader->nPopulate],
  131687. nRead,
  131688. pReader->nPopulate
  131689. );
  131690. if( rc==SQLITE_OK ){
  131691. pReader->nPopulate += nRead;
  131692. memset(&pReader->aNode[pReader->nPopulate], 0, FTS3_NODE_PADDING);
  131693. if( pReader->nPopulate==pReader->nNode ){
  131694. sqlite3_blob_close(pReader->pBlob);
  131695. pReader->pBlob = 0;
  131696. pReader->nPopulate = 0;
  131697. }
  131698. }
  131699. return rc;
  131700. }
  131701. static int fts3SegReaderRequire(Fts3SegReader *pReader, char *pFrom, int nByte){
  131702. int rc = SQLITE_OK;
  131703. assert( !pReader->pBlob
  131704. || (pFrom>=pReader->aNode && pFrom<&pReader->aNode[pReader->nNode])
  131705. );
  131706. while( pReader->pBlob && rc==SQLITE_OK
  131707. && (pFrom - pReader->aNode + nByte)>pReader->nPopulate
  131708. ){
  131709. rc = fts3SegReaderIncrRead(pReader);
  131710. }
  131711. return rc;
  131712. }
  131713. /*
  131714. ** Set an Fts3SegReader cursor to point at EOF.
  131715. */
  131716. static void fts3SegReaderSetEof(Fts3SegReader *pSeg){
  131717. if( !fts3SegReaderIsRootOnly(pSeg) ){
  131718. sqlite3_free(pSeg->aNode);
  131719. sqlite3_blob_close(pSeg->pBlob);
  131720. pSeg->pBlob = 0;
  131721. }
  131722. pSeg->aNode = 0;
  131723. }
  131724. /*
  131725. ** Move the iterator passed as the first argument to the next term in the
  131726. ** segment. If successful, SQLITE_OK is returned. If there is no next term,
  131727. ** SQLITE_DONE. Otherwise, an SQLite error code.
  131728. */
  131729. static int fts3SegReaderNext(
  131730. Fts3Table *p,
  131731. Fts3SegReader *pReader,
  131732. int bIncr
  131733. ){
  131734. int rc; /* Return code of various sub-routines */
  131735. char *pNext; /* Cursor variable */
  131736. int nPrefix; /* Number of bytes in term prefix */
  131737. int nSuffix; /* Number of bytes in term suffix */
  131738. if( !pReader->aDoclist ){
  131739. pNext = pReader->aNode;
  131740. }else{
  131741. pNext = &pReader->aDoclist[pReader->nDoclist];
  131742. }
  131743. if( !pNext || pNext>=&pReader->aNode[pReader->nNode] ){
  131744. if( fts3SegReaderIsPending(pReader) ){
  131745. Fts3HashElem *pElem = *(pReader->ppNextElem);
  131746. if( pElem==0 ){
  131747. pReader->aNode = 0;
  131748. }else{
  131749. PendingList *pList = (PendingList *)fts3HashData(pElem);
  131750. pReader->zTerm = (char *)fts3HashKey(pElem);
  131751. pReader->nTerm = fts3HashKeysize(pElem);
  131752. pReader->nNode = pReader->nDoclist = pList->nData + 1;
  131753. pReader->aNode = pReader->aDoclist = pList->aData;
  131754. pReader->ppNextElem++;
  131755. assert( pReader->aNode );
  131756. }
  131757. return SQLITE_OK;
  131758. }
  131759. fts3SegReaderSetEof(pReader);
  131760. /* If iCurrentBlock>=iLeafEndBlock, this is an EOF condition. All leaf
  131761. ** blocks have already been traversed. */
  131762. assert( pReader->iCurrentBlock<=pReader->iLeafEndBlock );
  131763. if( pReader->iCurrentBlock>=pReader->iLeafEndBlock ){
  131764. return SQLITE_OK;
  131765. }
  131766. rc = sqlite3Fts3ReadBlock(
  131767. p, ++pReader->iCurrentBlock, &pReader->aNode, &pReader->nNode,
  131768. (bIncr ? &pReader->nPopulate : 0)
  131769. );
  131770. if( rc!=SQLITE_OK ) return rc;
  131771. assert( pReader->pBlob==0 );
  131772. if( bIncr && pReader->nPopulate<pReader->nNode ){
  131773. pReader->pBlob = p->pSegments;
  131774. p->pSegments = 0;
  131775. }
  131776. pNext = pReader->aNode;
  131777. }
  131778. assert( !fts3SegReaderIsPending(pReader) );
  131779. rc = fts3SegReaderRequire(pReader, pNext, FTS3_VARINT_MAX*2);
  131780. if( rc!=SQLITE_OK ) return rc;
  131781. /* Because of the FTS3_NODE_PADDING bytes of padding, the following is
  131782. ** safe (no risk of overread) even if the node data is corrupted. */
  131783. pNext += fts3GetVarint32(pNext, &nPrefix);
  131784. pNext += fts3GetVarint32(pNext, &nSuffix);
  131785. if( nPrefix<0 || nSuffix<=0
  131786. || &pNext[nSuffix]>&pReader->aNode[pReader->nNode]
  131787. ){
  131788. return FTS_CORRUPT_VTAB;
  131789. }
  131790. if( nPrefix+nSuffix>pReader->nTermAlloc ){
  131791. int nNew = (nPrefix+nSuffix)*2;
  131792. char *zNew = sqlite3_realloc(pReader->zTerm, nNew);
  131793. if( !zNew ){
  131794. return SQLITE_NOMEM;
  131795. }
  131796. pReader->zTerm = zNew;
  131797. pReader->nTermAlloc = nNew;
  131798. }
  131799. rc = fts3SegReaderRequire(pReader, pNext, nSuffix+FTS3_VARINT_MAX);
  131800. if( rc!=SQLITE_OK ) return rc;
  131801. memcpy(&pReader->zTerm[nPrefix], pNext, nSuffix);
  131802. pReader->nTerm = nPrefix+nSuffix;
  131803. pNext += nSuffix;
  131804. pNext += fts3GetVarint32(pNext, &pReader->nDoclist);
  131805. pReader->aDoclist = pNext;
  131806. pReader->pOffsetList = 0;
  131807. /* Check that the doclist does not appear to extend past the end of the
  131808. ** b-tree node. And that the final byte of the doclist is 0x00. If either
  131809. ** of these statements is untrue, then the data structure is corrupt.
  131810. */
  131811. if( &pReader->aDoclist[pReader->nDoclist]>&pReader->aNode[pReader->nNode]
  131812. || (pReader->nPopulate==0 && pReader->aDoclist[pReader->nDoclist-1])
  131813. ){
  131814. return FTS_CORRUPT_VTAB;
  131815. }
  131816. return SQLITE_OK;
  131817. }
  131818. /*
  131819. ** Set the SegReader to point to the first docid in the doclist associated
  131820. ** with the current term.
  131821. */
  131822. static int fts3SegReaderFirstDocid(Fts3Table *pTab, Fts3SegReader *pReader){
  131823. int rc = SQLITE_OK;
  131824. assert( pReader->aDoclist );
  131825. assert( !pReader->pOffsetList );
  131826. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  131827. u8 bEof = 0;
  131828. pReader->iDocid = 0;
  131829. pReader->nOffsetList = 0;
  131830. sqlite3Fts3DoclistPrev(0,
  131831. pReader->aDoclist, pReader->nDoclist, &pReader->pOffsetList,
  131832. &pReader->iDocid, &pReader->nOffsetList, &bEof
  131833. );
  131834. }else{
  131835. rc = fts3SegReaderRequire(pReader, pReader->aDoclist, FTS3_VARINT_MAX);
  131836. if( rc==SQLITE_OK ){
  131837. int n = sqlite3Fts3GetVarint(pReader->aDoclist, &pReader->iDocid);
  131838. pReader->pOffsetList = &pReader->aDoclist[n];
  131839. }
  131840. }
  131841. return rc;
  131842. }
  131843. /*
  131844. ** Advance the SegReader to point to the next docid in the doclist
  131845. ** associated with the current term.
  131846. **
  131847. ** If arguments ppOffsetList and pnOffsetList are not NULL, then
  131848. ** *ppOffsetList is set to point to the first column-offset list
  131849. ** in the doclist entry (i.e. immediately past the docid varint).
  131850. ** *pnOffsetList is set to the length of the set of column-offset
  131851. ** lists, not including the nul-terminator byte. For example:
  131852. */
  131853. static int fts3SegReaderNextDocid(
  131854. Fts3Table *pTab,
  131855. Fts3SegReader *pReader, /* Reader to advance to next docid */
  131856. char **ppOffsetList, /* OUT: Pointer to current position-list */
  131857. int *pnOffsetList /* OUT: Length of *ppOffsetList in bytes */
  131858. ){
  131859. int rc = SQLITE_OK;
  131860. char *p = pReader->pOffsetList;
  131861. char c = 0;
  131862. assert( p );
  131863. if( pTab->bDescIdx && fts3SegReaderIsPending(pReader) ){
  131864. /* A pending-terms seg-reader for an FTS4 table that uses order=desc.
  131865. ** Pending-terms doclists are always built up in ascending order, so
  131866. ** we have to iterate through them backwards here. */
  131867. u8 bEof = 0;
  131868. if( ppOffsetList ){
  131869. *ppOffsetList = pReader->pOffsetList;
  131870. *pnOffsetList = pReader->nOffsetList - 1;
  131871. }
  131872. sqlite3Fts3DoclistPrev(0,
  131873. pReader->aDoclist, pReader->nDoclist, &p, &pReader->iDocid,
  131874. &pReader->nOffsetList, &bEof
  131875. );
  131876. if( bEof ){
  131877. pReader->pOffsetList = 0;
  131878. }else{
  131879. pReader->pOffsetList = p;
  131880. }
  131881. }else{
  131882. char *pEnd = &pReader->aDoclist[pReader->nDoclist];
  131883. /* Pointer p currently points at the first byte of an offset list. The
  131884. ** following block advances it to point one byte past the end of
  131885. ** the same offset list. */
  131886. while( 1 ){
  131887. /* The following line of code (and the "p++" below the while() loop) is
  131888. ** normally all that is required to move pointer p to the desired
  131889. ** position. The exception is if this node is being loaded from disk
  131890. ** incrementally and pointer "p" now points to the first byte past
  131891. ** the populated part of pReader->aNode[].
  131892. */
  131893. while( *p | c ) c = *p++ & 0x80;
  131894. assert( *p==0 );
  131895. if( pReader->pBlob==0 || p<&pReader->aNode[pReader->nPopulate] ) break;
  131896. rc = fts3SegReaderIncrRead(pReader);
  131897. if( rc!=SQLITE_OK ) return rc;
  131898. }
  131899. p++;
  131900. /* If required, populate the output variables with a pointer to and the
  131901. ** size of the previous offset-list.
  131902. */
  131903. if( ppOffsetList ){
  131904. *ppOffsetList = pReader->pOffsetList;
  131905. *pnOffsetList = (int)(p - pReader->pOffsetList - 1);
  131906. }
  131907. /* List may have been edited in place by fts3EvalNearTrim() */
  131908. while( p<pEnd && *p==0 ) p++;
  131909. /* If there are no more entries in the doclist, set pOffsetList to
  131910. ** NULL. Otherwise, set Fts3SegReader.iDocid to the next docid and
  131911. ** Fts3SegReader.pOffsetList to point to the next offset list before
  131912. ** returning.
  131913. */
  131914. if( p>=pEnd ){
  131915. pReader->pOffsetList = 0;
  131916. }else{
  131917. rc = fts3SegReaderRequire(pReader, p, FTS3_VARINT_MAX);
  131918. if( rc==SQLITE_OK ){
  131919. sqlite3_int64 iDelta;
  131920. pReader->pOffsetList = p + sqlite3Fts3GetVarint(p, &iDelta);
  131921. if( pTab->bDescIdx ){
  131922. pReader->iDocid -= iDelta;
  131923. }else{
  131924. pReader->iDocid += iDelta;
  131925. }
  131926. }
  131927. }
  131928. }
  131929. return SQLITE_OK;
  131930. }
  131931. SQLITE_PRIVATE int sqlite3Fts3MsrOvfl(
  131932. Fts3Cursor *pCsr,
  131933. Fts3MultiSegReader *pMsr,
  131934. int *pnOvfl
  131935. ){
  131936. Fts3Table *p = (Fts3Table*)pCsr->base.pVtab;
  131937. int nOvfl = 0;
  131938. int ii;
  131939. int rc = SQLITE_OK;
  131940. int pgsz = p->nPgsz;
  131941. assert( p->bFts4 );
  131942. assert( pgsz>0 );
  131943. for(ii=0; rc==SQLITE_OK && ii<pMsr->nSegment; ii++){
  131944. Fts3SegReader *pReader = pMsr->apSegment[ii];
  131945. if( !fts3SegReaderIsPending(pReader)
  131946. && !fts3SegReaderIsRootOnly(pReader)
  131947. ){
  131948. sqlite3_int64 jj;
  131949. for(jj=pReader->iStartBlock; jj<=pReader->iLeafEndBlock; jj++){
  131950. int nBlob;
  131951. rc = sqlite3Fts3ReadBlock(p, jj, 0, &nBlob, 0);
  131952. if( rc!=SQLITE_OK ) break;
  131953. if( (nBlob+35)>pgsz ){
  131954. nOvfl += (nBlob + 34)/pgsz;
  131955. }
  131956. }
  131957. }
  131958. }
  131959. *pnOvfl = nOvfl;
  131960. return rc;
  131961. }
  131962. /*
  131963. ** Free all allocations associated with the iterator passed as the
  131964. ** second argument.
  131965. */
  131966. SQLITE_PRIVATE void sqlite3Fts3SegReaderFree(Fts3SegReader *pReader){
  131967. if( pReader && !fts3SegReaderIsPending(pReader) ){
  131968. sqlite3_free(pReader->zTerm);
  131969. if( !fts3SegReaderIsRootOnly(pReader) ){
  131970. sqlite3_free(pReader->aNode);
  131971. sqlite3_blob_close(pReader->pBlob);
  131972. }
  131973. }
  131974. sqlite3_free(pReader);
  131975. }
  131976. /*
  131977. ** Allocate a new SegReader object.
  131978. */
  131979. SQLITE_PRIVATE int sqlite3Fts3SegReaderNew(
  131980. int iAge, /* Segment "age". */
  131981. int bLookup, /* True for a lookup only */
  131982. sqlite3_int64 iStartLeaf, /* First leaf to traverse */
  131983. sqlite3_int64 iEndLeaf, /* Final leaf to traverse */
  131984. sqlite3_int64 iEndBlock, /* Final block of segment */
  131985. const char *zRoot, /* Buffer containing root node */
  131986. int nRoot, /* Size of buffer containing root node */
  131987. Fts3SegReader **ppReader /* OUT: Allocated Fts3SegReader */
  131988. ){
  131989. Fts3SegReader *pReader; /* Newly allocated SegReader object */
  131990. int nExtra = 0; /* Bytes to allocate segment root node */
  131991. assert( iStartLeaf<=iEndLeaf );
  131992. if( iStartLeaf==0 ){
  131993. nExtra = nRoot + FTS3_NODE_PADDING;
  131994. }
  131995. pReader = (Fts3SegReader *)sqlite3_malloc(sizeof(Fts3SegReader) + nExtra);
  131996. if( !pReader ){
  131997. return SQLITE_NOMEM;
  131998. }
  131999. memset(pReader, 0, sizeof(Fts3SegReader));
  132000. pReader->iIdx = iAge;
  132001. pReader->bLookup = bLookup!=0;
  132002. pReader->iStartBlock = iStartLeaf;
  132003. pReader->iLeafEndBlock = iEndLeaf;
  132004. pReader->iEndBlock = iEndBlock;
  132005. if( nExtra ){
  132006. /* The entire segment is stored in the root node. */
  132007. pReader->aNode = (char *)&pReader[1];
  132008. pReader->rootOnly = 1;
  132009. pReader->nNode = nRoot;
  132010. memcpy(pReader->aNode, zRoot, nRoot);
  132011. memset(&pReader->aNode[nRoot], 0, FTS3_NODE_PADDING);
  132012. }else{
  132013. pReader->iCurrentBlock = iStartLeaf-1;
  132014. }
  132015. *ppReader = pReader;
  132016. return SQLITE_OK;
  132017. }
  132018. /*
  132019. ** This is a comparison function used as a qsort() callback when sorting
  132020. ** an array of pending terms by term. This occurs as part of flushing
  132021. ** the contents of the pending-terms hash table to the database.
  132022. */
  132023. static int fts3CompareElemByTerm(const void *lhs, const void *rhs){
  132024. char *z1 = fts3HashKey(*(Fts3HashElem **)lhs);
  132025. char *z2 = fts3HashKey(*(Fts3HashElem **)rhs);
  132026. int n1 = fts3HashKeysize(*(Fts3HashElem **)lhs);
  132027. int n2 = fts3HashKeysize(*(Fts3HashElem **)rhs);
  132028. int n = (n1<n2 ? n1 : n2);
  132029. int c = memcmp(z1, z2, n);
  132030. if( c==0 ){
  132031. c = n1 - n2;
  132032. }
  132033. return c;
  132034. }
  132035. /*
  132036. ** This function is used to allocate an Fts3SegReader that iterates through
  132037. ** a subset of the terms stored in the Fts3Table.pendingTerms array.
  132038. **
  132039. ** If the isPrefixIter parameter is zero, then the returned SegReader iterates
  132040. ** through each term in the pending-terms table. Or, if isPrefixIter is
  132041. ** non-zero, it iterates through each term and its prefixes. For example, if
  132042. ** the pending terms hash table contains the terms "sqlite", "mysql" and
  132043. ** "firebird", then the iterator visits the following 'terms' (in the order
  132044. ** shown):
  132045. **
  132046. ** f fi fir fire fireb firebi firebir firebird
  132047. ** m my mys mysq mysql
  132048. ** s sq sql sqli sqlit sqlite
  132049. **
  132050. ** Whereas if isPrefixIter is zero, the terms visited are:
  132051. **
  132052. ** firebird mysql sqlite
  132053. */
  132054. SQLITE_PRIVATE int sqlite3Fts3SegReaderPending(
  132055. Fts3Table *p, /* Virtual table handle */
  132056. int iIndex, /* Index for p->aIndex */
  132057. const char *zTerm, /* Term to search for */
  132058. int nTerm, /* Size of buffer zTerm */
  132059. int bPrefix, /* True for a prefix iterator */
  132060. Fts3SegReader **ppReader /* OUT: SegReader for pending-terms */
  132061. ){
  132062. Fts3SegReader *pReader = 0; /* Fts3SegReader object to return */
  132063. Fts3HashElem *pE; /* Iterator variable */
  132064. Fts3HashElem **aElem = 0; /* Array of term hash entries to scan */
  132065. int nElem = 0; /* Size of array at aElem */
  132066. int rc = SQLITE_OK; /* Return Code */
  132067. Fts3Hash *pHash;
  132068. pHash = &p->aIndex[iIndex].hPending;
  132069. if( bPrefix ){
  132070. int nAlloc = 0; /* Size of allocated array at aElem */
  132071. for(pE=fts3HashFirst(pHash); pE; pE=fts3HashNext(pE)){
  132072. char *zKey = (char *)fts3HashKey(pE);
  132073. int nKey = fts3HashKeysize(pE);
  132074. if( nTerm==0 || (nKey>=nTerm && 0==memcmp(zKey, zTerm, nTerm)) ){
  132075. if( nElem==nAlloc ){
  132076. Fts3HashElem **aElem2;
  132077. nAlloc += 16;
  132078. aElem2 = (Fts3HashElem **)sqlite3_realloc(
  132079. aElem, nAlloc*sizeof(Fts3HashElem *)
  132080. );
  132081. if( !aElem2 ){
  132082. rc = SQLITE_NOMEM;
  132083. nElem = 0;
  132084. break;
  132085. }
  132086. aElem = aElem2;
  132087. }
  132088. aElem[nElem++] = pE;
  132089. }
  132090. }
  132091. /* If more than one term matches the prefix, sort the Fts3HashElem
  132092. ** objects in term order using qsort(). This uses the same comparison
  132093. ** callback as is used when flushing terms to disk.
  132094. */
  132095. if( nElem>1 ){
  132096. qsort(aElem, nElem, sizeof(Fts3HashElem *), fts3CompareElemByTerm);
  132097. }
  132098. }else{
  132099. /* The query is a simple term lookup that matches at most one term in
  132100. ** the index. All that is required is a straight hash-lookup.
  132101. **
  132102. ** Because the stack address of pE may be accessed via the aElem pointer
  132103. ** below, the "Fts3HashElem *pE" must be declared so that it is valid
  132104. ** within this entire function, not just this "else{...}" block.
  132105. */
  132106. pE = fts3HashFindElem(pHash, zTerm, nTerm);
  132107. if( pE ){
  132108. aElem = &pE;
  132109. nElem = 1;
  132110. }
  132111. }
  132112. if( nElem>0 ){
  132113. int nByte = sizeof(Fts3SegReader) + (nElem+1)*sizeof(Fts3HashElem *);
  132114. pReader = (Fts3SegReader *)sqlite3_malloc(nByte);
  132115. if( !pReader ){
  132116. rc = SQLITE_NOMEM;
  132117. }else{
  132118. memset(pReader, 0, nByte);
  132119. pReader->iIdx = 0x7FFFFFFF;
  132120. pReader->ppNextElem = (Fts3HashElem **)&pReader[1];
  132121. memcpy(pReader->ppNextElem, aElem, nElem*sizeof(Fts3HashElem *));
  132122. }
  132123. }
  132124. if( bPrefix ){
  132125. sqlite3_free(aElem);
  132126. }
  132127. *ppReader = pReader;
  132128. return rc;
  132129. }
  132130. /*
  132131. ** Compare the entries pointed to by two Fts3SegReader structures.
  132132. ** Comparison is as follows:
  132133. **
  132134. ** 1) EOF is greater than not EOF.
  132135. **
  132136. ** 2) The current terms (if any) are compared using memcmp(). If one
  132137. ** term is a prefix of another, the longer term is considered the
  132138. ** larger.
  132139. **
  132140. ** 3) By segment age. An older segment is considered larger.
  132141. */
  132142. static int fts3SegReaderCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  132143. int rc;
  132144. if( pLhs->aNode && pRhs->aNode ){
  132145. int rc2 = pLhs->nTerm - pRhs->nTerm;
  132146. if( rc2<0 ){
  132147. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pLhs->nTerm);
  132148. }else{
  132149. rc = memcmp(pLhs->zTerm, pRhs->zTerm, pRhs->nTerm);
  132150. }
  132151. if( rc==0 ){
  132152. rc = rc2;
  132153. }
  132154. }else{
  132155. rc = (pLhs->aNode==0) - (pRhs->aNode==0);
  132156. }
  132157. if( rc==0 ){
  132158. rc = pRhs->iIdx - pLhs->iIdx;
  132159. }
  132160. assert( rc!=0 );
  132161. return rc;
  132162. }
  132163. /*
  132164. ** A different comparison function for SegReader structures. In this
  132165. ** version, it is assumed that each SegReader points to an entry in
  132166. ** a doclist for identical terms. Comparison is made as follows:
  132167. **
  132168. ** 1) EOF (end of doclist in this case) is greater than not EOF.
  132169. **
  132170. ** 2) By current docid.
  132171. **
  132172. ** 3) By segment age. An older segment is considered larger.
  132173. */
  132174. static int fts3SegReaderDoclistCmp(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  132175. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  132176. if( rc==0 ){
  132177. if( pLhs->iDocid==pRhs->iDocid ){
  132178. rc = pRhs->iIdx - pLhs->iIdx;
  132179. }else{
  132180. rc = (pLhs->iDocid > pRhs->iDocid) ? 1 : -1;
  132181. }
  132182. }
  132183. assert( pLhs->aNode && pRhs->aNode );
  132184. return rc;
  132185. }
  132186. static int fts3SegReaderDoclistCmpRev(Fts3SegReader *pLhs, Fts3SegReader *pRhs){
  132187. int rc = (pLhs->pOffsetList==0)-(pRhs->pOffsetList==0);
  132188. if( rc==0 ){
  132189. if( pLhs->iDocid==pRhs->iDocid ){
  132190. rc = pRhs->iIdx - pLhs->iIdx;
  132191. }else{
  132192. rc = (pLhs->iDocid < pRhs->iDocid) ? 1 : -1;
  132193. }
  132194. }
  132195. assert( pLhs->aNode && pRhs->aNode );
  132196. return rc;
  132197. }
  132198. /*
  132199. ** Compare the term that the Fts3SegReader object passed as the first argument
  132200. ** points to with the term specified by arguments zTerm and nTerm.
  132201. **
  132202. ** If the pSeg iterator is already at EOF, return 0. Otherwise, return
  132203. ** -ve if the pSeg term is less than zTerm/nTerm, 0 if the two terms are
  132204. ** equal, or +ve if the pSeg term is greater than zTerm/nTerm.
  132205. */
  132206. static int fts3SegReaderTermCmp(
  132207. Fts3SegReader *pSeg, /* Segment reader object */
  132208. const char *zTerm, /* Term to compare to */
  132209. int nTerm /* Size of term zTerm in bytes */
  132210. ){
  132211. int res = 0;
  132212. if( pSeg->aNode ){
  132213. if( pSeg->nTerm>nTerm ){
  132214. res = memcmp(pSeg->zTerm, zTerm, nTerm);
  132215. }else{
  132216. res = memcmp(pSeg->zTerm, zTerm, pSeg->nTerm);
  132217. }
  132218. if( res==0 ){
  132219. res = pSeg->nTerm-nTerm;
  132220. }
  132221. }
  132222. return res;
  132223. }
  132224. /*
  132225. ** Argument apSegment is an array of nSegment elements. It is known that
  132226. ** the final (nSegment-nSuspect) members are already in sorted order
  132227. ** (according to the comparison function provided). This function shuffles
  132228. ** the array around until all entries are in sorted order.
  132229. */
  132230. static void fts3SegReaderSort(
  132231. Fts3SegReader **apSegment, /* Array to sort entries of */
  132232. int nSegment, /* Size of apSegment array */
  132233. int nSuspect, /* Unsorted entry count */
  132234. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) /* Comparison function */
  132235. ){
  132236. int i; /* Iterator variable */
  132237. assert( nSuspect<=nSegment );
  132238. if( nSuspect==nSegment ) nSuspect--;
  132239. for(i=nSuspect-1; i>=0; i--){
  132240. int j;
  132241. for(j=i; j<(nSegment-1); j++){
  132242. Fts3SegReader *pTmp;
  132243. if( xCmp(apSegment[j], apSegment[j+1])<0 ) break;
  132244. pTmp = apSegment[j+1];
  132245. apSegment[j+1] = apSegment[j];
  132246. apSegment[j] = pTmp;
  132247. }
  132248. }
  132249. #ifndef NDEBUG
  132250. /* Check that the list really is sorted now. */
  132251. for(i=0; i<(nSuspect-1); i++){
  132252. assert( xCmp(apSegment[i], apSegment[i+1])<0 );
  132253. }
  132254. #endif
  132255. }
  132256. /*
  132257. ** Insert a record into the %_segments table.
  132258. */
  132259. static int fts3WriteSegment(
  132260. Fts3Table *p, /* Virtual table handle */
  132261. sqlite3_int64 iBlock, /* Block id for new block */
  132262. char *z, /* Pointer to buffer containing block data */
  132263. int n /* Size of buffer z in bytes */
  132264. ){
  132265. sqlite3_stmt *pStmt;
  132266. int rc = fts3SqlStmt(p, SQL_INSERT_SEGMENTS, &pStmt, 0);
  132267. if( rc==SQLITE_OK ){
  132268. sqlite3_bind_int64(pStmt, 1, iBlock);
  132269. sqlite3_bind_blob(pStmt, 2, z, n, SQLITE_STATIC);
  132270. sqlite3_step(pStmt);
  132271. rc = sqlite3_reset(pStmt);
  132272. }
  132273. return rc;
  132274. }
  132275. /*
  132276. ** Find the largest relative level number in the table. If successful, set
  132277. ** *pnMax to this value and return SQLITE_OK. Otherwise, if an error occurs,
  132278. ** set *pnMax to zero and return an SQLite error code.
  132279. */
  132280. SQLITE_PRIVATE int sqlite3Fts3MaxLevel(Fts3Table *p, int *pnMax){
  132281. int rc;
  132282. int mxLevel = 0;
  132283. sqlite3_stmt *pStmt = 0;
  132284. rc = fts3SqlStmt(p, SQL_SELECT_MXLEVEL, &pStmt, 0);
  132285. if( rc==SQLITE_OK ){
  132286. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  132287. mxLevel = sqlite3_column_int(pStmt, 0);
  132288. }
  132289. rc = sqlite3_reset(pStmt);
  132290. }
  132291. *pnMax = mxLevel;
  132292. return rc;
  132293. }
  132294. /*
  132295. ** Insert a record into the %_segdir table.
  132296. */
  132297. static int fts3WriteSegdir(
  132298. Fts3Table *p, /* Virtual table handle */
  132299. sqlite3_int64 iLevel, /* Value for "level" field (absolute level) */
  132300. int iIdx, /* Value for "idx" field */
  132301. sqlite3_int64 iStartBlock, /* Value for "start_block" field */
  132302. sqlite3_int64 iLeafEndBlock, /* Value for "leaves_end_block" field */
  132303. sqlite3_int64 iEndBlock, /* Value for "end_block" field */
  132304. sqlite3_int64 nLeafData, /* Bytes of leaf data in segment */
  132305. char *zRoot, /* Blob value for "root" field */
  132306. int nRoot /* Number of bytes in buffer zRoot */
  132307. ){
  132308. sqlite3_stmt *pStmt;
  132309. int rc = fts3SqlStmt(p, SQL_INSERT_SEGDIR, &pStmt, 0);
  132310. if( rc==SQLITE_OK ){
  132311. sqlite3_bind_int64(pStmt, 1, iLevel);
  132312. sqlite3_bind_int(pStmt, 2, iIdx);
  132313. sqlite3_bind_int64(pStmt, 3, iStartBlock);
  132314. sqlite3_bind_int64(pStmt, 4, iLeafEndBlock);
  132315. if( nLeafData==0 ){
  132316. sqlite3_bind_int64(pStmt, 5, iEndBlock);
  132317. }else{
  132318. char *zEnd = sqlite3_mprintf("%lld %lld", iEndBlock, nLeafData);
  132319. if( !zEnd ) return SQLITE_NOMEM;
  132320. sqlite3_bind_text(pStmt, 5, zEnd, -1, sqlite3_free);
  132321. }
  132322. sqlite3_bind_blob(pStmt, 6, zRoot, nRoot, SQLITE_STATIC);
  132323. sqlite3_step(pStmt);
  132324. rc = sqlite3_reset(pStmt);
  132325. }
  132326. return rc;
  132327. }
  132328. /*
  132329. ** Return the size of the common prefix (if any) shared by zPrev and
  132330. ** zNext, in bytes. For example,
  132331. **
  132332. ** fts3PrefixCompress("abc", 3, "abcdef", 6) // returns 3
  132333. ** fts3PrefixCompress("abX", 3, "abcdef", 6) // returns 2
  132334. ** fts3PrefixCompress("abX", 3, "Xbcdef", 6) // returns 0
  132335. */
  132336. static int fts3PrefixCompress(
  132337. const char *zPrev, /* Buffer containing previous term */
  132338. int nPrev, /* Size of buffer zPrev in bytes */
  132339. const char *zNext, /* Buffer containing next term */
  132340. int nNext /* Size of buffer zNext in bytes */
  132341. ){
  132342. int n;
  132343. UNUSED_PARAMETER(nNext);
  132344. for(n=0; n<nPrev && zPrev[n]==zNext[n]; n++);
  132345. return n;
  132346. }
  132347. /*
  132348. ** Add term zTerm to the SegmentNode. It is guaranteed that zTerm is larger
  132349. ** (according to memcmp) than the previous term.
  132350. */
  132351. static int fts3NodeAddTerm(
  132352. Fts3Table *p, /* Virtual table handle */
  132353. SegmentNode **ppTree, /* IN/OUT: SegmentNode handle */
  132354. int isCopyTerm, /* True if zTerm/nTerm is transient */
  132355. const char *zTerm, /* Pointer to buffer containing term */
  132356. int nTerm /* Size of term in bytes */
  132357. ){
  132358. SegmentNode *pTree = *ppTree;
  132359. int rc;
  132360. SegmentNode *pNew;
  132361. /* First try to append the term to the current node. Return early if
  132362. ** this is possible.
  132363. */
  132364. if( pTree ){
  132365. int nData = pTree->nData; /* Current size of node in bytes */
  132366. int nReq = nData; /* Required space after adding zTerm */
  132367. int nPrefix; /* Number of bytes of prefix compression */
  132368. int nSuffix; /* Suffix length */
  132369. nPrefix = fts3PrefixCompress(pTree->zTerm, pTree->nTerm, zTerm, nTerm);
  132370. nSuffix = nTerm-nPrefix;
  132371. nReq += sqlite3Fts3VarintLen(nPrefix)+sqlite3Fts3VarintLen(nSuffix)+nSuffix;
  132372. if( nReq<=p->nNodeSize || !pTree->zTerm ){
  132373. if( nReq>p->nNodeSize ){
  132374. /* An unusual case: this is the first term to be added to the node
  132375. ** and the static node buffer (p->nNodeSize bytes) is not large
  132376. ** enough. Use a separately malloced buffer instead This wastes
  132377. ** p->nNodeSize bytes, but since this scenario only comes about when
  132378. ** the database contain two terms that share a prefix of almost 2KB,
  132379. ** this is not expected to be a serious problem.
  132380. */
  132381. assert( pTree->aData==(char *)&pTree[1] );
  132382. pTree->aData = (char *)sqlite3_malloc(nReq);
  132383. if( !pTree->aData ){
  132384. return SQLITE_NOMEM;
  132385. }
  132386. }
  132387. if( pTree->zTerm ){
  132388. /* There is no prefix-length field for first term in a node */
  132389. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nPrefix);
  132390. }
  132391. nData += sqlite3Fts3PutVarint(&pTree->aData[nData], nSuffix);
  132392. memcpy(&pTree->aData[nData], &zTerm[nPrefix], nSuffix);
  132393. pTree->nData = nData + nSuffix;
  132394. pTree->nEntry++;
  132395. if( isCopyTerm ){
  132396. if( pTree->nMalloc<nTerm ){
  132397. char *zNew = sqlite3_realloc(pTree->zMalloc, nTerm*2);
  132398. if( !zNew ){
  132399. return SQLITE_NOMEM;
  132400. }
  132401. pTree->nMalloc = nTerm*2;
  132402. pTree->zMalloc = zNew;
  132403. }
  132404. pTree->zTerm = pTree->zMalloc;
  132405. memcpy(pTree->zTerm, zTerm, nTerm);
  132406. pTree->nTerm = nTerm;
  132407. }else{
  132408. pTree->zTerm = (char *)zTerm;
  132409. pTree->nTerm = nTerm;
  132410. }
  132411. return SQLITE_OK;
  132412. }
  132413. }
  132414. /* If control flows to here, it was not possible to append zTerm to the
  132415. ** current node. Create a new node (a right-sibling of the current node).
  132416. ** If this is the first node in the tree, the term is added to it.
  132417. **
  132418. ** Otherwise, the term is not added to the new node, it is left empty for
  132419. ** now. Instead, the term is inserted into the parent of pTree. If pTree
  132420. ** has no parent, one is created here.
  132421. */
  132422. pNew = (SegmentNode *)sqlite3_malloc(sizeof(SegmentNode) + p->nNodeSize);
  132423. if( !pNew ){
  132424. return SQLITE_NOMEM;
  132425. }
  132426. memset(pNew, 0, sizeof(SegmentNode));
  132427. pNew->nData = 1 + FTS3_VARINT_MAX;
  132428. pNew->aData = (char *)&pNew[1];
  132429. if( pTree ){
  132430. SegmentNode *pParent = pTree->pParent;
  132431. rc = fts3NodeAddTerm(p, &pParent, isCopyTerm, zTerm, nTerm);
  132432. if( pTree->pParent==0 ){
  132433. pTree->pParent = pParent;
  132434. }
  132435. pTree->pRight = pNew;
  132436. pNew->pLeftmost = pTree->pLeftmost;
  132437. pNew->pParent = pParent;
  132438. pNew->zMalloc = pTree->zMalloc;
  132439. pNew->nMalloc = pTree->nMalloc;
  132440. pTree->zMalloc = 0;
  132441. }else{
  132442. pNew->pLeftmost = pNew;
  132443. rc = fts3NodeAddTerm(p, &pNew, isCopyTerm, zTerm, nTerm);
  132444. }
  132445. *ppTree = pNew;
  132446. return rc;
  132447. }
  132448. /*
  132449. ** Helper function for fts3NodeWrite().
  132450. */
  132451. static int fts3TreeFinishNode(
  132452. SegmentNode *pTree,
  132453. int iHeight,
  132454. sqlite3_int64 iLeftChild
  132455. ){
  132456. int nStart;
  132457. assert( iHeight>=1 && iHeight<128 );
  132458. nStart = FTS3_VARINT_MAX - sqlite3Fts3VarintLen(iLeftChild);
  132459. pTree->aData[nStart] = (char)iHeight;
  132460. sqlite3Fts3PutVarint(&pTree->aData[nStart+1], iLeftChild);
  132461. return nStart;
  132462. }
  132463. /*
  132464. ** Write the buffer for the segment node pTree and all of its peers to the
  132465. ** database. Then call this function recursively to write the parent of
  132466. ** pTree and its peers to the database.
  132467. **
  132468. ** Except, if pTree is a root node, do not write it to the database. Instead,
  132469. ** set output variables *paRoot and *pnRoot to contain the root node.
  132470. **
  132471. ** If successful, SQLITE_OK is returned and output variable *piLast is
  132472. ** set to the largest blockid written to the database (or zero if no
  132473. ** blocks were written to the db). Otherwise, an SQLite error code is
  132474. ** returned.
  132475. */
  132476. static int fts3NodeWrite(
  132477. Fts3Table *p, /* Virtual table handle */
  132478. SegmentNode *pTree, /* SegmentNode handle */
  132479. int iHeight, /* Height of this node in tree */
  132480. sqlite3_int64 iLeaf, /* Block id of first leaf node */
  132481. sqlite3_int64 iFree, /* Block id of next free slot in %_segments */
  132482. sqlite3_int64 *piLast, /* OUT: Block id of last entry written */
  132483. char **paRoot, /* OUT: Data for root node */
  132484. int *pnRoot /* OUT: Size of root node in bytes */
  132485. ){
  132486. int rc = SQLITE_OK;
  132487. if( !pTree->pParent ){
  132488. /* Root node of the tree. */
  132489. int nStart = fts3TreeFinishNode(pTree, iHeight, iLeaf);
  132490. *piLast = iFree-1;
  132491. *pnRoot = pTree->nData - nStart;
  132492. *paRoot = &pTree->aData[nStart];
  132493. }else{
  132494. SegmentNode *pIter;
  132495. sqlite3_int64 iNextFree = iFree;
  132496. sqlite3_int64 iNextLeaf = iLeaf;
  132497. for(pIter=pTree->pLeftmost; pIter && rc==SQLITE_OK; pIter=pIter->pRight){
  132498. int nStart = fts3TreeFinishNode(pIter, iHeight, iNextLeaf);
  132499. int nWrite = pIter->nData - nStart;
  132500. rc = fts3WriteSegment(p, iNextFree, &pIter->aData[nStart], nWrite);
  132501. iNextFree++;
  132502. iNextLeaf += (pIter->nEntry+1);
  132503. }
  132504. if( rc==SQLITE_OK ){
  132505. assert( iNextLeaf==iFree );
  132506. rc = fts3NodeWrite(
  132507. p, pTree->pParent, iHeight+1, iFree, iNextFree, piLast, paRoot, pnRoot
  132508. );
  132509. }
  132510. }
  132511. return rc;
  132512. }
  132513. /*
  132514. ** Free all memory allocations associated with the tree pTree.
  132515. */
  132516. static void fts3NodeFree(SegmentNode *pTree){
  132517. if( pTree ){
  132518. SegmentNode *p = pTree->pLeftmost;
  132519. fts3NodeFree(p->pParent);
  132520. while( p ){
  132521. SegmentNode *pRight = p->pRight;
  132522. if( p->aData!=(char *)&p[1] ){
  132523. sqlite3_free(p->aData);
  132524. }
  132525. assert( pRight==0 || p->zMalloc==0 );
  132526. sqlite3_free(p->zMalloc);
  132527. sqlite3_free(p);
  132528. p = pRight;
  132529. }
  132530. }
  132531. }
  132532. /*
  132533. ** Add a term to the segment being constructed by the SegmentWriter object
  132534. ** *ppWriter. When adding the first term to a segment, *ppWriter should
  132535. ** be passed NULL. This function will allocate a new SegmentWriter object
  132536. ** and return it via the input/output variable *ppWriter in this case.
  132537. **
  132538. ** If successful, SQLITE_OK is returned. Otherwise, an SQLite error code.
  132539. */
  132540. static int fts3SegWriterAdd(
  132541. Fts3Table *p, /* Virtual table handle */
  132542. SegmentWriter **ppWriter, /* IN/OUT: SegmentWriter handle */
  132543. int isCopyTerm, /* True if buffer zTerm must be copied */
  132544. const char *zTerm, /* Pointer to buffer containing term */
  132545. int nTerm, /* Size of term in bytes */
  132546. const char *aDoclist, /* Pointer to buffer containing doclist */
  132547. int nDoclist /* Size of doclist in bytes */
  132548. ){
  132549. int nPrefix; /* Size of term prefix in bytes */
  132550. int nSuffix; /* Size of term suffix in bytes */
  132551. int nReq; /* Number of bytes required on leaf page */
  132552. int nData;
  132553. SegmentWriter *pWriter = *ppWriter;
  132554. if( !pWriter ){
  132555. int rc;
  132556. sqlite3_stmt *pStmt;
  132557. /* Allocate the SegmentWriter structure */
  132558. pWriter = (SegmentWriter *)sqlite3_malloc(sizeof(SegmentWriter));
  132559. if( !pWriter ) return SQLITE_NOMEM;
  132560. memset(pWriter, 0, sizeof(SegmentWriter));
  132561. *ppWriter = pWriter;
  132562. /* Allocate a buffer in which to accumulate data */
  132563. pWriter->aData = (char *)sqlite3_malloc(p->nNodeSize);
  132564. if( !pWriter->aData ) return SQLITE_NOMEM;
  132565. pWriter->nSize = p->nNodeSize;
  132566. /* Find the next free blockid in the %_segments table */
  132567. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pStmt, 0);
  132568. if( rc!=SQLITE_OK ) return rc;
  132569. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  132570. pWriter->iFree = sqlite3_column_int64(pStmt, 0);
  132571. pWriter->iFirst = pWriter->iFree;
  132572. }
  132573. rc = sqlite3_reset(pStmt);
  132574. if( rc!=SQLITE_OK ) return rc;
  132575. }
  132576. nData = pWriter->nData;
  132577. nPrefix = fts3PrefixCompress(pWriter->zTerm, pWriter->nTerm, zTerm, nTerm);
  132578. nSuffix = nTerm-nPrefix;
  132579. /* Figure out how many bytes are required by this new entry */
  132580. nReq = sqlite3Fts3VarintLen(nPrefix) + /* varint containing prefix size */
  132581. sqlite3Fts3VarintLen(nSuffix) + /* varint containing suffix size */
  132582. nSuffix + /* Term suffix */
  132583. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  132584. nDoclist; /* Doclist data */
  132585. if( nData>0 && nData+nReq>p->nNodeSize ){
  132586. int rc;
  132587. /* The current leaf node is full. Write it out to the database. */
  132588. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, nData);
  132589. if( rc!=SQLITE_OK ) return rc;
  132590. p->nLeafAdd++;
  132591. /* Add the current term to the interior node tree. The term added to
  132592. ** the interior tree must:
  132593. **
  132594. ** a) be greater than the largest term on the leaf node just written
  132595. ** to the database (still available in pWriter->zTerm), and
  132596. **
  132597. ** b) be less than or equal to the term about to be added to the new
  132598. ** leaf node (zTerm/nTerm).
  132599. **
  132600. ** In other words, it must be the prefix of zTerm 1 byte longer than
  132601. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  132602. */
  132603. assert( nPrefix<nTerm );
  132604. rc = fts3NodeAddTerm(p, &pWriter->pTree, isCopyTerm, zTerm, nPrefix+1);
  132605. if( rc!=SQLITE_OK ) return rc;
  132606. nData = 0;
  132607. pWriter->nTerm = 0;
  132608. nPrefix = 0;
  132609. nSuffix = nTerm;
  132610. nReq = 1 + /* varint containing prefix size */
  132611. sqlite3Fts3VarintLen(nTerm) + /* varint containing suffix size */
  132612. nTerm + /* Term suffix */
  132613. sqlite3Fts3VarintLen(nDoclist) + /* Size of doclist */
  132614. nDoclist; /* Doclist data */
  132615. }
  132616. /* Increase the total number of bytes written to account for the new entry. */
  132617. pWriter->nLeafData += nReq;
  132618. /* If the buffer currently allocated is too small for this entry, realloc
  132619. ** the buffer to make it large enough.
  132620. */
  132621. if( nReq>pWriter->nSize ){
  132622. char *aNew = sqlite3_realloc(pWriter->aData, nReq);
  132623. if( !aNew ) return SQLITE_NOMEM;
  132624. pWriter->aData = aNew;
  132625. pWriter->nSize = nReq;
  132626. }
  132627. assert( nData+nReq<=pWriter->nSize );
  132628. /* Append the prefix-compressed term and doclist to the buffer. */
  132629. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nPrefix);
  132630. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nSuffix);
  132631. memcpy(&pWriter->aData[nData], &zTerm[nPrefix], nSuffix);
  132632. nData += nSuffix;
  132633. nData += sqlite3Fts3PutVarint(&pWriter->aData[nData], nDoclist);
  132634. memcpy(&pWriter->aData[nData], aDoclist, nDoclist);
  132635. pWriter->nData = nData + nDoclist;
  132636. /* Save the current term so that it can be used to prefix-compress the next.
  132637. ** If the isCopyTerm parameter is true, then the buffer pointed to by
  132638. ** zTerm is transient, so take a copy of the term data. Otherwise, just
  132639. ** store a copy of the pointer.
  132640. */
  132641. if( isCopyTerm ){
  132642. if( nTerm>pWriter->nMalloc ){
  132643. char *zNew = sqlite3_realloc(pWriter->zMalloc, nTerm*2);
  132644. if( !zNew ){
  132645. return SQLITE_NOMEM;
  132646. }
  132647. pWriter->nMalloc = nTerm*2;
  132648. pWriter->zMalloc = zNew;
  132649. pWriter->zTerm = zNew;
  132650. }
  132651. assert( pWriter->zTerm==pWriter->zMalloc );
  132652. memcpy(pWriter->zTerm, zTerm, nTerm);
  132653. }else{
  132654. pWriter->zTerm = (char *)zTerm;
  132655. }
  132656. pWriter->nTerm = nTerm;
  132657. return SQLITE_OK;
  132658. }
  132659. /*
  132660. ** Flush all data associated with the SegmentWriter object pWriter to the
  132661. ** database. This function must be called after all terms have been added
  132662. ** to the segment using fts3SegWriterAdd(). If successful, SQLITE_OK is
  132663. ** returned. Otherwise, an SQLite error code.
  132664. */
  132665. static int fts3SegWriterFlush(
  132666. Fts3Table *p, /* Virtual table handle */
  132667. SegmentWriter *pWriter, /* SegmentWriter to flush to the db */
  132668. sqlite3_int64 iLevel, /* Value for 'level' column of %_segdir */
  132669. int iIdx /* Value for 'idx' column of %_segdir */
  132670. ){
  132671. int rc; /* Return code */
  132672. if( pWriter->pTree ){
  132673. sqlite3_int64 iLast = 0; /* Largest block id written to database */
  132674. sqlite3_int64 iLastLeaf; /* Largest leaf block id written to db */
  132675. char *zRoot = NULL; /* Pointer to buffer containing root node */
  132676. int nRoot = 0; /* Size of buffer zRoot */
  132677. iLastLeaf = pWriter->iFree;
  132678. rc = fts3WriteSegment(p, pWriter->iFree++, pWriter->aData, pWriter->nData);
  132679. if( rc==SQLITE_OK ){
  132680. rc = fts3NodeWrite(p, pWriter->pTree, 1,
  132681. pWriter->iFirst, pWriter->iFree, &iLast, &zRoot, &nRoot);
  132682. }
  132683. if( rc==SQLITE_OK ){
  132684. rc = fts3WriteSegdir(p, iLevel, iIdx,
  132685. pWriter->iFirst, iLastLeaf, iLast, pWriter->nLeafData, zRoot, nRoot);
  132686. }
  132687. }else{
  132688. /* The entire tree fits on the root node. Write it to the segdir table. */
  132689. rc = fts3WriteSegdir(p, iLevel, iIdx,
  132690. 0, 0, 0, pWriter->nLeafData, pWriter->aData, pWriter->nData);
  132691. }
  132692. p->nLeafAdd++;
  132693. return rc;
  132694. }
  132695. /*
  132696. ** Release all memory held by the SegmentWriter object passed as the
  132697. ** first argument.
  132698. */
  132699. static void fts3SegWriterFree(SegmentWriter *pWriter){
  132700. if( pWriter ){
  132701. sqlite3_free(pWriter->aData);
  132702. sqlite3_free(pWriter->zMalloc);
  132703. fts3NodeFree(pWriter->pTree);
  132704. sqlite3_free(pWriter);
  132705. }
  132706. }
  132707. /*
  132708. ** The first value in the apVal[] array is assumed to contain an integer.
  132709. ** This function tests if there exist any documents with docid values that
  132710. ** are different from that integer. i.e. if deleting the document with docid
  132711. ** pRowid would mean the FTS3 table were empty.
  132712. **
  132713. ** If successful, *pisEmpty is set to true if the table is empty except for
  132714. ** document pRowid, or false otherwise, and SQLITE_OK is returned. If an
  132715. ** error occurs, an SQLite error code is returned.
  132716. */
  132717. static int fts3IsEmpty(Fts3Table *p, sqlite3_value *pRowid, int *pisEmpty){
  132718. sqlite3_stmt *pStmt;
  132719. int rc;
  132720. if( p->zContentTbl ){
  132721. /* If using the content=xxx option, assume the table is never empty */
  132722. *pisEmpty = 0;
  132723. rc = SQLITE_OK;
  132724. }else{
  132725. rc = fts3SqlStmt(p, SQL_IS_EMPTY, &pStmt, &pRowid);
  132726. if( rc==SQLITE_OK ){
  132727. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  132728. *pisEmpty = sqlite3_column_int(pStmt, 0);
  132729. }
  132730. rc = sqlite3_reset(pStmt);
  132731. }
  132732. }
  132733. return rc;
  132734. }
  132735. /*
  132736. ** Set *pnMax to the largest segment level in the database for the index
  132737. ** iIndex.
  132738. **
  132739. ** Segment levels are stored in the 'level' column of the %_segdir table.
  132740. **
  132741. ** Return SQLITE_OK if successful, or an SQLite error code if not.
  132742. */
  132743. static int fts3SegmentMaxLevel(
  132744. Fts3Table *p,
  132745. int iLangid,
  132746. int iIndex,
  132747. sqlite3_int64 *pnMax
  132748. ){
  132749. sqlite3_stmt *pStmt;
  132750. int rc;
  132751. assert( iIndex>=0 && iIndex<p->nIndex );
  132752. /* Set pStmt to the compiled version of:
  132753. **
  132754. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  132755. **
  132756. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  132757. */
  132758. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  132759. if( rc!=SQLITE_OK ) return rc;
  132760. sqlite3_bind_int64(pStmt, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  132761. sqlite3_bind_int64(pStmt, 2,
  132762. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  132763. );
  132764. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  132765. *pnMax = sqlite3_column_int64(pStmt, 0);
  132766. }
  132767. return sqlite3_reset(pStmt);
  132768. }
  132769. /*
  132770. ** iAbsLevel is an absolute level that may be assumed to exist within
  132771. ** the database. This function checks if it is the largest level number
  132772. ** within its index. Assuming no error occurs, *pbMax is set to 1 if
  132773. ** iAbsLevel is indeed the largest level, or 0 otherwise, and SQLITE_OK
  132774. ** is returned. If an error occurs, an error code is returned and the
  132775. ** final value of *pbMax is undefined.
  132776. */
  132777. static int fts3SegmentIsMaxLevel(Fts3Table *p, i64 iAbsLevel, int *pbMax){
  132778. /* Set pStmt to the compiled version of:
  132779. **
  132780. ** SELECT max(level) FROM %Q.'%q_segdir' WHERE level BETWEEN ? AND ?
  132781. **
  132782. ** (1024 is actually the value of macro FTS3_SEGDIR_PREFIXLEVEL_STR).
  132783. */
  132784. sqlite3_stmt *pStmt;
  132785. int rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR_MAX_LEVEL, &pStmt, 0);
  132786. if( rc!=SQLITE_OK ) return rc;
  132787. sqlite3_bind_int64(pStmt, 1, iAbsLevel+1);
  132788. sqlite3_bind_int64(pStmt, 2,
  132789. ((iAbsLevel/FTS3_SEGDIR_MAXLEVEL)+1) * FTS3_SEGDIR_MAXLEVEL
  132790. );
  132791. *pbMax = 0;
  132792. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  132793. *pbMax = sqlite3_column_type(pStmt, 0)==SQLITE_NULL;
  132794. }
  132795. return sqlite3_reset(pStmt);
  132796. }
  132797. /*
  132798. ** Delete all entries in the %_segments table associated with the segment
  132799. ** opened with seg-reader pSeg. This function does not affect the contents
  132800. ** of the %_segdir table.
  132801. */
  132802. static int fts3DeleteSegment(
  132803. Fts3Table *p, /* FTS table handle */
  132804. Fts3SegReader *pSeg /* Segment to delete */
  132805. ){
  132806. int rc = SQLITE_OK; /* Return code */
  132807. if( pSeg->iStartBlock ){
  132808. sqlite3_stmt *pDelete; /* SQL statement to delete rows */
  132809. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDelete, 0);
  132810. if( rc==SQLITE_OK ){
  132811. sqlite3_bind_int64(pDelete, 1, pSeg->iStartBlock);
  132812. sqlite3_bind_int64(pDelete, 2, pSeg->iEndBlock);
  132813. sqlite3_step(pDelete);
  132814. rc = sqlite3_reset(pDelete);
  132815. }
  132816. }
  132817. return rc;
  132818. }
  132819. /*
  132820. ** This function is used after merging multiple segments into a single large
  132821. ** segment to delete the old, now redundant, segment b-trees. Specifically,
  132822. ** it:
  132823. **
  132824. ** 1) Deletes all %_segments entries for the segments associated with
  132825. ** each of the SegReader objects in the array passed as the third
  132826. ** argument, and
  132827. **
  132828. ** 2) deletes all %_segdir entries with level iLevel, or all %_segdir
  132829. ** entries regardless of level if (iLevel<0).
  132830. **
  132831. ** SQLITE_OK is returned if successful, otherwise an SQLite error code.
  132832. */
  132833. static int fts3DeleteSegdir(
  132834. Fts3Table *p, /* Virtual table handle */
  132835. int iLangid, /* Language id */
  132836. int iIndex, /* Index for p->aIndex */
  132837. int iLevel, /* Level of %_segdir entries to delete */
  132838. Fts3SegReader **apSegment, /* Array of SegReader objects */
  132839. int nReader /* Size of array apSegment */
  132840. ){
  132841. int rc = SQLITE_OK; /* Return Code */
  132842. int i; /* Iterator variable */
  132843. sqlite3_stmt *pDelete = 0; /* SQL statement to delete rows */
  132844. for(i=0; rc==SQLITE_OK && i<nReader; i++){
  132845. rc = fts3DeleteSegment(p, apSegment[i]);
  132846. }
  132847. if( rc!=SQLITE_OK ){
  132848. return rc;
  132849. }
  132850. assert( iLevel>=0 || iLevel==FTS3_SEGCURSOR_ALL );
  132851. if( iLevel==FTS3_SEGCURSOR_ALL ){
  132852. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_RANGE, &pDelete, 0);
  132853. if( rc==SQLITE_OK ){
  132854. sqlite3_bind_int64(pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, 0));
  132855. sqlite3_bind_int64(pDelete, 2,
  132856. getAbsoluteLevel(p, iLangid, iIndex, FTS3_SEGDIR_MAXLEVEL-1)
  132857. );
  132858. }
  132859. }else{
  132860. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_LEVEL, &pDelete, 0);
  132861. if( rc==SQLITE_OK ){
  132862. sqlite3_bind_int64(
  132863. pDelete, 1, getAbsoluteLevel(p, iLangid, iIndex, iLevel)
  132864. );
  132865. }
  132866. }
  132867. if( rc==SQLITE_OK ){
  132868. sqlite3_step(pDelete);
  132869. rc = sqlite3_reset(pDelete);
  132870. }
  132871. return rc;
  132872. }
  132873. /*
  132874. ** When this function is called, buffer *ppList (size *pnList bytes) contains
  132875. ** a position list that may (or may not) feature multiple columns. This
  132876. ** function adjusts the pointer *ppList and the length *pnList so that they
  132877. ** identify the subset of the position list that corresponds to column iCol.
  132878. **
  132879. ** If there are no entries in the input position list for column iCol, then
  132880. ** *pnList is set to zero before returning.
  132881. **
  132882. ** If parameter bZero is non-zero, then any part of the input list following
  132883. ** the end of the output list is zeroed before returning.
  132884. */
  132885. static void fts3ColumnFilter(
  132886. int iCol, /* Column to filter on */
  132887. int bZero, /* Zero out anything following *ppList */
  132888. char **ppList, /* IN/OUT: Pointer to position list */
  132889. int *pnList /* IN/OUT: Size of buffer *ppList in bytes */
  132890. ){
  132891. char *pList = *ppList;
  132892. int nList = *pnList;
  132893. char *pEnd = &pList[nList];
  132894. int iCurrent = 0;
  132895. char *p = pList;
  132896. assert( iCol>=0 );
  132897. while( 1 ){
  132898. char c = 0;
  132899. while( p<pEnd && (c | *p)&0xFE ) c = *p++ & 0x80;
  132900. if( iCol==iCurrent ){
  132901. nList = (int)(p - pList);
  132902. break;
  132903. }
  132904. nList -= (int)(p - pList);
  132905. pList = p;
  132906. if( nList==0 ){
  132907. break;
  132908. }
  132909. p = &pList[1];
  132910. p += fts3GetVarint32(p, &iCurrent);
  132911. }
  132912. if( bZero && &pList[nList]!=pEnd ){
  132913. memset(&pList[nList], 0, pEnd - &pList[nList]);
  132914. }
  132915. *ppList = pList;
  132916. *pnList = nList;
  132917. }
  132918. /*
  132919. ** Cache data in the Fts3MultiSegReader.aBuffer[] buffer (overwriting any
  132920. ** existing data). Grow the buffer if required.
  132921. **
  132922. ** If successful, return SQLITE_OK. Otherwise, if an OOM error is encountered
  132923. ** trying to resize the buffer, return SQLITE_NOMEM.
  132924. */
  132925. static int fts3MsrBufferData(
  132926. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  132927. char *pList,
  132928. int nList
  132929. ){
  132930. if( nList>pMsr->nBuffer ){
  132931. char *pNew;
  132932. pMsr->nBuffer = nList*2;
  132933. pNew = (char *)sqlite3_realloc(pMsr->aBuffer, pMsr->nBuffer);
  132934. if( !pNew ) return SQLITE_NOMEM;
  132935. pMsr->aBuffer = pNew;
  132936. }
  132937. memcpy(pMsr->aBuffer, pList, nList);
  132938. return SQLITE_OK;
  132939. }
  132940. SQLITE_PRIVATE int sqlite3Fts3MsrIncrNext(
  132941. Fts3Table *p, /* Virtual table handle */
  132942. Fts3MultiSegReader *pMsr, /* Multi-segment-reader handle */
  132943. sqlite3_int64 *piDocid, /* OUT: Docid value */
  132944. char **paPoslist, /* OUT: Pointer to position list */
  132945. int *pnPoslist /* OUT: Size of position list in bytes */
  132946. ){
  132947. int nMerge = pMsr->nAdvance;
  132948. Fts3SegReader **apSegment = pMsr->apSegment;
  132949. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  132950. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  132951. );
  132952. if( nMerge==0 ){
  132953. *paPoslist = 0;
  132954. return SQLITE_OK;
  132955. }
  132956. while( 1 ){
  132957. Fts3SegReader *pSeg;
  132958. pSeg = pMsr->apSegment[0];
  132959. if( pSeg->pOffsetList==0 ){
  132960. *paPoslist = 0;
  132961. break;
  132962. }else{
  132963. int rc;
  132964. char *pList;
  132965. int nList;
  132966. int j;
  132967. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  132968. rc = fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  132969. j = 1;
  132970. while( rc==SQLITE_OK
  132971. && j<nMerge
  132972. && apSegment[j]->pOffsetList
  132973. && apSegment[j]->iDocid==iDocid
  132974. ){
  132975. rc = fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  132976. j++;
  132977. }
  132978. if( rc!=SQLITE_OK ) return rc;
  132979. fts3SegReaderSort(pMsr->apSegment, nMerge, j, xCmp);
  132980. if( nList>0 && fts3SegReaderIsPending(apSegment[0]) ){
  132981. rc = fts3MsrBufferData(pMsr, pList, nList+1);
  132982. if( rc!=SQLITE_OK ) return rc;
  132983. assert( (pMsr->aBuffer[nList] & 0xFE)==0x00 );
  132984. pList = pMsr->aBuffer;
  132985. }
  132986. if( pMsr->iColFilter>=0 ){
  132987. fts3ColumnFilter(pMsr->iColFilter, 1, &pList, &nList);
  132988. }
  132989. if( nList>0 ){
  132990. *paPoslist = pList;
  132991. *piDocid = iDocid;
  132992. *pnPoslist = nList;
  132993. break;
  132994. }
  132995. }
  132996. }
  132997. return SQLITE_OK;
  132998. }
  132999. static int fts3SegReaderStart(
  133000. Fts3Table *p, /* Virtual table handle */
  133001. Fts3MultiSegReader *pCsr, /* Cursor object */
  133002. const char *zTerm, /* Term searched for (or NULL) */
  133003. int nTerm /* Length of zTerm in bytes */
  133004. ){
  133005. int i;
  133006. int nSeg = pCsr->nSegment;
  133007. /* If the Fts3SegFilter defines a specific term (or term prefix) to search
  133008. ** for, then advance each segment iterator until it points to a term of
  133009. ** equal or greater value than the specified term. This prevents many
  133010. ** unnecessary merge/sort operations for the case where single segment
  133011. ** b-tree leaf nodes contain more than one term.
  133012. */
  133013. for(i=0; pCsr->bRestart==0 && i<pCsr->nSegment; i++){
  133014. int res = 0;
  133015. Fts3SegReader *pSeg = pCsr->apSegment[i];
  133016. do {
  133017. int rc = fts3SegReaderNext(p, pSeg, 0);
  133018. if( rc!=SQLITE_OK ) return rc;
  133019. }while( zTerm && (res = fts3SegReaderTermCmp(pSeg, zTerm, nTerm))<0 );
  133020. if( pSeg->bLookup && res!=0 ){
  133021. fts3SegReaderSetEof(pSeg);
  133022. }
  133023. }
  133024. fts3SegReaderSort(pCsr->apSegment, nSeg, nSeg, fts3SegReaderCmp);
  133025. return SQLITE_OK;
  133026. }
  133027. SQLITE_PRIVATE int sqlite3Fts3SegReaderStart(
  133028. Fts3Table *p, /* Virtual table handle */
  133029. Fts3MultiSegReader *pCsr, /* Cursor object */
  133030. Fts3SegFilter *pFilter /* Restrictions on range of iteration */
  133031. ){
  133032. pCsr->pFilter = pFilter;
  133033. return fts3SegReaderStart(p, pCsr, pFilter->zTerm, pFilter->nTerm);
  133034. }
  133035. SQLITE_PRIVATE int sqlite3Fts3MsrIncrStart(
  133036. Fts3Table *p, /* Virtual table handle */
  133037. Fts3MultiSegReader *pCsr, /* Cursor object */
  133038. int iCol, /* Column to match on. */
  133039. const char *zTerm, /* Term to iterate through a doclist for */
  133040. int nTerm /* Number of bytes in zTerm */
  133041. ){
  133042. int i;
  133043. int rc;
  133044. int nSegment = pCsr->nSegment;
  133045. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  133046. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  133047. );
  133048. assert( pCsr->pFilter==0 );
  133049. assert( zTerm && nTerm>0 );
  133050. /* Advance each segment iterator until it points to the term zTerm/nTerm. */
  133051. rc = fts3SegReaderStart(p, pCsr, zTerm, nTerm);
  133052. if( rc!=SQLITE_OK ) return rc;
  133053. /* Determine how many of the segments actually point to zTerm/nTerm. */
  133054. for(i=0; i<nSegment; i++){
  133055. Fts3SegReader *pSeg = pCsr->apSegment[i];
  133056. if( !pSeg->aNode || fts3SegReaderTermCmp(pSeg, zTerm, nTerm) ){
  133057. break;
  133058. }
  133059. }
  133060. pCsr->nAdvance = i;
  133061. /* Advance each of the segments to point to the first docid. */
  133062. for(i=0; i<pCsr->nAdvance; i++){
  133063. rc = fts3SegReaderFirstDocid(p, pCsr->apSegment[i]);
  133064. if( rc!=SQLITE_OK ) return rc;
  133065. }
  133066. fts3SegReaderSort(pCsr->apSegment, i, i, xCmp);
  133067. assert( iCol<0 || iCol<p->nColumn );
  133068. pCsr->iColFilter = iCol;
  133069. return SQLITE_OK;
  133070. }
  133071. /*
  133072. ** This function is called on a MultiSegReader that has been started using
  133073. ** sqlite3Fts3MsrIncrStart(). One or more calls to MsrIncrNext() may also
  133074. ** have been made. Calling this function puts the MultiSegReader in such
  133075. ** a state that if the next two calls are:
  133076. **
  133077. ** sqlite3Fts3SegReaderStart()
  133078. ** sqlite3Fts3SegReaderStep()
  133079. **
  133080. ** then the entire doclist for the term is available in
  133081. ** MultiSegReader.aDoclist/nDoclist.
  133082. */
  133083. SQLITE_PRIVATE int sqlite3Fts3MsrIncrRestart(Fts3MultiSegReader *pCsr){
  133084. int i; /* Used to iterate through segment-readers */
  133085. assert( pCsr->zTerm==0 );
  133086. assert( pCsr->nTerm==0 );
  133087. assert( pCsr->aDoclist==0 );
  133088. assert( pCsr->nDoclist==0 );
  133089. pCsr->nAdvance = 0;
  133090. pCsr->bRestart = 1;
  133091. for(i=0; i<pCsr->nSegment; i++){
  133092. pCsr->apSegment[i]->pOffsetList = 0;
  133093. pCsr->apSegment[i]->nOffsetList = 0;
  133094. pCsr->apSegment[i]->iDocid = 0;
  133095. }
  133096. return SQLITE_OK;
  133097. }
  133098. SQLITE_PRIVATE int sqlite3Fts3SegReaderStep(
  133099. Fts3Table *p, /* Virtual table handle */
  133100. Fts3MultiSegReader *pCsr /* Cursor object */
  133101. ){
  133102. int rc = SQLITE_OK;
  133103. int isIgnoreEmpty = (pCsr->pFilter->flags & FTS3_SEGMENT_IGNORE_EMPTY);
  133104. int isRequirePos = (pCsr->pFilter->flags & FTS3_SEGMENT_REQUIRE_POS);
  133105. int isColFilter = (pCsr->pFilter->flags & FTS3_SEGMENT_COLUMN_FILTER);
  133106. int isPrefix = (pCsr->pFilter->flags & FTS3_SEGMENT_PREFIX);
  133107. int isScan = (pCsr->pFilter->flags & FTS3_SEGMENT_SCAN);
  133108. int isFirst = (pCsr->pFilter->flags & FTS3_SEGMENT_FIRST);
  133109. Fts3SegReader **apSegment = pCsr->apSegment;
  133110. int nSegment = pCsr->nSegment;
  133111. Fts3SegFilter *pFilter = pCsr->pFilter;
  133112. int (*xCmp)(Fts3SegReader *, Fts3SegReader *) = (
  133113. p->bDescIdx ? fts3SegReaderDoclistCmpRev : fts3SegReaderDoclistCmp
  133114. );
  133115. if( pCsr->nSegment==0 ) return SQLITE_OK;
  133116. do {
  133117. int nMerge;
  133118. int i;
  133119. /* Advance the first pCsr->nAdvance entries in the apSegment[] array
  133120. ** forward. Then sort the list in order of current term again.
  133121. */
  133122. for(i=0; i<pCsr->nAdvance; i++){
  133123. Fts3SegReader *pSeg = apSegment[i];
  133124. if( pSeg->bLookup ){
  133125. fts3SegReaderSetEof(pSeg);
  133126. }else{
  133127. rc = fts3SegReaderNext(p, pSeg, 0);
  133128. }
  133129. if( rc!=SQLITE_OK ) return rc;
  133130. }
  133131. fts3SegReaderSort(apSegment, nSegment, pCsr->nAdvance, fts3SegReaderCmp);
  133132. pCsr->nAdvance = 0;
  133133. /* If all the seg-readers are at EOF, we're finished. return SQLITE_OK. */
  133134. assert( rc==SQLITE_OK );
  133135. if( apSegment[0]->aNode==0 ) break;
  133136. pCsr->nTerm = apSegment[0]->nTerm;
  133137. pCsr->zTerm = apSegment[0]->zTerm;
  133138. /* If this is a prefix-search, and if the term that apSegment[0] points
  133139. ** to does not share a suffix with pFilter->zTerm/nTerm, then all
  133140. ** required callbacks have been made. In this case exit early.
  133141. **
  133142. ** Similarly, if this is a search for an exact match, and the first term
  133143. ** of segment apSegment[0] is not a match, exit early.
  133144. */
  133145. if( pFilter->zTerm && !isScan ){
  133146. if( pCsr->nTerm<pFilter->nTerm
  133147. || (!isPrefix && pCsr->nTerm>pFilter->nTerm)
  133148. || memcmp(pCsr->zTerm, pFilter->zTerm, pFilter->nTerm)
  133149. ){
  133150. break;
  133151. }
  133152. }
  133153. nMerge = 1;
  133154. while( nMerge<nSegment
  133155. && apSegment[nMerge]->aNode
  133156. && apSegment[nMerge]->nTerm==pCsr->nTerm
  133157. && 0==memcmp(pCsr->zTerm, apSegment[nMerge]->zTerm, pCsr->nTerm)
  133158. ){
  133159. nMerge++;
  133160. }
  133161. assert( isIgnoreEmpty || (isRequirePos && !isColFilter) );
  133162. if( nMerge==1
  133163. && !isIgnoreEmpty
  133164. && !isFirst
  133165. && (p->bDescIdx==0 || fts3SegReaderIsPending(apSegment[0])==0)
  133166. ){
  133167. pCsr->nDoclist = apSegment[0]->nDoclist;
  133168. if( fts3SegReaderIsPending(apSegment[0]) ){
  133169. rc = fts3MsrBufferData(pCsr, apSegment[0]->aDoclist, pCsr->nDoclist);
  133170. pCsr->aDoclist = pCsr->aBuffer;
  133171. }else{
  133172. pCsr->aDoclist = apSegment[0]->aDoclist;
  133173. }
  133174. if( rc==SQLITE_OK ) rc = SQLITE_ROW;
  133175. }else{
  133176. int nDoclist = 0; /* Size of doclist */
  133177. sqlite3_int64 iPrev = 0; /* Previous docid stored in doclist */
  133178. /* The current term of the first nMerge entries in the array
  133179. ** of Fts3SegReader objects is the same. The doclists must be merged
  133180. ** and a single term returned with the merged doclist.
  133181. */
  133182. for(i=0; i<nMerge; i++){
  133183. fts3SegReaderFirstDocid(p, apSegment[i]);
  133184. }
  133185. fts3SegReaderSort(apSegment, nMerge, nMerge, xCmp);
  133186. while( apSegment[0]->pOffsetList ){
  133187. int j; /* Number of segments that share a docid */
  133188. char *pList = 0;
  133189. int nList = 0;
  133190. int nByte;
  133191. sqlite3_int64 iDocid = apSegment[0]->iDocid;
  133192. fts3SegReaderNextDocid(p, apSegment[0], &pList, &nList);
  133193. j = 1;
  133194. while( j<nMerge
  133195. && apSegment[j]->pOffsetList
  133196. && apSegment[j]->iDocid==iDocid
  133197. ){
  133198. fts3SegReaderNextDocid(p, apSegment[j], 0, 0);
  133199. j++;
  133200. }
  133201. if( isColFilter ){
  133202. fts3ColumnFilter(pFilter->iCol, 0, &pList, &nList);
  133203. }
  133204. if( !isIgnoreEmpty || nList>0 ){
  133205. /* Calculate the 'docid' delta value to write into the merged
  133206. ** doclist. */
  133207. sqlite3_int64 iDelta;
  133208. if( p->bDescIdx && nDoclist>0 ){
  133209. iDelta = iPrev - iDocid;
  133210. }else{
  133211. iDelta = iDocid - iPrev;
  133212. }
  133213. assert( iDelta>0 || (nDoclist==0 && iDelta==iDocid) );
  133214. assert( nDoclist>0 || iDelta==iDocid );
  133215. nByte = sqlite3Fts3VarintLen(iDelta) + (isRequirePos?nList+1:0);
  133216. if( nDoclist+nByte>pCsr->nBuffer ){
  133217. char *aNew;
  133218. pCsr->nBuffer = (nDoclist+nByte)*2;
  133219. aNew = sqlite3_realloc(pCsr->aBuffer, pCsr->nBuffer);
  133220. if( !aNew ){
  133221. return SQLITE_NOMEM;
  133222. }
  133223. pCsr->aBuffer = aNew;
  133224. }
  133225. if( isFirst ){
  133226. char *a = &pCsr->aBuffer[nDoclist];
  133227. int nWrite;
  133228. nWrite = sqlite3Fts3FirstFilter(iDelta, pList, nList, a);
  133229. if( nWrite ){
  133230. iPrev = iDocid;
  133231. nDoclist += nWrite;
  133232. }
  133233. }else{
  133234. nDoclist += sqlite3Fts3PutVarint(&pCsr->aBuffer[nDoclist], iDelta);
  133235. iPrev = iDocid;
  133236. if( isRequirePos ){
  133237. memcpy(&pCsr->aBuffer[nDoclist], pList, nList);
  133238. nDoclist += nList;
  133239. pCsr->aBuffer[nDoclist++] = '\0';
  133240. }
  133241. }
  133242. }
  133243. fts3SegReaderSort(apSegment, nMerge, j, xCmp);
  133244. }
  133245. if( nDoclist>0 ){
  133246. pCsr->aDoclist = pCsr->aBuffer;
  133247. pCsr->nDoclist = nDoclist;
  133248. rc = SQLITE_ROW;
  133249. }
  133250. }
  133251. pCsr->nAdvance = nMerge;
  133252. }while( rc==SQLITE_OK );
  133253. return rc;
  133254. }
  133255. SQLITE_PRIVATE void sqlite3Fts3SegReaderFinish(
  133256. Fts3MultiSegReader *pCsr /* Cursor object */
  133257. ){
  133258. if( pCsr ){
  133259. int i;
  133260. for(i=0; i<pCsr->nSegment; i++){
  133261. sqlite3Fts3SegReaderFree(pCsr->apSegment[i]);
  133262. }
  133263. sqlite3_free(pCsr->apSegment);
  133264. sqlite3_free(pCsr->aBuffer);
  133265. pCsr->nSegment = 0;
  133266. pCsr->apSegment = 0;
  133267. pCsr->aBuffer = 0;
  133268. }
  133269. }
  133270. /*
  133271. ** Decode the "end_block" field, selected by column iCol of the SELECT
  133272. ** statement passed as the first argument.
  133273. **
  133274. ** The "end_block" field may contain either an integer, or a text field
  133275. ** containing the text representation of two non-negative integers separated
  133276. ** by one or more space (0x20) characters. In the first case, set *piEndBlock
  133277. ** to the integer value and *pnByte to zero before returning. In the second,
  133278. ** set *piEndBlock to the first value and *pnByte to the second.
  133279. */
  133280. static void fts3ReadEndBlockField(
  133281. sqlite3_stmt *pStmt,
  133282. int iCol,
  133283. i64 *piEndBlock,
  133284. i64 *pnByte
  133285. ){
  133286. const unsigned char *zText = sqlite3_column_text(pStmt, iCol);
  133287. if( zText ){
  133288. int i;
  133289. int iMul = 1;
  133290. i64 iVal = 0;
  133291. for(i=0; zText[i]>='0' && zText[i]<='9'; i++){
  133292. iVal = iVal*10 + (zText[i] - '0');
  133293. }
  133294. *piEndBlock = iVal;
  133295. while( zText[i]==' ' ) i++;
  133296. iVal = 0;
  133297. if( zText[i]=='-' ){
  133298. i++;
  133299. iMul = -1;
  133300. }
  133301. for(/* no-op */; zText[i]>='0' && zText[i]<='9'; i++){
  133302. iVal = iVal*10 + (zText[i] - '0');
  133303. }
  133304. *pnByte = (iVal * (i64)iMul);
  133305. }
  133306. }
  133307. /*
  133308. ** A segment of size nByte bytes has just been written to absolute level
  133309. ** iAbsLevel. Promote any segments that should be promoted as a result.
  133310. */
  133311. static int fts3PromoteSegments(
  133312. Fts3Table *p, /* FTS table handle */
  133313. sqlite3_int64 iAbsLevel, /* Absolute level just updated */
  133314. sqlite3_int64 nByte /* Size of new segment at iAbsLevel */
  133315. ){
  133316. int rc = SQLITE_OK;
  133317. sqlite3_stmt *pRange;
  133318. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL_RANGE2, &pRange, 0);
  133319. if( rc==SQLITE_OK ){
  133320. int bOk = 0;
  133321. i64 iLast = (iAbsLevel/FTS3_SEGDIR_MAXLEVEL + 1) * FTS3_SEGDIR_MAXLEVEL - 1;
  133322. i64 nLimit = (nByte*3)/2;
  133323. /* Loop through all entries in the %_segdir table corresponding to
  133324. ** segments in this index on levels greater than iAbsLevel. If there is
  133325. ** at least one such segment, and it is possible to determine that all
  133326. ** such segments are smaller than nLimit bytes in size, they will be
  133327. ** promoted to level iAbsLevel. */
  133328. sqlite3_bind_int64(pRange, 1, iAbsLevel+1);
  133329. sqlite3_bind_int64(pRange, 2, iLast);
  133330. while( SQLITE_ROW==sqlite3_step(pRange) ){
  133331. i64 nSize = 0, dummy;
  133332. fts3ReadEndBlockField(pRange, 2, &dummy, &nSize);
  133333. if( nSize<=0 || nSize>nLimit ){
  133334. /* If nSize==0, then the %_segdir.end_block field does not not
  133335. ** contain a size value. This happens if it was written by an
  133336. ** old version of FTS. In this case it is not possible to determine
  133337. ** the size of the segment, and so segment promotion does not
  133338. ** take place. */
  133339. bOk = 0;
  133340. break;
  133341. }
  133342. bOk = 1;
  133343. }
  133344. rc = sqlite3_reset(pRange);
  133345. if( bOk ){
  133346. int iIdx = 0;
  133347. sqlite3_stmt *pUpdate1;
  133348. sqlite3_stmt *pUpdate2;
  133349. if( rc==SQLITE_OK ){
  133350. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL_IDX, &pUpdate1, 0);
  133351. }
  133352. if( rc==SQLITE_OK ){
  133353. rc = fts3SqlStmt(p, SQL_UPDATE_LEVEL, &pUpdate2, 0);
  133354. }
  133355. if( rc==SQLITE_OK ){
  133356. /* Loop through all %_segdir entries for segments in this index with
  133357. ** levels equal to or greater than iAbsLevel. As each entry is visited,
  133358. ** updated it to set (level = -1) and (idx = N), where N is 0 for the
  133359. ** oldest segment in the range, 1 for the next oldest, and so on.
  133360. **
  133361. ** In other words, move all segments being promoted to level -1,
  133362. ** setting the "idx" fields as appropriate to keep them in the same
  133363. ** order. The contents of level -1 (which is never used, except
  133364. ** transiently here), will be moved back to level iAbsLevel below. */
  133365. sqlite3_bind_int64(pRange, 1, iAbsLevel);
  133366. while( SQLITE_ROW==sqlite3_step(pRange) ){
  133367. sqlite3_bind_int(pUpdate1, 1, iIdx++);
  133368. sqlite3_bind_int(pUpdate1, 2, sqlite3_column_int(pRange, 0));
  133369. sqlite3_bind_int(pUpdate1, 3, sqlite3_column_int(pRange, 1));
  133370. sqlite3_step(pUpdate1);
  133371. rc = sqlite3_reset(pUpdate1);
  133372. if( rc!=SQLITE_OK ){
  133373. sqlite3_reset(pRange);
  133374. break;
  133375. }
  133376. }
  133377. }
  133378. if( rc==SQLITE_OK ){
  133379. rc = sqlite3_reset(pRange);
  133380. }
  133381. /* Move level -1 to level iAbsLevel */
  133382. if( rc==SQLITE_OK ){
  133383. sqlite3_bind_int64(pUpdate2, 1, iAbsLevel);
  133384. sqlite3_step(pUpdate2);
  133385. rc = sqlite3_reset(pUpdate2);
  133386. }
  133387. }
  133388. }
  133389. return rc;
  133390. }
  133391. /*
  133392. ** Merge all level iLevel segments in the database into a single
  133393. ** iLevel+1 segment. Or, if iLevel<0, merge all segments into a
  133394. ** single segment with a level equal to the numerically largest level
  133395. ** currently present in the database.
  133396. **
  133397. ** If this function is called with iLevel<0, but there is only one
  133398. ** segment in the database, SQLITE_DONE is returned immediately.
  133399. ** Otherwise, if successful, SQLITE_OK is returned. If an error occurs,
  133400. ** an SQLite error code is returned.
  133401. */
  133402. static int fts3SegmentMerge(
  133403. Fts3Table *p,
  133404. int iLangid, /* Language id to merge */
  133405. int iIndex, /* Index in p->aIndex[] to merge */
  133406. int iLevel /* Level to merge */
  133407. ){
  133408. int rc; /* Return code */
  133409. int iIdx = 0; /* Index of new segment */
  133410. sqlite3_int64 iNewLevel = 0; /* Level/index to create new segment at */
  133411. SegmentWriter *pWriter = 0; /* Used to write the new, merged, segment */
  133412. Fts3SegFilter filter; /* Segment term filter condition */
  133413. Fts3MultiSegReader csr; /* Cursor to iterate through level(s) */
  133414. int bIgnoreEmpty = 0; /* True to ignore empty segments */
  133415. i64 iMaxLevel = 0; /* Max level number for this index/langid */
  133416. assert( iLevel==FTS3_SEGCURSOR_ALL
  133417. || iLevel==FTS3_SEGCURSOR_PENDING
  133418. || iLevel>=0
  133419. );
  133420. assert( iLevel<FTS3_SEGDIR_MAXLEVEL );
  133421. assert( iIndex>=0 && iIndex<p->nIndex );
  133422. rc = sqlite3Fts3SegReaderCursor(p, iLangid, iIndex, iLevel, 0, 0, 1, 0, &csr);
  133423. if( rc!=SQLITE_OK || csr.nSegment==0 ) goto finished;
  133424. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  133425. rc = fts3SegmentMaxLevel(p, iLangid, iIndex, &iMaxLevel);
  133426. if( rc!=SQLITE_OK ) goto finished;
  133427. }
  133428. if( iLevel==FTS3_SEGCURSOR_ALL ){
  133429. /* This call is to merge all segments in the database to a single
  133430. ** segment. The level of the new segment is equal to the numerically
  133431. ** greatest segment level currently present in the database for this
  133432. ** index. The idx of the new segment is always 0. */
  133433. if( csr.nSegment==1 ){
  133434. rc = SQLITE_DONE;
  133435. goto finished;
  133436. }
  133437. iNewLevel = iMaxLevel;
  133438. bIgnoreEmpty = 1;
  133439. }else{
  133440. /* This call is to merge all segments at level iLevel. find the next
  133441. ** available segment index at level iLevel+1. The call to
  133442. ** fts3AllocateSegdirIdx() will merge the segments at level iLevel+1 to
  133443. ** a single iLevel+2 segment if necessary. */
  133444. assert( FTS3_SEGCURSOR_PENDING==-1 );
  133445. iNewLevel = getAbsoluteLevel(p, iLangid, iIndex, iLevel+1);
  133446. rc = fts3AllocateSegdirIdx(p, iLangid, iIndex, iLevel+1, &iIdx);
  133447. bIgnoreEmpty = (iLevel!=FTS3_SEGCURSOR_PENDING) && (iNewLevel>iMaxLevel);
  133448. }
  133449. if( rc!=SQLITE_OK ) goto finished;
  133450. assert( csr.nSegment>0 );
  133451. assert( iNewLevel>=getAbsoluteLevel(p, iLangid, iIndex, 0) );
  133452. assert( iNewLevel<getAbsoluteLevel(p, iLangid, iIndex,FTS3_SEGDIR_MAXLEVEL) );
  133453. memset(&filter, 0, sizeof(Fts3SegFilter));
  133454. filter.flags = FTS3_SEGMENT_REQUIRE_POS;
  133455. filter.flags |= (bIgnoreEmpty ? FTS3_SEGMENT_IGNORE_EMPTY : 0);
  133456. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  133457. while( SQLITE_OK==rc ){
  133458. rc = sqlite3Fts3SegReaderStep(p, &csr);
  133459. if( rc!=SQLITE_ROW ) break;
  133460. rc = fts3SegWriterAdd(p, &pWriter, 1,
  133461. csr.zTerm, csr.nTerm, csr.aDoclist, csr.nDoclist);
  133462. }
  133463. if( rc!=SQLITE_OK ) goto finished;
  133464. assert( pWriter || bIgnoreEmpty );
  133465. if( iLevel!=FTS3_SEGCURSOR_PENDING ){
  133466. rc = fts3DeleteSegdir(
  133467. p, iLangid, iIndex, iLevel, csr.apSegment, csr.nSegment
  133468. );
  133469. if( rc!=SQLITE_OK ) goto finished;
  133470. }
  133471. if( pWriter ){
  133472. rc = fts3SegWriterFlush(p, pWriter, iNewLevel, iIdx);
  133473. if( rc==SQLITE_OK ){
  133474. if( iLevel==FTS3_SEGCURSOR_PENDING || iNewLevel<iMaxLevel ){
  133475. rc = fts3PromoteSegments(p, iNewLevel, pWriter->nLeafData);
  133476. }
  133477. }
  133478. }
  133479. finished:
  133480. fts3SegWriterFree(pWriter);
  133481. sqlite3Fts3SegReaderFinish(&csr);
  133482. return rc;
  133483. }
  133484. /*
  133485. ** Flush the contents of pendingTerms to level 0 segments.
  133486. */
  133487. SQLITE_PRIVATE int sqlite3Fts3PendingTermsFlush(Fts3Table *p){
  133488. int rc = SQLITE_OK;
  133489. int i;
  133490. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  133491. rc = fts3SegmentMerge(p, p->iPrevLangid, i, FTS3_SEGCURSOR_PENDING);
  133492. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  133493. }
  133494. sqlite3Fts3PendingTermsClear(p);
  133495. /* Determine the auto-incr-merge setting if unknown. If enabled,
  133496. ** estimate the number of leaf blocks of content to be written
  133497. */
  133498. if( rc==SQLITE_OK && p->bHasStat
  133499. && p->nAutoincrmerge==0xff && p->nLeafAdd>0
  133500. ){
  133501. sqlite3_stmt *pStmt = 0;
  133502. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  133503. if( rc==SQLITE_OK ){
  133504. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  133505. rc = sqlite3_step(pStmt);
  133506. if( rc==SQLITE_ROW ){
  133507. p->nAutoincrmerge = sqlite3_column_int(pStmt, 0);
  133508. if( p->nAutoincrmerge==1 ) p->nAutoincrmerge = 8;
  133509. }else if( rc==SQLITE_DONE ){
  133510. p->nAutoincrmerge = 0;
  133511. }
  133512. rc = sqlite3_reset(pStmt);
  133513. }
  133514. }
  133515. return rc;
  133516. }
  133517. /*
  133518. ** Encode N integers as varints into a blob.
  133519. */
  133520. static void fts3EncodeIntArray(
  133521. int N, /* The number of integers to encode */
  133522. u32 *a, /* The integer values */
  133523. char *zBuf, /* Write the BLOB here */
  133524. int *pNBuf /* Write number of bytes if zBuf[] used here */
  133525. ){
  133526. int i, j;
  133527. for(i=j=0; i<N; i++){
  133528. j += sqlite3Fts3PutVarint(&zBuf[j], (sqlite3_int64)a[i]);
  133529. }
  133530. *pNBuf = j;
  133531. }
  133532. /*
  133533. ** Decode a blob of varints into N integers
  133534. */
  133535. static void fts3DecodeIntArray(
  133536. int N, /* The number of integers to decode */
  133537. u32 *a, /* Write the integer values */
  133538. const char *zBuf, /* The BLOB containing the varints */
  133539. int nBuf /* size of the BLOB */
  133540. ){
  133541. int i, j;
  133542. UNUSED_PARAMETER(nBuf);
  133543. for(i=j=0; i<N; i++){
  133544. sqlite3_int64 x;
  133545. j += sqlite3Fts3GetVarint(&zBuf[j], &x);
  133546. assert(j<=nBuf);
  133547. a[i] = (u32)(x & 0xffffffff);
  133548. }
  133549. }
  133550. /*
  133551. ** Insert the sizes (in tokens) for each column of the document
  133552. ** with docid equal to p->iPrevDocid. The sizes are encoded as
  133553. ** a blob of varints.
  133554. */
  133555. static void fts3InsertDocsize(
  133556. int *pRC, /* Result code */
  133557. Fts3Table *p, /* Table into which to insert */
  133558. u32 *aSz /* Sizes of each column, in tokens */
  133559. ){
  133560. char *pBlob; /* The BLOB encoding of the document size */
  133561. int nBlob; /* Number of bytes in the BLOB */
  133562. sqlite3_stmt *pStmt; /* Statement used to insert the encoding */
  133563. int rc; /* Result code from subfunctions */
  133564. if( *pRC ) return;
  133565. pBlob = sqlite3_malloc( 10*p->nColumn );
  133566. if( pBlob==0 ){
  133567. *pRC = SQLITE_NOMEM;
  133568. return;
  133569. }
  133570. fts3EncodeIntArray(p->nColumn, aSz, pBlob, &nBlob);
  133571. rc = fts3SqlStmt(p, SQL_REPLACE_DOCSIZE, &pStmt, 0);
  133572. if( rc ){
  133573. sqlite3_free(pBlob);
  133574. *pRC = rc;
  133575. return;
  133576. }
  133577. sqlite3_bind_int64(pStmt, 1, p->iPrevDocid);
  133578. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, sqlite3_free);
  133579. sqlite3_step(pStmt);
  133580. *pRC = sqlite3_reset(pStmt);
  133581. }
  133582. /*
  133583. ** Record 0 of the %_stat table contains a blob consisting of N varints,
  133584. ** where N is the number of user defined columns in the fts3 table plus
  133585. ** two. If nCol is the number of user defined columns, then values of the
  133586. ** varints are set as follows:
  133587. **
  133588. ** Varint 0: Total number of rows in the table.
  133589. **
  133590. ** Varint 1..nCol: For each column, the total number of tokens stored in
  133591. ** the column for all rows of the table.
  133592. **
  133593. ** Varint 1+nCol: The total size, in bytes, of all text values in all
  133594. ** columns of all rows of the table.
  133595. **
  133596. */
  133597. static void fts3UpdateDocTotals(
  133598. int *pRC, /* The result code */
  133599. Fts3Table *p, /* Table being updated */
  133600. u32 *aSzIns, /* Size increases */
  133601. u32 *aSzDel, /* Size decreases */
  133602. int nChng /* Change in the number of documents */
  133603. ){
  133604. char *pBlob; /* Storage for BLOB written into %_stat */
  133605. int nBlob; /* Size of BLOB written into %_stat */
  133606. u32 *a; /* Array of integers that becomes the BLOB */
  133607. sqlite3_stmt *pStmt; /* Statement for reading and writing */
  133608. int i; /* Loop counter */
  133609. int rc; /* Result code from subfunctions */
  133610. const int nStat = p->nColumn+2;
  133611. if( *pRC ) return;
  133612. a = sqlite3_malloc( (sizeof(u32)+10)*nStat );
  133613. if( a==0 ){
  133614. *pRC = SQLITE_NOMEM;
  133615. return;
  133616. }
  133617. pBlob = (char*)&a[nStat];
  133618. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pStmt, 0);
  133619. if( rc ){
  133620. sqlite3_free(a);
  133621. *pRC = rc;
  133622. return;
  133623. }
  133624. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  133625. if( sqlite3_step(pStmt)==SQLITE_ROW ){
  133626. fts3DecodeIntArray(nStat, a,
  133627. sqlite3_column_blob(pStmt, 0),
  133628. sqlite3_column_bytes(pStmt, 0));
  133629. }else{
  133630. memset(a, 0, sizeof(u32)*(nStat) );
  133631. }
  133632. rc = sqlite3_reset(pStmt);
  133633. if( rc!=SQLITE_OK ){
  133634. sqlite3_free(a);
  133635. *pRC = rc;
  133636. return;
  133637. }
  133638. if( nChng<0 && a[0]<(u32)(-nChng) ){
  133639. a[0] = 0;
  133640. }else{
  133641. a[0] += nChng;
  133642. }
  133643. for(i=0; i<p->nColumn+1; i++){
  133644. u32 x = a[i+1];
  133645. if( x+aSzIns[i] < aSzDel[i] ){
  133646. x = 0;
  133647. }else{
  133648. x = x + aSzIns[i] - aSzDel[i];
  133649. }
  133650. a[i+1] = x;
  133651. }
  133652. fts3EncodeIntArray(nStat, a, pBlob, &nBlob);
  133653. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  133654. if( rc ){
  133655. sqlite3_free(a);
  133656. *pRC = rc;
  133657. return;
  133658. }
  133659. sqlite3_bind_int(pStmt, 1, FTS_STAT_DOCTOTAL);
  133660. sqlite3_bind_blob(pStmt, 2, pBlob, nBlob, SQLITE_STATIC);
  133661. sqlite3_step(pStmt);
  133662. *pRC = sqlite3_reset(pStmt);
  133663. sqlite3_free(a);
  133664. }
  133665. /*
  133666. ** Merge the entire database so that there is one segment for each
  133667. ** iIndex/iLangid combination.
  133668. */
  133669. static int fts3DoOptimize(Fts3Table *p, int bReturnDone){
  133670. int bSeenDone = 0;
  133671. int rc;
  133672. sqlite3_stmt *pAllLangid = 0;
  133673. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  133674. if( rc==SQLITE_OK ){
  133675. int rc2;
  133676. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  133677. while( sqlite3_step(pAllLangid)==SQLITE_ROW ){
  133678. int i;
  133679. int iLangid = sqlite3_column_int(pAllLangid, 0);
  133680. for(i=0; rc==SQLITE_OK && i<p->nIndex; i++){
  133681. rc = fts3SegmentMerge(p, iLangid, i, FTS3_SEGCURSOR_ALL);
  133682. if( rc==SQLITE_DONE ){
  133683. bSeenDone = 1;
  133684. rc = SQLITE_OK;
  133685. }
  133686. }
  133687. }
  133688. rc2 = sqlite3_reset(pAllLangid);
  133689. if( rc==SQLITE_OK ) rc = rc2;
  133690. }
  133691. sqlite3Fts3SegmentsClose(p);
  133692. sqlite3Fts3PendingTermsClear(p);
  133693. return (rc==SQLITE_OK && bReturnDone && bSeenDone) ? SQLITE_DONE : rc;
  133694. }
  133695. /*
  133696. ** This function is called when the user executes the following statement:
  133697. **
  133698. ** INSERT INTO <tbl>(<tbl>) VALUES('rebuild');
  133699. **
  133700. ** The entire FTS index is discarded and rebuilt. If the table is one
  133701. ** created using the content=xxx option, then the new index is based on
  133702. ** the current contents of the xxx table. Otherwise, it is rebuilt based
  133703. ** on the contents of the %_content table.
  133704. */
  133705. static int fts3DoRebuild(Fts3Table *p){
  133706. int rc; /* Return Code */
  133707. rc = fts3DeleteAll(p, 0);
  133708. if( rc==SQLITE_OK ){
  133709. u32 *aSz = 0;
  133710. u32 *aSzIns = 0;
  133711. u32 *aSzDel = 0;
  133712. sqlite3_stmt *pStmt = 0;
  133713. int nEntry = 0;
  133714. /* Compose and prepare an SQL statement to loop through the content table */
  133715. char *zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  133716. if( !zSql ){
  133717. rc = SQLITE_NOMEM;
  133718. }else{
  133719. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  133720. sqlite3_free(zSql);
  133721. }
  133722. if( rc==SQLITE_OK ){
  133723. int nByte = sizeof(u32) * (p->nColumn+1)*3;
  133724. aSz = (u32 *)sqlite3_malloc(nByte);
  133725. if( aSz==0 ){
  133726. rc = SQLITE_NOMEM;
  133727. }else{
  133728. memset(aSz, 0, nByte);
  133729. aSzIns = &aSz[p->nColumn+1];
  133730. aSzDel = &aSzIns[p->nColumn+1];
  133731. }
  133732. }
  133733. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  133734. int iCol;
  133735. int iLangid = langidFromSelect(p, pStmt);
  133736. rc = fts3PendingTermsDocid(p, iLangid, sqlite3_column_int64(pStmt, 0));
  133737. memset(aSz, 0, sizeof(aSz[0]) * (p->nColumn+1));
  133738. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  133739. if( p->abNotindexed[iCol]==0 ){
  133740. const char *z = (const char *) sqlite3_column_text(pStmt, iCol+1);
  133741. rc = fts3PendingTermsAdd(p, iLangid, z, iCol, &aSz[iCol]);
  133742. aSz[p->nColumn] += sqlite3_column_bytes(pStmt, iCol+1);
  133743. }
  133744. }
  133745. if( p->bHasDocsize ){
  133746. fts3InsertDocsize(&rc, p, aSz);
  133747. }
  133748. if( rc!=SQLITE_OK ){
  133749. sqlite3_finalize(pStmt);
  133750. pStmt = 0;
  133751. }else{
  133752. nEntry++;
  133753. for(iCol=0; iCol<=p->nColumn; iCol++){
  133754. aSzIns[iCol] += aSz[iCol];
  133755. }
  133756. }
  133757. }
  133758. if( p->bFts4 ){
  133759. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nEntry);
  133760. }
  133761. sqlite3_free(aSz);
  133762. if( pStmt ){
  133763. int rc2 = sqlite3_finalize(pStmt);
  133764. if( rc==SQLITE_OK ){
  133765. rc = rc2;
  133766. }
  133767. }
  133768. }
  133769. return rc;
  133770. }
  133771. /*
  133772. ** This function opens a cursor used to read the input data for an
  133773. ** incremental merge operation. Specifically, it opens a cursor to scan
  133774. ** the oldest nSeg segments (idx=0 through idx=(nSeg-1)) in absolute
  133775. ** level iAbsLevel.
  133776. */
  133777. static int fts3IncrmergeCsr(
  133778. Fts3Table *p, /* FTS3 table handle */
  133779. sqlite3_int64 iAbsLevel, /* Absolute level to open */
  133780. int nSeg, /* Number of segments to merge */
  133781. Fts3MultiSegReader *pCsr /* Cursor object to populate */
  133782. ){
  133783. int rc; /* Return Code */
  133784. sqlite3_stmt *pStmt = 0; /* Statement used to read %_segdir entry */
  133785. int nByte; /* Bytes allocated at pCsr->apSegment[] */
  133786. /* Allocate space for the Fts3MultiSegReader.aCsr[] array */
  133787. memset(pCsr, 0, sizeof(*pCsr));
  133788. nByte = sizeof(Fts3SegReader *) * nSeg;
  133789. pCsr->apSegment = (Fts3SegReader **)sqlite3_malloc(nByte);
  133790. if( pCsr->apSegment==0 ){
  133791. rc = SQLITE_NOMEM;
  133792. }else{
  133793. memset(pCsr->apSegment, 0, nByte);
  133794. rc = fts3SqlStmt(p, SQL_SELECT_LEVEL, &pStmt, 0);
  133795. }
  133796. if( rc==SQLITE_OK ){
  133797. int i;
  133798. int rc2;
  133799. sqlite3_bind_int64(pStmt, 1, iAbsLevel);
  133800. assert( pCsr->nSegment==0 );
  133801. for(i=0; rc==SQLITE_OK && sqlite3_step(pStmt)==SQLITE_ROW && i<nSeg; i++){
  133802. rc = sqlite3Fts3SegReaderNew(i, 0,
  133803. sqlite3_column_int64(pStmt, 1), /* segdir.start_block */
  133804. sqlite3_column_int64(pStmt, 2), /* segdir.leaves_end_block */
  133805. sqlite3_column_int64(pStmt, 3), /* segdir.end_block */
  133806. sqlite3_column_blob(pStmt, 4), /* segdir.root */
  133807. sqlite3_column_bytes(pStmt, 4), /* segdir.root */
  133808. &pCsr->apSegment[i]
  133809. );
  133810. pCsr->nSegment++;
  133811. }
  133812. rc2 = sqlite3_reset(pStmt);
  133813. if( rc==SQLITE_OK ) rc = rc2;
  133814. }
  133815. return rc;
  133816. }
  133817. typedef struct IncrmergeWriter IncrmergeWriter;
  133818. typedef struct NodeWriter NodeWriter;
  133819. typedef struct Blob Blob;
  133820. typedef struct NodeReader NodeReader;
  133821. /*
  133822. ** An instance of the following structure is used as a dynamic buffer
  133823. ** to build up nodes or other blobs of data in.
  133824. **
  133825. ** The function blobGrowBuffer() is used to extend the allocation.
  133826. */
  133827. struct Blob {
  133828. char *a; /* Pointer to allocation */
  133829. int n; /* Number of valid bytes of data in a[] */
  133830. int nAlloc; /* Allocated size of a[] (nAlloc>=n) */
  133831. };
  133832. /*
  133833. ** This structure is used to build up buffers containing segment b-tree
  133834. ** nodes (blocks).
  133835. */
  133836. struct NodeWriter {
  133837. sqlite3_int64 iBlock; /* Current block id */
  133838. Blob key; /* Last key written to the current block */
  133839. Blob block; /* Current block image */
  133840. };
  133841. /*
  133842. ** An object of this type contains the state required to create or append
  133843. ** to an appendable b-tree segment.
  133844. */
  133845. struct IncrmergeWriter {
  133846. int nLeafEst; /* Space allocated for leaf blocks */
  133847. int nWork; /* Number of leaf pages flushed */
  133848. sqlite3_int64 iAbsLevel; /* Absolute level of input segments */
  133849. int iIdx; /* Index of *output* segment in iAbsLevel+1 */
  133850. sqlite3_int64 iStart; /* Block number of first allocated block */
  133851. sqlite3_int64 iEnd; /* Block number of last allocated block */
  133852. sqlite3_int64 nLeafData; /* Bytes of leaf page data so far */
  133853. u8 bNoLeafData; /* If true, store 0 for segment size */
  133854. NodeWriter aNodeWriter[FTS_MAX_APPENDABLE_HEIGHT];
  133855. };
  133856. /*
  133857. ** An object of the following type is used to read data from a single
  133858. ** FTS segment node. See the following functions:
  133859. **
  133860. ** nodeReaderInit()
  133861. ** nodeReaderNext()
  133862. ** nodeReaderRelease()
  133863. */
  133864. struct NodeReader {
  133865. const char *aNode;
  133866. int nNode;
  133867. int iOff; /* Current offset within aNode[] */
  133868. /* Output variables. Containing the current node entry. */
  133869. sqlite3_int64 iChild; /* Pointer to child node */
  133870. Blob term; /* Current term */
  133871. const char *aDoclist; /* Pointer to doclist */
  133872. int nDoclist; /* Size of doclist in bytes */
  133873. };
  133874. /*
  133875. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  133876. ** Otherwise, if the allocation at pBlob->a is not already at least nMin
  133877. ** bytes in size, extend (realloc) it to be so.
  133878. **
  133879. ** If an OOM error occurs, set *pRc to SQLITE_NOMEM and leave pBlob->a
  133880. ** unmodified. Otherwise, if the allocation succeeds, update pBlob->nAlloc
  133881. ** to reflect the new size of the pBlob->a[] buffer.
  133882. */
  133883. static void blobGrowBuffer(Blob *pBlob, int nMin, int *pRc){
  133884. if( *pRc==SQLITE_OK && nMin>pBlob->nAlloc ){
  133885. int nAlloc = nMin;
  133886. char *a = (char *)sqlite3_realloc(pBlob->a, nAlloc);
  133887. if( a ){
  133888. pBlob->nAlloc = nAlloc;
  133889. pBlob->a = a;
  133890. }else{
  133891. *pRc = SQLITE_NOMEM;
  133892. }
  133893. }
  133894. }
  133895. /*
  133896. ** Attempt to advance the node-reader object passed as the first argument to
  133897. ** the next entry on the node.
  133898. **
  133899. ** Return an error code if an error occurs (SQLITE_NOMEM is possible).
  133900. ** Otherwise return SQLITE_OK. If there is no next entry on the node
  133901. ** (e.g. because the current entry is the last) set NodeReader->aNode to
  133902. ** NULL to indicate EOF. Otherwise, populate the NodeReader structure output
  133903. ** variables for the new entry.
  133904. */
  133905. static int nodeReaderNext(NodeReader *p){
  133906. int bFirst = (p->term.n==0); /* True for first term on the node */
  133907. int nPrefix = 0; /* Bytes to copy from previous term */
  133908. int nSuffix = 0; /* Bytes to append to the prefix */
  133909. int rc = SQLITE_OK; /* Return code */
  133910. assert( p->aNode );
  133911. if( p->iChild && bFirst==0 ) p->iChild++;
  133912. if( p->iOff>=p->nNode ){
  133913. /* EOF */
  133914. p->aNode = 0;
  133915. }else{
  133916. if( bFirst==0 ){
  133917. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nPrefix);
  133918. }
  133919. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &nSuffix);
  133920. blobGrowBuffer(&p->term, nPrefix+nSuffix, &rc);
  133921. if( rc==SQLITE_OK ){
  133922. memcpy(&p->term.a[nPrefix], &p->aNode[p->iOff], nSuffix);
  133923. p->term.n = nPrefix+nSuffix;
  133924. p->iOff += nSuffix;
  133925. if( p->iChild==0 ){
  133926. p->iOff += fts3GetVarint32(&p->aNode[p->iOff], &p->nDoclist);
  133927. p->aDoclist = &p->aNode[p->iOff];
  133928. p->iOff += p->nDoclist;
  133929. }
  133930. }
  133931. }
  133932. assert( p->iOff<=p->nNode );
  133933. return rc;
  133934. }
  133935. /*
  133936. ** Release all dynamic resources held by node-reader object *p.
  133937. */
  133938. static void nodeReaderRelease(NodeReader *p){
  133939. sqlite3_free(p->term.a);
  133940. }
  133941. /*
  133942. ** Initialize a node-reader object to read the node in buffer aNode/nNode.
  133943. **
  133944. ** If successful, SQLITE_OK is returned and the NodeReader object set to
  133945. ** point to the first entry on the node (if any). Otherwise, an SQLite
  133946. ** error code is returned.
  133947. */
  133948. static int nodeReaderInit(NodeReader *p, const char *aNode, int nNode){
  133949. memset(p, 0, sizeof(NodeReader));
  133950. p->aNode = aNode;
  133951. p->nNode = nNode;
  133952. /* Figure out if this is a leaf or an internal node. */
  133953. if( p->aNode[0] ){
  133954. /* An internal node. */
  133955. p->iOff = 1 + sqlite3Fts3GetVarint(&p->aNode[1], &p->iChild);
  133956. }else{
  133957. p->iOff = 1;
  133958. }
  133959. return nodeReaderNext(p);
  133960. }
  133961. /*
  133962. ** This function is called while writing an FTS segment each time a leaf o
  133963. ** node is finished and written to disk. The key (zTerm/nTerm) is guaranteed
  133964. ** to be greater than the largest key on the node just written, but smaller
  133965. ** than or equal to the first key that will be written to the next leaf
  133966. ** node.
  133967. **
  133968. ** The block id of the leaf node just written to disk may be found in
  133969. ** (pWriter->aNodeWriter[0].iBlock) when this function is called.
  133970. */
  133971. static int fts3IncrmergePush(
  133972. Fts3Table *p, /* Fts3 table handle */
  133973. IncrmergeWriter *pWriter, /* Writer object */
  133974. const char *zTerm, /* Term to write to internal node */
  133975. int nTerm /* Bytes at zTerm */
  133976. ){
  133977. sqlite3_int64 iPtr = pWriter->aNodeWriter[0].iBlock;
  133978. int iLayer;
  133979. assert( nTerm>0 );
  133980. for(iLayer=1; ALWAYS(iLayer<FTS_MAX_APPENDABLE_HEIGHT); iLayer++){
  133981. sqlite3_int64 iNextPtr = 0;
  133982. NodeWriter *pNode = &pWriter->aNodeWriter[iLayer];
  133983. int rc = SQLITE_OK;
  133984. int nPrefix;
  133985. int nSuffix;
  133986. int nSpace;
  133987. /* Figure out how much space the key will consume if it is written to
  133988. ** the current node of layer iLayer. Due to the prefix compression,
  133989. ** the space required changes depending on which node the key is to
  133990. ** be added to. */
  133991. nPrefix = fts3PrefixCompress(pNode->key.a, pNode->key.n, zTerm, nTerm);
  133992. nSuffix = nTerm - nPrefix;
  133993. nSpace = sqlite3Fts3VarintLen(nPrefix);
  133994. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  133995. if( pNode->key.n==0 || (pNode->block.n + nSpace)<=p->nNodeSize ){
  133996. /* If the current node of layer iLayer contains zero keys, or if adding
  133997. ** the key to it will not cause it to grow to larger than nNodeSize
  133998. ** bytes in size, write the key here. */
  133999. Blob *pBlk = &pNode->block;
  134000. if( pBlk->n==0 ){
  134001. blobGrowBuffer(pBlk, p->nNodeSize, &rc);
  134002. if( rc==SQLITE_OK ){
  134003. pBlk->a[0] = (char)iLayer;
  134004. pBlk->n = 1 + sqlite3Fts3PutVarint(&pBlk->a[1], iPtr);
  134005. }
  134006. }
  134007. blobGrowBuffer(pBlk, pBlk->n + nSpace, &rc);
  134008. blobGrowBuffer(&pNode->key, nTerm, &rc);
  134009. if( rc==SQLITE_OK ){
  134010. if( pNode->key.n ){
  134011. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nPrefix);
  134012. }
  134013. pBlk->n += sqlite3Fts3PutVarint(&pBlk->a[pBlk->n], nSuffix);
  134014. memcpy(&pBlk->a[pBlk->n], &zTerm[nPrefix], nSuffix);
  134015. pBlk->n += nSuffix;
  134016. memcpy(pNode->key.a, zTerm, nTerm);
  134017. pNode->key.n = nTerm;
  134018. }
  134019. }else{
  134020. /* Otherwise, flush the current node of layer iLayer to disk.
  134021. ** Then allocate a new, empty sibling node. The key will be written
  134022. ** into the parent of this node. */
  134023. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  134024. assert( pNode->block.nAlloc>=p->nNodeSize );
  134025. pNode->block.a[0] = (char)iLayer;
  134026. pNode->block.n = 1 + sqlite3Fts3PutVarint(&pNode->block.a[1], iPtr+1);
  134027. iNextPtr = pNode->iBlock;
  134028. pNode->iBlock++;
  134029. pNode->key.n = 0;
  134030. }
  134031. if( rc!=SQLITE_OK || iNextPtr==0 ) return rc;
  134032. iPtr = iNextPtr;
  134033. }
  134034. assert( 0 );
  134035. return 0;
  134036. }
  134037. /*
  134038. ** Append a term and (optionally) doclist to the FTS segment node currently
  134039. ** stored in blob *pNode. The node need not contain any terms, but the
  134040. ** header must be written before this function is called.
  134041. **
  134042. ** A node header is a single 0x00 byte for a leaf node, or a height varint
  134043. ** followed by the left-hand-child varint for an internal node.
  134044. **
  134045. ** The term to be appended is passed via arguments zTerm/nTerm. For a
  134046. ** leaf node, the doclist is passed as aDoclist/nDoclist. For an internal
  134047. ** node, both aDoclist and nDoclist must be passed 0.
  134048. **
  134049. ** If the size of the value in blob pPrev is zero, then this is the first
  134050. ** term written to the node. Otherwise, pPrev contains a copy of the
  134051. ** previous term. Before this function returns, it is updated to contain a
  134052. ** copy of zTerm/nTerm.
  134053. **
  134054. ** It is assumed that the buffer associated with pNode is already large
  134055. ** enough to accommodate the new entry. The buffer associated with pPrev
  134056. ** is extended by this function if requrired.
  134057. **
  134058. ** If an error (i.e. OOM condition) occurs, an SQLite error code is
  134059. ** returned. Otherwise, SQLITE_OK.
  134060. */
  134061. static int fts3AppendToNode(
  134062. Blob *pNode, /* Current node image to append to */
  134063. Blob *pPrev, /* Buffer containing previous term written */
  134064. const char *zTerm, /* New term to write */
  134065. int nTerm, /* Size of zTerm in bytes */
  134066. const char *aDoclist, /* Doclist (or NULL) to write */
  134067. int nDoclist /* Size of aDoclist in bytes */
  134068. ){
  134069. int rc = SQLITE_OK; /* Return code */
  134070. int bFirst = (pPrev->n==0); /* True if this is the first term written */
  134071. int nPrefix; /* Size of term prefix in bytes */
  134072. int nSuffix; /* Size of term suffix in bytes */
  134073. /* Node must have already been started. There must be a doclist for a
  134074. ** leaf node, and there must not be a doclist for an internal node. */
  134075. assert( pNode->n>0 );
  134076. assert( (pNode->a[0]=='\0')==(aDoclist!=0) );
  134077. blobGrowBuffer(pPrev, nTerm, &rc);
  134078. if( rc!=SQLITE_OK ) return rc;
  134079. nPrefix = fts3PrefixCompress(pPrev->a, pPrev->n, zTerm, nTerm);
  134080. nSuffix = nTerm - nPrefix;
  134081. memcpy(pPrev->a, zTerm, nTerm);
  134082. pPrev->n = nTerm;
  134083. if( bFirst==0 ){
  134084. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nPrefix);
  134085. }
  134086. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nSuffix);
  134087. memcpy(&pNode->a[pNode->n], &zTerm[nPrefix], nSuffix);
  134088. pNode->n += nSuffix;
  134089. if( aDoclist ){
  134090. pNode->n += sqlite3Fts3PutVarint(&pNode->a[pNode->n], nDoclist);
  134091. memcpy(&pNode->a[pNode->n], aDoclist, nDoclist);
  134092. pNode->n += nDoclist;
  134093. }
  134094. assert( pNode->n<=pNode->nAlloc );
  134095. return SQLITE_OK;
  134096. }
  134097. /*
  134098. ** Append the current term and doclist pointed to by cursor pCsr to the
  134099. ** appendable b-tree segment opened for writing by pWriter.
  134100. **
  134101. ** Return SQLITE_OK if successful, or an SQLite error code otherwise.
  134102. */
  134103. static int fts3IncrmergeAppend(
  134104. Fts3Table *p, /* Fts3 table handle */
  134105. IncrmergeWriter *pWriter, /* Writer object */
  134106. Fts3MultiSegReader *pCsr /* Cursor containing term and doclist */
  134107. ){
  134108. const char *zTerm = pCsr->zTerm;
  134109. int nTerm = pCsr->nTerm;
  134110. const char *aDoclist = pCsr->aDoclist;
  134111. int nDoclist = pCsr->nDoclist;
  134112. int rc = SQLITE_OK; /* Return code */
  134113. int nSpace; /* Total space in bytes required on leaf */
  134114. int nPrefix; /* Size of prefix shared with previous term */
  134115. int nSuffix; /* Size of suffix (nTerm - nPrefix) */
  134116. NodeWriter *pLeaf; /* Object used to write leaf nodes */
  134117. pLeaf = &pWriter->aNodeWriter[0];
  134118. nPrefix = fts3PrefixCompress(pLeaf->key.a, pLeaf->key.n, zTerm, nTerm);
  134119. nSuffix = nTerm - nPrefix;
  134120. nSpace = sqlite3Fts3VarintLen(nPrefix);
  134121. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  134122. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  134123. /* If the current block is not empty, and if adding this term/doclist
  134124. ** to the current block would make it larger than Fts3Table.nNodeSize
  134125. ** bytes, write this block out to the database. */
  134126. if( pLeaf->block.n>0 && (pLeaf->block.n + nSpace)>p->nNodeSize ){
  134127. rc = fts3WriteSegment(p, pLeaf->iBlock, pLeaf->block.a, pLeaf->block.n);
  134128. pWriter->nWork++;
  134129. /* Add the current term to the parent node. The term added to the
  134130. ** parent must:
  134131. **
  134132. ** a) be greater than the largest term on the leaf node just written
  134133. ** to the database (still available in pLeaf->key), and
  134134. **
  134135. ** b) be less than or equal to the term about to be added to the new
  134136. ** leaf node (zTerm/nTerm).
  134137. **
  134138. ** In other words, it must be the prefix of zTerm 1 byte longer than
  134139. ** the common prefix (if any) of zTerm and pWriter->zTerm.
  134140. */
  134141. if( rc==SQLITE_OK ){
  134142. rc = fts3IncrmergePush(p, pWriter, zTerm, nPrefix+1);
  134143. }
  134144. /* Advance to the next output block */
  134145. pLeaf->iBlock++;
  134146. pLeaf->key.n = 0;
  134147. pLeaf->block.n = 0;
  134148. nSuffix = nTerm;
  134149. nSpace = 1;
  134150. nSpace += sqlite3Fts3VarintLen(nSuffix) + nSuffix;
  134151. nSpace += sqlite3Fts3VarintLen(nDoclist) + nDoclist;
  134152. }
  134153. pWriter->nLeafData += nSpace;
  134154. blobGrowBuffer(&pLeaf->block, pLeaf->block.n + nSpace, &rc);
  134155. if( rc==SQLITE_OK ){
  134156. if( pLeaf->block.n==0 ){
  134157. pLeaf->block.n = 1;
  134158. pLeaf->block.a[0] = '\0';
  134159. }
  134160. rc = fts3AppendToNode(
  134161. &pLeaf->block, &pLeaf->key, zTerm, nTerm, aDoclist, nDoclist
  134162. );
  134163. }
  134164. return rc;
  134165. }
  134166. /*
  134167. ** This function is called to release all dynamic resources held by the
  134168. ** merge-writer object pWriter, and if no error has occurred, to flush
  134169. ** all outstanding node buffers held by pWriter to disk.
  134170. **
  134171. ** If *pRc is not SQLITE_OK when this function is called, then no attempt
  134172. ** is made to write any data to disk. Instead, this function serves only
  134173. ** to release outstanding resources.
  134174. **
  134175. ** Otherwise, if *pRc is initially SQLITE_OK and an error occurs while
  134176. ** flushing buffers to disk, *pRc is set to an SQLite error code before
  134177. ** returning.
  134178. */
  134179. static void fts3IncrmergeRelease(
  134180. Fts3Table *p, /* FTS3 table handle */
  134181. IncrmergeWriter *pWriter, /* Merge-writer object */
  134182. int *pRc /* IN/OUT: Error code */
  134183. ){
  134184. int i; /* Used to iterate through non-root layers */
  134185. int iRoot; /* Index of root in pWriter->aNodeWriter */
  134186. NodeWriter *pRoot; /* NodeWriter for root node */
  134187. int rc = *pRc; /* Error code */
  134188. /* Set iRoot to the index in pWriter->aNodeWriter[] of the output segment
  134189. ** root node. If the segment fits entirely on a single leaf node, iRoot
  134190. ** will be set to 0. If the root node is the parent of the leaves, iRoot
  134191. ** will be 1. And so on. */
  134192. for(iRoot=FTS_MAX_APPENDABLE_HEIGHT-1; iRoot>=0; iRoot--){
  134193. NodeWriter *pNode = &pWriter->aNodeWriter[iRoot];
  134194. if( pNode->block.n>0 ) break;
  134195. assert( *pRc || pNode->block.nAlloc==0 );
  134196. assert( *pRc || pNode->key.nAlloc==0 );
  134197. sqlite3_free(pNode->block.a);
  134198. sqlite3_free(pNode->key.a);
  134199. }
  134200. /* Empty output segment. This is a no-op. */
  134201. if( iRoot<0 ) return;
  134202. /* The entire output segment fits on a single node. Normally, this means
  134203. ** the node would be stored as a blob in the "root" column of the %_segdir
  134204. ** table. However, this is not permitted in this case. The problem is that
  134205. ** space has already been reserved in the %_segments table, and so the
  134206. ** start_block and end_block fields of the %_segdir table must be populated.
  134207. ** And, by design or by accident, released versions of FTS cannot handle
  134208. ** segments that fit entirely on the root node with start_block!=0.
  134209. **
  134210. ** Instead, create a synthetic root node that contains nothing but a
  134211. ** pointer to the single content node. So that the segment consists of a
  134212. ** single leaf and a single interior (root) node.
  134213. **
  134214. ** Todo: Better might be to defer allocating space in the %_segments
  134215. ** table until we are sure it is needed.
  134216. */
  134217. if( iRoot==0 ){
  134218. Blob *pBlock = &pWriter->aNodeWriter[1].block;
  134219. blobGrowBuffer(pBlock, 1 + FTS3_VARINT_MAX, &rc);
  134220. if( rc==SQLITE_OK ){
  134221. pBlock->a[0] = 0x01;
  134222. pBlock->n = 1 + sqlite3Fts3PutVarint(
  134223. &pBlock->a[1], pWriter->aNodeWriter[0].iBlock
  134224. );
  134225. }
  134226. iRoot = 1;
  134227. }
  134228. pRoot = &pWriter->aNodeWriter[iRoot];
  134229. /* Flush all currently outstanding nodes to disk. */
  134230. for(i=0; i<iRoot; i++){
  134231. NodeWriter *pNode = &pWriter->aNodeWriter[i];
  134232. if( pNode->block.n>0 && rc==SQLITE_OK ){
  134233. rc = fts3WriteSegment(p, pNode->iBlock, pNode->block.a, pNode->block.n);
  134234. }
  134235. sqlite3_free(pNode->block.a);
  134236. sqlite3_free(pNode->key.a);
  134237. }
  134238. /* Write the %_segdir record. */
  134239. if( rc==SQLITE_OK ){
  134240. rc = fts3WriteSegdir(p,
  134241. pWriter->iAbsLevel+1, /* level */
  134242. pWriter->iIdx, /* idx */
  134243. pWriter->iStart, /* start_block */
  134244. pWriter->aNodeWriter[0].iBlock, /* leaves_end_block */
  134245. pWriter->iEnd, /* end_block */
  134246. (pWriter->bNoLeafData==0 ? pWriter->nLeafData : 0), /* end_block */
  134247. pRoot->block.a, pRoot->block.n /* root */
  134248. );
  134249. }
  134250. sqlite3_free(pRoot->block.a);
  134251. sqlite3_free(pRoot->key.a);
  134252. *pRc = rc;
  134253. }
  134254. /*
  134255. ** Compare the term in buffer zLhs (size in bytes nLhs) with that in
  134256. ** zRhs (size in bytes nRhs) using memcmp. If one term is a prefix of
  134257. ** the other, it is considered to be smaller than the other.
  134258. **
  134259. ** Return -ve if zLhs is smaller than zRhs, 0 if it is equal, or +ve
  134260. ** if it is greater.
  134261. */
  134262. static int fts3TermCmp(
  134263. const char *zLhs, int nLhs, /* LHS of comparison */
  134264. const char *zRhs, int nRhs /* RHS of comparison */
  134265. ){
  134266. int nCmp = MIN(nLhs, nRhs);
  134267. int res;
  134268. res = memcmp(zLhs, zRhs, nCmp);
  134269. if( res==0 ) res = nLhs - nRhs;
  134270. return res;
  134271. }
  134272. /*
  134273. ** Query to see if the entry in the %_segments table with blockid iEnd is
  134274. ** NULL. If no error occurs and the entry is NULL, set *pbRes 1 before
  134275. ** returning. Otherwise, set *pbRes to 0.
  134276. **
  134277. ** Or, if an error occurs while querying the database, return an SQLite
  134278. ** error code. The final value of *pbRes is undefined in this case.
  134279. **
  134280. ** This is used to test if a segment is an "appendable" segment. If it
  134281. ** is, then a NULL entry has been inserted into the %_segments table
  134282. ** with blockid %_segdir.end_block.
  134283. */
  134284. static int fts3IsAppendable(Fts3Table *p, sqlite3_int64 iEnd, int *pbRes){
  134285. int bRes = 0; /* Result to set *pbRes to */
  134286. sqlite3_stmt *pCheck = 0; /* Statement to query database with */
  134287. int rc; /* Return code */
  134288. rc = fts3SqlStmt(p, SQL_SEGMENT_IS_APPENDABLE, &pCheck, 0);
  134289. if( rc==SQLITE_OK ){
  134290. sqlite3_bind_int64(pCheck, 1, iEnd);
  134291. if( SQLITE_ROW==sqlite3_step(pCheck) ) bRes = 1;
  134292. rc = sqlite3_reset(pCheck);
  134293. }
  134294. *pbRes = bRes;
  134295. return rc;
  134296. }
  134297. /*
  134298. ** This function is called when initializing an incremental-merge operation.
  134299. ** It checks if the existing segment with index value iIdx at absolute level
  134300. ** (iAbsLevel+1) can be appended to by the incremental merge. If it can, the
  134301. ** merge-writer object *pWriter is initialized to write to it.
  134302. **
  134303. ** An existing segment can be appended to by an incremental merge if:
  134304. **
  134305. ** * It was initially created as an appendable segment (with all required
  134306. ** space pre-allocated), and
  134307. **
  134308. ** * The first key read from the input (arguments zKey and nKey) is
  134309. ** greater than the largest key currently stored in the potential
  134310. ** output segment.
  134311. */
  134312. static int fts3IncrmergeLoad(
  134313. Fts3Table *p, /* Fts3 table handle */
  134314. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  134315. int iIdx, /* Index of candidate output segment */
  134316. const char *zKey, /* First key to write */
  134317. int nKey, /* Number of bytes in nKey */
  134318. IncrmergeWriter *pWriter /* Populate this object */
  134319. ){
  134320. int rc; /* Return code */
  134321. sqlite3_stmt *pSelect = 0; /* SELECT to read %_segdir entry */
  134322. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pSelect, 0);
  134323. if( rc==SQLITE_OK ){
  134324. sqlite3_int64 iStart = 0; /* Value of %_segdir.start_block */
  134325. sqlite3_int64 iLeafEnd = 0; /* Value of %_segdir.leaves_end_block */
  134326. sqlite3_int64 iEnd = 0; /* Value of %_segdir.end_block */
  134327. const char *aRoot = 0; /* Pointer to %_segdir.root buffer */
  134328. int nRoot = 0; /* Size of aRoot[] in bytes */
  134329. int rc2; /* Return code from sqlite3_reset() */
  134330. int bAppendable = 0; /* Set to true if segment is appendable */
  134331. /* Read the %_segdir entry for index iIdx absolute level (iAbsLevel+1) */
  134332. sqlite3_bind_int64(pSelect, 1, iAbsLevel+1);
  134333. sqlite3_bind_int(pSelect, 2, iIdx);
  134334. if( sqlite3_step(pSelect)==SQLITE_ROW ){
  134335. iStart = sqlite3_column_int64(pSelect, 1);
  134336. iLeafEnd = sqlite3_column_int64(pSelect, 2);
  134337. fts3ReadEndBlockField(pSelect, 3, &iEnd, &pWriter->nLeafData);
  134338. if( pWriter->nLeafData<0 ){
  134339. pWriter->nLeafData = pWriter->nLeafData * -1;
  134340. }
  134341. pWriter->bNoLeafData = (pWriter->nLeafData==0);
  134342. nRoot = sqlite3_column_bytes(pSelect, 4);
  134343. aRoot = sqlite3_column_blob(pSelect, 4);
  134344. }else{
  134345. return sqlite3_reset(pSelect);
  134346. }
  134347. /* Check for the zero-length marker in the %_segments table */
  134348. rc = fts3IsAppendable(p, iEnd, &bAppendable);
  134349. /* Check that zKey/nKey is larger than the largest key the candidate */
  134350. if( rc==SQLITE_OK && bAppendable ){
  134351. char *aLeaf = 0;
  134352. int nLeaf = 0;
  134353. rc = sqlite3Fts3ReadBlock(p, iLeafEnd, &aLeaf, &nLeaf, 0);
  134354. if( rc==SQLITE_OK ){
  134355. NodeReader reader;
  134356. for(rc = nodeReaderInit(&reader, aLeaf, nLeaf);
  134357. rc==SQLITE_OK && reader.aNode;
  134358. rc = nodeReaderNext(&reader)
  134359. ){
  134360. assert( reader.aNode );
  134361. }
  134362. if( fts3TermCmp(zKey, nKey, reader.term.a, reader.term.n)<=0 ){
  134363. bAppendable = 0;
  134364. }
  134365. nodeReaderRelease(&reader);
  134366. }
  134367. sqlite3_free(aLeaf);
  134368. }
  134369. if( rc==SQLITE_OK && bAppendable ){
  134370. /* It is possible to append to this segment. Set up the IncrmergeWriter
  134371. ** object to do so. */
  134372. int i;
  134373. int nHeight = (int)aRoot[0];
  134374. NodeWriter *pNode;
  134375. pWriter->nLeafEst = (int)((iEnd - iStart) + 1)/FTS_MAX_APPENDABLE_HEIGHT;
  134376. pWriter->iStart = iStart;
  134377. pWriter->iEnd = iEnd;
  134378. pWriter->iAbsLevel = iAbsLevel;
  134379. pWriter->iIdx = iIdx;
  134380. for(i=nHeight+1; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  134381. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  134382. }
  134383. pNode = &pWriter->aNodeWriter[nHeight];
  134384. pNode->iBlock = pWriter->iStart + pWriter->nLeafEst*nHeight;
  134385. blobGrowBuffer(&pNode->block, MAX(nRoot, p->nNodeSize), &rc);
  134386. if( rc==SQLITE_OK ){
  134387. memcpy(pNode->block.a, aRoot, nRoot);
  134388. pNode->block.n = nRoot;
  134389. }
  134390. for(i=nHeight; i>=0 && rc==SQLITE_OK; i--){
  134391. NodeReader reader;
  134392. pNode = &pWriter->aNodeWriter[i];
  134393. rc = nodeReaderInit(&reader, pNode->block.a, pNode->block.n);
  134394. while( reader.aNode && rc==SQLITE_OK ) rc = nodeReaderNext(&reader);
  134395. blobGrowBuffer(&pNode->key, reader.term.n, &rc);
  134396. if( rc==SQLITE_OK ){
  134397. memcpy(pNode->key.a, reader.term.a, reader.term.n);
  134398. pNode->key.n = reader.term.n;
  134399. if( i>0 ){
  134400. char *aBlock = 0;
  134401. int nBlock = 0;
  134402. pNode = &pWriter->aNodeWriter[i-1];
  134403. pNode->iBlock = reader.iChild;
  134404. rc = sqlite3Fts3ReadBlock(p, reader.iChild, &aBlock, &nBlock, 0);
  134405. blobGrowBuffer(&pNode->block, MAX(nBlock, p->nNodeSize), &rc);
  134406. if( rc==SQLITE_OK ){
  134407. memcpy(pNode->block.a, aBlock, nBlock);
  134408. pNode->block.n = nBlock;
  134409. }
  134410. sqlite3_free(aBlock);
  134411. }
  134412. }
  134413. nodeReaderRelease(&reader);
  134414. }
  134415. }
  134416. rc2 = sqlite3_reset(pSelect);
  134417. if( rc==SQLITE_OK ) rc = rc2;
  134418. }
  134419. return rc;
  134420. }
  134421. /*
  134422. ** Determine the largest segment index value that exists within absolute
  134423. ** level iAbsLevel+1. If no error occurs, set *piIdx to this value plus
  134424. ** one before returning SQLITE_OK. Or, if there are no segments at all
  134425. ** within level iAbsLevel, set *piIdx to zero.
  134426. **
  134427. ** If an error occurs, return an SQLite error code. The final value of
  134428. ** *piIdx is undefined in this case.
  134429. */
  134430. static int fts3IncrmergeOutputIdx(
  134431. Fts3Table *p, /* FTS Table handle */
  134432. sqlite3_int64 iAbsLevel, /* Absolute index of input segments */
  134433. int *piIdx /* OUT: Next free index at iAbsLevel+1 */
  134434. ){
  134435. int rc;
  134436. sqlite3_stmt *pOutputIdx = 0; /* SQL used to find output index */
  134437. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENT_INDEX, &pOutputIdx, 0);
  134438. if( rc==SQLITE_OK ){
  134439. sqlite3_bind_int64(pOutputIdx, 1, iAbsLevel+1);
  134440. sqlite3_step(pOutputIdx);
  134441. *piIdx = sqlite3_column_int(pOutputIdx, 0);
  134442. rc = sqlite3_reset(pOutputIdx);
  134443. }
  134444. return rc;
  134445. }
  134446. /*
  134447. ** Allocate an appendable output segment on absolute level iAbsLevel+1
  134448. ** with idx value iIdx.
  134449. **
  134450. ** In the %_segdir table, a segment is defined by the values in three
  134451. ** columns:
  134452. **
  134453. ** start_block
  134454. ** leaves_end_block
  134455. ** end_block
  134456. **
  134457. ** When an appendable segment is allocated, it is estimated that the
  134458. ** maximum number of leaf blocks that may be required is the sum of the
  134459. ** number of leaf blocks consumed by the input segments, plus the number
  134460. ** of input segments, multiplied by two. This value is stored in stack
  134461. ** variable nLeafEst.
  134462. **
  134463. ** A total of 16*nLeafEst blocks are allocated when an appendable segment
  134464. ** is created ((1 + end_block - start_block)==16*nLeafEst). The contiguous
  134465. ** array of leaf nodes starts at the first block allocated. The array
  134466. ** of interior nodes that are parents of the leaf nodes start at block
  134467. ** (start_block + (1 + end_block - start_block) / 16). And so on.
  134468. **
  134469. ** In the actual code below, the value "16" is replaced with the
  134470. ** pre-processor macro FTS_MAX_APPENDABLE_HEIGHT.
  134471. */
  134472. static int fts3IncrmergeWriter(
  134473. Fts3Table *p, /* Fts3 table handle */
  134474. sqlite3_int64 iAbsLevel, /* Absolute level of input segments */
  134475. int iIdx, /* Index of new output segment */
  134476. Fts3MultiSegReader *pCsr, /* Cursor that data will be read from */
  134477. IncrmergeWriter *pWriter /* Populate this object */
  134478. ){
  134479. int rc; /* Return Code */
  134480. int i; /* Iterator variable */
  134481. int nLeafEst = 0; /* Blocks allocated for leaf nodes */
  134482. sqlite3_stmt *pLeafEst = 0; /* SQL used to determine nLeafEst */
  134483. sqlite3_stmt *pFirstBlock = 0; /* SQL used to determine first block */
  134484. /* Calculate nLeafEst. */
  134485. rc = fts3SqlStmt(p, SQL_MAX_LEAF_NODE_ESTIMATE, &pLeafEst, 0);
  134486. if( rc==SQLITE_OK ){
  134487. sqlite3_bind_int64(pLeafEst, 1, iAbsLevel);
  134488. sqlite3_bind_int64(pLeafEst, 2, pCsr->nSegment);
  134489. if( SQLITE_ROW==sqlite3_step(pLeafEst) ){
  134490. nLeafEst = sqlite3_column_int(pLeafEst, 0);
  134491. }
  134492. rc = sqlite3_reset(pLeafEst);
  134493. }
  134494. if( rc!=SQLITE_OK ) return rc;
  134495. /* Calculate the first block to use in the output segment */
  134496. rc = fts3SqlStmt(p, SQL_NEXT_SEGMENTS_ID, &pFirstBlock, 0);
  134497. if( rc==SQLITE_OK ){
  134498. if( SQLITE_ROW==sqlite3_step(pFirstBlock) ){
  134499. pWriter->iStart = sqlite3_column_int64(pFirstBlock, 0);
  134500. pWriter->iEnd = pWriter->iStart - 1;
  134501. pWriter->iEnd += nLeafEst * FTS_MAX_APPENDABLE_HEIGHT;
  134502. }
  134503. rc = sqlite3_reset(pFirstBlock);
  134504. }
  134505. if( rc!=SQLITE_OK ) return rc;
  134506. /* Insert the marker in the %_segments table to make sure nobody tries
  134507. ** to steal the space just allocated. This is also used to identify
  134508. ** appendable segments. */
  134509. rc = fts3WriteSegment(p, pWriter->iEnd, 0, 0);
  134510. if( rc!=SQLITE_OK ) return rc;
  134511. pWriter->iAbsLevel = iAbsLevel;
  134512. pWriter->nLeafEst = nLeafEst;
  134513. pWriter->iIdx = iIdx;
  134514. /* Set up the array of NodeWriter objects */
  134515. for(i=0; i<FTS_MAX_APPENDABLE_HEIGHT; i++){
  134516. pWriter->aNodeWriter[i].iBlock = pWriter->iStart + i*pWriter->nLeafEst;
  134517. }
  134518. return SQLITE_OK;
  134519. }
  134520. /*
  134521. ** Remove an entry from the %_segdir table. This involves running the
  134522. ** following two statements:
  134523. **
  134524. ** DELETE FROM %_segdir WHERE level = :iAbsLevel AND idx = :iIdx
  134525. ** UPDATE %_segdir SET idx = idx - 1 WHERE level = :iAbsLevel AND idx > :iIdx
  134526. **
  134527. ** The DELETE statement removes the specific %_segdir level. The UPDATE
  134528. ** statement ensures that the remaining segments have contiguously allocated
  134529. ** idx values.
  134530. */
  134531. static int fts3RemoveSegdirEntry(
  134532. Fts3Table *p, /* FTS3 table handle */
  134533. sqlite3_int64 iAbsLevel, /* Absolute level to delete from */
  134534. int iIdx /* Index of %_segdir entry to delete */
  134535. ){
  134536. int rc; /* Return code */
  134537. sqlite3_stmt *pDelete = 0; /* DELETE statement */
  134538. rc = fts3SqlStmt(p, SQL_DELETE_SEGDIR_ENTRY, &pDelete, 0);
  134539. if( rc==SQLITE_OK ){
  134540. sqlite3_bind_int64(pDelete, 1, iAbsLevel);
  134541. sqlite3_bind_int(pDelete, 2, iIdx);
  134542. sqlite3_step(pDelete);
  134543. rc = sqlite3_reset(pDelete);
  134544. }
  134545. return rc;
  134546. }
  134547. /*
  134548. ** One or more segments have just been removed from absolute level iAbsLevel.
  134549. ** Update the 'idx' values of the remaining segments in the level so that
  134550. ** the idx values are a contiguous sequence starting from 0.
  134551. */
  134552. static int fts3RepackSegdirLevel(
  134553. Fts3Table *p, /* FTS3 table handle */
  134554. sqlite3_int64 iAbsLevel /* Absolute level to repack */
  134555. ){
  134556. int rc; /* Return code */
  134557. int *aIdx = 0; /* Array of remaining idx values */
  134558. int nIdx = 0; /* Valid entries in aIdx[] */
  134559. int nAlloc = 0; /* Allocated size of aIdx[] */
  134560. int i; /* Iterator variable */
  134561. sqlite3_stmt *pSelect = 0; /* Select statement to read idx values */
  134562. sqlite3_stmt *pUpdate = 0; /* Update statement to modify idx values */
  134563. rc = fts3SqlStmt(p, SQL_SELECT_INDEXES, &pSelect, 0);
  134564. if( rc==SQLITE_OK ){
  134565. int rc2;
  134566. sqlite3_bind_int64(pSelect, 1, iAbsLevel);
  134567. while( SQLITE_ROW==sqlite3_step(pSelect) ){
  134568. if( nIdx>=nAlloc ){
  134569. int *aNew;
  134570. nAlloc += 16;
  134571. aNew = sqlite3_realloc(aIdx, nAlloc*sizeof(int));
  134572. if( !aNew ){
  134573. rc = SQLITE_NOMEM;
  134574. break;
  134575. }
  134576. aIdx = aNew;
  134577. }
  134578. aIdx[nIdx++] = sqlite3_column_int(pSelect, 0);
  134579. }
  134580. rc2 = sqlite3_reset(pSelect);
  134581. if( rc==SQLITE_OK ) rc = rc2;
  134582. }
  134583. if( rc==SQLITE_OK ){
  134584. rc = fts3SqlStmt(p, SQL_SHIFT_SEGDIR_ENTRY, &pUpdate, 0);
  134585. }
  134586. if( rc==SQLITE_OK ){
  134587. sqlite3_bind_int64(pUpdate, 2, iAbsLevel);
  134588. }
  134589. assert( p->bIgnoreSavepoint==0 );
  134590. p->bIgnoreSavepoint = 1;
  134591. for(i=0; rc==SQLITE_OK && i<nIdx; i++){
  134592. if( aIdx[i]!=i ){
  134593. sqlite3_bind_int(pUpdate, 3, aIdx[i]);
  134594. sqlite3_bind_int(pUpdate, 1, i);
  134595. sqlite3_step(pUpdate);
  134596. rc = sqlite3_reset(pUpdate);
  134597. }
  134598. }
  134599. p->bIgnoreSavepoint = 0;
  134600. sqlite3_free(aIdx);
  134601. return rc;
  134602. }
  134603. static void fts3StartNode(Blob *pNode, int iHeight, sqlite3_int64 iChild){
  134604. pNode->a[0] = (char)iHeight;
  134605. if( iChild ){
  134606. assert( pNode->nAlloc>=1+sqlite3Fts3VarintLen(iChild) );
  134607. pNode->n = 1 + sqlite3Fts3PutVarint(&pNode->a[1], iChild);
  134608. }else{
  134609. assert( pNode->nAlloc>=1 );
  134610. pNode->n = 1;
  134611. }
  134612. }
  134613. /*
  134614. ** The first two arguments are a pointer to and the size of a segment b-tree
  134615. ** node. The node may be a leaf or an internal node.
  134616. **
  134617. ** This function creates a new node image in blob object *pNew by copying
  134618. ** all terms that are greater than or equal to zTerm/nTerm (for leaf nodes)
  134619. ** or greater than zTerm/nTerm (for internal nodes) from aNode/nNode.
  134620. */
  134621. static int fts3TruncateNode(
  134622. const char *aNode, /* Current node image */
  134623. int nNode, /* Size of aNode in bytes */
  134624. Blob *pNew, /* OUT: Write new node image here */
  134625. const char *zTerm, /* Omit all terms smaller than this */
  134626. int nTerm, /* Size of zTerm in bytes */
  134627. sqlite3_int64 *piBlock /* OUT: Block number in next layer down */
  134628. ){
  134629. NodeReader reader; /* Reader object */
  134630. Blob prev = {0, 0, 0}; /* Previous term written to new node */
  134631. int rc = SQLITE_OK; /* Return code */
  134632. int bLeaf = aNode[0]=='\0'; /* True for a leaf node */
  134633. /* Allocate required output space */
  134634. blobGrowBuffer(pNew, nNode, &rc);
  134635. if( rc!=SQLITE_OK ) return rc;
  134636. pNew->n = 0;
  134637. /* Populate new node buffer */
  134638. for(rc = nodeReaderInit(&reader, aNode, nNode);
  134639. rc==SQLITE_OK && reader.aNode;
  134640. rc = nodeReaderNext(&reader)
  134641. ){
  134642. if( pNew->n==0 ){
  134643. int res = fts3TermCmp(reader.term.a, reader.term.n, zTerm, nTerm);
  134644. if( res<0 || (bLeaf==0 && res==0) ) continue;
  134645. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  134646. *piBlock = reader.iChild;
  134647. }
  134648. rc = fts3AppendToNode(
  134649. pNew, &prev, reader.term.a, reader.term.n,
  134650. reader.aDoclist, reader.nDoclist
  134651. );
  134652. if( rc!=SQLITE_OK ) break;
  134653. }
  134654. if( pNew->n==0 ){
  134655. fts3StartNode(pNew, (int)aNode[0], reader.iChild);
  134656. *piBlock = reader.iChild;
  134657. }
  134658. assert( pNew->n<=pNew->nAlloc );
  134659. nodeReaderRelease(&reader);
  134660. sqlite3_free(prev.a);
  134661. return rc;
  134662. }
  134663. /*
  134664. ** Remove all terms smaller than zTerm/nTerm from segment iIdx in absolute
  134665. ** level iAbsLevel. This may involve deleting entries from the %_segments
  134666. ** table, and modifying existing entries in both the %_segments and %_segdir
  134667. ** tables.
  134668. **
  134669. ** SQLITE_OK is returned if the segment is updated successfully. Or an
  134670. ** SQLite error code otherwise.
  134671. */
  134672. static int fts3TruncateSegment(
  134673. Fts3Table *p, /* FTS3 table handle */
  134674. sqlite3_int64 iAbsLevel, /* Absolute level of segment to modify */
  134675. int iIdx, /* Index within level of segment to modify */
  134676. const char *zTerm, /* Remove terms smaller than this */
  134677. int nTerm /* Number of bytes in buffer zTerm */
  134678. ){
  134679. int rc = SQLITE_OK; /* Return code */
  134680. Blob root = {0,0,0}; /* New root page image */
  134681. Blob block = {0,0,0}; /* Buffer used for any other block */
  134682. sqlite3_int64 iBlock = 0; /* Block id */
  134683. sqlite3_int64 iNewStart = 0; /* New value for iStartBlock */
  134684. sqlite3_int64 iOldStart = 0; /* Old value for iStartBlock */
  134685. sqlite3_stmt *pFetch = 0; /* Statement used to fetch segdir */
  134686. rc = fts3SqlStmt(p, SQL_SELECT_SEGDIR, &pFetch, 0);
  134687. if( rc==SQLITE_OK ){
  134688. int rc2; /* sqlite3_reset() return code */
  134689. sqlite3_bind_int64(pFetch, 1, iAbsLevel);
  134690. sqlite3_bind_int(pFetch, 2, iIdx);
  134691. if( SQLITE_ROW==sqlite3_step(pFetch) ){
  134692. const char *aRoot = sqlite3_column_blob(pFetch, 4);
  134693. int nRoot = sqlite3_column_bytes(pFetch, 4);
  134694. iOldStart = sqlite3_column_int64(pFetch, 1);
  134695. rc = fts3TruncateNode(aRoot, nRoot, &root, zTerm, nTerm, &iBlock);
  134696. }
  134697. rc2 = sqlite3_reset(pFetch);
  134698. if( rc==SQLITE_OK ) rc = rc2;
  134699. }
  134700. while( rc==SQLITE_OK && iBlock ){
  134701. char *aBlock = 0;
  134702. int nBlock = 0;
  134703. iNewStart = iBlock;
  134704. rc = sqlite3Fts3ReadBlock(p, iBlock, &aBlock, &nBlock, 0);
  134705. if( rc==SQLITE_OK ){
  134706. rc = fts3TruncateNode(aBlock, nBlock, &block, zTerm, nTerm, &iBlock);
  134707. }
  134708. if( rc==SQLITE_OK ){
  134709. rc = fts3WriteSegment(p, iNewStart, block.a, block.n);
  134710. }
  134711. sqlite3_free(aBlock);
  134712. }
  134713. /* Variable iNewStart now contains the first valid leaf node. */
  134714. if( rc==SQLITE_OK && iNewStart ){
  134715. sqlite3_stmt *pDel = 0;
  134716. rc = fts3SqlStmt(p, SQL_DELETE_SEGMENTS_RANGE, &pDel, 0);
  134717. if( rc==SQLITE_OK ){
  134718. sqlite3_bind_int64(pDel, 1, iOldStart);
  134719. sqlite3_bind_int64(pDel, 2, iNewStart-1);
  134720. sqlite3_step(pDel);
  134721. rc = sqlite3_reset(pDel);
  134722. }
  134723. }
  134724. if( rc==SQLITE_OK ){
  134725. sqlite3_stmt *pChomp = 0;
  134726. rc = fts3SqlStmt(p, SQL_CHOMP_SEGDIR, &pChomp, 0);
  134727. if( rc==SQLITE_OK ){
  134728. sqlite3_bind_int64(pChomp, 1, iNewStart);
  134729. sqlite3_bind_blob(pChomp, 2, root.a, root.n, SQLITE_STATIC);
  134730. sqlite3_bind_int64(pChomp, 3, iAbsLevel);
  134731. sqlite3_bind_int(pChomp, 4, iIdx);
  134732. sqlite3_step(pChomp);
  134733. rc = sqlite3_reset(pChomp);
  134734. }
  134735. }
  134736. sqlite3_free(root.a);
  134737. sqlite3_free(block.a);
  134738. return rc;
  134739. }
  134740. /*
  134741. ** This function is called after an incrmental-merge operation has run to
  134742. ** merge (or partially merge) two or more segments from absolute level
  134743. ** iAbsLevel.
  134744. **
  134745. ** Each input segment is either removed from the db completely (if all of
  134746. ** its data was copied to the output segment by the incrmerge operation)
  134747. ** or modified in place so that it no longer contains those entries that
  134748. ** have been duplicated in the output segment.
  134749. */
  134750. static int fts3IncrmergeChomp(
  134751. Fts3Table *p, /* FTS table handle */
  134752. sqlite3_int64 iAbsLevel, /* Absolute level containing segments */
  134753. Fts3MultiSegReader *pCsr, /* Chomp all segments opened by this cursor */
  134754. int *pnRem /* Number of segments not deleted */
  134755. ){
  134756. int i;
  134757. int nRem = 0;
  134758. int rc = SQLITE_OK;
  134759. for(i=pCsr->nSegment-1; i>=0 && rc==SQLITE_OK; i--){
  134760. Fts3SegReader *pSeg = 0;
  134761. int j;
  134762. /* Find the Fts3SegReader object with Fts3SegReader.iIdx==i. It is hiding
  134763. ** somewhere in the pCsr->apSegment[] array. */
  134764. for(j=0; ALWAYS(j<pCsr->nSegment); j++){
  134765. pSeg = pCsr->apSegment[j];
  134766. if( pSeg->iIdx==i ) break;
  134767. }
  134768. assert( j<pCsr->nSegment && pSeg->iIdx==i );
  134769. if( pSeg->aNode==0 ){
  134770. /* Seg-reader is at EOF. Remove the entire input segment. */
  134771. rc = fts3DeleteSegment(p, pSeg);
  134772. if( rc==SQLITE_OK ){
  134773. rc = fts3RemoveSegdirEntry(p, iAbsLevel, pSeg->iIdx);
  134774. }
  134775. *pnRem = 0;
  134776. }else{
  134777. /* The incremental merge did not copy all the data from this
  134778. ** segment to the upper level. The segment is modified in place
  134779. ** so that it contains no keys smaller than zTerm/nTerm. */
  134780. const char *zTerm = pSeg->zTerm;
  134781. int nTerm = pSeg->nTerm;
  134782. rc = fts3TruncateSegment(p, iAbsLevel, pSeg->iIdx, zTerm, nTerm);
  134783. nRem++;
  134784. }
  134785. }
  134786. if( rc==SQLITE_OK && nRem!=pCsr->nSegment ){
  134787. rc = fts3RepackSegdirLevel(p, iAbsLevel);
  134788. }
  134789. *pnRem = nRem;
  134790. return rc;
  134791. }
  134792. /*
  134793. ** Store an incr-merge hint in the database.
  134794. */
  134795. static int fts3IncrmergeHintStore(Fts3Table *p, Blob *pHint){
  134796. sqlite3_stmt *pReplace = 0;
  134797. int rc; /* Return code */
  134798. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pReplace, 0);
  134799. if( rc==SQLITE_OK ){
  134800. sqlite3_bind_int(pReplace, 1, FTS_STAT_INCRMERGEHINT);
  134801. sqlite3_bind_blob(pReplace, 2, pHint->a, pHint->n, SQLITE_STATIC);
  134802. sqlite3_step(pReplace);
  134803. rc = sqlite3_reset(pReplace);
  134804. }
  134805. return rc;
  134806. }
  134807. /*
  134808. ** Load an incr-merge hint from the database. The incr-merge hint, if one
  134809. ** exists, is stored in the rowid==1 row of the %_stat table.
  134810. **
  134811. ** If successful, populate blob *pHint with the value read from the %_stat
  134812. ** table and return SQLITE_OK. Otherwise, if an error occurs, return an
  134813. ** SQLite error code.
  134814. */
  134815. static int fts3IncrmergeHintLoad(Fts3Table *p, Blob *pHint){
  134816. sqlite3_stmt *pSelect = 0;
  134817. int rc;
  134818. pHint->n = 0;
  134819. rc = fts3SqlStmt(p, SQL_SELECT_STAT, &pSelect, 0);
  134820. if( rc==SQLITE_OK ){
  134821. int rc2;
  134822. sqlite3_bind_int(pSelect, 1, FTS_STAT_INCRMERGEHINT);
  134823. if( SQLITE_ROW==sqlite3_step(pSelect) ){
  134824. const char *aHint = sqlite3_column_blob(pSelect, 0);
  134825. int nHint = sqlite3_column_bytes(pSelect, 0);
  134826. if( aHint ){
  134827. blobGrowBuffer(pHint, nHint, &rc);
  134828. if( rc==SQLITE_OK ){
  134829. memcpy(pHint->a, aHint, nHint);
  134830. pHint->n = nHint;
  134831. }
  134832. }
  134833. }
  134834. rc2 = sqlite3_reset(pSelect);
  134835. if( rc==SQLITE_OK ) rc = rc2;
  134836. }
  134837. return rc;
  134838. }
  134839. /*
  134840. ** If *pRc is not SQLITE_OK when this function is called, it is a no-op.
  134841. ** Otherwise, append an entry to the hint stored in blob *pHint. Each entry
  134842. ** consists of two varints, the absolute level number of the input segments
  134843. ** and the number of input segments.
  134844. **
  134845. ** If successful, leave *pRc set to SQLITE_OK and return. If an error occurs,
  134846. ** set *pRc to an SQLite error code before returning.
  134847. */
  134848. static void fts3IncrmergeHintPush(
  134849. Blob *pHint, /* Hint blob to append to */
  134850. i64 iAbsLevel, /* First varint to store in hint */
  134851. int nInput, /* Second varint to store in hint */
  134852. int *pRc /* IN/OUT: Error code */
  134853. ){
  134854. blobGrowBuffer(pHint, pHint->n + 2*FTS3_VARINT_MAX, pRc);
  134855. if( *pRc==SQLITE_OK ){
  134856. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], iAbsLevel);
  134857. pHint->n += sqlite3Fts3PutVarint(&pHint->a[pHint->n], (i64)nInput);
  134858. }
  134859. }
  134860. /*
  134861. ** Read the last entry (most recently pushed) from the hint blob *pHint
  134862. ** and then remove the entry. Write the two values read to *piAbsLevel and
  134863. ** *pnInput before returning.
  134864. **
  134865. ** If no error occurs, return SQLITE_OK. If the hint blob in *pHint does
  134866. ** not contain at least two valid varints, return SQLITE_CORRUPT_VTAB.
  134867. */
  134868. static int fts3IncrmergeHintPop(Blob *pHint, i64 *piAbsLevel, int *pnInput){
  134869. const int nHint = pHint->n;
  134870. int i;
  134871. i = pHint->n-2;
  134872. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  134873. while( i>0 && (pHint->a[i-1] & 0x80) ) i--;
  134874. pHint->n = i;
  134875. i += sqlite3Fts3GetVarint(&pHint->a[i], piAbsLevel);
  134876. i += fts3GetVarint32(&pHint->a[i], pnInput);
  134877. if( i!=nHint ) return SQLITE_CORRUPT_VTAB;
  134878. return SQLITE_OK;
  134879. }
  134880. /*
  134881. ** Attempt an incremental merge that writes nMerge leaf blocks.
  134882. **
  134883. ** Incremental merges happen nMin segments at a time. The segments
  134884. ** to be merged are the nMin oldest segments (the ones with the smallest
  134885. ** values for the _segdir.idx field) in the highest level that contains
  134886. ** at least nMin segments. Multiple merges might occur in an attempt to
  134887. ** write the quota of nMerge leaf blocks.
  134888. */
  134889. SQLITE_PRIVATE int sqlite3Fts3Incrmerge(Fts3Table *p, int nMerge, int nMin){
  134890. int rc; /* Return code */
  134891. int nRem = nMerge; /* Number of leaf pages yet to be written */
  134892. Fts3MultiSegReader *pCsr; /* Cursor used to read input data */
  134893. Fts3SegFilter *pFilter; /* Filter used with cursor pCsr */
  134894. IncrmergeWriter *pWriter; /* Writer object */
  134895. int nSeg = 0; /* Number of input segments */
  134896. sqlite3_int64 iAbsLevel = 0; /* Absolute level number to work on */
  134897. Blob hint = {0, 0, 0}; /* Hint read from %_stat table */
  134898. int bDirtyHint = 0; /* True if blob 'hint' has been modified */
  134899. /* Allocate space for the cursor, filter and writer objects */
  134900. const int nAlloc = sizeof(*pCsr) + sizeof(*pFilter) + sizeof(*pWriter);
  134901. pWriter = (IncrmergeWriter *)sqlite3_malloc(nAlloc);
  134902. if( !pWriter ) return SQLITE_NOMEM;
  134903. pFilter = (Fts3SegFilter *)&pWriter[1];
  134904. pCsr = (Fts3MultiSegReader *)&pFilter[1];
  134905. rc = fts3IncrmergeHintLoad(p, &hint);
  134906. while( rc==SQLITE_OK && nRem>0 ){
  134907. const i64 nMod = FTS3_SEGDIR_MAXLEVEL * p->nIndex;
  134908. sqlite3_stmt *pFindLevel = 0; /* SQL used to determine iAbsLevel */
  134909. int bUseHint = 0; /* True if attempting to append */
  134910. int iIdx = 0; /* Largest idx in level (iAbsLevel+1) */
  134911. /* Search the %_segdir table for the absolute level with the smallest
  134912. ** relative level number that contains at least nMin segments, if any.
  134913. ** If one is found, set iAbsLevel to the absolute level number and
  134914. ** nSeg to nMin. If no level with at least nMin segments can be found,
  134915. ** set nSeg to -1.
  134916. */
  134917. rc = fts3SqlStmt(p, SQL_FIND_MERGE_LEVEL, &pFindLevel, 0);
  134918. sqlite3_bind_int(pFindLevel, 1, nMin);
  134919. if( sqlite3_step(pFindLevel)==SQLITE_ROW ){
  134920. iAbsLevel = sqlite3_column_int64(pFindLevel, 0);
  134921. nSeg = nMin;
  134922. }else{
  134923. nSeg = -1;
  134924. }
  134925. rc = sqlite3_reset(pFindLevel);
  134926. /* If the hint read from the %_stat table is not empty, check if the
  134927. ** last entry in it specifies a relative level smaller than or equal
  134928. ** to the level identified by the block above (if any). If so, this
  134929. ** iteration of the loop will work on merging at the hinted level.
  134930. */
  134931. if( rc==SQLITE_OK && hint.n ){
  134932. int nHint = hint.n;
  134933. sqlite3_int64 iHintAbsLevel = 0; /* Hint level */
  134934. int nHintSeg = 0; /* Hint number of segments */
  134935. rc = fts3IncrmergeHintPop(&hint, &iHintAbsLevel, &nHintSeg);
  134936. if( nSeg<0 || (iAbsLevel % nMod) >= (iHintAbsLevel % nMod) ){
  134937. iAbsLevel = iHintAbsLevel;
  134938. nSeg = nHintSeg;
  134939. bUseHint = 1;
  134940. bDirtyHint = 1;
  134941. }else{
  134942. /* This undoes the effect of the HintPop() above - so that no entry
  134943. ** is removed from the hint blob. */
  134944. hint.n = nHint;
  134945. }
  134946. }
  134947. /* If nSeg is less that zero, then there is no level with at least
  134948. ** nMin segments and no hint in the %_stat table. No work to do.
  134949. ** Exit early in this case. */
  134950. if( nSeg<0 ) break;
  134951. /* Open a cursor to iterate through the contents of the oldest nSeg
  134952. ** indexes of absolute level iAbsLevel. If this cursor is opened using
  134953. ** the 'hint' parameters, it is possible that there are less than nSeg
  134954. ** segments available in level iAbsLevel. In this case, no work is
  134955. ** done on iAbsLevel - fall through to the next iteration of the loop
  134956. ** to start work on some other level. */
  134957. memset(pWriter, 0, nAlloc);
  134958. pFilter->flags = FTS3_SEGMENT_REQUIRE_POS;
  134959. if( rc==SQLITE_OK ){
  134960. rc = fts3IncrmergeOutputIdx(p, iAbsLevel, &iIdx);
  134961. assert( bUseHint==1 || bUseHint==0 );
  134962. if( iIdx==0 || (bUseHint && iIdx==1) ){
  134963. int bIgnore = 0;
  134964. rc = fts3SegmentIsMaxLevel(p, iAbsLevel+1, &bIgnore);
  134965. if( bIgnore ){
  134966. pFilter->flags |= FTS3_SEGMENT_IGNORE_EMPTY;
  134967. }
  134968. }
  134969. }
  134970. if( rc==SQLITE_OK ){
  134971. rc = fts3IncrmergeCsr(p, iAbsLevel, nSeg, pCsr);
  134972. }
  134973. if( SQLITE_OK==rc && pCsr->nSegment==nSeg
  134974. && SQLITE_OK==(rc = sqlite3Fts3SegReaderStart(p, pCsr, pFilter))
  134975. && SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, pCsr))
  134976. ){
  134977. if( bUseHint && iIdx>0 ){
  134978. const char *zKey = pCsr->zTerm;
  134979. int nKey = pCsr->nTerm;
  134980. rc = fts3IncrmergeLoad(p, iAbsLevel, iIdx-1, zKey, nKey, pWriter);
  134981. }else{
  134982. rc = fts3IncrmergeWriter(p, iAbsLevel, iIdx, pCsr, pWriter);
  134983. }
  134984. if( rc==SQLITE_OK && pWriter->nLeafEst ){
  134985. fts3LogMerge(nSeg, iAbsLevel);
  134986. do {
  134987. rc = fts3IncrmergeAppend(p, pWriter, pCsr);
  134988. if( rc==SQLITE_OK ) rc = sqlite3Fts3SegReaderStep(p, pCsr);
  134989. if( pWriter->nWork>=nRem && rc==SQLITE_ROW ) rc = SQLITE_OK;
  134990. }while( rc==SQLITE_ROW );
  134991. /* Update or delete the input segments */
  134992. if( rc==SQLITE_OK ){
  134993. nRem -= (1 + pWriter->nWork);
  134994. rc = fts3IncrmergeChomp(p, iAbsLevel, pCsr, &nSeg);
  134995. if( nSeg!=0 ){
  134996. bDirtyHint = 1;
  134997. fts3IncrmergeHintPush(&hint, iAbsLevel, nSeg, &rc);
  134998. }
  134999. }
  135000. }
  135001. if( nSeg!=0 ){
  135002. pWriter->nLeafData = pWriter->nLeafData * -1;
  135003. }
  135004. fts3IncrmergeRelease(p, pWriter, &rc);
  135005. if( nSeg==0 && pWriter->bNoLeafData==0 ){
  135006. fts3PromoteSegments(p, iAbsLevel+1, pWriter->nLeafData);
  135007. }
  135008. }
  135009. sqlite3Fts3SegReaderFinish(pCsr);
  135010. }
  135011. /* Write the hint values into the %_stat table for the next incr-merger */
  135012. if( bDirtyHint && rc==SQLITE_OK ){
  135013. rc = fts3IncrmergeHintStore(p, &hint);
  135014. }
  135015. sqlite3_free(pWriter);
  135016. sqlite3_free(hint.a);
  135017. return rc;
  135018. }
  135019. /*
  135020. ** Convert the text beginning at *pz into an integer and return
  135021. ** its value. Advance *pz to point to the first character past
  135022. ** the integer.
  135023. */
  135024. static int fts3Getint(const char **pz){
  135025. const char *z = *pz;
  135026. int i = 0;
  135027. while( (*z)>='0' && (*z)<='9' ) i = 10*i + *(z++) - '0';
  135028. *pz = z;
  135029. return i;
  135030. }
  135031. /*
  135032. ** Process statements of the form:
  135033. **
  135034. ** INSERT INTO table(table) VALUES('merge=A,B');
  135035. **
  135036. ** A and B are integers that decode to be the number of leaf pages
  135037. ** written for the merge, and the minimum number of segments on a level
  135038. ** before it will be selected for a merge, respectively.
  135039. */
  135040. static int fts3DoIncrmerge(
  135041. Fts3Table *p, /* FTS3 table handle */
  135042. const char *zParam /* Nul-terminated string containing "A,B" */
  135043. ){
  135044. int rc;
  135045. int nMin = (FTS3_MERGE_COUNT / 2);
  135046. int nMerge = 0;
  135047. const char *z = zParam;
  135048. /* Read the first integer value */
  135049. nMerge = fts3Getint(&z);
  135050. /* If the first integer value is followed by a ',', read the second
  135051. ** integer value. */
  135052. if( z[0]==',' && z[1]!='\0' ){
  135053. z++;
  135054. nMin = fts3Getint(&z);
  135055. }
  135056. if( z[0]!='\0' || nMin<2 ){
  135057. rc = SQLITE_ERROR;
  135058. }else{
  135059. rc = SQLITE_OK;
  135060. if( !p->bHasStat ){
  135061. assert( p->bFts4==0 );
  135062. sqlite3Fts3CreateStatTable(&rc, p);
  135063. }
  135064. if( rc==SQLITE_OK ){
  135065. rc = sqlite3Fts3Incrmerge(p, nMerge, nMin);
  135066. }
  135067. sqlite3Fts3SegmentsClose(p);
  135068. }
  135069. return rc;
  135070. }
  135071. /*
  135072. ** Process statements of the form:
  135073. **
  135074. ** INSERT INTO table(table) VALUES('automerge=X');
  135075. **
  135076. ** where X is an integer. X==0 means to turn automerge off. X!=0 means
  135077. ** turn it on. The setting is persistent.
  135078. */
  135079. static int fts3DoAutoincrmerge(
  135080. Fts3Table *p, /* FTS3 table handle */
  135081. const char *zParam /* Nul-terminated string containing boolean */
  135082. ){
  135083. int rc = SQLITE_OK;
  135084. sqlite3_stmt *pStmt = 0;
  135085. p->nAutoincrmerge = fts3Getint(&zParam);
  135086. if( p->nAutoincrmerge==1 || p->nAutoincrmerge>FTS3_MERGE_COUNT ){
  135087. p->nAutoincrmerge = 8;
  135088. }
  135089. if( !p->bHasStat ){
  135090. assert( p->bFts4==0 );
  135091. sqlite3Fts3CreateStatTable(&rc, p);
  135092. if( rc ) return rc;
  135093. }
  135094. rc = fts3SqlStmt(p, SQL_REPLACE_STAT, &pStmt, 0);
  135095. if( rc ) return rc;
  135096. sqlite3_bind_int(pStmt, 1, FTS_STAT_AUTOINCRMERGE);
  135097. sqlite3_bind_int(pStmt, 2, p->nAutoincrmerge);
  135098. sqlite3_step(pStmt);
  135099. rc = sqlite3_reset(pStmt);
  135100. return rc;
  135101. }
  135102. /*
  135103. ** Return a 64-bit checksum for the FTS index entry specified by the
  135104. ** arguments to this function.
  135105. */
  135106. static u64 fts3ChecksumEntry(
  135107. const char *zTerm, /* Pointer to buffer containing term */
  135108. int nTerm, /* Size of zTerm in bytes */
  135109. int iLangid, /* Language id for current row */
  135110. int iIndex, /* Index (0..Fts3Table.nIndex-1) */
  135111. i64 iDocid, /* Docid for current row. */
  135112. int iCol, /* Column number */
  135113. int iPos /* Position */
  135114. ){
  135115. int i;
  135116. u64 ret = (u64)iDocid;
  135117. ret += (ret<<3) + iLangid;
  135118. ret += (ret<<3) + iIndex;
  135119. ret += (ret<<3) + iCol;
  135120. ret += (ret<<3) + iPos;
  135121. for(i=0; i<nTerm; i++) ret += (ret<<3) + zTerm[i];
  135122. return ret;
  135123. }
  135124. /*
  135125. ** Return a checksum of all entries in the FTS index that correspond to
  135126. ** language id iLangid. The checksum is calculated by XORing the checksums
  135127. ** of each individual entry (see fts3ChecksumEntry()) together.
  135128. **
  135129. ** If successful, the checksum value is returned and *pRc set to SQLITE_OK.
  135130. ** Otherwise, if an error occurs, *pRc is set to an SQLite error code. The
  135131. ** return value is undefined in this case.
  135132. */
  135133. static u64 fts3ChecksumIndex(
  135134. Fts3Table *p, /* FTS3 table handle */
  135135. int iLangid, /* Language id to return cksum for */
  135136. int iIndex, /* Index to cksum (0..p->nIndex-1) */
  135137. int *pRc /* OUT: Return code */
  135138. ){
  135139. Fts3SegFilter filter;
  135140. Fts3MultiSegReader csr;
  135141. int rc;
  135142. u64 cksum = 0;
  135143. assert( *pRc==SQLITE_OK );
  135144. memset(&filter, 0, sizeof(filter));
  135145. memset(&csr, 0, sizeof(csr));
  135146. filter.flags = FTS3_SEGMENT_REQUIRE_POS|FTS3_SEGMENT_IGNORE_EMPTY;
  135147. filter.flags |= FTS3_SEGMENT_SCAN;
  135148. rc = sqlite3Fts3SegReaderCursor(
  135149. p, iLangid, iIndex, FTS3_SEGCURSOR_ALL, 0, 0, 0, 1,&csr
  135150. );
  135151. if( rc==SQLITE_OK ){
  135152. rc = sqlite3Fts3SegReaderStart(p, &csr, &filter);
  135153. }
  135154. if( rc==SQLITE_OK ){
  135155. while( SQLITE_ROW==(rc = sqlite3Fts3SegReaderStep(p, &csr)) ){
  135156. char *pCsr = csr.aDoclist;
  135157. char *pEnd = &pCsr[csr.nDoclist];
  135158. i64 iDocid = 0;
  135159. i64 iCol = 0;
  135160. i64 iPos = 0;
  135161. pCsr += sqlite3Fts3GetVarint(pCsr, &iDocid);
  135162. while( pCsr<pEnd ){
  135163. i64 iVal = 0;
  135164. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  135165. if( pCsr<pEnd ){
  135166. if( iVal==0 || iVal==1 ){
  135167. iCol = 0;
  135168. iPos = 0;
  135169. if( iVal ){
  135170. pCsr += sqlite3Fts3GetVarint(pCsr, &iCol);
  135171. }else{
  135172. pCsr += sqlite3Fts3GetVarint(pCsr, &iVal);
  135173. iDocid += iVal;
  135174. }
  135175. }else{
  135176. iPos += (iVal - 2);
  135177. cksum = cksum ^ fts3ChecksumEntry(
  135178. csr.zTerm, csr.nTerm, iLangid, iIndex, iDocid,
  135179. (int)iCol, (int)iPos
  135180. );
  135181. }
  135182. }
  135183. }
  135184. }
  135185. }
  135186. sqlite3Fts3SegReaderFinish(&csr);
  135187. *pRc = rc;
  135188. return cksum;
  135189. }
  135190. /*
  135191. ** Check if the contents of the FTS index match the current contents of the
  135192. ** content table. If no error occurs and the contents do match, set *pbOk
  135193. ** to true and return SQLITE_OK. Or if the contents do not match, set *pbOk
  135194. ** to false before returning.
  135195. **
  135196. ** If an error occurs (e.g. an OOM or IO error), return an SQLite error
  135197. ** code. The final value of *pbOk is undefined in this case.
  135198. */
  135199. static int fts3IntegrityCheck(Fts3Table *p, int *pbOk){
  135200. int rc = SQLITE_OK; /* Return code */
  135201. u64 cksum1 = 0; /* Checksum based on FTS index contents */
  135202. u64 cksum2 = 0; /* Checksum based on %_content contents */
  135203. sqlite3_stmt *pAllLangid = 0; /* Statement to return all language-ids */
  135204. /* This block calculates the checksum according to the FTS index. */
  135205. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  135206. if( rc==SQLITE_OK ){
  135207. int rc2;
  135208. sqlite3_bind_int(pAllLangid, 1, p->nIndex);
  135209. while( rc==SQLITE_OK && sqlite3_step(pAllLangid)==SQLITE_ROW ){
  135210. int iLangid = sqlite3_column_int(pAllLangid, 0);
  135211. int i;
  135212. for(i=0; i<p->nIndex; i++){
  135213. cksum1 = cksum1 ^ fts3ChecksumIndex(p, iLangid, i, &rc);
  135214. }
  135215. }
  135216. rc2 = sqlite3_reset(pAllLangid);
  135217. if( rc==SQLITE_OK ) rc = rc2;
  135218. }
  135219. /* This block calculates the checksum according to the %_content table */
  135220. rc = fts3SqlStmt(p, SQL_SELECT_ALL_LANGID, &pAllLangid, 0);
  135221. if( rc==SQLITE_OK ){
  135222. sqlite3_tokenizer_module const *pModule = p->pTokenizer->pModule;
  135223. sqlite3_stmt *pStmt = 0;
  135224. char *zSql;
  135225. zSql = sqlite3_mprintf("SELECT %s" , p->zReadExprlist);
  135226. if( !zSql ){
  135227. rc = SQLITE_NOMEM;
  135228. }else{
  135229. rc = sqlite3_prepare_v2(p->db, zSql, -1, &pStmt, 0);
  135230. sqlite3_free(zSql);
  135231. }
  135232. while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pStmt) ){
  135233. i64 iDocid = sqlite3_column_int64(pStmt, 0);
  135234. int iLang = langidFromSelect(p, pStmt);
  135235. int iCol;
  135236. for(iCol=0; rc==SQLITE_OK && iCol<p->nColumn; iCol++){
  135237. if( p->abNotindexed[iCol]==0 ){
  135238. const char *zText = (const char *)sqlite3_column_text(pStmt, iCol+1);
  135239. int nText = sqlite3_column_bytes(pStmt, iCol+1);
  135240. sqlite3_tokenizer_cursor *pT = 0;
  135241. rc = sqlite3Fts3OpenTokenizer(p->pTokenizer, iLang, zText, nText,&pT);
  135242. while( rc==SQLITE_OK ){
  135243. char const *zToken; /* Buffer containing token */
  135244. int nToken = 0; /* Number of bytes in token */
  135245. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  135246. int iPos = 0; /* Position of token in zText */
  135247. rc = pModule->xNext(pT, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  135248. if( rc==SQLITE_OK ){
  135249. int i;
  135250. cksum2 = cksum2 ^ fts3ChecksumEntry(
  135251. zToken, nToken, iLang, 0, iDocid, iCol, iPos
  135252. );
  135253. for(i=1; i<p->nIndex; i++){
  135254. if( p->aIndex[i].nPrefix<=nToken ){
  135255. cksum2 = cksum2 ^ fts3ChecksumEntry(
  135256. zToken, p->aIndex[i].nPrefix, iLang, i, iDocid, iCol, iPos
  135257. );
  135258. }
  135259. }
  135260. }
  135261. }
  135262. if( pT ) pModule->xClose(pT);
  135263. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  135264. }
  135265. }
  135266. }
  135267. sqlite3_finalize(pStmt);
  135268. }
  135269. *pbOk = (cksum1==cksum2);
  135270. return rc;
  135271. }
  135272. /*
  135273. ** Run the integrity-check. If no error occurs and the current contents of
  135274. ** the FTS index are correct, return SQLITE_OK. Or, if the contents of the
  135275. ** FTS index are incorrect, return SQLITE_CORRUPT_VTAB.
  135276. **
  135277. ** Or, if an error (e.g. an OOM or IO error) occurs, return an SQLite
  135278. ** error code.
  135279. **
  135280. ** The integrity-check works as follows. For each token and indexed token
  135281. ** prefix in the document set, a 64-bit checksum is calculated (by code
  135282. ** in fts3ChecksumEntry()) based on the following:
  135283. **
  135284. ** + The index number (0 for the main index, 1 for the first prefix
  135285. ** index etc.),
  135286. ** + The token (or token prefix) text itself,
  135287. ** + The language-id of the row it appears in,
  135288. ** + The docid of the row it appears in,
  135289. ** + The column it appears in, and
  135290. ** + The tokens position within that column.
  135291. **
  135292. ** The checksums for all entries in the index are XORed together to create
  135293. ** a single checksum for the entire index.
  135294. **
  135295. ** The integrity-check code calculates the same checksum in two ways:
  135296. **
  135297. ** 1. By scanning the contents of the FTS index, and
  135298. ** 2. By scanning and tokenizing the content table.
  135299. **
  135300. ** If the two checksums are identical, the integrity-check is deemed to have
  135301. ** passed.
  135302. */
  135303. static int fts3DoIntegrityCheck(
  135304. Fts3Table *p /* FTS3 table handle */
  135305. ){
  135306. int rc;
  135307. int bOk = 0;
  135308. rc = fts3IntegrityCheck(p, &bOk);
  135309. if( rc==SQLITE_OK && bOk==0 ) rc = SQLITE_CORRUPT_VTAB;
  135310. return rc;
  135311. }
  135312. /*
  135313. ** Handle a 'special' INSERT of the form:
  135314. **
  135315. ** "INSERT INTO tbl(tbl) VALUES(<expr>)"
  135316. **
  135317. ** Argument pVal contains the result of <expr>. Currently the only
  135318. ** meaningful value to insert is the text 'optimize'.
  135319. */
  135320. static int fts3SpecialInsert(Fts3Table *p, sqlite3_value *pVal){
  135321. int rc; /* Return Code */
  135322. const char *zVal = (const char *)sqlite3_value_text(pVal);
  135323. int nVal = sqlite3_value_bytes(pVal);
  135324. if( !zVal ){
  135325. return SQLITE_NOMEM;
  135326. }else if( nVal==8 && 0==sqlite3_strnicmp(zVal, "optimize", 8) ){
  135327. rc = fts3DoOptimize(p, 0);
  135328. }else if( nVal==7 && 0==sqlite3_strnicmp(zVal, "rebuild", 7) ){
  135329. rc = fts3DoRebuild(p);
  135330. }else if( nVal==15 && 0==sqlite3_strnicmp(zVal, "integrity-check", 15) ){
  135331. rc = fts3DoIntegrityCheck(p);
  135332. }else if( nVal>6 && 0==sqlite3_strnicmp(zVal, "merge=", 6) ){
  135333. rc = fts3DoIncrmerge(p, &zVal[6]);
  135334. }else if( nVal>10 && 0==sqlite3_strnicmp(zVal, "automerge=", 10) ){
  135335. rc = fts3DoAutoincrmerge(p, &zVal[10]);
  135336. #ifdef SQLITE_TEST
  135337. }else if( nVal>9 && 0==sqlite3_strnicmp(zVal, "nodesize=", 9) ){
  135338. p->nNodeSize = atoi(&zVal[9]);
  135339. rc = SQLITE_OK;
  135340. }else if( nVal>11 && 0==sqlite3_strnicmp(zVal, "maxpending=", 9) ){
  135341. p->nMaxPendingData = atoi(&zVal[11]);
  135342. rc = SQLITE_OK;
  135343. }else if( nVal>21 && 0==sqlite3_strnicmp(zVal, "test-no-incr-doclist=", 21) ){
  135344. p->bNoIncrDoclist = atoi(&zVal[21]);
  135345. rc = SQLITE_OK;
  135346. #endif
  135347. }else{
  135348. rc = SQLITE_ERROR;
  135349. }
  135350. return rc;
  135351. }
  135352. #ifndef SQLITE_DISABLE_FTS4_DEFERRED
  135353. /*
  135354. ** Delete all cached deferred doclists. Deferred doclists are cached
  135355. ** (allocated) by the sqlite3Fts3CacheDeferredDoclists() function.
  135356. */
  135357. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredDoclists(Fts3Cursor *pCsr){
  135358. Fts3DeferredToken *pDef;
  135359. for(pDef=pCsr->pDeferred; pDef; pDef=pDef->pNext){
  135360. fts3PendingListDelete(pDef->pList);
  135361. pDef->pList = 0;
  135362. }
  135363. }
  135364. /*
  135365. ** Free all entries in the pCsr->pDeffered list. Entries are added to
  135366. ** this list using sqlite3Fts3DeferToken().
  135367. */
  135368. SQLITE_PRIVATE void sqlite3Fts3FreeDeferredTokens(Fts3Cursor *pCsr){
  135369. Fts3DeferredToken *pDef;
  135370. Fts3DeferredToken *pNext;
  135371. for(pDef=pCsr->pDeferred; pDef; pDef=pNext){
  135372. pNext = pDef->pNext;
  135373. fts3PendingListDelete(pDef->pList);
  135374. sqlite3_free(pDef);
  135375. }
  135376. pCsr->pDeferred = 0;
  135377. }
  135378. /*
  135379. ** Generate deferred-doclists for all tokens in the pCsr->pDeferred list
  135380. ** based on the row that pCsr currently points to.
  135381. **
  135382. ** A deferred-doclist is like any other doclist with position information
  135383. ** included, except that it only contains entries for a single row of the
  135384. ** table, not for all rows.
  135385. */
  135386. SQLITE_PRIVATE int sqlite3Fts3CacheDeferredDoclists(Fts3Cursor *pCsr){
  135387. int rc = SQLITE_OK; /* Return code */
  135388. if( pCsr->pDeferred ){
  135389. int i; /* Used to iterate through table columns */
  135390. sqlite3_int64 iDocid; /* Docid of the row pCsr points to */
  135391. Fts3DeferredToken *pDef; /* Used to iterate through deferred tokens */
  135392. Fts3Table *p = (Fts3Table *)pCsr->base.pVtab;
  135393. sqlite3_tokenizer *pT = p->pTokenizer;
  135394. sqlite3_tokenizer_module const *pModule = pT->pModule;
  135395. assert( pCsr->isRequireSeek==0 );
  135396. iDocid = sqlite3_column_int64(pCsr->pStmt, 0);
  135397. for(i=0; i<p->nColumn && rc==SQLITE_OK; i++){
  135398. if( p->abNotindexed[i]==0 ){
  135399. const char *zText = (const char *)sqlite3_column_text(pCsr->pStmt, i+1);
  135400. sqlite3_tokenizer_cursor *pTC = 0;
  135401. rc = sqlite3Fts3OpenTokenizer(pT, pCsr->iLangid, zText, -1, &pTC);
  135402. while( rc==SQLITE_OK ){
  135403. char const *zToken; /* Buffer containing token */
  135404. int nToken = 0; /* Number of bytes in token */
  135405. int iDum1 = 0, iDum2 = 0; /* Dummy variables */
  135406. int iPos = 0; /* Position of token in zText */
  135407. rc = pModule->xNext(pTC, &zToken, &nToken, &iDum1, &iDum2, &iPos);
  135408. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  135409. Fts3PhraseToken *pPT = pDef->pToken;
  135410. if( (pDef->iCol>=p->nColumn || pDef->iCol==i)
  135411. && (pPT->bFirst==0 || iPos==0)
  135412. && (pPT->n==nToken || (pPT->isPrefix && pPT->n<nToken))
  135413. && (0==memcmp(zToken, pPT->z, pPT->n))
  135414. ){
  135415. fts3PendingListAppend(&pDef->pList, iDocid, i, iPos, &rc);
  135416. }
  135417. }
  135418. }
  135419. if( pTC ) pModule->xClose(pTC);
  135420. if( rc==SQLITE_DONE ) rc = SQLITE_OK;
  135421. }
  135422. }
  135423. for(pDef=pCsr->pDeferred; pDef && rc==SQLITE_OK; pDef=pDef->pNext){
  135424. if( pDef->pList ){
  135425. rc = fts3PendingListAppendVarint(&pDef->pList, 0);
  135426. }
  135427. }
  135428. }
  135429. return rc;
  135430. }
  135431. SQLITE_PRIVATE int sqlite3Fts3DeferredTokenList(
  135432. Fts3DeferredToken *p,
  135433. char **ppData,
  135434. int *pnData
  135435. ){
  135436. char *pRet;
  135437. int nSkip;
  135438. sqlite3_int64 dummy;
  135439. *ppData = 0;
  135440. *pnData = 0;
  135441. if( p->pList==0 ){
  135442. return SQLITE_OK;
  135443. }
  135444. pRet = (char *)sqlite3_malloc(p->pList->nData);
  135445. if( !pRet ) return SQLITE_NOMEM;
  135446. nSkip = sqlite3Fts3GetVarint(p->pList->aData, &dummy);
  135447. *pnData = p->pList->nData - nSkip;
  135448. *ppData = pRet;
  135449. memcpy(pRet, &p->pList->aData[nSkip], *pnData);
  135450. return SQLITE_OK;
  135451. }
  135452. /*
  135453. ** Add an entry for token pToken to the pCsr->pDeferred list.
  135454. */
  135455. SQLITE_PRIVATE int sqlite3Fts3DeferToken(
  135456. Fts3Cursor *pCsr, /* Fts3 table cursor */
  135457. Fts3PhraseToken *pToken, /* Token to defer */
  135458. int iCol /* Column that token must appear in (or -1) */
  135459. ){
  135460. Fts3DeferredToken *pDeferred;
  135461. pDeferred = sqlite3_malloc(sizeof(*pDeferred));
  135462. if( !pDeferred ){
  135463. return SQLITE_NOMEM;
  135464. }
  135465. memset(pDeferred, 0, sizeof(*pDeferred));
  135466. pDeferred->pToken = pToken;
  135467. pDeferred->pNext = pCsr->pDeferred;
  135468. pDeferred->iCol = iCol;
  135469. pCsr->pDeferred = pDeferred;
  135470. assert( pToken->pDeferred==0 );
  135471. pToken->pDeferred = pDeferred;
  135472. return SQLITE_OK;
  135473. }
  135474. #endif
  135475. /*
  135476. ** SQLite value pRowid contains the rowid of a row that may or may not be
  135477. ** present in the FTS3 table. If it is, delete it and adjust the contents
  135478. ** of subsiduary data structures accordingly.
  135479. */
  135480. static int fts3DeleteByRowid(
  135481. Fts3Table *p,
  135482. sqlite3_value *pRowid,
  135483. int *pnChng, /* IN/OUT: Decrement if row is deleted */
  135484. u32 *aSzDel
  135485. ){
  135486. int rc = SQLITE_OK; /* Return code */
  135487. int bFound = 0; /* True if *pRowid really is in the table */
  135488. fts3DeleteTerms(&rc, p, pRowid, aSzDel, &bFound);
  135489. if( bFound && rc==SQLITE_OK ){
  135490. int isEmpty = 0; /* Deleting *pRowid leaves the table empty */
  135491. rc = fts3IsEmpty(p, pRowid, &isEmpty);
  135492. if( rc==SQLITE_OK ){
  135493. if( isEmpty ){
  135494. /* Deleting this row means the whole table is empty. In this case
  135495. ** delete the contents of all three tables and throw away any
  135496. ** data in the pendingTerms hash table. */
  135497. rc = fts3DeleteAll(p, 1);
  135498. *pnChng = 0;
  135499. memset(aSzDel, 0, sizeof(u32) * (p->nColumn+1) * 2);
  135500. }else{
  135501. *pnChng = *pnChng - 1;
  135502. if( p->zContentTbl==0 ){
  135503. fts3SqlExec(&rc, p, SQL_DELETE_CONTENT, &pRowid);
  135504. }
  135505. if( p->bHasDocsize ){
  135506. fts3SqlExec(&rc, p, SQL_DELETE_DOCSIZE, &pRowid);
  135507. }
  135508. }
  135509. }
  135510. }
  135511. return rc;
  135512. }
  135513. /*
  135514. ** This function does the work for the xUpdate method of FTS3 virtual
  135515. ** tables. The schema of the virtual table being:
  135516. **
  135517. ** CREATE TABLE <table name>(
  135518. ** <user columns>,
  135519. ** <table name> HIDDEN,
  135520. ** docid HIDDEN,
  135521. ** <langid> HIDDEN
  135522. ** );
  135523. **
  135524. **
  135525. */
  135526. SQLITE_PRIVATE int sqlite3Fts3UpdateMethod(
  135527. sqlite3_vtab *pVtab, /* FTS3 vtab object */
  135528. int nArg, /* Size of argument array */
  135529. sqlite3_value **apVal, /* Array of arguments */
  135530. sqlite_int64 *pRowid /* OUT: The affected (or effected) rowid */
  135531. ){
  135532. Fts3Table *p = (Fts3Table *)pVtab;
  135533. int rc = SQLITE_OK; /* Return Code */
  135534. int isRemove = 0; /* True for an UPDATE or DELETE */
  135535. u32 *aSzIns = 0; /* Sizes of inserted documents */
  135536. u32 *aSzDel = 0; /* Sizes of deleted documents */
  135537. int nChng = 0; /* Net change in number of documents */
  135538. int bInsertDone = 0;
  135539. /* At this point it must be known if the %_stat table exists or not.
  135540. ** So bHasStat may not be 2. */
  135541. assert( p->bHasStat==0 || p->bHasStat==1 );
  135542. assert( p->pSegments==0 );
  135543. assert(
  135544. nArg==1 /* DELETE operations */
  135545. || nArg==(2 + p->nColumn + 3) /* INSERT or UPDATE operations */
  135546. );
  135547. /* Check for a "special" INSERT operation. One of the form:
  135548. **
  135549. ** INSERT INTO xyz(xyz) VALUES('command');
  135550. */
  135551. if( nArg>1
  135552. && sqlite3_value_type(apVal[0])==SQLITE_NULL
  135553. && sqlite3_value_type(apVal[p->nColumn+2])!=SQLITE_NULL
  135554. ){
  135555. rc = fts3SpecialInsert(p, apVal[p->nColumn+2]);
  135556. goto update_out;
  135557. }
  135558. if( nArg>1 && sqlite3_value_int(apVal[2 + p->nColumn + 2])<0 ){
  135559. rc = SQLITE_CONSTRAINT;
  135560. goto update_out;
  135561. }
  135562. /* Allocate space to hold the change in document sizes */
  135563. aSzDel = sqlite3_malloc( sizeof(aSzDel[0])*(p->nColumn+1)*2 );
  135564. if( aSzDel==0 ){
  135565. rc = SQLITE_NOMEM;
  135566. goto update_out;
  135567. }
  135568. aSzIns = &aSzDel[p->nColumn+1];
  135569. memset(aSzDel, 0, sizeof(aSzDel[0])*(p->nColumn+1)*2);
  135570. rc = fts3Writelock(p);
  135571. if( rc!=SQLITE_OK ) goto update_out;
  135572. /* If this is an INSERT operation, or an UPDATE that modifies the rowid
  135573. ** value, then this operation requires constraint handling.
  135574. **
  135575. ** If the on-conflict mode is REPLACE, this means that the existing row
  135576. ** should be deleted from the database before inserting the new row. Or,
  135577. ** if the on-conflict mode is other than REPLACE, then this method must
  135578. ** detect the conflict and return SQLITE_CONSTRAINT before beginning to
  135579. ** modify the database file.
  135580. */
  135581. if( nArg>1 && p->zContentTbl==0 ){
  135582. /* Find the value object that holds the new rowid value. */
  135583. sqlite3_value *pNewRowid = apVal[3+p->nColumn];
  135584. if( sqlite3_value_type(pNewRowid)==SQLITE_NULL ){
  135585. pNewRowid = apVal[1];
  135586. }
  135587. if( sqlite3_value_type(pNewRowid)!=SQLITE_NULL && (
  135588. sqlite3_value_type(apVal[0])==SQLITE_NULL
  135589. || sqlite3_value_int64(apVal[0])!=sqlite3_value_int64(pNewRowid)
  135590. )){
  135591. /* The new rowid is not NULL (in this case the rowid will be
  135592. ** automatically assigned and there is no chance of a conflict), and
  135593. ** the statement is either an INSERT or an UPDATE that modifies the
  135594. ** rowid column. So if the conflict mode is REPLACE, then delete any
  135595. ** existing row with rowid=pNewRowid.
  135596. **
  135597. ** Or, if the conflict mode is not REPLACE, insert the new record into
  135598. ** the %_content table. If we hit the duplicate rowid constraint (or any
  135599. ** other error) while doing so, return immediately.
  135600. **
  135601. ** This branch may also run if pNewRowid contains a value that cannot
  135602. ** be losslessly converted to an integer. In this case, the eventual
  135603. ** call to fts3InsertData() (either just below or further on in this
  135604. ** function) will return SQLITE_MISMATCH. If fts3DeleteByRowid is
  135605. ** invoked, it will delete zero rows (since no row will have
  135606. ** docid=$pNewRowid if $pNewRowid is not an integer value).
  135607. */
  135608. if( sqlite3_vtab_on_conflict(p->db)==SQLITE_REPLACE ){
  135609. rc = fts3DeleteByRowid(p, pNewRowid, &nChng, aSzDel);
  135610. }else{
  135611. rc = fts3InsertData(p, apVal, pRowid);
  135612. bInsertDone = 1;
  135613. }
  135614. }
  135615. }
  135616. if( rc!=SQLITE_OK ){
  135617. goto update_out;
  135618. }
  135619. /* If this is a DELETE or UPDATE operation, remove the old record. */
  135620. if( sqlite3_value_type(apVal[0])!=SQLITE_NULL ){
  135621. assert( sqlite3_value_type(apVal[0])==SQLITE_INTEGER );
  135622. rc = fts3DeleteByRowid(p, apVal[0], &nChng, aSzDel);
  135623. isRemove = 1;
  135624. }
  135625. /* If this is an INSERT or UPDATE operation, insert the new record. */
  135626. if( nArg>1 && rc==SQLITE_OK ){
  135627. int iLangid = sqlite3_value_int(apVal[2 + p->nColumn + 2]);
  135628. if( bInsertDone==0 ){
  135629. rc = fts3InsertData(p, apVal, pRowid);
  135630. if( rc==SQLITE_CONSTRAINT && p->zContentTbl==0 ){
  135631. rc = FTS_CORRUPT_VTAB;
  135632. }
  135633. }
  135634. if( rc==SQLITE_OK && (!isRemove || *pRowid!=p->iPrevDocid ) ){
  135635. rc = fts3PendingTermsDocid(p, iLangid, *pRowid);
  135636. }
  135637. if( rc==SQLITE_OK ){
  135638. assert( p->iPrevDocid==*pRowid );
  135639. rc = fts3InsertTerms(p, iLangid, apVal, aSzIns);
  135640. }
  135641. if( p->bHasDocsize ){
  135642. fts3InsertDocsize(&rc, p, aSzIns);
  135643. }
  135644. nChng++;
  135645. }
  135646. if( p->bFts4 ){
  135647. fts3UpdateDocTotals(&rc, p, aSzIns, aSzDel, nChng);
  135648. }
  135649. update_out:
  135650. sqlite3_free(aSzDel);
  135651. sqlite3Fts3SegmentsClose(p);
  135652. return rc;
  135653. }
  135654. /*
  135655. ** Flush any data in the pending-terms hash table to disk. If successful,
  135656. ** merge all segments in the database (including the new segment, if
  135657. ** there was any data to flush) into a single segment.
  135658. */
  135659. SQLITE_PRIVATE int sqlite3Fts3Optimize(Fts3Table *p){
  135660. int rc;
  135661. rc = sqlite3_exec(p->db, "SAVEPOINT fts3", 0, 0, 0);
  135662. if( rc==SQLITE_OK ){
  135663. rc = fts3DoOptimize(p, 1);
  135664. if( rc==SQLITE_OK || rc==SQLITE_DONE ){
  135665. int rc2 = sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  135666. if( rc2!=SQLITE_OK ) rc = rc2;
  135667. }else{
  135668. sqlite3_exec(p->db, "ROLLBACK TO fts3", 0, 0, 0);
  135669. sqlite3_exec(p->db, "RELEASE fts3", 0, 0, 0);
  135670. }
  135671. }
  135672. sqlite3Fts3SegmentsClose(p);
  135673. return rc;
  135674. }
  135675. #endif
  135676. /************** End of fts3_write.c ******************************************/
  135677. /************** Begin file fts3_snippet.c ************************************/
  135678. /*
  135679. ** 2009 Oct 23
  135680. **
  135681. ** The author disclaims copyright to this source code. In place of
  135682. ** a legal notice, here is a blessing:
  135683. **
  135684. ** May you do good and not evil.
  135685. ** May you find forgiveness for yourself and forgive others.
  135686. ** May you share freely, never taking more than you give.
  135687. **
  135688. ******************************************************************************
  135689. */
  135690. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  135691. /* #include <string.h> */
  135692. /* #include <assert.h> */
  135693. /*
  135694. ** Characters that may appear in the second argument to matchinfo().
  135695. */
  135696. #define FTS3_MATCHINFO_NPHRASE 'p' /* 1 value */
  135697. #define FTS3_MATCHINFO_NCOL 'c' /* 1 value */
  135698. #define FTS3_MATCHINFO_NDOC 'n' /* 1 value */
  135699. #define FTS3_MATCHINFO_AVGLENGTH 'a' /* nCol values */
  135700. #define FTS3_MATCHINFO_LENGTH 'l' /* nCol values */
  135701. #define FTS3_MATCHINFO_LCS 's' /* nCol values */
  135702. #define FTS3_MATCHINFO_HITS 'x' /* 3*nCol*nPhrase values */
  135703. /*
  135704. ** The default value for the second argument to matchinfo().
  135705. */
  135706. #define FTS3_MATCHINFO_DEFAULT "pcx"
  135707. /*
  135708. ** Used as an fts3ExprIterate() context when loading phrase doclists to
  135709. ** Fts3Expr.aDoclist[]/nDoclist.
  135710. */
  135711. typedef struct LoadDoclistCtx LoadDoclistCtx;
  135712. struct LoadDoclistCtx {
  135713. Fts3Cursor *pCsr; /* FTS3 Cursor */
  135714. int nPhrase; /* Number of phrases seen so far */
  135715. int nToken; /* Number of tokens seen so far */
  135716. };
  135717. /*
  135718. ** The following types are used as part of the implementation of the
  135719. ** fts3BestSnippet() routine.
  135720. */
  135721. typedef struct SnippetIter SnippetIter;
  135722. typedef struct SnippetPhrase SnippetPhrase;
  135723. typedef struct SnippetFragment SnippetFragment;
  135724. struct SnippetIter {
  135725. Fts3Cursor *pCsr; /* Cursor snippet is being generated from */
  135726. int iCol; /* Extract snippet from this column */
  135727. int nSnippet; /* Requested snippet length (in tokens) */
  135728. int nPhrase; /* Number of phrases in query */
  135729. SnippetPhrase *aPhrase; /* Array of size nPhrase */
  135730. int iCurrent; /* First token of current snippet */
  135731. };
  135732. struct SnippetPhrase {
  135733. int nToken; /* Number of tokens in phrase */
  135734. char *pList; /* Pointer to start of phrase position list */
  135735. int iHead; /* Next value in position list */
  135736. char *pHead; /* Position list data following iHead */
  135737. int iTail; /* Next value in trailing position list */
  135738. char *pTail; /* Position list data following iTail */
  135739. };
  135740. struct SnippetFragment {
  135741. int iCol; /* Column snippet is extracted from */
  135742. int iPos; /* Index of first token in snippet */
  135743. u64 covered; /* Mask of query phrases covered */
  135744. u64 hlmask; /* Mask of snippet terms to highlight */
  135745. };
  135746. /*
  135747. ** This type is used as an fts3ExprIterate() context object while
  135748. ** accumulating the data returned by the matchinfo() function.
  135749. */
  135750. typedef struct MatchInfo MatchInfo;
  135751. struct MatchInfo {
  135752. Fts3Cursor *pCursor; /* FTS3 Cursor */
  135753. int nCol; /* Number of columns in table */
  135754. int nPhrase; /* Number of matchable phrases in query */
  135755. sqlite3_int64 nDoc; /* Number of docs in database */
  135756. u32 *aMatchinfo; /* Pre-allocated buffer */
  135757. };
  135758. /*
  135759. ** The snippet() and offsets() functions both return text values. An instance
  135760. ** of the following structure is used to accumulate those values while the
  135761. ** functions are running. See fts3StringAppend() for details.
  135762. */
  135763. typedef struct StrBuffer StrBuffer;
  135764. struct StrBuffer {
  135765. char *z; /* Pointer to buffer containing string */
  135766. int n; /* Length of z in bytes (excl. nul-term) */
  135767. int nAlloc; /* Allocated size of buffer z in bytes */
  135768. };
  135769. /*
  135770. ** This function is used to help iterate through a position-list. A position
  135771. ** list is a list of unique integers, sorted from smallest to largest. Each
  135772. ** element of the list is represented by an FTS3 varint that takes the value
  135773. ** of the difference between the current element and the previous one plus
  135774. ** two. For example, to store the position-list:
  135775. **
  135776. ** 4 9 113
  135777. **
  135778. ** the three varints:
  135779. **
  135780. ** 6 7 106
  135781. **
  135782. ** are encoded.
  135783. **
  135784. ** When this function is called, *pp points to the start of an element of
  135785. ** the list. *piPos contains the value of the previous entry in the list.
  135786. ** After it returns, *piPos contains the value of the next element of the
  135787. ** list and *pp is advanced to the following varint.
  135788. */
  135789. static void fts3GetDeltaPosition(char **pp, int *piPos){
  135790. int iVal;
  135791. *pp += fts3GetVarint32(*pp, &iVal);
  135792. *piPos += (iVal-2);
  135793. }
  135794. /*
  135795. ** Helper function for fts3ExprIterate() (see below).
  135796. */
  135797. static int fts3ExprIterate2(
  135798. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  135799. int *piPhrase, /* Pointer to phrase counter */
  135800. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  135801. void *pCtx /* Second argument to pass to callback */
  135802. ){
  135803. int rc; /* Return code */
  135804. int eType = pExpr->eType; /* Type of expression node pExpr */
  135805. if( eType!=FTSQUERY_PHRASE ){
  135806. assert( pExpr->pLeft && pExpr->pRight );
  135807. rc = fts3ExprIterate2(pExpr->pLeft, piPhrase, x, pCtx);
  135808. if( rc==SQLITE_OK && eType!=FTSQUERY_NOT ){
  135809. rc = fts3ExprIterate2(pExpr->pRight, piPhrase, x, pCtx);
  135810. }
  135811. }else{
  135812. rc = x(pExpr, *piPhrase, pCtx);
  135813. (*piPhrase)++;
  135814. }
  135815. return rc;
  135816. }
  135817. /*
  135818. ** Iterate through all phrase nodes in an FTS3 query, except those that
  135819. ** are part of a sub-tree that is the right-hand-side of a NOT operator.
  135820. ** For each phrase node found, the supplied callback function is invoked.
  135821. **
  135822. ** If the callback function returns anything other than SQLITE_OK,
  135823. ** the iteration is abandoned and the error code returned immediately.
  135824. ** Otherwise, SQLITE_OK is returned after a callback has been made for
  135825. ** all eligible phrase nodes.
  135826. */
  135827. static int fts3ExprIterate(
  135828. Fts3Expr *pExpr, /* Expression to iterate phrases of */
  135829. int (*x)(Fts3Expr*,int,void*), /* Callback function to invoke for phrases */
  135830. void *pCtx /* Second argument to pass to callback */
  135831. ){
  135832. int iPhrase = 0; /* Variable used as the phrase counter */
  135833. return fts3ExprIterate2(pExpr, &iPhrase, x, pCtx);
  135834. }
  135835. /*
  135836. ** This is an fts3ExprIterate() callback used while loading the doclists
  135837. ** for each phrase into Fts3Expr.aDoclist[]/nDoclist. See also
  135838. ** fts3ExprLoadDoclists().
  135839. */
  135840. static int fts3ExprLoadDoclistsCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  135841. int rc = SQLITE_OK;
  135842. Fts3Phrase *pPhrase = pExpr->pPhrase;
  135843. LoadDoclistCtx *p = (LoadDoclistCtx *)ctx;
  135844. UNUSED_PARAMETER(iPhrase);
  135845. p->nPhrase++;
  135846. p->nToken += pPhrase->nToken;
  135847. return rc;
  135848. }
  135849. /*
  135850. ** Load the doclists for each phrase in the query associated with FTS3 cursor
  135851. ** pCsr.
  135852. **
  135853. ** If pnPhrase is not NULL, then *pnPhrase is set to the number of matchable
  135854. ** phrases in the expression (all phrases except those directly or
  135855. ** indirectly descended from the right-hand-side of a NOT operator). If
  135856. ** pnToken is not NULL, then it is set to the number of tokens in all
  135857. ** matchable phrases of the expression.
  135858. */
  135859. static int fts3ExprLoadDoclists(
  135860. Fts3Cursor *pCsr, /* Fts3 cursor for current query */
  135861. int *pnPhrase, /* OUT: Number of phrases in query */
  135862. int *pnToken /* OUT: Number of tokens in query */
  135863. ){
  135864. int rc; /* Return Code */
  135865. LoadDoclistCtx sCtx = {0,0,0}; /* Context for fts3ExprIterate() */
  135866. sCtx.pCsr = pCsr;
  135867. rc = fts3ExprIterate(pCsr->pExpr, fts3ExprLoadDoclistsCb, (void *)&sCtx);
  135868. if( pnPhrase ) *pnPhrase = sCtx.nPhrase;
  135869. if( pnToken ) *pnToken = sCtx.nToken;
  135870. return rc;
  135871. }
  135872. static int fts3ExprPhraseCountCb(Fts3Expr *pExpr, int iPhrase, void *ctx){
  135873. (*(int *)ctx)++;
  135874. UNUSED_PARAMETER(pExpr);
  135875. UNUSED_PARAMETER(iPhrase);
  135876. return SQLITE_OK;
  135877. }
  135878. static int fts3ExprPhraseCount(Fts3Expr *pExpr){
  135879. int nPhrase = 0;
  135880. (void)fts3ExprIterate(pExpr, fts3ExprPhraseCountCb, (void *)&nPhrase);
  135881. return nPhrase;
  135882. }
  135883. /*
  135884. ** Advance the position list iterator specified by the first two
  135885. ** arguments so that it points to the first element with a value greater
  135886. ** than or equal to parameter iNext.
  135887. */
  135888. static void fts3SnippetAdvance(char **ppIter, int *piIter, int iNext){
  135889. char *pIter = *ppIter;
  135890. if( pIter ){
  135891. int iIter = *piIter;
  135892. while( iIter<iNext ){
  135893. if( 0==(*pIter & 0xFE) ){
  135894. iIter = -1;
  135895. pIter = 0;
  135896. break;
  135897. }
  135898. fts3GetDeltaPosition(&pIter, &iIter);
  135899. }
  135900. *piIter = iIter;
  135901. *ppIter = pIter;
  135902. }
  135903. }
  135904. /*
  135905. ** Advance the snippet iterator to the next candidate snippet.
  135906. */
  135907. static int fts3SnippetNextCandidate(SnippetIter *pIter){
  135908. int i; /* Loop counter */
  135909. if( pIter->iCurrent<0 ){
  135910. /* The SnippetIter object has just been initialized. The first snippet
  135911. ** candidate always starts at offset 0 (even if this candidate has a
  135912. ** score of 0.0).
  135913. */
  135914. pIter->iCurrent = 0;
  135915. /* Advance the 'head' iterator of each phrase to the first offset that
  135916. ** is greater than or equal to (iNext+nSnippet).
  135917. */
  135918. for(i=0; i<pIter->nPhrase; i++){
  135919. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  135920. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, pIter->nSnippet);
  135921. }
  135922. }else{
  135923. int iStart;
  135924. int iEnd = 0x7FFFFFFF;
  135925. for(i=0; i<pIter->nPhrase; i++){
  135926. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  135927. if( pPhrase->pHead && pPhrase->iHead<iEnd ){
  135928. iEnd = pPhrase->iHead;
  135929. }
  135930. }
  135931. if( iEnd==0x7FFFFFFF ){
  135932. return 1;
  135933. }
  135934. pIter->iCurrent = iStart = iEnd - pIter->nSnippet + 1;
  135935. for(i=0; i<pIter->nPhrase; i++){
  135936. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  135937. fts3SnippetAdvance(&pPhrase->pHead, &pPhrase->iHead, iEnd+1);
  135938. fts3SnippetAdvance(&pPhrase->pTail, &pPhrase->iTail, iStart);
  135939. }
  135940. }
  135941. return 0;
  135942. }
  135943. /*
  135944. ** Retrieve information about the current candidate snippet of snippet
  135945. ** iterator pIter.
  135946. */
  135947. static void fts3SnippetDetails(
  135948. SnippetIter *pIter, /* Snippet iterator */
  135949. u64 mCovered, /* Bitmask of phrases already covered */
  135950. int *piToken, /* OUT: First token of proposed snippet */
  135951. int *piScore, /* OUT: "Score" for this snippet */
  135952. u64 *pmCover, /* OUT: Bitmask of phrases covered */
  135953. u64 *pmHighlight /* OUT: Bitmask of terms to highlight */
  135954. ){
  135955. int iStart = pIter->iCurrent; /* First token of snippet */
  135956. int iScore = 0; /* Score of this snippet */
  135957. int i; /* Loop counter */
  135958. u64 mCover = 0; /* Mask of phrases covered by this snippet */
  135959. u64 mHighlight = 0; /* Mask of tokens to highlight in snippet */
  135960. for(i=0; i<pIter->nPhrase; i++){
  135961. SnippetPhrase *pPhrase = &pIter->aPhrase[i];
  135962. if( pPhrase->pTail ){
  135963. char *pCsr = pPhrase->pTail;
  135964. int iCsr = pPhrase->iTail;
  135965. while( iCsr<(iStart+pIter->nSnippet) ){
  135966. int j;
  135967. u64 mPhrase = (u64)1 << i;
  135968. u64 mPos = (u64)1 << (iCsr - iStart);
  135969. assert( iCsr>=iStart );
  135970. if( (mCover|mCovered)&mPhrase ){
  135971. iScore++;
  135972. }else{
  135973. iScore += 1000;
  135974. }
  135975. mCover |= mPhrase;
  135976. for(j=0; j<pPhrase->nToken; j++){
  135977. mHighlight |= (mPos>>j);
  135978. }
  135979. if( 0==(*pCsr & 0x0FE) ) break;
  135980. fts3GetDeltaPosition(&pCsr, &iCsr);
  135981. }
  135982. }
  135983. }
  135984. /* Set the output variables before returning. */
  135985. *piToken = iStart;
  135986. *piScore = iScore;
  135987. *pmCover = mCover;
  135988. *pmHighlight = mHighlight;
  135989. }
  135990. /*
  135991. ** This function is an fts3ExprIterate() callback used by fts3BestSnippet().
  135992. ** Each invocation populates an element of the SnippetIter.aPhrase[] array.
  135993. */
  135994. static int fts3SnippetFindPositions(Fts3Expr *pExpr, int iPhrase, void *ctx){
  135995. SnippetIter *p = (SnippetIter *)ctx;
  135996. SnippetPhrase *pPhrase = &p->aPhrase[iPhrase];
  135997. char *pCsr;
  135998. int rc;
  135999. pPhrase->nToken = pExpr->pPhrase->nToken;
  136000. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pCsr);
  136001. assert( rc==SQLITE_OK || pCsr==0 );
  136002. if( pCsr ){
  136003. int iFirst = 0;
  136004. pPhrase->pList = pCsr;
  136005. fts3GetDeltaPosition(&pCsr, &iFirst);
  136006. assert( iFirst>=0 );
  136007. pPhrase->pHead = pCsr;
  136008. pPhrase->pTail = pCsr;
  136009. pPhrase->iHead = iFirst;
  136010. pPhrase->iTail = iFirst;
  136011. }else{
  136012. assert( rc!=SQLITE_OK || (
  136013. pPhrase->pList==0 && pPhrase->pHead==0 && pPhrase->pTail==0
  136014. ));
  136015. }
  136016. return rc;
  136017. }
  136018. /*
  136019. ** Select the fragment of text consisting of nFragment contiguous tokens
  136020. ** from column iCol that represent the "best" snippet. The best snippet
  136021. ** is the snippet with the highest score, where scores are calculated
  136022. ** by adding:
  136023. **
  136024. ** (a) +1 point for each occurrence of a matchable phrase in the snippet.
  136025. **
  136026. ** (b) +1000 points for the first occurrence of each matchable phrase in
  136027. ** the snippet for which the corresponding mCovered bit is not set.
  136028. **
  136029. ** The selected snippet parameters are stored in structure *pFragment before
  136030. ** returning. The score of the selected snippet is stored in *piScore
  136031. ** before returning.
  136032. */
  136033. static int fts3BestSnippet(
  136034. int nSnippet, /* Desired snippet length */
  136035. Fts3Cursor *pCsr, /* Cursor to create snippet for */
  136036. int iCol, /* Index of column to create snippet from */
  136037. u64 mCovered, /* Mask of phrases already covered */
  136038. u64 *pmSeen, /* IN/OUT: Mask of phrases seen */
  136039. SnippetFragment *pFragment, /* OUT: Best snippet found */
  136040. int *piScore /* OUT: Score of snippet pFragment */
  136041. ){
  136042. int rc; /* Return Code */
  136043. int nList; /* Number of phrases in expression */
  136044. SnippetIter sIter; /* Iterates through snippet candidates */
  136045. int nByte; /* Number of bytes of space to allocate */
  136046. int iBestScore = -1; /* Best snippet score found so far */
  136047. int i; /* Loop counter */
  136048. memset(&sIter, 0, sizeof(sIter));
  136049. /* Iterate through the phrases in the expression to count them. The same
  136050. ** callback makes sure the doclists are loaded for each phrase.
  136051. */
  136052. rc = fts3ExprLoadDoclists(pCsr, &nList, 0);
  136053. if( rc!=SQLITE_OK ){
  136054. return rc;
  136055. }
  136056. /* Now that it is known how many phrases there are, allocate and zero
  136057. ** the required space using malloc().
  136058. */
  136059. nByte = sizeof(SnippetPhrase) * nList;
  136060. sIter.aPhrase = (SnippetPhrase *)sqlite3_malloc(nByte);
  136061. if( !sIter.aPhrase ){
  136062. return SQLITE_NOMEM;
  136063. }
  136064. memset(sIter.aPhrase, 0, nByte);
  136065. /* Initialize the contents of the SnippetIter object. Then iterate through
  136066. ** the set of phrases in the expression to populate the aPhrase[] array.
  136067. */
  136068. sIter.pCsr = pCsr;
  136069. sIter.iCol = iCol;
  136070. sIter.nSnippet = nSnippet;
  136071. sIter.nPhrase = nList;
  136072. sIter.iCurrent = -1;
  136073. (void)fts3ExprIterate(pCsr->pExpr, fts3SnippetFindPositions, (void *)&sIter);
  136074. /* Set the *pmSeen output variable. */
  136075. for(i=0; i<nList; i++){
  136076. if( sIter.aPhrase[i].pHead ){
  136077. *pmSeen |= (u64)1 << i;
  136078. }
  136079. }
  136080. /* Loop through all candidate snippets. Store the best snippet in
  136081. ** *pFragment. Store its associated 'score' in iBestScore.
  136082. */
  136083. pFragment->iCol = iCol;
  136084. while( !fts3SnippetNextCandidate(&sIter) ){
  136085. int iPos;
  136086. int iScore;
  136087. u64 mCover;
  136088. u64 mHighlight;
  136089. fts3SnippetDetails(&sIter, mCovered, &iPos, &iScore, &mCover, &mHighlight);
  136090. assert( iScore>=0 );
  136091. if( iScore>iBestScore ){
  136092. pFragment->iPos = iPos;
  136093. pFragment->hlmask = mHighlight;
  136094. pFragment->covered = mCover;
  136095. iBestScore = iScore;
  136096. }
  136097. }
  136098. sqlite3_free(sIter.aPhrase);
  136099. *piScore = iBestScore;
  136100. return SQLITE_OK;
  136101. }
  136102. /*
  136103. ** Append a string to the string-buffer passed as the first argument.
  136104. **
  136105. ** If nAppend is negative, then the length of the string zAppend is
  136106. ** determined using strlen().
  136107. */
  136108. static int fts3StringAppend(
  136109. StrBuffer *pStr, /* Buffer to append to */
  136110. const char *zAppend, /* Pointer to data to append to buffer */
  136111. int nAppend /* Size of zAppend in bytes (or -1) */
  136112. ){
  136113. if( nAppend<0 ){
  136114. nAppend = (int)strlen(zAppend);
  136115. }
  136116. /* If there is insufficient space allocated at StrBuffer.z, use realloc()
  136117. ** to grow the buffer until so that it is big enough to accomadate the
  136118. ** appended data.
  136119. */
  136120. if( pStr->n+nAppend+1>=pStr->nAlloc ){
  136121. int nAlloc = pStr->nAlloc+nAppend+100;
  136122. char *zNew = sqlite3_realloc(pStr->z, nAlloc);
  136123. if( !zNew ){
  136124. return SQLITE_NOMEM;
  136125. }
  136126. pStr->z = zNew;
  136127. pStr->nAlloc = nAlloc;
  136128. }
  136129. assert( pStr->z!=0 && (pStr->nAlloc >= pStr->n+nAppend+1) );
  136130. /* Append the data to the string buffer. */
  136131. memcpy(&pStr->z[pStr->n], zAppend, nAppend);
  136132. pStr->n += nAppend;
  136133. pStr->z[pStr->n] = '\0';
  136134. return SQLITE_OK;
  136135. }
  136136. /*
  136137. ** The fts3BestSnippet() function often selects snippets that end with a
  136138. ** query term. That is, the final term of the snippet is always a term
  136139. ** that requires highlighting. For example, if 'X' is a highlighted term
  136140. ** and '.' is a non-highlighted term, BestSnippet() may select:
  136141. **
  136142. ** ........X.....X
  136143. **
  136144. ** This function "shifts" the beginning of the snippet forward in the
  136145. ** document so that there are approximately the same number of
  136146. ** non-highlighted terms to the right of the final highlighted term as there
  136147. ** are to the left of the first highlighted term. For example, to this:
  136148. **
  136149. ** ....X.....X....
  136150. **
  136151. ** This is done as part of extracting the snippet text, not when selecting
  136152. ** the snippet. Snippet selection is done based on doclists only, so there
  136153. ** is no way for fts3BestSnippet() to know whether or not the document
  136154. ** actually contains terms that follow the final highlighted term.
  136155. */
  136156. static int fts3SnippetShift(
  136157. Fts3Table *pTab, /* FTS3 table snippet comes from */
  136158. int iLangid, /* Language id to use in tokenizing */
  136159. int nSnippet, /* Number of tokens desired for snippet */
  136160. const char *zDoc, /* Document text to extract snippet from */
  136161. int nDoc, /* Size of buffer zDoc in bytes */
  136162. int *piPos, /* IN/OUT: First token of snippet */
  136163. u64 *pHlmask /* IN/OUT: Mask of tokens to highlight */
  136164. ){
  136165. u64 hlmask = *pHlmask; /* Local copy of initial highlight-mask */
  136166. if( hlmask ){
  136167. int nLeft; /* Tokens to the left of first highlight */
  136168. int nRight; /* Tokens to the right of last highlight */
  136169. int nDesired; /* Ideal number of tokens to shift forward */
  136170. for(nLeft=0; !(hlmask & ((u64)1 << nLeft)); nLeft++);
  136171. for(nRight=0; !(hlmask & ((u64)1 << (nSnippet-1-nRight))); nRight++);
  136172. nDesired = (nLeft-nRight)/2;
  136173. /* Ideally, the start of the snippet should be pushed forward in the
  136174. ** document nDesired tokens. This block checks if there are actually
  136175. ** nDesired tokens to the right of the snippet. If so, *piPos and
  136176. ** *pHlMask are updated to shift the snippet nDesired tokens to the
  136177. ** right. Otherwise, the snippet is shifted by the number of tokens
  136178. ** available.
  136179. */
  136180. if( nDesired>0 ){
  136181. int nShift; /* Number of tokens to shift snippet by */
  136182. int iCurrent = 0; /* Token counter */
  136183. int rc; /* Return Code */
  136184. sqlite3_tokenizer_module *pMod;
  136185. sqlite3_tokenizer_cursor *pC;
  136186. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  136187. /* Open a cursor on zDoc/nDoc. Check if there are (nSnippet+nDesired)
  136188. ** or more tokens in zDoc/nDoc.
  136189. */
  136190. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, iLangid, zDoc, nDoc, &pC);
  136191. if( rc!=SQLITE_OK ){
  136192. return rc;
  136193. }
  136194. while( rc==SQLITE_OK && iCurrent<(nSnippet+nDesired) ){
  136195. const char *ZDUMMY; int DUMMY1 = 0, DUMMY2 = 0, DUMMY3 = 0;
  136196. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &DUMMY2, &DUMMY3, &iCurrent);
  136197. }
  136198. pMod->xClose(pC);
  136199. if( rc!=SQLITE_OK && rc!=SQLITE_DONE ){ return rc; }
  136200. nShift = (rc==SQLITE_DONE)+iCurrent-nSnippet;
  136201. assert( nShift<=nDesired );
  136202. if( nShift>0 ){
  136203. *piPos += nShift;
  136204. *pHlmask = hlmask >> nShift;
  136205. }
  136206. }
  136207. }
  136208. return SQLITE_OK;
  136209. }
  136210. /*
  136211. ** Extract the snippet text for fragment pFragment from cursor pCsr and
  136212. ** append it to string buffer pOut.
  136213. */
  136214. static int fts3SnippetText(
  136215. Fts3Cursor *pCsr, /* FTS3 Cursor */
  136216. SnippetFragment *pFragment, /* Snippet to extract */
  136217. int iFragment, /* Fragment number */
  136218. int isLast, /* True for final fragment in snippet */
  136219. int nSnippet, /* Number of tokens in extracted snippet */
  136220. const char *zOpen, /* String inserted before highlighted term */
  136221. const char *zClose, /* String inserted after highlighted term */
  136222. const char *zEllipsis, /* String inserted between snippets */
  136223. StrBuffer *pOut /* Write output here */
  136224. ){
  136225. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  136226. int rc; /* Return code */
  136227. const char *zDoc; /* Document text to extract snippet from */
  136228. int nDoc; /* Size of zDoc in bytes */
  136229. int iCurrent = 0; /* Current token number of document */
  136230. int iEnd = 0; /* Byte offset of end of current token */
  136231. int isShiftDone = 0; /* True after snippet is shifted */
  136232. int iPos = pFragment->iPos; /* First token of snippet */
  136233. u64 hlmask = pFragment->hlmask; /* Highlight-mask for snippet */
  136234. int iCol = pFragment->iCol+1; /* Query column to extract text from */
  136235. sqlite3_tokenizer_module *pMod; /* Tokenizer module methods object */
  136236. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor open on zDoc/nDoc */
  136237. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol);
  136238. if( zDoc==0 ){
  136239. if( sqlite3_column_type(pCsr->pStmt, iCol)!=SQLITE_NULL ){
  136240. return SQLITE_NOMEM;
  136241. }
  136242. return SQLITE_OK;
  136243. }
  136244. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol);
  136245. /* Open a token cursor on the document. */
  136246. pMod = (sqlite3_tokenizer_module *)pTab->pTokenizer->pModule;
  136247. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid, zDoc,nDoc,&pC);
  136248. if( rc!=SQLITE_OK ){
  136249. return rc;
  136250. }
  136251. while( rc==SQLITE_OK ){
  136252. const char *ZDUMMY; /* Dummy argument used with tokenizer */
  136253. int DUMMY1 = -1; /* Dummy argument used with tokenizer */
  136254. int iBegin = 0; /* Offset in zDoc of start of token */
  136255. int iFin = 0; /* Offset in zDoc of end of token */
  136256. int isHighlight = 0; /* True for highlighted terms */
  136257. /* Variable DUMMY1 is initialized to a negative value above. Elsewhere
  136258. ** in the FTS code the variable that the third argument to xNext points to
  136259. ** is initialized to zero before the first (*but not necessarily
  136260. ** subsequent*) call to xNext(). This is done for a particular application
  136261. ** that needs to know whether or not the tokenizer is being used for
  136262. ** snippet generation or for some other purpose.
  136263. **
  136264. ** Extreme care is required when writing code to depend on this
  136265. ** initialization. It is not a documented part of the tokenizer interface.
  136266. ** If a tokenizer is used directly by any code outside of FTS, this
  136267. ** convention might not be respected. */
  136268. rc = pMod->xNext(pC, &ZDUMMY, &DUMMY1, &iBegin, &iFin, &iCurrent);
  136269. if( rc!=SQLITE_OK ){
  136270. if( rc==SQLITE_DONE ){
  136271. /* Special case - the last token of the snippet is also the last token
  136272. ** of the column. Append any punctuation that occurred between the end
  136273. ** of the previous token and the end of the document to the output.
  136274. ** Then break out of the loop. */
  136275. rc = fts3StringAppend(pOut, &zDoc[iEnd], -1);
  136276. }
  136277. break;
  136278. }
  136279. if( iCurrent<iPos ){ continue; }
  136280. if( !isShiftDone ){
  136281. int n = nDoc - iBegin;
  136282. rc = fts3SnippetShift(
  136283. pTab, pCsr->iLangid, nSnippet, &zDoc[iBegin], n, &iPos, &hlmask
  136284. );
  136285. isShiftDone = 1;
  136286. /* Now that the shift has been done, check if the initial "..." are
  136287. ** required. They are required if (a) this is not the first fragment,
  136288. ** or (b) this fragment does not begin at position 0 of its column.
  136289. */
  136290. if( rc==SQLITE_OK && (iPos>0 || iFragment>0) ){
  136291. rc = fts3StringAppend(pOut, zEllipsis, -1);
  136292. }
  136293. if( rc!=SQLITE_OK || iCurrent<iPos ) continue;
  136294. }
  136295. if( iCurrent>=(iPos+nSnippet) ){
  136296. if( isLast ){
  136297. rc = fts3StringAppend(pOut, zEllipsis, -1);
  136298. }
  136299. break;
  136300. }
  136301. /* Set isHighlight to true if this term should be highlighted. */
  136302. isHighlight = (hlmask & ((u64)1 << (iCurrent-iPos)))!=0;
  136303. if( iCurrent>iPos ) rc = fts3StringAppend(pOut, &zDoc[iEnd], iBegin-iEnd);
  136304. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zOpen, -1);
  136305. if( rc==SQLITE_OK ) rc = fts3StringAppend(pOut, &zDoc[iBegin], iFin-iBegin);
  136306. if( rc==SQLITE_OK && isHighlight ) rc = fts3StringAppend(pOut, zClose, -1);
  136307. iEnd = iFin;
  136308. }
  136309. pMod->xClose(pC);
  136310. return rc;
  136311. }
  136312. /*
  136313. ** This function is used to count the entries in a column-list (a
  136314. ** delta-encoded list of term offsets within a single column of a single
  136315. ** row). When this function is called, *ppCollist should point to the
  136316. ** beginning of the first varint in the column-list (the varint that
  136317. ** contains the position of the first matching term in the column data).
  136318. ** Before returning, *ppCollist is set to point to the first byte after
  136319. ** the last varint in the column-list (either the 0x00 signifying the end
  136320. ** of the position-list, or the 0x01 that precedes the column number of
  136321. ** the next column in the position-list).
  136322. **
  136323. ** The number of elements in the column-list is returned.
  136324. */
  136325. static int fts3ColumnlistCount(char **ppCollist){
  136326. char *pEnd = *ppCollist;
  136327. char c = 0;
  136328. int nEntry = 0;
  136329. /* A column-list is terminated by either a 0x01 or 0x00. */
  136330. while( 0xFE & (*pEnd | c) ){
  136331. c = *pEnd++ & 0x80;
  136332. if( !c ) nEntry++;
  136333. }
  136334. *ppCollist = pEnd;
  136335. return nEntry;
  136336. }
  136337. /*
  136338. ** fts3ExprIterate() callback used to collect the "global" matchinfo stats
  136339. ** for a single query.
  136340. **
  136341. ** fts3ExprIterate() callback to load the 'global' elements of a
  136342. ** FTS3_MATCHINFO_HITS matchinfo array. The global stats are those elements
  136343. ** of the matchinfo array that are constant for all rows returned by the
  136344. ** current query.
  136345. **
  136346. ** Argument pCtx is actually a pointer to a struct of type MatchInfo. This
  136347. ** function populates Matchinfo.aMatchinfo[] as follows:
  136348. **
  136349. ** for(iCol=0; iCol<nCol; iCol++){
  136350. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 1] = X;
  136351. ** aMatchinfo[3*iPhrase*nCol + 3*iCol + 2] = Y;
  136352. ** }
  136353. **
  136354. ** where X is the number of matches for phrase iPhrase is column iCol of all
  136355. ** rows of the table. Y is the number of rows for which column iCol contains
  136356. ** at least one instance of phrase iPhrase.
  136357. **
  136358. ** If the phrase pExpr consists entirely of deferred tokens, then all X and
  136359. ** Y values are set to nDoc, where nDoc is the number of documents in the
  136360. ** file system. This is done because the full-text index doclist is required
  136361. ** to calculate these values properly, and the full-text index doclist is
  136362. ** not available for deferred tokens.
  136363. */
  136364. static int fts3ExprGlobalHitsCb(
  136365. Fts3Expr *pExpr, /* Phrase expression node */
  136366. int iPhrase, /* Phrase number (numbered from zero) */
  136367. void *pCtx /* Pointer to MatchInfo structure */
  136368. ){
  136369. MatchInfo *p = (MatchInfo *)pCtx;
  136370. return sqlite3Fts3EvalPhraseStats(
  136371. p->pCursor, pExpr, &p->aMatchinfo[3*iPhrase*p->nCol]
  136372. );
  136373. }
  136374. /*
  136375. ** fts3ExprIterate() callback used to collect the "local" part of the
  136376. ** FTS3_MATCHINFO_HITS array. The local stats are those elements of the
  136377. ** array that are different for each row returned by the query.
  136378. */
  136379. static int fts3ExprLocalHitsCb(
  136380. Fts3Expr *pExpr, /* Phrase expression node */
  136381. int iPhrase, /* Phrase number */
  136382. void *pCtx /* Pointer to MatchInfo structure */
  136383. ){
  136384. int rc = SQLITE_OK;
  136385. MatchInfo *p = (MatchInfo *)pCtx;
  136386. int iStart = iPhrase * p->nCol * 3;
  136387. int i;
  136388. for(i=0; i<p->nCol && rc==SQLITE_OK; i++){
  136389. char *pCsr;
  136390. rc = sqlite3Fts3EvalPhrasePoslist(p->pCursor, pExpr, i, &pCsr);
  136391. if( pCsr ){
  136392. p->aMatchinfo[iStart+i*3] = fts3ColumnlistCount(&pCsr);
  136393. }else{
  136394. p->aMatchinfo[iStart+i*3] = 0;
  136395. }
  136396. }
  136397. return rc;
  136398. }
  136399. static int fts3MatchinfoCheck(
  136400. Fts3Table *pTab,
  136401. char cArg,
  136402. char **pzErr
  136403. ){
  136404. if( (cArg==FTS3_MATCHINFO_NPHRASE)
  136405. || (cArg==FTS3_MATCHINFO_NCOL)
  136406. || (cArg==FTS3_MATCHINFO_NDOC && pTab->bFts4)
  136407. || (cArg==FTS3_MATCHINFO_AVGLENGTH && pTab->bFts4)
  136408. || (cArg==FTS3_MATCHINFO_LENGTH && pTab->bHasDocsize)
  136409. || (cArg==FTS3_MATCHINFO_LCS)
  136410. || (cArg==FTS3_MATCHINFO_HITS)
  136411. ){
  136412. return SQLITE_OK;
  136413. }
  136414. *pzErr = sqlite3_mprintf("unrecognized matchinfo request: %c", cArg);
  136415. return SQLITE_ERROR;
  136416. }
  136417. static int fts3MatchinfoSize(MatchInfo *pInfo, char cArg){
  136418. int nVal; /* Number of integers output by cArg */
  136419. switch( cArg ){
  136420. case FTS3_MATCHINFO_NDOC:
  136421. case FTS3_MATCHINFO_NPHRASE:
  136422. case FTS3_MATCHINFO_NCOL:
  136423. nVal = 1;
  136424. break;
  136425. case FTS3_MATCHINFO_AVGLENGTH:
  136426. case FTS3_MATCHINFO_LENGTH:
  136427. case FTS3_MATCHINFO_LCS:
  136428. nVal = pInfo->nCol;
  136429. break;
  136430. default:
  136431. assert( cArg==FTS3_MATCHINFO_HITS );
  136432. nVal = pInfo->nCol * pInfo->nPhrase * 3;
  136433. break;
  136434. }
  136435. return nVal;
  136436. }
  136437. static int fts3MatchinfoSelectDoctotal(
  136438. Fts3Table *pTab,
  136439. sqlite3_stmt **ppStmt,
  136440. sqlite3_int64 *pnDoc,
  136441. const char **paLen
  136442. ){
  136443. sqlite3_stmt *pStmt;
  136444. const char *a;
  136445. sqlite3_int64 nDoc;
  136446. if( !*ppStmt ){
  136447. int rc = sqlite3Fts3SelectDoctotal(pTab, ppStmt);
  136448. if( rc!=SQLITE_OK ) return rc;
  136449. }
  136450. pStmt = *ppStmt;
  136451. assert( sqlite3_data_count(pStmt)==1 );
  136452. a = sqlite3_column_blob(pStmt, 0);
  136453. a += sqlite3Fts3GetVarint(a, &nDoc);
  136454. if( nDoc==0 ) return FTS_CORRUPT_VTAB;
  136455. *pnDoc = (u32)nDoc;
  136456. if( paLen ) *paLen = a;
  136457. return SQLITE_OK;
  136458. }
  136459. /*
  136460. ** An instance of the following structure is used to store state while
  136461. ** iterating through a multi-column position-list corresponding to the
  136462. ** hits for a single phrase on a single row in order to calculate the
  136463. ** values for a matchinfo() FTS3_MATCHINFO_LCS request.
  136464. */
  136465. typedef struct LcsIterator LcsIterator;
  136466. struct LcsIterator {
  136467. Fts3Expr *pExpr; /* Pointer to phrase expression */
  136468. int iPosOffset; /* Tokens count up to end of this phrase */
  136469. char *pRead; /* Cursor used to iterate through aDoclist */
  136470. int iPos; /* Current position */
  136471. };
  136472. /*
  136473. ** If LcsIterator.iCol is set to the following value, the iterator has
  136474. ** finished iterating through all offsets for all columns.
  136475. */
  136476. #define LCS_ITERATOR_FINISHED 0x7FFFFFFF;
  136477. static int fts3MatchinfoLcsCb(
  136478. Fts3Expr *pExpr, /* Phrase expression node */
  136479. int iPhrase, /* Phrase number (numbered from zero) */
  136480. void *pCtx /* Pointer to MatchInfo structure */
  136481. ){
  136482. LcsIterator *aIter = (LcsIterator *)pCtx;
  136483. aIter[iPhrase].pExpr = pExpr;
  136484. return SQLITE_OK;
  136485. }
  136486. /*
  136487. ** Advance the iterator passed as an argument to the next position. Return
  136488. ** 1 if the iterator is at EOF or if it now points to the start of the
  136489. ** position list for the next column.
  136490. */
  136491. static int fts3LcsIteratorAdvance(LcsIterator *pIter){
  136492. char *pRead = pIter->pRead;
  136493. sqlite3_int64 iRead;
  136494. int rc = 0;
  136495. pRead += sqlite3Fts3GetVarint(pRead, &iRead);
  136496. if( iRead==0 || iRead==1 ){
  136497. pRead = 0;
  136498. rc = 1;
  136499. }else{
  136500. pIter->iPos += (int)(iRead-2);
  136501. }
  136502. pIter->pRead = pRead;
  136503. return rc;
  136504. }
  136505. /*
  136506. ** This function implements the FTS3_MATCHINFO_LCS matchinfo() flag.
  136507. **
  136508. ** If the call is successful, the longest-common-substring lengths for each
  136509. ** column are written into the first nCol elements of the pInfo->aMatchinfo[]
  136510. ** array before returning. SQLITE_OK is returned in this case.
  136511. **
  136512. ** Otherwise, if an error occurs, an SQLite error code is returned and the
  136513. ** data written to the first nCol elements of pInfo->aMatchinfo[] is
  136514. ** undefined.
  136515. */
  136516. static int fts3MatchinfoLcs(Fts3Cursor *pCsr, MatchInfo *pInfo){
  136517. LcsIterator *aIter;
  136518. int i;
  136519. int iCol;
  136520. int nToken = 0;
  136521. /* Allocate and populate the array of LcsIterator objects. The array
  136522. ** contains one element for each matchable phrase in the query.
  136523. **/
  136524. aIter = sqlite3_malloc(sizeof(LcsIterator) * pCsr->nPhrase);
  136525. if( !aIter ) return SQLITE_NOMEM;
  136526. memset(aIter, 0, sizeof(LcsIterator) * pCsr->nPhrase);
  136527. (void)fts3ExprIterate(pCsr->pExpr, fts3MatchinfoLcsCb, (void*)aIter);
  136528. for(i=0; i<pInfo->nPhrase; i++){
  136529. LcsIterator *pIter = &aIter[i];
  136530. nToken -= pIter->pExpr->pPhrase->nToken;
  136531. pIter->iPosOffset = nToken;
  136532. }
  136533. for(iCol=0; iCol<pInfo->nCol; iCol++){
  136534. int nLcs = 0; /* LCS value for this column */
  136535. int nLive = 0; /* Number of iterators in aIter not at EOF */
  136536. for(i=0; i<pInfo->nPhrase; i++){
  136537. int rc;
  136538. LcsIterator *pIt = &aIter[i];
  136539. rc = sqlite3Fts3EvalPhrasePoslist(pCsr, pIt->pExpr, iCol, &pIt->pRead);
  136540. if( rc!=SQLITE_OK ) return rc;
  136541. if( pIt->pRead ){
  136542. pIt->iPos = pIt->iPosOffset;
  136543. fts3LcsIteratorAdvance(&aIter[i]);
  136544. nLive++;
  136545. }
  136546. }
  136547. while( nLive>0 ){
  136548. LcsIterator *pAdv = 0; /* The iterator to advance by one position */
  136549. int nThisLcs = 0; /* LCS for the current iterator positions */
  136550. for(i=0; i<pInfo->nPhrase; i++){
  136551. LcsIterator *pIter = &aIter[i];
  136552. if( pIter->pRead==0 ){
  136553. /* This iterator is already at EOF for this column. */
  136554. nThisLcs = 0;
  136555. }else{
  136556. if( pAdv==0 || pIter->iPos<pAdv->iPos ){
  136557. pAdv = pIter;
  136558. }
  136559. if( nThisLcs==0 || pIter->iPos==pIter[-1].iPos ){
  136560. nThisLcs++;
  136561. }else{
  136562. nThisLcs = 1;
  136563. }
  136564. if( nThisLcs>nLcs ) nLcs = nThisLcs;
  136565. }
  136566. }
  136567. if( fts3LcsIteratorAdvance(pAdv) ) nLive--;
  136568. }
  136569. pInfo->aMatchinfo[iCol] = nLcs;
  136570. }
  136571. sqlite3_free(aIter);
  136572. return SQLITE_OK;
  136573. }
  136574. /*
  136575. ** Populate the buffer pInfo->aMatchinfo[] with an array of integers to
  136576. ** be returned by the matchinfo() function. Argument zArg contains the
  136577. ** format string passed as the second argument to matchinfo (or the
  136578. ** default value "pcx" if no second argument was specified). The format
  136579. ** string has already been validated and the pInfo->aMatchinfo[] array
  136580. ** is guaranteed to be large enough for the output.
  136581. **
  136582. ** If bGlobal is true, then populate all fields of the matchinfo() output.
  136583. ** If it is false, then assume that those fields that do not change between
  136584. ** rows (i.e. FTS3_MATCHINFO_NPHRASE, NCOL, NDOC, AVGLENGTH and part of HITS)
  136585. ** have already been populated.
  136586. **
  136587. ** Return SQLITE_OK if successful, or an SQLite error code if an error
  136588. ** occurs. If a value other than SQLITE_OK is returned, the state the
  136589. ** pInfo->aMatchinfo[] buffer is left in is undefined.
  136590. */
  136591. static int fts3MatchinfoValues(
  136592. Fts3Cursor *pCsr, /* FTS3 cursor object */
  136593. int bGlobal, /* True to grab the global stats */
  136594. MatchInfo *pInfo, /* Matchinfo context object */
  136595. const char *zArg /* Matchinfo format string */
  136596. ){
  136597. int rc = SQLITE_OK;
  136598. int i;
  136599. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  136600. sqlite3_stmt *pSelect = 0;
  136601. for(i=0; rc==SQLITE_OK && zArg[i]; i++){
  136602. switch( zArg[i] ){
  136603. case FTS3_MATCHINFO_NPHRASE:
  136604. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nPhrase;
  136605. break;
  136606. case FTS3_MATCHINFO_NCOL:
  136607. if( bGlobal ) pInfo->aMatchinfo[0] = pInfo->nCol;
  136608. break;
  136609. case FTS3_MATCHINFO_NDOC:
  136610. if( bGlobal ){
  136611. sqlite3_int64 nDoc = 0;
  136612. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, 0);
  136613. pInfo->aMatchinfo[0] = (u32)nDoc;
  136614. }
  136615. break;
  136616. case FTS3_MATCHINFO_AVGLENGTH:
  136617. if( bGlobal ){
  136618. sqlite3_int64 nDoc; /* Number of rows in table */
  136619. const char *a; /* Aggregate column length array */
  136620. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &nDoc, &a);
  136621. if( rc==SQLITE_OK ){
  136622. int iCol;
  136623. for(iCol=0; iCol<pInfo->nCol; iCol++){
  136624. u32 iVal;
  136625. sqlite3_int64 nToken;
  136626. a += sqlite3Fts3GetVarint(a, &nToken);
  136627. iVal = (u32)(((u32)(nToken&0xffffffff)+nDoc/2)/nDoc);
  136628. pInfo->aMatchinfo[iCol] = iVal;
  136629. }
  136630. }
  136631. }
  136632. break;
  136633. case FTS3_MATCHINFO_LENGTH: {
  136634. sqlite3_stmt *pSelectDocsize = 0;
  136635. rc = sqlite3Fts3SelectDocsize(pTab, pCsr->iPrevId, &pSelectDocsize);
  136636. if( rc==SQLITE_OK ){
  136637. int iCol;
  136638. const char *a = sqlite3_column_blob(pSelectDocsize, 0);
  136639. for(iCol=0; iCol<pInfo->nCol; iCol++){
  136640. sqlite3_int64 nToken;
  136641. a += sqlite3Fts3GetVarint(a, &nToken);
  136642. pInfo->aMatchinfo[iCol] = (u32)nToken;
  136643. }
  136644. }
  136645. sqlite3_reset(pSelectDocsize);
  136646. break;
  136647. }
  136648. case FTS3_MATCHINFO_LCS:
  136649. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  136650. if( rc==SQLITE_OK ){
  136651. rc = fts3MatchinfoLcs(pCsr, pInfo);
  136652. }
  136653. break;
  136654. default: {
  136655. Fts3Expr *pExpr;
  136656. assert( zArg[i]==FTS3_MATCHINFO_HITS );
  136657. pExpr = pCsr->pExpr;
  136658. rc = fts3ExprLoadDoclists(pCsr, 0, 0);
  136659. if( rc!=SQLITE_OK ) break;
  136660. if( bGlobal ){
  136661. if( pCsr->pDeferred ){
  136662. rc = fts3MatchinfoSelectDoctotal(pTab, &pSelect, &pInfo->nDoc, 0);
  136663. if( rc!=SQLITE_OK ) break;
  136664. }
  136665. rc = fts3ExprIterate(pExpr, fts3ExprGlobalHitsCb,(void*)pInfo);
  136666. if( rc!=SQLITE_OK ) break;
  136667. }
  136668. (void)fts3ExprIterate(pExpr, fts3ExprLocalHitsCb,(void*)pInfo);
  136669. break;
  136670. }
  136671. }
  136672. pInfo->aMatchinfo += fts3MatchinfoSize(pInfo, zArg[i]);
  136673. }
  136674. sqlite3_reset(pSelect);
  136675. return rc;
  136676. }
  136677. /*
  136678. ** Populate pCsr->aMatchinfo[] with data for the current row. The
  136679. ** 'matchinfo' data is an array of 32-bit unsigned integers (C type u32).
  136680. */
  136681. static int fts3GetMatchinfo(
  136682. Fts3Cursor *pCsr, /* FTS3 Cursor object */
  136683. const char *zArg /* Second argument to matchinfo() function */
  136684. ){
  136685. MatchInfo sInfo;
  136686. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  136687. int rc = SQLITE_OK;
  136688. int bGlobal = 0; /* Collect 'global' stats as well as local */
  136689. memset(&sInfo, 0, sizeof(MatchInfo));
  136690. sInfo.pCursor = pCsr;
  136691. sInfo.nCol = pTab->nColumn;
  136692. /* If there is cached matchinfo() data, but the format string for the
  136693. ** cache does not match the format string for this request, discard
  136694. ** the cached data. */
  136695. if( pCsr->zMatchinfo && strcmp(pCsr->zMatchinfo, zArg) ){
  136696. assert( pCsr->aMatchinfo );
  136697. sqlite3_free(pCsr->aMatchinfo);
  136698. pCsr->zMatchinfo = 0;
  136699. pCsr->aMatchinfo = 0;
  136700. }
  136701. /* If Fts3Cursor.aMatchinfo[] is NULL, then this is the first time the
  136702. ** matchinfo function has been called for this query. In this case
  136703. ** allocate the array used to accumulate the matchinfo data and
  136704. ** initialize those elements that are constant for every row.
  136705. */
  136706. if( pCsr->aMatchinfo==0 ){
  136707. int nMatchinfo = 0; /* Number of u32 elements in match-info */
  136708. int nArg; /* Bytes in zArg */
  136709. int i; /* Used to iterate through zArg */
  136710. /* Determine the number of phrases in the query */
  136711. pCsr->nPhrase = fts3ExprPhraseCount(pCsr->pExpr);
  136712. sInfo.nPhrase = pCsr->nPhrase;
  136713. /* Determine the number of integers in the buffer returned by this call. */
  136714. for(i=0; zArg[i]; i++){
  136715. nMatchinfo += fts3MatchinfoSize(&sInfo, zArg[i]);
  136716. }
  136717. /* Allocate space for Fts3Cursor.aMatchinfo[] and Fts3Cursor.zMatchinfo. */
  136718. nArg = (int)strlen(zArg);
  136719. pCsr->aMatchinfo = (u32 *)sqlite3_malloc(sizeof(u32)*nMatchinfo + nArg + 1);
  136720. if( !pCsr->aMatchinfo ) return SQLITE_NOMEM;
  136721. pCsr->zMatchinfo = (char *)&pCsr->aMatchinfo[nMatchinfo];
  136722. pCsr->nMatchinfo = nMatchinfo;
  136723. memcpy(pCsr->zMatchinfo, zArg, nArg+1);
  136724. memset(pCsr->aMatchinfo, 0, sizeof(u32)*nMatchinfo);
  136725. pCsr->isMatchinfoNeeded = 1;
  136726. bGlobal = 1;
  136727. }
  136728. sInfo.aMatchinfo = pCsr->aMatchinfo;
  136729. sInfo.nPhrase = pCsr->nPhrase;
  136730. if( pCsr->isMatchinfoNeeded ){
  136731. rc = fts3MatchinfoValues(pCsr, bGlobal, &sInfo, zArg);
  136732. pCsr->isMatchinfoNeeded = 0;
  136733. }
  136734. return rc;
  136735. }
  136736. /*
  136737. ** Implementation of snippet() function.
  136738. */
  136739. SQLITE_PRIVATE void sqlite3Fts3Snippet(
  136740. sqlite3_context *pCtx, /* SQLite function call context */
  136741. Fts3Cursor *pCsr, /* Cursor object */
  136742. const char *zStart, /* Snippet start text - "<b>" */
  136743. const char *zEnd, /* Snippet end text - "</b>" */
  136744. const char *zEllipsis, /* Snippet ellipsis text - "<b>...</b>" */
  136745. int iCol, /* Extract snippet from this column */
  136746. int nToken /* Approximate number of tokens in snippet */
  136747. ){
  136748. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  136749. int rc = SQLITE_OK;
  136750. int i;
  136751. StrBuffer res = {0, 0, 0};
  136752. /* The returned text includes up to four fragments of text extracted from
  136753. ** the data in the current row. The first iteration of the for(...) loop
  136754. ** below attempts to locate a single fragment of text nToken tokens in
  136755. ** size that contains at least one instance of all phrases in the query
  136756. ** expression that appear in the current row. If such a fragment of text
  136757. ** cannot be found, the second iteration of the loop attempts to locate
  136758. ** a pair of fragments, and so on.
  136759. */
  136760. int nSnippet = 0; /* Number of fragments in this snippet */
  136761. SnippetFragment aSnippet[4]; /* Maximum of 4 fragments per snippet */
  136762. int nFToken = -1; /* Number of tokens in each fragment */
  136763. if( !pCsr->pExpr ){
  136764. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  136765. return;
  136766. }
  136767. for(nSnippet=1; 1; nSnippet++){
  136768. int iSnip; /* Loop counter 0..nSnippet-1 */
  136769. u64 mCovered = 0; /* Bitmask of phrases covered by snippet */
  136770. u64 mSeen = 0; /* Bitmask of phrases seen by BestSnippet() */
  136771. if( nToken>=0 ){
  136772. nFToken = (nToken+nSnippet-1) / nSnippet;
  136773. }else{
  136774. nFToken = -1 * nToken;
  136775. }
  136776. for(iSnip=0; iSnip<nSnippet; iSnip++){
  136777. int iBestScore = -1; /* Best score of columns checked so far */
  136778. int iRead; /* Used to iterate through columns */
  136779. SnippetFragment *pFragment = &aSnippet[iSnip];
  136780. memset(pFragment, 0, sizeof(*pFragment));
  136781. /* Loop through all columns of the table being considered for snippets.
  136782. ** If the iCol argument to this function was negative, this means all
  136783. ** columns of the FTS3 table. Otherwise, only column iCol is considered.
  136784. */
  136785. for(iRead=0; iRead<pTab->nColumn; iRead++){
  136786. SnippetFragment sF = {0, 0, 0, 0};
  136787. int iS;
  136788. if( iCol>=0 && iRead!=iCol ) continue;
  136789. /* Find the best snippet of nFToken tokens in column iRead. */
  136790. rc = fts3BestSnippet(nFToken, pCsr, iRead, mCovered, &mSeen, &sF, &iS);
  136791. if( rc!=SQLITE_OK ){
  136792. goto snippet_out;
  136793. }
  136794. if( iS>iBestScore ){
  136795. *pFragment = sF;
  136796. iBestScore = iS;
  136797. }
  136798. }
  136799. mCovered |= pFragment->covered;
  136800. }
  136801. /* If all query phrases seen by fts3BestSnippet() are present in at least
  136802. ** one of the nSnippet snippet fragments, break out of the loop.
  136803. */
  136804. assert( (mCovered&mSeen)==mCovered );
  136805. if( mSeen==mCovered || nSnippet==SizeofArray(aSnippet) ) break;
  136806. }
  136807. assert( nFToken>0 );
  136808. for(i=0; i<nSnippet && rc==SQLITE_OK; i++){
  136809. rc = fts3SnippetText(pCsr, &aSnippet[i],
  136810. i, (i==nSnippet-1), nFToken, zStart, zEnd, zEllipsis, &res
  136811. );
  136812. }
  136813. snippet_out:
  136814. sqlite3Fts3SegmentsClose(pTab);
  136815. if( rc!=SQLITE_OK ){
  136816. sqlite3_result_error_code(pCtx, rc);
  136817. sqlite3_free(res.z);
  136818. }else{
  136819. sqlite3_result_text(pCtx, res.z, -1, sqlite3_free);
  136820. }
  136821. }
  136822. typedef struct TermOffset TermOffset;
  136823. typedef struct TermOffsetCtx TermOffsetCtx;
  136824. struct TermOffset {
  136825. char *pList; /* Position-list */
  136826. int iPos; /* Position just read from pList */
  136827. int iOff; /* Offset of this term from read positions */
  136828. };
  136829. struct TermOffsetCtx {
  136830. Fts3Cursor *pCsr;
  136831. int iCol; /* Column of table to populate aTerm for */
  136832. int iTerm;
  136833. sqlite3_int64 iDocid;
  136834. TermOffset *aTerm;
  136835. };
  136836. /*
  136837. ** This function is an fts3ExprIterate() callback used by sqlite3Fts3Offsets().
  136838. */
  136839. static int fts3ExprTermOffsetInit(Fts3Expr *pExpr, int iPhrase, void *ctx){
  136840. TermOffsetCtx *p = (TermOffsetCtx *)ctx;
  136841. int nTerm; /* Number of tokens in phrase */
  136842. int iTerm; /* For looping through nTerm phrase terms */
  136843. char *pList; /* Pointer to position list for phrase */
  136844. int iPos = 0; /* First position in position-list */
  136845. int rc;
  136846. UNUSED_PARAMETER(iPhrase);
  136847. rc = sqlite3Fts3EvalPhrasePoslist(p->pCsr, pExpr, p->iCol, &pList);
  136848. nTerm = pExpr->pPhrase->nToken;
  136849. if( pList ){
  136850. fts3GetDeltaPosition(&pList, &iPos);
  136851. assert( iPos>=0 );
  136852. }
  136853. for(iTerm=0; iTerm<nTerm; iTerm++){
  136854. TermOffset *pT = &p->aTerm[p->iTerm++];
  136855. pT->iOff = nTerm-iTerm-1;
  136856. pT->pList = pList;
  136857. pT->iPos = iPos;
  136858. }
  136859. return rc;
  136860. }
  136861. /*
  136862. ** Implementation of offsets() function.
  136863. */
  136864. SQLITE_PRIVATE void sqlite3Fts3Offsets(
  136865. sqlite3_context *pCtx, /* SQLite function call context */
  136866. Fts3Cursor *pCsr /* Cursor object */
  136867. ){
  136868. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  136869. sqlite3_tokenizer_module const *pMod = pTab->pTokenizer->pModule;
  136870. int rc; /* Return Code */
  136871. int nToken; /* Number of tokens in query */
  136872. int iCol; /* Column currently being processed */
  136873. StrBuffer res = {0, 0, 0}; /* Result string */
  136874. TermOffsetCtx sCtx; /* Context for fts3ExprTermOffsetInit() */
  136875. if( !pCsr->pExpr ){
  136876. sqlite3_result_text(pCtx, "", 0, SQLITE_STATIC);
  136877. return;
  136878. }
  136879. memset(&sCtx, 0, sizeof(sCtx));
  136880. assert( pCsr->isRequireSeek==0 );
  136881. /* Count the number of terms in the query */
  136882. rc = fts3ExprLoadDoclists(pCsr, 0, &nToken);
  136883. if( rc!=SQLITE_OK ) goto offsets_out;
  136884. /* Allocate the array of TermOffset iterators. */
  136885. sCtx.aTerm = (TermOffset *)sqlite3_malloc(sizeof(TermOffset)*nToken);
  136886. if( 0==sCtx.aTerm ){
  136887. rc = SQLITE_NOMEM;
  136888. goto offsets_out;
  136889. }
  136890. sCtx.iDocid = pCsr->iPrevId;
  136891. sCtx.pCsr = pCsr;
  136892. /* Loop through the table columns, appending offset information to
  136893. ** string-buffer res for each column.
  136894. */
  136895. for(iCol=0; iCol<pTab->nColumn; iCol++){
  136896. sqlite3_tokenizer_cursor *pC; /* Tokenizer cursor */
  136897. const char *ZDUMMY; /* Dummy argument used with xNext() */
  136898. int NDUMMY = 0; /* Dummy argument used with xNext() */
  136899. int iStart = 0;
  136900. int iEnd = 0;
  136901. int iCurrent = 0;
  136902. const char *zDoc;
  136903. int nDoc;
  136904. /* Initialize the contents of sCtx.aTerm[] for column iCol. There is
  136905. ** no way that this operation can fail, so the return code from
  136906. ** fts3ExprIterate() can be discarded.
  136907. */
  136908. sCtx.iCol = iCol;
  136909. sCtx.iTerm = 0;
  136910. (void)fts3ExprIterate(pCsr->pExpr, fts3ExprTermOffsetInit, (void *)&sCtx);
  136911. /* Retreive the text stored in column iCol. If an SQL NULL is stored
  136912. ** in column iCol, jump immediately to the next iteration of the loop.
  136913. ** If an OOM occurs while retrieving the data (this can happen if SQLite
  136914. ** needs to transform the data from utf-16 to utf-8), return SQLITE_NOMEM
  136915. ** to the caller.
  136916. */
  136917. zDoc = (const char *)sqlite3_column_text(pCsr->pStmt, iCol+1);
  136918. nDoc = sqlite3_column_bytes(pCsr->pStmt, iCol+1);
  136919. if( zDoc==0 ){
  136920. if( sqlite3_column_type(pCsr->pStmt, iCol+1)==SQLITE_NULL ){
  136921. continue;
  136922. }
  136923. rc = SQLITE_NOMEM;
  136924. goto offsets_out;
  136925. }
  136926. /* Initialize a tokenizer iterator to iterate through column iCol. */
  136927. rc = sqlite3Fts3OpenTokenizer(pTab->pTokenizer, pCsr->iLangid,
  136928. zDoc, nDoc, &pC
  136929. );
  136930. if( rc!=SQLITE_OK ) goto offsets_out;
  136931. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  136932. while( rc==SQLITE_OK ){
  136933. int i; /* Used to loop through terms */
  136934. int iMinPos = 0x7FFFFFFF; /* Position of next token */
  136935. TermOffset *pTerm = 0; /* TermOffset associated with next token */
  136936. for(i=0; i<nToken; i++){
  136937. TermOffset *pT = &sCtx.aTerm[i];
  136938. if( pT->pList && (pT->iPos-pT->iOff)<iMinPos ){
  136939. iMinPos = pT->iPos-pT->iOff;
  136940. pTerm = pT;
  136941. }
  136942. }
  136943. if( !pTerm ){
  136944. /* All offsets for this column have been gathered. */
  136945. rc = SQLITE_DONE;
  136946. }else{
  136947. assert( iCurrent<=iMinPos );
  136948. if( 0==(0xFE&*pTerm->pList) ){
  136949. pTerm->pList = 0;
  136950. }else{
  136951. fts3GetDeltaPosition(&pTerm->pList, &pTerm->iPos);
  136952. }
  136953. while( rc==SQLITE_OK && iCurrent<iMinPos ){
  136954. rc = pMod->xNext(pC, &ZDUMMY, &NDUMMY, &iStart, &iEnd, &iCurrent);
  136955. }
  136956. if( rc==SQLITE_OK ){
  136957. char aBuffer[64];
  136958. sqlite3_snprintf(sizeof(aBuffer), aBuffer,
  136959. "%d %d %d %d ", iCol, pTerm-sCtx.aTerm, iStart, iEnd-iStart
  136960. );
  136961. rc = fts3StringAppend(&res, aBuffer, -1);
  136962. }else if( rc==SQLITE_DONE && pTab->zContentTbl==0 ){
  136963. rc = FTS_CORRUPT_VTAB;
  136964. }
  136965. }
  136966. }
  136967. if( rc==SQLITE_DONE ){
  136968. rc = SQLITE_OK;
  136969. }
  136970. pMod->xClose(pC);
  136971. if( rc!=SQLITE_OK ) goto offsets_out;
  136972. }
  136973. offsets_out:
  136974. sqlite3_free(sCtx.aTerm);
  136975. assert( rc!=SQLITE_DONE );
  136976. sqlite3Fts3SegmentsClose(pTab);
  136977. if( rc!=SQLITE_OK ){
  136978. sqlite3_result_error_code(pCtx, rc);
  136979. sqlite3_free(res.z);
  136980. }else{
  136981. sqlite3_result_text(pCtx, res.z, res.n-1, sqlite3_free);
  136982. }
  136983. return;
  136984. }
  136985. /*
  136986. ** Implementation of matchinfo() function.
  136987. */
  136988. SQLITE_PRIVATE void sqlite3Fts3Matchinfo(
  136989. sqlite3_context *pContext, /* Function call context */
  136990. Fts3Cursor *pCsr, /* FTS3 table cursor */
  136991. const char *zArg /* Second arg to matchinfo() function */
  136992. ){
  136993. Fts3Table *pTab = (Fts3Table *)pCsr->base.pVtab;
  136994. int rc;
  136995. int i;
  136996. const char *zFormat;
  136997. if( zArg ){
  136998. for(i=0; zArg[i]; i++){
  136999. char *zErr = 0;
  137000. if( fts3MatchinfoCheck(pTab, zArg[i], &zErr) ){
  137001. sqlite3_result_error(pContext, zErr, -1);
  137002. sqlite3_free(zErr);
  137003. return;
  137004. }
  137005. }
  137006. zFormat = zArg;
  137007. }else{
  137008. zFormat = FTS3_MATCHINFO_DEFAULT;
  137009. }
  137010. if( !pCsr->pExpr ){
  137011. sqlite3_result_blob(pContext, "", 0, SQLITE_STATIC);
  137012. return;
  137013. }
  137014. /* Retrieve matchinfo() data. */
  137015. rc = fts3GetMatchinfo(pCsr, zFormat);
  137016. sqlite3Fts3SegmentsClose(pTab);
  137017. if( rc!=SQLITE_OK ){
  137018. sqlite3_result_error_code(pContext, rc);
  137019. }else{
  137020. int n = pCsr->nMatchinfo * sizeof(u32);
  137021. sqlite3_result_blob(pContext, pCsr->aMatchinfo, n, SQLITE_TRANSIENT);
  137022. }
  137023. }
  137024. #endif
  137025. /************** End of fts3_snippet.c ****************************************/
  137026. /************** Begin file fts3_unicode.c ************************************/
  137027. /*
  137028. ** 2012 May 24
  137029. **
  137030. ** The author disclaims copyright to this source code. In place of
  137031. ** a legal notice, here is a blessing:
  137032. **
  137033. ** May you do good and not evil.
  137034. ** May you find forgiveness for yourself and forgive others.
  137035. ** May you share freely, never taking more than you give.
  137036. **
  137037. ******************************************************************************
  137038. **
  137039. ** Implementation of the "unicode" full-text-search tokenizer.
  137040. */
  137041. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  137042. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  137043. /* #include <assert.h> */
  137044. /* #include <stdlib.h> */
  137045. /* #include <stdio.h> */
  137046. /* #include <string.h> */
  137047. /*
  137048. ** The following two macros - READ_UTF8 and WRITE_UTF8 - have been copied
  137049. ** from the sqlite3 source file utf.c. If this file is compiled as part
  137050. ** of the amalgamation, they are not required.
  137051. */
  137052. #ifndef SQLITE_AMALGAMATION
  137053. static const unsigned char sqlite3Utf8Trans1[] = {
  137054. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  137055. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  137056. 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
  137057. 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
  137058. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  137059. 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
  137060. 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  137061. 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x00, 0x00,
  137062. };
  137063. #define READ_UTF8(zIn, zTerm, c) \
  137064. c = *(zIn++); \
  137065. if( c>=0xc0 ){ \
  137066. c = sqlite3Utf8Trans1[c-0xc0]; \
  137067. while( zIn!=zTerm && (*zIn & 0xc0)==0x80 ){ \
  137068. c = (c<<6) + (0x3f & *(zIn++)); \
  137069. } \
  137070. if( c<0x80 \
  137071. || (c&0xFFFFF800)==0xD800 \
  137072. || (c&0xFFFFFFFE)==0xFFFE ){ c = 0xFFFD; } \
  137073. }
  137074. #define WRITE_UTF8(zOut, c) { \
  137075. if( c<0x00080 ){ \
  137076. *zOut++ = (u8)(c&0xFF); \
  137077. } \
  137078. else if( c<0x00800 ){ \
  137079. *zOut++ = 0xC0 + (u8)((c>>6)&0x1F); \
  137080. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  137081. } \
  137082. else if( c<0x10000 ){ \
  137083. *zOut++ = 0xE0 + (u8)((c>>12)&0x0F); \
  137084. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  137085. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  137086. }else{ \
  137087. *zOut++ = 0xF0 + (u8)((c>>18) & 0x07); \
  137088. *zOut++ = 0x80 + (u8)((c>>12) & 0x3F); \
  137089. *zOut++ = 0x80 + (u8)((c>>6) & 0x3F); \
  137090. *zOut++ = 0x80 + (u8)(c & 0x3F); \
  137091. } \
  137092. }
  137093. #endif /* ifndef SQLITE_AMALGAMATION */
  137094. typedef struct unicode_tokenizer unicode_tokenizer;
  137095. typedef struct unicode_cursor unicode_cursor;
  137096. struct unicode_tokenizer {
  137097. sqlite3_tokenizer base;
  137098. int bRemoveDiacritic;
  137099. int nException;
  137100. int *aiException;
  137101. };
  137102. struct unicode_cursor {
  137103. sqlite3_tokenizer_cursor base;
  137104. const unsigned char *aInput; /* Input text being tokenized */
  137105. int nInput; /* Size of aInput[] in bytes */
  137106. int iOff; /* Current offset within aInput[] */
  137107. int iToken; /* Index of next token to be returned */
  137108. char *zToken; /* storage for current token */
  137109. int nAlloc; /* space allocated at zToken */
  137110. };
  137111. /*
  137112. ** Destroy a tokenizer allocated by unicodeCreate().
  137113. */
  137114. static int unicodeDestroy(sqlite3_tokenizer *pTokenizer){
  137115. if( pTokenizer ){
  137116. unicode_tokenizer *p = (unicode_tokenizer *)pTokenizer;
  137117. sqlite3_free(p->aiException);
  137118. sqlite3_free(p);
  137119. }
  137120. return SQLITE_OK;
  137121. }
  137122. /*
  137123. ** As part of a tokenchars= or separators= option, the CREATE VIRTUAL TABLE
  137124. ** statement has specified that the tokenizer for this table shall consider
  137125. ** all characters in string zIn/nIn to be separators (if bAlnum==0) or
  137126. ** token characters (if bAlnum==1).
  137127. **
  137128. ** For each codepoint in the zIn/nIn string, this function checks if the
  137129. ** sqlite3FtsUnicodeIsalnum() function already returns the desired result.
  137130. ** If so, no action is taken. Otherwise, the codepoint is added to the
  137131. ** unicode_tokenizer.aiException[] array. For the purposes of tokenization,
  137132. ** the return value of sqlite3FtsUnicodeIsalnum() is inverted for all
  137133. ** codepoints in the aiException[] array.
  137134. **
  137135. ** If a standalone diacritic mark (one that sqlite3FtsUnicodeIsdiacritic()
  137136. ** identifies as a diacritic) occurs in the zIn/nIn string it is ignored.
  137137. ** It is not possible to change the behavior of the tokenizer with respect
  137138. ** to these codepoints.
  137139. */
  137140. static int unicodeAddExceptions(
  137141. unicode_tokenizer *p, /* Tokenizer to add exceptions to */
  137142. int bAlnum, /* Replace Isalnum() return value with this */
  137143. const char *zIn, /* Array of characters to make exceptions */
  137144. int nIn /* Length of z in bytes */
  137145. ){
  137146. const unsigned char *z = (const unsigned char *)zIn;
  137147. const unsigned char *zTerm = &z[nIn];
  137148. int iCode;
  137149. int nEntry = 0;
  137150. assert( bAlnum==0 || bAlnum==1 );
  137151. while( z<zTerm ){
  137152. READ_UTF8(z, zTerm, iCode);
  137153. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  137154. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  137155. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  137156. ){
  137157. nEntry++;
  137158. }
  137159. }
  137160. if( nEntry ){
  137161. int *aNew; /* New aiException[] array */
  137162. int nNew; /* Number of valid entries in array aNew[] */
  137163. aNew = sqlite3_realloc(p->aiException, (p->nException+nEntry)*sizeof(int));
  137164. if( aNew==0 ) return SQLITE_NOMEM;
  137165. nNew = p->nException;
  137166. z = (const unsigned char *)zIn;
  137167. while( z<zTerm ){
  137168. READ_UTF8(z, zTerm, iCode);
  137169. if( sqlite3FtsUnicodeIsalnum(iCode)!=bAlnum
  137170. && sqlite3FtsUnicodeIsdiacritic(iCode)==0
  137171. ){
  137172. int i, j;
  137173. for(i=0; i<nNew && aNew[i]<iCode; i++);
  137174. for(j=nNew; j>i; j--) aNew[j] = aNew[j-1];
  137175. aNew[i] = iCode;
  137176. nNew++;
  137177. }
  137178. }
  137179. p->aiException = aNew;
  137180. p->nException = nNew;
  137181. }
  137182. return SQLITE_OK;
  137183. }
  137184. /*
  137185. ** Return true if the p->aiException[] array contains the value iCode.
  137186. */
  137187. static int unicodeIsException(unicode_tokenizer *p, int iCode){
  137188. if( p->nException>0 ){
  137189. int *a = p->aiException;
  137190. int iLo = 0;
  137191. int iHi = p->nException-1;
  137192. while( iHi>=iLo ){
  137193. int iTest = (iHi + iLo) / 2;
  137194. if( iCode==a[iTest] ){
  137195. return 1;
  137196. }else if( iCode>a[iTest] ){
  137197. iLo = iTest+1;
  137198. }else{
  137199. iHi = iTest-1;
  137200. }
  137201. }
  137202. }
  137203. return 0;
  137204. }
  137205. /*
  137206. ** Return true if, for the purposes of tokenization, codepoint iCode is
  137207. ** considered a token character (not a separator).
  137208. */
  137209. static int unicodeIsAlnum(unicode_tokenizer *p, int iCode){
  137210. assert( (sqlite3FtsUnicodeIsalnum(iCode) & 0xFFFFFFFE)==0 );
  137211. return sqlite3FtsUnicodeIsalnum(iCode) ^ unicodeIsException(p, iCode);
  137212. }
  137213. /*
  137214. ** Create a new tokenizer instance.
  137215. */
  137216. static int unicodeCreate(
  137217. int nArg, /* Size of array argv[] */
  137218. const char * const *azArg, /* Tokenizer creation arguments */
  137219. sqlite3_tokenizer **pp /* OUT: New tokenizer handle */
  137220. ){
  137221. unicode_tokenizer *pNew; /* New tokenizer object */
  137222. int i;
  137223. int rc = SQLITE_OK;
  137224. pNew = (unicode_tokenizer *) sqlite3_malloc(sizeof(unicode_tokenizer));
  137225. if( pNew==NULL ) return SQLITE_NOMEM;
  137226. memset(pNew, 0, sizeof(unicode_tokenizer));
  137227. pNew->bRemoveDiacritic = 1;
  137228. for(i=0; rc==SQLITE_OK && i<nArg; i++){
  137229. const char *z = azArg[i];
  137230. int n = (int)strlen(z);
  137231. if( n==19 && memcmp("remove_diacritics=1", z, 19)==0 ){
  137232. pNew->bRemoveDiacritic = 1;
  137233. }
  137234. else if( n==19 && memcmp("remove_diacritics=0", z, 19)==0 ){
  137235. pNew->bRemoveDiacritic = 0;
  137236. }
  137237. else if( n>=11 && memcmp("tokenchars=", z, 11)==0 ){
  137238. rc = unicodeAddExceptions(pNew, 1, &z[11], n-11);
  137239. }
  137240. else if( n>=11 && memcmp("separators=", z, 11)==0 ){
  137241. rc = unicodeAddExceptions(pNew, 0, &z[11], n-11);
  137242. }
  137243. else{
  137244. /* Unrecognized argument */
  137245. rc = SQLITE_ERROR;
  137246. }
  137247. }
  137248. if( rc!=SQLITE_OK ){
  137249. unicodeDestroy((sqlite3_tokenizer *)pNew);
  137250. pNew = 0;
  137251. }
  137252. *pp = (sqlite3_tokenizer *)pNew;
  137253. return rc;
  137254. }
  137255. /*
  137256. ** Prepare to begin tokenizing a particular string. The input
  137257. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  137258. ** used to incrementally tokenize this string is returned in
  137259. ** *ppCursor.
  137260. */
  137261. static int unicodeOpen(
  137262. sqlite3_tokenizer *p, /* The tokenizer */
  137263. const char *aInput, /* Input string */
  137264. int nInput, /* Size of string aInput in bytes */
  137265. sqlite3_tokenizer_cursor **pp /* OUT: New cursor object */
  137266. ){
  137267. unicode_cursor *pCsr;
  137268. pCsr = (unicode_cursor *)sqlite3_malloc(sizeof(unicode_cursor));
  137269. if( pCsr==0 ){
  137270. return SQLITE_NOMEM;
  137271. }
  137272. memset(pCsr, 0, sizeof(unicode_cursor));
  137273. pCsr->aInput = (const unsigned char *)aInput;
  137274. if( aInput==0 ){
  137275. pCsr->nInput = 0;
  137276. }else if( nInput<0 ){
  137277. pCsr->nInput = (int)strlen(aInput);
  137278. }else{
  137279. pCsr->nInput = nInput;
  137280. }
  137281. *pp = &pCsr->base;
  137282. UNUSED_PARAMETER(p);
  137283. return SQLITE_OK;
  137284. }
  137285. /*
  137286. ** Close a tokenization cursor previously opened by a call to
  137287. ** simpleOpen() above.
  137288. */
  137289. static int unicodeClose(sqlite3_tokenizer_cursor *pCursor){
  137290. unicode_cursor *pCsr = (unicode_cursor *) pCursor;
  137291. sqlite3_free(pCsr->zToken);
  137292. sqlite3_free(pCsr);
  137293. return SQLITE_OK;
  137294. }
  137295. /*
  137296. ** Extract the next token from a tokenization cursor. The cursor must
  137297. ** have been opened by a prior call to simpleOpen().
  137298. */
  137299. static int unicodeNext(
  137300. sqlite3_tokenizer_cursor *pC, /* Cursor returned by simpleOpen */
  137301. const char **paToken, /* OUT: Token text */
  137302. int *pnToken, /* OUT: Number of bytes at *paToken */
  137303. int *piStart, /* OUT: Starting offset of token */
  137304. int *piEnd, /* OUT: Ending offset of token */
  137305. int *piPos /* OUT: Position integer of token */
  137306. ){
  137307. unicode_cursor *pCsr = (unicode_cursor *)pC;
  137308. unicode_tokenizer *p = ((unicode_tokenizer *)pCsr->base.pTokenizer);
  137309. int iCode = 0;
  137310. char *zOut;
  137311. const unsigned char *z = &pCsr->aInput[pCsr->iOff];
  137312. const unsigned char *zStart = z;
  137313. const unsigned char *zEnd;
  137314. const unsigned char *zTerm = &pCsr->aInput[pCsr->nInput];
  137315. /* Scan past any delimiter characters before the start of the next token.
  137316. ** Return SQLITE_DONE early if this takes us all the way to the end of
  137317. ** the input. */
  137318. while( z<zTerm ){
  137319. READ_UTF8(z, zTerm, iCode);
  137320. if( unicodeIsAlnum(p, iCode) ) break;
  137321. zStart = z;
  137322. }
  137323. if( zStart>=zTerm ) return SQLITE_DONE;
  137324. zOut = pCsr->zToken;
  137325. do {
  137326. int iOut;
  137327. /* Grow the output buffer if required. */
  137328. if( (zOut-pCsr->zToken)>=(pCsr->nAlloc-4) ){
  137329. char *zNew = sqlite3_realloc(pCsr->zToken, pCsr->nAlloc+64);
  137330. if( !zNew ) return SQLITE_NOMEM;
  137331. zOut = &zNew[zOut - pCsr->zToken];
  137332. pCsr->zToken = zNew;
  137333. pCsr->nAlloc += 64;
  137334. }
  137335. /* Write the folded case of the last character read to the output */
  137336. zEnd = z;
  137337. iOut = sqlite3FtsUnicodeFold(iCode, p->bRemoveDiacritic);
  137338. if( iOut ){
  137339. WRITE_UTF8(zOut, iOut);
  137340. }
  137341. /* If the cursor is not at EOF, read the next character */
  137342. if( z>=zTerm ) break;
  137343. READ_UTF8(z, zTerm, iCode);
  137344. }while( unicodeIsAlnum(p, iCode)
  137345. || sqlite3FtsUnicodeIsdiacritic(iCode)
  137346. );
  137347. /* Set the output variables and return. */
  137348. pCsr->iOff = (int)(z - pCsr->aInput);
  137349. *paToken = pCsr->zToken;
  137350. *pnToken = (int)(zOut - pCsr->zToken);
  137351. *piStart = (int)(zStart - pCsr->aInput);
  137352. *piEnd = (int)(zEnd - pCsr->aInput);
  137353. *piPos = pCsr->iToken++;
  137354. return SQLITE_OK;
  137355. }
  137356. /*
  137357. ** Set *ppModule to a pointer to the sqlite3_tokenizer_module
  137358. ** structure for the unicode tokenizer.
  137359. */
  137360. SQLITE_PRIVATE void sqlite3Fts3UnicodeTokenizer(sqlite3_tokenizer_module const **ppModule){
  137361. static const sqlite3_tokenizer_module module = {
  137362. 0,
  137363. unicodeCreate,
  137364. unicodeDestroy,
  137365. unicodeOpen,
  137366. unicodeClose,
  137367. unicodeNext,
  137368. 0,
  137369. };
  137370. *ppModule = &module;
  137371. }
  137372. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  137373. #endif /* ifndef SQLITE_DISABLE_FTS3_UNICODE */
  137374. /************** End of fts3_unicode.c ****************************************/
  137375. /************** Begin file fts3_unicode2.c ***********************************/
  137376. /*
  137377. ** 2012 May 25
  137378. **
  137379. ** The author disclaims copyright to this source code. In place of
  137380. ** a legal notice, here is a blessing:
  137381. **
  137382. ** May you do good and not evil.
  137383. ** May you find forgiveness for yourself and forgive others.
  137384. ** May you share freely, never taking more than you give.
  137385. **
  137386. ******************************************************************************
  137387. */
  137388. /*
  137389. ** DO NOT EDIT THIS MACHINE GENERATED FILE.
  137390. */
  137391. #ifndef SQLITE_DISABLE_FTS3_UNICODE
  137392. #if defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4)
  137393. /* #include <assert.h> */
  137394. /*
  137395. ** Return true if the argument corresponds to a unicode codepoint
  137396. ** classified as either a letter or a number. Otherwise false.
  137397. **
  137398. ** The results are undefined if the value passed to this function
  137399. ** is less than zero.
  137400. */
  137401. SQLITE_PRIVATE int sqlite3FtsUnicodeIsalnum(int c){
  137402. /* Each unsigned integer in the following array corresponds to a contiguous
  137403. ** range of unicode codepoints that are not either letters or numbers (i.e.
  137404. ** codepoints for which this function should return 0).
  137405. **
  137406. ** The most significant 22 bits in each 32-bit value contain the first
  137407. ** codepoint in the range. The least significant 10 bits are used to store
  137408. ** the size of the range (always at least 1). In other words, the value
  137409. ** ((C<<22) + N) represents a range of N codepoints starting with codepoint
  137410. ** C. It is not possible to represent a range larger than 1023 codepoints
  137411. ** using this format.
  137412. */
  137413. static const unsigned int aEntry[] = {
  137414. 0x00000030, 0x0000E807, 0x00016C06, 0x0001EC2F, 0x0002AC07,
  137415. 0x0002D001, 0x0002D803, 0x0002EC01, 0x0002FC01, 0x00035C01,
  137416. 0x0003DC01, 0x000B0804, 0x000B480E, 0x000B9407, 0x000BB401,
  137417. 0x000BBC81, 0x000DD401, 0x000DF801, 0x000E1002, 0x000E1C01,
  137418. 0x000FD801, 0x00120808, 0x00156806, 0x00162402, 0x00163C01,
  137419. 0x00164437, 0x0017CC02, 0x00180005, 0x00181816, 0x00187802,
  137420. 0x00192C15, 0x0019A804, 0x0019C001, 0x001B5001, 0x001B580F,
  137421. 0x001B9C07, 0x001BF402, 0x001C000E, 0x001C3C01, 0x001C4401,
  137422. 0x001CC01B, 0x001E980B, 0x001FAC09, 0x001FD804, 0x00205804,
  137423. 0x00206C09, 0x00209403, 0x0020A405, 0x0020C00F, 0x00216403,
  137424. 0x00217801, 0x0023901B, 0x00240004, 0x0024E803, 0x0024F812,
  137425. 0x00254407, 0x00258804, 0x0025C001, 0x00260403, 0x0026F001,
  137426. 0x0026F807, 0x00271C02, 0x00272C03, 0x00275C01, 0x00278802,
  137427. 0x0027C802, 0x0027E802, 0x00280403, 0x0028F001, 0x0028F805,
  137428. 0x00291C02, 0x00292C03, 0x00294401, 0x0029C002, 0x0029D401,
  137429. 0x002A0403, 0x002AF001, 0x002AF808, 0x002B1C03, 0x002B2C03,
  137430. 0x002B8802, 0x002BC002, 0x002C0403, 0x002CF001, 0x002CF807,
  137431. 0x002D1C02, 0x002D2C03, 0x002D5802, 0x002D8802, 0x002DC001,
  137432. 0x002E0801, 0x002EF805, 0x002F1803, 0x002F2804, 0x002F5C01,
  137433. 0x002FCC08, 0x00300403, 0x0030F807, 0x00311803, 0x00312804,
  137434. 0x00315402, 0x00318802, 0x0031FC01, 0x00320802, 0x0032F001,
  137435. 0x0032F807, 0x00331803, 0x00332804, 0x00335402, 0x00338802,
  137436. 0x00340802, 0x0034F807, 0x00351803, 0x00352804, 0x00355C01,
  137437. 0x00358802, 0x0035E401, 0x00360802, 0x00372801, 0x00373C06,
  137438. 0x00375801, 0x00376008, 0x0037C803, 0x0038C401, 0x0038D007,
  137439. 0x0038FC01, 0x00391C09, 0x00396802, 0x003AC401, 0x003AD006,
  137440. 0x003AEC02, 0x003B2006, 0x003C041F, 0x003CD00C, 0x003DC417,
  137441. 0x003E340B, 0x003E6424, 0x003EF80F, 0x003F380D, 0x0040AC14,
  137442. 0x00412806, 0x00415804, 0x00417803, 0x00418803, 0x00419C07,
  137443. 0x0041C404, 0x0042080C, 0x00423C01, 0x00426806, 0x0043EC01,
  137444. 0x004D740C, 0x004E400A, 0x00500001, 0x0059B402, 0x005A0001,
  137445. 0x005A6C02, 0x005BAC03, 0x005C4803, 0x005CC805, 0x005D4802,
  137446. 0x005DC802, 0x005ED023, 0x005F6004, 0x005F7401, 0x0060000F,
  137447. 0x0062A401, 0x0064800C, 0x0064C00C, 0x00650001, 0x00651002,
  137448. 0x0066C011, 0x00672002, 0x00677822, 0x00685C05, 0x00687802,
  137449. 0x0069540A, 0x0069801D, 0x0069FC01, 0x006A8007, 0x006AA006,
  137450. 0x006C0005, 0x006CD011, 0x006D6823, 0x006E0003, 0x006E840D,
  137451. 0x006F980E, 0x006FF004, 0x00709014, 0x0070EC05, 0x0071F802,
  137452. 0x00730008, 0x00734019, 0x0073B401, 0x0073C803, 0x00770027,
  137453. 0x0077F004, 0x007EF401, 0x007EFC03, 0x007F3403, 0x007F7403,
  137454. 0x007FB403, 0x007FF402, 0x00800065, 0x0081A806, 0x0081E805,
  137455. 0x00822805, 0x0082801A, 0x00834021, 0x00840002, 0x00840C04,
  137456. 0x00842002, 0x00845001, 0x00845803, 0x00847806, 0x00849401,
  137457. 0x00849C01, 0x0084A401, 0x0084B801, 0x0084E802, 0x00850005,
  137458. 0x00852804, 0x00853C01, 0x00864264, 0x00900027, 0x0091000B,
  137459. 0x0092704E, 0x00940200, 0x009C0475, 0x009E53B9, 0x00AD400A,
  137460. 0x00B39406, 0x00B3BC03, 0x00B3E404, 0x00B3F802, 0x00B5C001,
  137461. 0x00B5FC01, 0x00B7804F, 0x00B8C00C, 0x00BA001A, 0x00BA6C59,
  137462. 0x00BC00D6, 0x00BFC00C, 0x00C00005, 0x00C02019, 0x00C0A807,
  137463. 0x00C0D802, 0x00C0F403, 0x00C26404, 0x00C28001, 0x00C3EC01,
  137464. 0x00C64002, 0x00C6580A, 0x00C70024, 0x00C8001F, 0x00C8A81E,
  137465. 0x00C94001, 0x00C98020, 0x00CA2827, 0x00CB003F, 0x00CC0100,
  137466. 0x01370040, 0x02924037, 0x0293F802, 0x02983403, 0x0299BC10,
  137467. 0x029A7C01, 0x029BC008, 0x029C0017, 0x029C8002, 0x029E2402,
  137468. 0x02A00801, 0x02A01801, 0x02A02C01, 0x02A08C09, 0x02A0D804,
  137469. 0x02A1D004, 0x02A20002, 0x02A2D011, 0x02A33802, 0x02A38012,
  137470. 0x02A3E003, 0x02A4980A, 0x02A51C0D, 0x02A57C01, 0x02A60004,
  137471. 0x02A6CC1B, 0x02A77802, 0x02A8A40E, 0x02A90C01, 0x02A93002,
  137472. 0x02A97004, 0x02A9DC03, 0x02A9EC01, 0x02AAC001, 0x02AAC803,
  137473. 0x02AADC02, 0x02AAF802, 0x02AB0401, 0x02AB7802, 0x02ABAC07,
  137474. 0x02ABD402, 0x02AF8C0B, 0x03600001, 0x036DFC02, 0x036FFC02,
  137475. 0x037FFC01, 0x03EC7801, 0x03ECA401, 0x03EEC810, 0x03F4F802,
  137476. 0x03F7F002, 0x03F8001A, 0x03F88007, 0x03F8C023, 0x03F95013,
  137477. 0x03F9A004, 0x03FBFC01, 0x03FC040F, 0x03FC6807, 0x03FCEC06,
  137478. 0x03FD6C0B, 0x03FF8007, 0x03FFA007, 0x03FFE405, 0x04040003,
  137479. 0x0404DC09, 0x0405E411, 0x0406400C, 0x0407402E, 0x040E7C01,
  137480. 0x040F4001, 0x04215C01, 0x04247C01, 0x0424FC01, 0x04280403,
  137481. 0x04281402, 0x04283004, 0x0428E003, 0x0428FC01, 0x04294009,
  137482. 0x0429FC01, 0x042CE407, 0x04400003, 0x0440E016, 0x04420003,
  137483. 0x0442C012, 0x04440003, 0x04449C0E, 0x04450004, 0x04460003,
  137484. 0x0446CC0E, 0x04471404, 0x045AAC0D, 0x0491C004, 0x05BD442E,
  137485. 0x05BE3C04, 0x074000F6, 0x07440027, 0x0744A4B5, 0x07480046,
  137486. 0x074C0057, 0x075B0401, 0x075B6C01, 0x075BEC01, 0x075C5401,
  137487. 0x075CD401, 0x075D3C01, 0x075DBC01, 0x075E2401, 0x075EA401,
  137488. 0x075F0C01, 0x07BBC002, 0x07C0002C, 0x07C0C064, 0x07C2800F,
  137489. 0x07C2C40E, 0x07C3040F, 0x07C3440F, 0x07C4401F, 0x07C4C03C,
  137490. 0x07C5C02B, 0x07C7981D, 0x07C8402B, 0x07C90009, 0x07C94002,
  137491. 0x07CC0021, 0x07CCC006, 0x07CCDC46, 0x07CE0014, 0x07CE8025,
  137492. 0x07CF1805, 0x07CF8011, 0x07D0003F, 0x07D10001, 0x07D108B6,
  137493. 0x07D3E404, 0x07D4003E, 0x07D50004, 0x07D54018, 0x07D7EC46,
  137494. 0x07D9140B, 0x07DA0046, 0x07DC0074, 0x38000401, 0x38008060,
  137495. 0x380400F0,
  137496. };
  137497. static const unsigned int aAscii[4] = {
  137498. 0xFFFFFFFF, 0xFC00FFFF, 0xF8000001, 0xF8000001,
  137499. };
  137500. if( c<128 ){
  137501. return ( (aAscii[c >> 5] & (1 << (c & 0x001F)))==0 );
  137502. }else if( c<(1<<22) ){
  137503. unsigned int key = (((unsigned int)c)<<10) | 0x000003FF;
  137504. int iRes = 0;
  137505. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  137506. int iLo = 0;
  137507. while( iHi>=iLo ){
  137508. int iTest = (iHi + iLo) / 2;
  137509. if( key >= aEntry[iTest] ){
  137510. iRes = iTest;
  137511. iLo = iTest+1;
  137512. }else{
  137513. iHi = iTest-1;
  137514. }
  137515. }
  137516. assert( aEntry[0]<key );
  137517. assert( key>=aEntry[iRes] );
  137518. return (((unsigned int)c) >= ((aEntry[iRes]>>10) + (aEntry[iRes]&0x3FF)));
  137519. }
  137520. return 1;
  137521. }
  137522. /*
  137523. ** If the argument is a codepoint corresponding to a lowercase letter
  137524. ** in the ASCII range with a diacritic added, return the codepoint
  137525. ** of the ASCII letter only. For example, if passed 235 - "LATIN
  137526. ** SMALL LETTER E WITH DIAERESIS" - return 65 ("LATIN SMALL LETTER
  137527. ** E"). The resuls of passing a codepoint that corresponds to an
  137528. ** uppercase letter are undefined.
  137529. */
  137530. static int remove_diacritic(int c){
  137531. unsigned short aDia[] = {
  137532. 0, 1797, 1848, 1859, 1891, 1928, 1940, 1995,
  137533. 2024, 2040, 2060, 2110, 2168, 2206, 2264, 2286,
  137534. 2344, 2383, 2472, 2488, 2516, 2596, 2668, 2732,
  137535. 2782, 2842, 2894, 2954, 2984, 3000, 3028, 3336,
  137536. 3456, 3696, 3712, 3728, 3744, 3896, 3912, 3928,
  137537. 3968, 4008, 4040, 4106, 4138, 4170, 4202, 4234,
  137538. 4266, 4296, 4312, 4344, 4408, 4424, 4472, 4504,
  137539. 6148, 6198, 6264, 6280, 6360, 6429, 6505, 6529,
  137540. 61448, 61468, 61534, 61592, 61642, 61688, 61704, 61726,
  137541. 61784, 61800, 61836, 61880, 61914, 61948, 61998, 62122,
  137542. 62154, 62200, 62218, 62302, 62364, 62442, 62478, 62536,
  137543. 62554, 62584, 62604, 62640, 62648, 62656, 62664, 62730,
  137544. 62924, 63050, 63082, 63274, 63390,
  137545. };
  137546. char aChar[] = {
  137547. '\0', 'a', 'c', 'e', 'i', 'n', 'o', 'u', 'y', 'y', 'a', 'c',
  137548. 'd', 'e', 'e', 'g', 'h', 'i', 'j', 'k', 'l', 'n', 'o', 'r',
  137549. 's', 't', 'u', 'u', 'w', 'y', 'z', 'o', 'u', 'a', 'i', 'o',
  137550. 'u', 'g', 'k', 'o', 'j', 'g', 'n', 'a', 'e', 'i', 'o', 'r',
  137551. 'u', 's', 't', 'h', 'a', 'e', 'o', 'y', '\0', '\0', '\0', '\0',
  137552. '\0', '\0', '\0', '\0', 'a', 'b', 'd', 'd', 'e', 'f', 'g', 'h',
  137553. 'h', 'i', 'k', 'l', 'l', 'm', 'n', 'p', 'r', 'r', 's', 't',
  137554. 'u', 'v', 'w', 'w', 'x', 'y', 'z', 'h', 't', 'w', 'y', 'a',
  137555. 'e', 'i', 'o', 'u', 'y',
  137556. };
  137557. unsigned int key = (((unsigned int)c)<<3) | 0x00000007;
  137558. int iRes = 0;
  137559. int iHi = sizeof(aDia)/sizeof(aDia[0]) - 1;
  137560. int iLo = 0;
  137561. while( iHi>=iLo ){
  137562. int iTest = (iHi + iLo) / 2;
  137563. if( key >= aDia[iTest] ){
  137564. iRes = iTest;
  137565. iLo = iTest+1;
  137566. }else{
  137567. iHi = iTest-1;
  137568. }
  137569. }
  137570. assert( key>=aDia[iRes] );
  137571. return ((c > (aDia[iRes]>>3) + (aDia[iRes]&0x07)) ? c : (int)aChar[iRes]);
  137572. }
  137573. /*
  137574. ** Return true if the argument interpreted as a unicode codepoint
  137575. ** is a diacritical modifier character.
  137576. */
  137577. SQLITE_PRIVATE int sqlite3FtsUnicodeIsdiacritic(int c){
  137578. unsigned int mask0 = 0x08029FDF;
  137579. unsigned int mask1 = 0x000361F8;
  137580. if( c<768 || c>817 ) return 0;
  137581. return (c < 768+32) ?
  137582. (mask0 & (1 << (c-768))) :
  137583. (mask1 & (1 << (c-768-32)));
  137584. }
  137585. /*
  137586. ** Interpret the argument as a unicode codepoint. If the codepoint
  137587. ** is an upper case character that has a lower case equivalent,
  137588. ** return the codepoint corresponding to the lower case version.
  137589. ** Otherwise, return a copy of the argument.
  137590. **
  137591. ** The results are undefined if the value passed to this function
  137592. ** is less than zero.
  137593. */
  137594. SQLITE_PRIVATE int sqlite3FtsUnicodeFold(int c, int bRemoveDiacritic){
  137595. /* Each entry in the following array defines a rule for folding a range
  137596. ** of codepoints to lower case. The rule applies to a range of nRange
  137597. ** codepoints starting at codepoint iCode.
  137598. **
  137599. ** If the least significant bit in flags is clear, then the rule applies
  137600. ** to all nRange codepoints (i.e. all nRange codepoints are upper case and
  137601. ** need to be folded). Or, if it is set, then the rule only applies to
  137602. ** every second codepoint in the range, starting with codepoint C.
  137603. **
  137604. ** The 7 most significant bits in flags are an index into the aiOff[]
  137605. ** array. If a specific codepoint C does require folding, then its lower
  137606. ** case equivalent is ((C + aiOff[flags>>1]) & 0xFFFF).
  137607. **
  137608. ** The contents of this array are generated by parsing the CaseFolding.txt
  137609. ** file distributed as part of the "Unicode Character Database". See
  137610. ** http://www.unicode.org for details.
  137611. */
  137612. static const struct TableEntry {
  137613. unsigned short iCode;
  137614. unsigned char flags;
  137615. unsigned char nRange;
  137616. } aEntry[] = {
  137617. {65, 14, 26}, {181, 64, 1}, {192, 14, 23},
  137618. {216, 14, 7}, {256, 1, 48}, {306, 1, 6},
  137619. {313, 1, 16}, {330, 1, 46}, {376, 116, 1},
  137620. {377, 1, 6}, {383, 104, 1}, {385, 50, 1},
  137621. {386, 1, 4}, {390, 44, 1}, {391, 0, 1},
  137622. {393, 42, 2}, {395, 0, 1}, {398, 32, 1},
  137623. {399, 38, 1}, {400, 40, 1}, {401, 0, 1},
  137624. {403, 42, 1}, {404, 46, 1}, {406, 52, 1},
  137625. {407, 48, 1}, {408, 0, 1}, {412, 52, 1},
  137626. {413, 54, 1}, {415, 56, 1}, {416, 1, 6},
  137627. {422, 60, 1}, {423, 0, 1}, {425, 60, 1},
  137628. {428, 0, 1}, {430, 60, 1}, {431, 0, 1},
  137629. {433, 58, 2}, {435, 1, 4}, {439, 62, 1},
  137630. {440, 0, 1}, {444, 0, 1}, {452, 2, 1},
  137631. {453, 0, 1}, {455, 2, 1}, {456, 0, 1},
  137632. {458, 2, 1}, {459, 1, 18}, {478, 1, 18},
  137633. {497, 2, 1}, {498, 1, 4}, {502, 122, 1},
  137634. {503, 134, 1}, {504, 1, 40}, {544, 110, 1},
  137635. {546, 1, 18}, {570, 70, 1}, {571, 0, 1},
  137636. {573, 108, 1}, {574, 68, 1}, {577, 0, 1},
  137637. {579, 106, 1}, {580, 28, 1}, {581, 30, 1},
  137638. {582, 1, 10}, {837, 36, 1}, {880, 1, 4},
  137639. {886, 0, 1}, {902, 18, 1}, {904, 16, 3},
  137640. {908, 26, 1}, {910, 24, 2}, {913, 14, 17},
  137641. {931, 14, 9}, {962, 0, 1}, {975, 4, 1},
  137642. {976, 140, 1}, {977, 142, 1}, {981, 146, 1},
  137643. {982, 144, 1}, {984, 1, 24}, {1008, 136, 1},
  137644. {1009, 138, 1}, {1012, 130, 1}, {1013, 128, 1},
  137645. {1015, 0, 1}, {1017, 152, 1}, {1018, 0, 1},
  137646. {1021, 110, 3}, {1024, 34, 16}, {1040, 14, 32},
  137647. {1120, 1, 34}, {1162, 1, 54}, {1216, 6, 1},
  137648. {1217, 1, 14}, {1232, 1, 88}, {1329, 22, 38},
  137649. {4256, 66, 38}, {4295, 66, 1}, {4301, 66, 1},
  137650. {7680, 1, 150}, {7835, 132, 1}, {7838, 96, 1},
  137651. {7840, 1, 96}, {7944, 150, 8}, {7960, 150, 6},
  137652. {7976, 150, 8}, {7992, 150, 8}, {8008, 150, 6},
  137653. {8025, 151, 8}, {8040, 150, 8}, {8072, 150, 8},
  137654. {8088, 150, 8}, {8104, 150, 8}, {8120, 150, 2},
  137655. {8122, 126, 2}, {8124, 148, 1}, {8126, 100, 1},
  137656. {8136, 124, 4}, {8140, 148, 1}, {8152, 150, 2},
  137657. {8154, 120, 2}, {8168, 150, 2}, {8170, 118, 2},
  137658. {8172, 152, 1}, {8184, 112, 2}, {8186, 114, 2},
  137659. {8188, 148, 1}, {8486, 98, 1}, {8490, 92, 1},
  137660. {8491, 94, 1}, {8498, 12, 1}, {8544, 8, 16},
  137661. {8579, 0, 1}, {9398, 10, 26}, {11264, 22, 47},
  137662. {11360, 0, 1}, {11362, 88, 1}, {11363, 102, 1},
  137663. {11364, 90, 1}, {11367, 1, 6}, {11373, 84, 1},
  137664. {11374, 86, 1}, {11375, 80, 1}, {11376, 82, 1},
  137665. {11378, 0, 1}, {11381, 0, 1}, {11390, 78, 2},
  137666. {11392, 1, 100}, {11499, 1, 4}, {11506, 0, 1},
  137667. {42560, 1, 46}, {42624, 1, 24}, {42786, 1, 14},
  137668. {42802, 1, 62}, {42873, 1, 4}, {42877, 76, 1},
  137669. {42878, 1, 10}, {42891, 0, 1}, {42893, 74, 1},
  137670. {42896, 1, 4}, {42912, 1, 10}, {42922, 72, 1},
  137671. {65313, 14, 26},
  137672. };
  137673. static const unsigned short aiOff[] = {
  137674. 1, 2, 8, 15, 16, 26, 28, 32,
  137675. 37, 38, 40, 48, 63, 64, 69, 71,
  137676. 79, 80, 116, 202, 203, 205, 206, 207,
  137677. 209, 210, 211, 213, 214, 217, 218, 219,
  137678. 775, 7264, 10792, 10795, 23228, 23256, 30204, 54721,
  137679. 54753, 54754, 54756, 54787, 54793, 54809, 57153, 57274,
  137680. 57921, 58019, 58363, 61722, 65268, 65341, 65373, 65406,
  137681. 65408, 65410, 65415, 65424, 65436, 65439, 65450, 65462,
  137682. 65472, 65476, 65478, 65480, 65482, 65488, 65506, 65511,
  137683. 65514, 65521, 65527, 65528, 65529,
  137684. };
  137685. int ret = c;
  137686. assert( c>=0 );
  137687. assert( sizeof(unsigned short)==2 && sizeof(unsigned char)==1 );
  137688. if( c<128 ){
  137689. if( c>='A' && c<='Z' ) ret = c + ('a' - 'A');
  137690. }else if( c<65536 ){
  137691. int iHi = sizeof(aEntry)/sizeof(aEntry[0]) - 1;
  137692. int iLo = 0;
  137693. int iRes = -1;
  137694. while( iHi>=iLo ){
  137695. int iTest = (iHi + iLo) / 2;
  137696. int cmp = (c - aEntry[iTest].iCode);
  137697. if( cmp>=0 ){
  137698. iRes = iTest;
  137699. iLo = iTest+1;
  137700. }else{
  137701. iHi = iTest-1;
  137702. }
  137703. }
  137704. assert( iRes<0 || c>=aEntry[iRes].iCode );
  137705. if( iRes>=0 ){
  137706. const struct TableEntry *p = &aEntry[iRes];
  137707. if( c<(p->iCode + p->nRange) && 0==(0x01 & p->flags & (p->iCode ^ c)) ){
  137708. ret = (c + (aiOff[p->flags>>1])) & 0x0000FFFF;
  137709. assert( ret>0 );
  137710. }
  137711. }
  137712. if( bRemoveDiacritic ) ret = remove_diacritic(ret);
  137713. }
  137714. else if( c>=66560 && c<66600 ){
  137715. ret = c + 40;
  137716. }
  137717. return ret;
  137718. }
  137719. #endif /* defined(SQLITE_ENABLE_FTS3) || defined(SQLITE_ENABLE_FTS4) */
  137720. #endif /* !defined(SQLITE_DISABLE_FTS3_UNICODE) */
  137721. /************** End of fts3_unicode2.c ***************************************/
  137722. /************** Begin file rtree.c *******************************************/
  137723. /*
  137724. ** 2001 September 15
  137725. **
  137726. ** The author disclaims copyright to this source code. In place of
  137727. ** a legal notice, here is a blessing:
  137728. **
  137729. ** May you do good and not evil.
  137730. ** May you find forgiveness for yourself and forgive others.
  137731. ** May you share freely, never taking more than you give.
  137732. **
  137733. *************************************************************************
  137734. ** This file contains code for implementations of the r-tree and r*-tree
  137735. ** algorithms packaged as an SQLite virtual table module.
  137736. */
  137737. /*
  137738. ** Database Format of R-Tree Tables
  137739. ** --------------------------------
  137740. **
  137741. ** The data structure for a single virtual r-tree table is stored in three
  137742. ** native SQLite tables declared as follows. In each case, the '%' character
  137743. ** in the table name is replaced with the user-supplied name of the r-tree
  137744. ** table.
  137745. **
  137746. ** CREATE TABLE %_node(nodeno INTEGER PRIMARY KEY, data BLOB)
  137747. ** CREATE TABLE %_parent(nodeno INTEGER PRIMARY KEY, parentnode INTEGER)
  137748. ** CREATE TABLE %_rowid(rowid INTEGER PRIMARY KEY, nodeno INTEGER)
  137749. **
  137750. ** The data for each node of the r-tree structure is stored in the %_node
  137751. ** table. For each node that is not the root node of the r-tree, there is
  137752. ** an entry in the %_parent table associating the node with its parent.
  137753. ** And for each row of data in the table, there is an entry in the %_rowid
  137754. ** table that maps from the entries rowid to the id of the node that it
  137755. ** is stored on.
  137756. **
  137757. ** The root node of an r-tree always exists, even if the r-tree table is
  137758. ** empty. The nodeno of the root node is always 1. All other nodes in the
  137759. ** table must be the same size as the root node. The content of each node
  137760. ** is formatted as follows:
  137761. **
  137762. ** 1. If the node is the root node (node 1), then the first 2 bytes
  137763. ** of the node contain the tree depth as a big-endian integer.
  137764. ** For non-root nodes, the first 2 bytes are left unused.
  137765. **
  137766. ** 2. The next 2 bytes contain the number of entries currently
  137767. ** stored in the node.
  137768. **
  137769. ** 3. The remainder of the node contains the node entries. Each entry
  137770. ** consists of a single 8-byte integer followed by an even number
  137771. ** of 4-byte coordinates. For leaf nodes the integer is the rowid
  137772. ** of a record. For internal nodes it is the node number of a
  137773. ** child page.
  137774. */
  137775. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_RTREE)
  137776. #ifndef SQLITE_CORE
  137777. SQLITE_EXTENSION_INIT1
  137778. #else
  137779. #endif
  137780. /* #include <string.h> */
  137781. /* #include <assert.h> */
  137782. /* #include <stdio.h> */
  137783. #ifndef SQLITE_AMALGAMATION
  137784. #include "sqlite3rtree.h"
  137785. typedef sqlite3_int64 i64;
  137786. typedef unsigned char u8;
  137787. typedef unsigned short u16;
  137788. typedef unsigned int u32;
  137789. #endif
  137790. /* The following macro is used to suppress compiler warnings.
  137791. */
  137792. #ifndef UNUSED_PARAMETER
  137793. # define UNUSED_PARAMETER(x) (void)(x)
  137794. #endif
  137795. typedef struct Rtree Rtree;
  137796. typedef struct RtreeCursor RtreeCursor;
  137797. typedef struct RtreeNode RtreeNode;
  137798. typedef struct RtreeCell RtreeCell;
  137799. typedef struct RtreeConstraint RtreeConstraint;
  137800. typedef struct RtreeMatchArg RtreeMatchArg;
  137801. typedef struct RtreeGeomCallback RtreeGeomCallback;
  137802. typedef union RtreeCoord RtreeCoord;
  137803. typedef struct RtreeSearchPoint RtreeSearchPoint;
  137804. /* The rtree may have between 1 and RTREE_MAX_DIMENSIONS dimensions. */
  137805. #define RTREE_MAX_DIMENSIONS 5
  137806. /* Size of hash table Rtree.aHash. This hash table is not expected to
  137807. ** ever contain very many entries, so a fixed number of buckets is
  137808. ** used.
  137809. */
  137810. #define HASHSIZE 97
  137811. /* The xBestIndex method of this virtual table requires an estimate of
  137812. ** the number of rows in the virtual table to calculate the costs of
  137813. ** various strategies. If possible, this estimate is loaded from the
  137814. ** sqlite_stat1 table (with RTREE_MIN_ROWEST as a hard-coded minimum).
  137815. ** Otherwise, if no sqlite_stat1 entry is available, use
  137816. ** RTREE_DEFAULT_ROWEST.
  137817. */
  137818. #define RTREE_DEFAULT_ROWEST 1048576
  137819. #define RTREE_MIN_ROWEST 100
  137820. /*
  137821. ** An rtree virtual-table object.
  137822. */
  137823. struct Rtree {
  137824. sqlite3_vtab base; /* Base class. Must be first */
  137825. sqlite3 *db; /* Host database connection */
  137826. int iNodeSize; /* Size in bytes of each node in the node table */
  137827. u8 nDim; /* Number of dimensions */
  137828. u8 eCoordType; /* RTREE_COORD_REAL32 or RTREE_COORD_INT32 */
  137829. u8 nBytesPerCell; /* Bytes consumed per cell */
  137830. int iDepth; /* Current depth of the r-tree structure */
  137831. char *zDb; /* Name of database containing r-tree table */
  137832. char *zName; /* Name of r-tree table */
  137833. int nBusy; /* Current number of users of this structure */
  137834. i64 nRowEst; /* Estimated number of rows in this table */
  137835. /* List of nodes removed during a CondenseTree operation. List is
  137836. ** linked together via the pointer normally used for hash chains -
  137837. ** RtreeNode.pNext. RtreeNode.iNode stores the depth of the sub-tree
  137838. ** headed by the node (leaf nodes have RtreeNode.iNode==0).
  137839. */
  137840. RtreeNode *pDeleted;
  137841. int iReinsertHeight; /* Height of sub-trees Reinsert() has run on */
  137842. /* Statements to read/write/delete a record from xxx_node */
  137843. sqlite3_stmt *pReadNode;
  137844. sqlite3_stmt *pWriteNode;
  137845. sqlite3_stmt *pDeleteNode;
  137846. /* Statements to read/write/delete a record from xxx_rowid */
  137847. sqlite3_stmt *pReadRowid;
  137848. sqlite3_stmt *pWriteRowid;
  137849. sqlite3_stmt *pDeleteRowid;
  137850. /* Statements to read/write/delete a record from xxx_parent */
  137851. sqlite3_stmt *pReadParent;
  137852. sqlite3_stmt *pWriteParent;
  137853. sqlite3_stmt *pDeleteParent;
  137854. RtreeNode *aHash[HASHSIZE]; /* Hash table of in-memory nodes. */
  137855. };
  137856. /* Possible values for Rtree.eCoordType: */
  137857. #define RTREE_COORD_REAL32 0
  137858. #define RTREE_COORD_INT32 1
  137859. /*
  137860. ** If SQLITE_RTREE_INT_ONLY is defined, then this virtual table will
  137861. ** only deal with integer coordinates. No floating point operations
  137862. ** will be done.
  137863. */
  137864. #ifdef SQLITE_RTREE_INT_ONLY
  137865. typedef sqlite3_int64 RtreeDValue; /* High accuracy coordinate */
  137866. typedef int RtreeValue; /* Low accuracy coordinate */
  137867. # define RTREE_ZERO 0
  137868. #else
  137869. typedef double RtreeDValue; /* High accuracy coordinate */
  137870. typedef float RtreeValue; /* Low accuracy coordinate */
  137871. # define RTREE_ZERO 0.0
  137872. #endif
  137873. /*
  137874. ** When doing a search of an r-tree, instances of the following structure
  137875. ** record intermediate results from the tree walk.
  137876. **
  137877. ** The id is always a node-id. For iLevel>=1 the id is the node-id of
  137878. ** the node that the RtreeSearchPoint represents. When iLevel==0, however,
  137879. ** the id is of the parent node and the cell that RtreeSearchPoint
  137880. ** represents is the iCell-th entry in the parent node.
  137881. */
  137882. struct RtreeSearchPoint {
  137883. RtreeDValue rScore; /* The score for this node. Smallest goes first. */
  137884. sqlite3_int64 id; /* Node ID */
  137885. u8 iLevel; /* 0=entries. 1=leaf node. 2+ for higher */
  137886. u8 eWithin; /* PARTLY_WITHIN or FULLY_WITHIN */
  137887. u8 iCell; /* Cell index within the node */
  137888. };
  137889. /*
  137890. ** The minimum number of cells allowed for a node is a third of the
  137891. ** maximum. In Gutman's notation:
  137892. **
  137893. ** m = M/3
  137894. **
  137895. ** If an R*-tree "Reinsert" operation is required, the same number of
  137896. ** cells are removed from the overfull node and reinserted into the tree.
  137897. */
  137898. #define RTREE_MINCELLS(p) ((((p)->iNodeSize-4)/(p)->nBytesPerCell)/3)
  137899. #define RTREE_REINSERT(p) RTREE_MINCELLS(p)
  137900. #define RTREE_MAXCELLS 51
  137901. /*
  137902. ** The smallest possible node-size is (512-64)==448 bytes. And the largest
  137903. ** supported cell size is 48 bytes (8 byte rowid + ten 4 byte coordinates).
  137904. ** Therefore all non-root nodes must contain at least 3 entries. Since
  137905. ** 2^40 is greater than 2^64, an r-tree structure always has a depth of
  137906. ** 40 or less.
  137907. */
  137908. #define RTREE_MAX_DEPTH 40
  137909. /*
  137910. ** Number of entries in the cursor RtreeNode cache. The first entry is
  137911. ** used to cache the RtreeNode for RtreeCursor.sPoint. The remaining
  137912. ** entries cache the RtreeNode for the first elements of the priority queue.
  137913. */
  137914. #define RTREE_CACHE_SZ 5
  137915. /*
  137916. ** An rtree cursor object.
  137917. */
  137918. struct RtreeCursor {
  137919. sqlite3_vtab_cursor base; /* Base class. Must be first */
  137920. u8 atEOF; /* True if at end of search */
  137921. u8 bPoint; /* True if sPoint is valid */
  137922. int iStrategy; /* Copy of idxNum search parameter */
  137923. int nConstraint; /* Number of entries in aConstraint */
  137924. RtreeConstraint *aConstraint; /* Search constraints. */
  137925. int nPointAlloc; /* Number of slots allocated for aPoint[] */
  137926. int nPoint; /* Number of slots used in aPoint[] */
  137927. int mxLevel; /* iLevel value for root of the tree */
  137928. RtreeSearchPoint *aPoint; /* Priority queue for search points */
  137929. RtreeSearchPoint sPoint; /* Cached next search point */
  137930. RtreeNode *aNode[RTREE_CACHE_SZ]; /* Rtree node cache */
  137931. u32 anQueue[RTREE_MAX_DEPTH+1]; /* Number of queued entries by iLevel */
  137932. };
  137933. /* Return the Rtree of a RtreeCursor */
  137934. #define RTREE_OF_CURSOR(X) ((Rtree*)((X)->base.pVtab))
  137935. /*
  137936. ** A coordinate can be either a floating point number or a integer. All
  137937. ** coordinates within a single R-Tree are always of the same time.
  137938. */
  137939. union RtreeCoord {
  137940. RtreeValue f; /* Floating point value */
  137941. int i; /* Integer value */
  137942. u32 u; /* Unsigned for byte-order conversions */
  137943. };
  137944. /*
  137945. ** The argument is an RtreeCoord. Return the value stored within the RtreeCoord
  137946. ** formatted as a RtreeDValue (double or int64). This macro assumes that local
  137947. ** variable pRtree points to the Rtree structure associated with the
  137948. ** RtreeCoord.
  137949. */
  137950. #ifdef SQLITE_RTREE_INT_ONLY
  137951. # define DCOORD(coord) ((RtreeDValue)coord.i)
  137952. #else
  137953. # define DCOORD(coord) ( \
  137954. (pRtree->eCoordType==RTREE_COORD_REAL32) ? \
  137955. ((double)coord.f) : \
  137956. ((double)coord.i) \
  137957. )
  137958. #endif
  137959. /*
  137960. ** A search constraint.
  137961. */
  137962. struct RtreeConstraint {
  137963. int iCoord; /* Index of constrained coordinate */
  137964. int op; /* Constraining operation */
  137965. union {
  137966. RtreeDValue rValue; /* Constraint value. */
  137967. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*);
  137968. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  137969. } u;
  137970. sqlite3_rtree_query_info *pInfo; /* xGeom and xQueryFunc argument */
  137971. };
  137972. /* Possible values for RtreeConstraint.op */
  137973. #define RTREE_EQ 0x41 /* A */
  137974. #define RTREE_LE 0x42 /* B */
  137975. #define RTREE_LT 0x43 /* C */
  137976. #define RTREE_GE 0x44 /* D */
  137977. #define RTREE_GT 0x45 /* E */
  137978. #define RTREE_MATCH 0x46 /* F: Old-style sqlite3_rtree_geometry_callback() */
  137979. #define RTREE_QUERY 0x47 /* G: New-style sqlite3_rtree_query_callback() */
  137980. /*
  137981. ** An rtree structure node.
  137982. */
  137983. struct RtreeNode {
  137984. RtreeNode *pParent; /* Parent node */
  137985. i64 iNode; /* The node number */
  137986. int nRef; /* Number of references to this node */
  137987. int isDirty; /* True if the node needs to be written to disk */
  137988. u8 *zData; /* Content of the node, as should be on disk */
  137989. RtreeNode *pNext; /* Next node in this hash collision chain */
  137990. };
  137991. /* Return the number of cells in a node */
  137992. #define NCELL(pNode) readInt16(&(pNode)->zData[2])
  137993. /*
  137994. ** A single cell from a node, deserialized
  137995. */
  137996. struct RtreeCell {
  137997. i64 iRowid; /* Node or entry ID */
  137998. RtreeCoord aCoord[RTREE_MAX_DIMENSIONS*2]; /* Bounding box coordinates */
  137999. };
  138000. /*
  138001. ** This object becomes the sqlite3_user_data() for the SQL functions
  138002. ** that are created by sqlite3_rtree_geometry_callback() and
  138003. ** sqlite3_rtree_query_callback() and which appear on the right of MATCH
  138004. ** operators in order to constrain a search.
  138005. **
  138006. ** xGeom and xQueryFunc are the callback functions. Exactly one of
  138007. ** xGeom and xQueryFunc fields is non-NULL, depending on whether the
  138008. ** SQL function was created using sqlite3_rtree_geometry_callback() or
  138009. ** sqlite3_rtree_query_callback().
  138010. **
  138011. ** This object is deleted automatically by the destructor mechanism in
  138012. ** sqlite3_create_function_v2().
  138013. */
  138014. struct RtreeGeomCallback {
  138015. int (*xGeom)(sqlite3_rtree_geometry*, int, RtreeDValue*, int*);
  138016. int (*xQueryFunc)(sqlite3_rtree_query_info*);
  138017. void (*xDestructor)(void*);
  138018. void *pContext;
  138019. };
  138020. /*
  138021. ** Value for the first field of every RtreeMatchArg object. The MATCH
  138022. ** operator tests that the first field of a blob operand matches this
  138023. ** value to avoid operating on invalid blobs (which could cause a segfault).
  138024. */
  138025. #define RTREE_GEOMETRY_MAGIC 0x891245AB
  138026. /*
  138027. ** An instance of this structure (in the form of a BLOB) is returned by
  138028. ** the SQL functions that sqlite3_rtree_geometry_callback() and
  138029. ** sqlite3_rtree_query_callback() create, and is read as the right-hand
  138030. ** operand to the MATCH operator of an R-Tree.
  138031. */
  138032. struct RtreeMatchArg {
  138033. u32 magic; /* Always RTREE_GEOMETRY_MAGIC */
  138034. RtreeGeomCallback cb; /* Info about the callback functions */
  138035. int nParam; /* Number of parameters to the SQL function */
  138036. RtreeDValue aParam[1]; /* Values for parameters to the SQL function */
  138037. };
  138038. #ifndef MAX
  138039. # define MAX(x,y) ((x) < (y) ? (y) : (x))
  138040. #endif
  138041. #ifndef MIN
  138042. # define MIN(x,y) ((x) > (y) ? (y) : (x))
  138043. #endif
  138044. /*
  138045. ** Functions to deserialize a 16 bit integer, 32 bit real number and
  138046. ** 64 bit integer. The deserialized value is returned.
  138047. */
  138048. static int readInt16(u8 *p){
  138049. return (p[0]<<8) + p[1];
  138050. }
  138051. static void readCoord(u8 *p, RtreeCoord *pCoord){
  138052. u32 i = (
  138053. (((u32)p[0]) << 24) +
  138054. (((u32)p[1]) << 16) +
  138055. (((u32)p[2]) << 8) +
  138056. (((u32)p[3]) << 0)
  138057. );
  138058. *(u32 *)pCoord = i;
  138059. }
  138060. static i64 readInt64(u8 *p){
  138061. return (
  138062. (((i64)p[0]) << 56) +
  138063. (((i64)p[1]) << 48) +
  138064. (((i64)p[2]) << 40) +
  138065. (((i64)p[3]) << 32) +
  138066. (((i64)p[4]) << 24) +
  138067. (((i64)p[5]) << 16) +
  138068. (((i64)p[6]) << 8) +
  138069. (((i64)p[7]) << 0)
  138070. );
  138071. }
  138072. /*
  138073. ** Functions to serialize a 16 bit integer, 32 bit real number and
  138074. ** 64 bit integer. The value returned is the number of bytes written
  138075. ** to the argument buffer (always 2, 4 and 8 respectively).
  138076. */
  138077. static int writeInt16(u8 *p, int i){
  138078. p[0] = (i>> 8)&0xFF;
  138079. p[1] = (i>> 0)&0xFF;
  138080. return 2;
  138081. }
  138082. static int writeCoord(u8 *p, RtreeCoord *pCoord){
  138083. u32 i;
  138084. assert( sizeof(RtreeCoord)==4 );
  138085. assert( sizeof(u32)==4 );
  138086. i = *(u32 *)pCoord;
  138087. p[0] = (i>>24)&0xFF;
  138088. p[1] = (i>>16)&0xFF;
  138089. p[2] = (i>> 8)&0xFF;
  138090. p[3] = (i>> 0)&0xFF;
  138091. return 4;
  138092. }
  138093. static int writeInt64(u8 *p, i64 i){
  138094. p[0] = (i>>56)&0xFF;
  138095. p[1] = (i>>48)&0xFF;
  138096. p[2] = (i>>40)&0xFF;
  138097. p[3] = (i>>32)&0xFF;
  138098. p[4] = (i>>24)&0xFF;
  138099. p[5] = (i>>16)&0xFF;
  138100. p[6] = (i>> 8)&0xFF;
  138101. p[7] = (i>> 0)&0xFF;
  138102. return 8;
  138103. }
  138104. /*
  138105. ** Increment the reference count of node p.
  138106. */
  138107. static void nodeReference(RtreeNode *p){
  138108. if( p ){
  138109. p->nRef++;
  138110. }
  138111. }
  138112. /*
  138113. ** Clear the content of node p (set all bytes to 0x00).
  138114. */
  138115. static void nodeZero(Rtree *pRtree, RtreeNode *p){
  138116. memset(&p->zData[2], 0, pRtree->iNodeSize-2);
  138117. p->isDirty = 1;
  138118. }
  138119. /*
  138120. ** Given a node number iNode, return the corresponding key to use
  138121. ** in the Rtree.aHash table.
  138122. */
  138123. static int nodeHash(i64 iNode){
  138124. return iNode % HASHSIZE;
  138125. }
  138126. /*
  138127. ** Search the node hash table for node iNode. If found, return a pointer
  138128. ** to it. Otherwise, return 0.
  138129. */
  138130. static RtreeNode *nodeHashLookup(Rtree *pRtree, i64 iNode){
  138131. RtreeNode *p;
  138132. for(p=pRtree->aHash[nodeHash(iNode)]; p && p->iNode!=iNode; p=p->pNext);
  138133. return p;
  138134. }
  138135. /*
  138136. ** Add node pNode to the node hash table.
  138137. */
  138138. static void nodeHashInsert(Rtree *pRtree, RtreeNode *pNode){
  138139. int iHash;
  138140. assert( pNode->pNext==0 );
  138141. iHash = nodeHash(pNode->iNode);
  138142. pNode->pNext = pRtree->aHash[iHash];
  138143. pRtree->aHash[iHash] = pNode;
  138144. }
  138145. /*
  138146. ** Remove node pNode from the node hash table.
  138147. */
  138148. static void nodeHashDelete(Rtree *pRtree, RtreeNode *pNode){
  138149. RtreeNode **pp;
  138150. if( pNode->iNode!=0 ){
  138151. pp = &pRtree->aHash[nodeHash(pNode->iNode)];
  138152. for( ; (*pp)!=pNode; pp = &(*pp)->pNext){ assert(*pp); }
  138153. *pp = pNode->pNext;
  138154. pNode->pNext = 0;
  138155. }
  138156. }
  138157. /*
  138158. ** Allocate and return new r-tree node. Initially, (RtreeNode.iNode==0),
  138159. ** indicating that node has not yet been assigned a node number. It is
  138160. ** assigned a node number when nodeWrite() is called to write the
  138161. ** node contents out to the database.
  138162. */
  138163. static RtreeNode *nodeNew(Rtree *pRtree, RtreeNode *pParent){
  138164. RtreeNode *pNode;
  138165. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode) + pRtree->iNodeSize);
  138166. if( pNode ){
  138167. memset(pNode, 0, sizeof(RtreeNode) + pRtree->iNodeSize);
  138168. pNode->zData = (u8 *)&pNode[1];
  138169. pNode->nRef = 1;
  138170. pNode->pParent = pParent;
  138171. pNode->isDirty = 1;
  138172. nodeReference(pParent);
  138173. }
  138174. return pNode;
  138175. }
  138176. /*
  138177. ** Obtain a reference to an r-tree node.
  138178. */
  138179. static int nodeAcquire(
  138180. Rtree *pRtree, /* R-tree structure */
  138181. i64 iNode, /* Node number to load */
  138182. RtreeNode *pParent, /* Either the parent node or NULL */
  138183. RtreeNode **ppNode /* OUT: Acquired node */
  138184. ){
  138185. int rc;
  138186. int rc2 = SQLITE_OK;
  138187. RtreeNode *pNode;
  138188. /* Check if the requested node is already in the hash table. If so,
  138189. ** increase its reference count and return it.
  138190. */
  138191. if( (pNode = nodeHashLookup(pRtree, iNode)) ){
  138192. assert( !pParent || !pNode->pParent || pNode->pParent==pParent );
  138193. if( pParent && !pNode->pParent ){
  138194. nodeReference(pParent);
  138195. pNode->pParent = pParent;
  138196. }
  138197. pNode->nRef++;
  138198. *ppNode = pNode;
  138199. return SQLITE_OK;
  138200. }
  138201. sqlite3_bind_int64(pRtree->pReadNode, 1, iNode);
  138202. rc = sqlite3_step(pRtree->pReadNode);
  138203. if( rc==SQLITE_ROW ){
  138204. const u8 *zBlob = sqlite3_column_blob(pRtree->pReadNode, 0);
  138205. if( pRtree->iNodeSize==sqlite3_column_bytes(pRtree->pReadNode, 0) ){
  138206. pNode = (RtreeNode *)sqlite3_malloc(sizeof(RtreeNode)+pRtree->iNodeSize);
  138207. if( !pNode ){
  138208. rc2 = SQLITE_NOMEM;
  138209. }else{
  138210. pNode->pParent = pParent;
  138211. pNode->zData = (u8 *)&pNode[1];
  138212. pNode->nRef = 1;
  138213. pNode->iNode = iNode;
  138214. pNode->isDirty = 0;
  138215. pNode->pNext = 0;
  138216. memcpy(pNode->zData, zBlob, pRtree->iNodeSize);
  138217. nodeReference(pParent);
  138218. }
  138219. }
  138220. }
  138221. rc = sqlite3_reset(pRtree->pReadNode);
  138222. if( rc==SQLITE_OK ) rc = rc2;
  138223. /* If the root node was just loaded, set pRtree->iDepth to the height
  138224. ** of the r-tree structure. A height of zero means all data is stored on
  138225. ** the root node. A height of one means the children of the root node
  138226. ** are the leaves, and so on. If the depth as specified on the root node
  138227. ** is greater than RTREE_MAX_DEPTH, the r-tree structure must be corrupt.
  138228. */
  138229. if( pNode && iNode==1 ){
  138230. pRtree->iDepth = readInt16(pNode->zData);
  138231. if( pRtree->iDepth>RTREE_MAX_DEPTH ){
  138232. rc = SQLITE_CORRUPT_VTAB;
  138233. }
  138234. }
  138235. /* If no error has occurred so far, check if the "number of entries"
  138236. ** field on the node is too large. If so, set the return code to
  138237. ** SQLITE_CORRUPT_VTAB.
  138238. */
  138239. if( pNode && rc==SQLITE_OK ){
  138240. if( NCELL(pNode)>((pRtree->iNodeSize-4)/pRtree->nBytesPerCell) ){
  138241. rc = SQLITE_CORRUPT_VTAB;
  138242. }
  138243. }
  138244. if( rc==SQLITE_OK ){
  138245. if( pNode!=0 ){
  138246. nodeHashInsert(pRtree, pNode);
  138247. }else{
  138248. rc = SQLITE_CORRUPT_VTAB;
  138249. }
  138250. *ppNode = pNode;
  138251. }else{
  138252. sqlite3_free(pNode);
  138253. *ppNode = 0;
  138254. }
  138255. return rc;
  138256. }
  138257. /*
  138258. ** Overwrite cell iCell of node pNode with the contents of pCell.
  138259. */
  138260. static void nodeOverwriteCell(
  138261. Rtree *pRtree, /* The overall R-Tree */
  138262. RtreeNode *pNode, /* The node into which the cell is to be written */
  138263. RtreeCell *pCell, /* The cell to write */
  138264. int iCell /* Index into pNode into which pCell is written */
  138265. ){
  138266. int ii;
  138267. u8 *p = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  138268. p += writeInt64(p, pCell->iRowid);
  138269. for(ii=0; ii<(pRtree->nDim*2); ii++){
  138270. p += writeCoord(p, &pCell->aCoord[ii]);
  138271. }
  138272. pNode->isDirty = 1;
  138273. }
  138274. /*
  138275. ** Remove the cell with index iCell from node pNode.
  138276. */
  138277. static void nodeDeleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell){
  138278. u8 *pDst = &pNode->zData[4 + pRtree->nBytesPerCell*iCell];
  138279. u8 *pSrc = &pDst[pRtree->nBytesPerCell];
  138280. int nByte = (NCELL(pNode) - iCell - 1) * pRtree->nBytesPerCell;
  138281. memmove(pDst, pSrc, nByte);
  138282. writeInt16(&pNode->zData[2], NCELL(pNode)-1);
  138283. pNode->isDirty = 1;
  138284. }
  138285. /*
  138286. ** Insert the contents of cell pCell into node pNode. If the insert
  138287. ** is successful, return SQLITE_OK.
  138288. **
  138289. ** If there is not enough free space in pNode, return SQLITE_FULL.
  138290. */
  138291. static int nodeInsertCell(
  138292. Rtree *pRtree, /* The overall R-Tree */
  138293. RtreeNode *pNode, /* Write new cell into this node */
  138294. RtreeCell *pCell /* The cell to be inserted */
  138295. ){
  138296. int nCell; /* Current number of cells in pNode */
  138297. int nMaxCell; /* Maximum number of cells for pNode */
  138298. nMaxCell = (pRtree->iNodeSize-4)/pRtree->nBytesPerCell;
  138299. nCell = NCELL(pNode);
  138300. assert( nCell<=nMaxCell );
  138301. if( nCell<nMaxCell ){
  138302. nodeOverwriteCell(pRtree, pNode, pCell, nCell);
  138303. writeInt16(&pNode->zData[2], nCell+1);
  138304. pNode->isDirty = 1;
  138305. }
  138306. return (nCell==nMaxCell);
  138307. }
  138308. /*
  138309. ** If the node is dirty, write it out to the database.
  138310. */
  138311. static int nodeWrite(Rtree *pRtree, RtreeNode *pNode){
  138312. int rc = SQLITE_OK;
  138313. if( pNode->isDirty ){
  138314. sqlite3_stmt *p = pRtree->pWriteNode;
  138315. if( pNode->iNode ){
  138316. sqlite3_bind_int64(p, 1, pNode->iNode);
  138317. }else{
  138318. sqlite3_bind_null(p, 1);
  138319. }
  138320. sqlite3_bind_blob(p, 2, pNode->zData, pRtree->iNodeSize, SQLITE_STATIC);
  138321. sqlite3_step(p);
  138322. pNode->isDirty = 0;
  138323. rc = sqlite3_reset(p);
  138324. if( pNode->iNode==0 && rc==SQLITE_OK ){
  138325. pNode->iNode = sqlite3_last_insert_rowid(pRtree->db);
  138326. nodeHashInsert(pRtree, pNode);
  138327. }
  138328. }
  138329. return rc;
  138330. }
  138331. /*
  138332. ** Release a reference to a node. If the node is dirty and the reference
  138333. ** count drops to zero, the node data is written to the database.
  138334. */
  138335. static int nodeRelease(Rtree *pRtree, RtreeNode *pNode){
  138336. int rc = SQLITE_OK;
  138337. if( pNode ){
  138338. assert( pNode->nRef>0 );
  138339. pNode->nRef--;
  138340. if( pNode->nRef==0 ){
  138341. if( pNode->iNode==1 ){
  138342. pRtree->iDepth = -1;
  138343. }
  138344. if( pNode->pParent ){
  138345. rc = nodeRelease(pRtree, pNode->pParent);
  138346. }
  138347. if( rc==SQLITE_OK ){
  138348. rc = nodeWrite(pRtree, pNode);
  138349. }
  138350. nodeHashDelete(pRtree, pNode);
  138351. sqlite3_free(pNode);
  138352. }
  138353. }
  138354. return rc;
  138355. }
  138356. /*
  138357. ** Return the 64-bit integer value associated with cell iCell of
  138358. ** node pNode. If pNode is a leaf node, this is a rowid. If it is
  138359. ** an internal node, then the 64-bit integer is a child page number.
  138360. */
  138361. static i64 nodeGetRowid(
  138362. Rtree *pRtree, /* The overall R-Tree */
  138363. RtreeNode *pNode, /* The node from which to extract the ID */
  138364. int iCell /* The cell index from which to extract the ID */
  138365. ){
  138366. assert( iCell<NCELL(pNode) );
  138367. return readInt64(&pNode->zData[4 + pRtree->nBytesPerCell*iCell]);
  138368. }
  138369. /*
  138370. ** Return coordinate iCoord from cell iCell in node pNode.
  138371. */
  138372. static void nodeGetCoord(
  138373. Rtree *pRtree, /* The overall R-Tree */
  138374. RtreeNode *pNode, /* The node from which to extract a coordinate */
  138375. int iCell, /* The index of the cell within the node */
  138376. int iCoord, /* Which coordinate to extract */
  138377. RtreeCoord *pCoord /* OUT: Space to write result to */
  138378. ){
  138379. readCoord(&pNode->zData[12 + pRtree->nBytesPerCell*iCell + 4*iCoord], pCoord);
  138380. }
  138381. /*
  138382. ** Deserialize cell iCell of node pNode. Populate the structure pointed
  138383. ** to by pCell with the results.
  138384. */
  138385. static void nodeGetCell(
  138386. Rtree *pRtree, /* The overall R-Tree */
  138387. RtreeNode *pNode, /* The node containing the cell to be read */
  138388. int iCell, /* Index of the cell within the node */
  138389. RtreeCell *pCell /* OUT: Write the cell contents here */
  138390. ){
  138391. u8 *pData;
  138392. u8 *pEnd;
  138393. RtreeCoord *pCoord;
  138394. pCell->iRowid = nodeGetRowid(pRtree, pNode, iCell);
  138395. pData = pNode->zData + (12 + pRtree->nBytesPerCell*iCell);
  138396. pEnd = pData + pRtree->nDim*8;
  138397. pCoord = pCell->aCoord;
  138398. for(; pData<pEnd; pData+=4, pCoord++){
  138399. readCoord(pData, pCoord);
  138400. }
  138401. }
  138402. /* Forward declaration for the function that does the work of
  138403. ** the virtual table module xCreate() and xConnect() methods.
  138404. */
  138405. static int rtreeInit(
  138406. sqlite3 *, void *, int, const char *const*, sqlite3_vtab **, char **, int
  138407. );
  138408. /*
  138409. ** Rtree virtual table module xCreate method.
  138410. */
  138411. static int rtreeCreate(
  138412. sqlite3 *db,
  138413. void *pAux,
  138414. int argc, const char *const*argv,
  138415. sqlite3_vtab **ppVtab,
  138416. char **pzErr
  138417. ){
  138418. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 1);
  138419. }
  138420. /*
  138421. ** Rtree virtual table module xConnect method.
  138422. */
  138423. static int rtreeConnect(
  138424. sqlite3 *db,
  138425. void *pAux,
  138426. int argc, const char *const*argv,
  138427. sqlite3_vtab **ppVtab,
  138428. char **pzErr
  138429. ){
  138430. return rtreeInit(db, pAux, argc, argv, ppVtab, pzErr, 0);
  138431. }
  138432. /*
  138433. ** Increment the r-tree reference count.
  138434. */
  138435. static void rtreeReference(Rtree *pRtree){
  138436. pRtree->nBusy++;
  138437. }
  138438. /*
  138439. ** Decrement the r-tree reference count. When the reference count reaches
  138440. ** zero the structure is deleted.
  138441. */
  138442. static void rtreeRelease(Rtree *pRtree){
  138443. pRtree->nBusy--;
  138444. if( pRtree->nBusy==0 ){
  138445. sqlite3_finalize(pRtree->pReadNode);
  138446. sqlite3_finalize(pRtree->pWriteNode);
  138447. sqlite3_finalize(pRtree->pDeleteNode);
  138448. sqlite3_finalize(pRtree->pReadRowid);
  138449. sqlite3_finalize(pRtree->pWriteRowid);
  138450. sqlite3_finalize(pRtree->pDeleteRowid);
  138451. sqlite3_finalize(pRtree->pReadParent);
  138452. sqlite3_finalize(pRtree->pWriteParent);
  138453. sqlite3_finalize(pRtree->pDeleteParent);
  138454. sqlite3_free(pRtree);
  138455. }
  138456. }
  138457. /*
  138458. ** Rtree virtual table module xDisconnect method.
  138459. */
  138460. static int rtreeDisconnect(sqlite3_vtab *pVtab){
  138461. rtreeRelease((Rtree *)pVtab);
  138462. return SQLITE_OK;
  138463. }
  138464. /*
  138465. ** Rtree virtual table module xDestroy method.
  138466. */
  138467. static int rtreeDestroy(sqlite3_vtab *pVtab){
  138468. Rtree *pRtree = (Rtree *)pVtab;
  138469. int rc;
  138470. char *zCreate = sqlite3_mprintf(
  138471. "DROP TABLE '%q'.'%q_node';"
  138472. "DROP TABLE '%q'.'%q_rowid';"
  138473. "DROP TABLE '%q'.'%q_parent';",
  138474. pRtree->zDb, pRtree->zName,
  138475. pRtree->zDb, pRtree->zName,
  138476. pRtree->zDb, pRtree->zName
  138477. );
  138478. if( !zCreate ){
  138479. rc = SQLITE_NOMEM;
  138480. }else{
  138481. rc = sqlite3_exec(pRtree->db, zCreate, 0, 0, 0);
  138482. sqlite3_free(zCreate);
  138483. }
  138484. if( rc==SQLITE_OK ){
  138485. rtreeRelease(pRtree);
  138486. }
  138487. return rc;
  138488. }
  138489. /*
  138490. ** Rtree virtual table module xOpen method.
  138491. */
  138492. static int rtreeOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
  138493. int rc = SQLITE_NOMEM;
  138494. RtreeCursor *pCsr;
  138495. pCsr = (RtreeCursor *)sqlite3_malloc(sizeof(RtreeCursor));
  138496. if( pCsr ){
  138497. memset(pCsr, 0, sizeof(RtreeCursor));
  138498. pCsr->base.pVtab = pVTab;
  138499. rc = SQLITE_OK;
  138500. }
  138501. *ppCursor = (sqlite3_vtab_cursor *)pCsr;
  138502. return rc;
  138503. }
  138504. /*
  138505. ** Free the RtreeCursor.aConstraint[] array and its contents.
  138506. */
  138507. static void freeCursorConstraints(RtreeCursor *pCsr){
  138508. if( pCsr->aConstraint ){
  138509. int i; /* Used to iterate through constraint array */
  138510. for(i=0; i<pCsr->nConstraint; i++){
  138511. sqlite3_rtree_query_info *pInfo = pCsr->aConstraint[i].pInfo;
  138512. if( pInfo ){
  138513. if( pInfo->xDelUser ) pInfo->xDelUser(pInfo->pUser);
  138514. sqlite3_free(pInfo);
  138515. }
  138516. }
  138517. sqlite3_free(pCsr->aConstraint);
  138518. pCsr->aConstraint = 0;
  138519. }
  138520. }
  138521. /*
  138522. ** Rtree virtual table module xClose method.
  138523. */
  138524. static int rtreeClose(sqlite3_vtab_cursor *cur){
  138525. Rtree *pRtree = (Rtree *)(cur->pVtab);
  138526. int ii;
  138527. RtreeCursor *pCsr = (RtreeCursor *)cur;
  138528. freeCursorConstraints(pCsr);
  138529. sqlite3_free(pCsr->aPoint);
  138530. for(ii=0; ii<RTREE_CACHE_SZ; ii++) nodeRelease(pRtree, pCsr->aNode[ii]);
  138531. sqlite3_free(pCsr);
  138532. return SQLITE_OK;
  138533. }
  138534. /*
  138535. ** Rtree virtual table module xEof method.
  138536. **
  138537. ** Return non-zero if the cursor does not currently point to a valid
  138538. ** record (i.e if the scan has finished), or zero otherwise.
  138539. */
  138540. static int rtreeEof(sqlite3_vtab_cursor *cur){
  138541. RtreeCursor *pCsr = (RtreeCursor *)cur;
  138542. return pCsr->atEOF;
  138543. }
  138544. /*
  138545. ** Convert raw bits from the on-disk RTree record into a coordinate value.
  138546. ** The on-disk format is big-endian and needs to be converted for little-
  138547. ** endian platforms. The on-disk record stores integer coordinates if
  138548. ** eInt is true and it stores 32-bit floating point records if eInt is
  138549. ** false. a[] is the four bytes of the on-disk record to be decoded.
  138550. ** Store the results in "r".
  138551. **
  138552. ** There are three versions of this macro, one each for little-endian and
  138553. ** big-endian processors and a third generic implementation. The endian-
  138554. ** specific implementations are much faster and are preferred if the
  138555. ** processor endianness is known at compile-time. The SQLITE_BYTEORDER
  138556. ** macro is part of sqliteInt.h and hence the endian-specific
  138557. ** implementation will only be used if this module is compiled as part
  138558. ** of the amalgamation.
  138559. */
  138560. #if defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==1234
  138561. #define RTREE_DECODE_COORD(eInt, a, r) { \
  138562. RtreeCoord c; /* Coordinate decoded */ \
  138563. memcpy(&c.u,a,4); \
  138564. c.u = ((c.u>>24)&0xff)|((c.u>>8)&0xff00)| \
  138565. ((c.u&0xff)<<24)|((c.u&0xff00)<<8); \
  138566. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  138567. }
  138568. #elif defined(SQLITE_BYTEORDER) && SQLITE_BYTEORDER==4321
  138569. #define RTREE_DECODE_COORD(eInt, a, r) { \
  138570. RtreeCoord c; /* Coordinate decoded */ \
  138571. memcpy(&c.u,a,4); \
  138572. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  138573. }
  138574. #else
  138575. #define RTREE_DECODE_COORD(eInt, a, r) { \
  138576. RtreeCoord c; /* Coordinate decoded */ \
  138577. c.u = ((u32)a[0]<<24) + ((u32)a[1]<<16) \
  138578. +((u32)a[2]<<8) + a[3]; \
  138579. r = eInt ? (sqlite3_rtree_dbl)c.i : (sqlite3_rtree_dbl)c.f; \
  138580. }
  138581. #endif
  138582. /*
  138583. ** Check the RTree node or entry given by pCellData and p against the MATCH
  138584. ** constraint pConstraint.
  138585. */
  138586. static int rtreeCallbackConstraint(
  138587. RtreeConstraint *pConstraint, /* The constraint to test */
  138588. int eInt, /* True if RTree holding integer coordinates */
  138589. u8 *pCellData, /* Raw cell content */
  138590. RtreeSearchPoint *pSearch, /* Container of this cell */
  138591. sqlite3_rtree_dbl *prScore, /* OUT: score for the cell */
  138592. int *peWithin /* OUT: visibility of the cell */
  138593. ){
  138594. int i; /* Loop counter */
  138595. sqlite3_rtree_query_info *pInfo = pConstraint->pInfo; /* Callback info */
  138596. int nCoord = pInfo->nCoord; /* No. of coordinates */
  138597. int rc; /* Callback return code */
  138598. sqlite3_rtree_dbl aCoord[RTREE_MAX_DIMENSIONS*2]; /* Decoded coordinates */
  138599. assert( pConstraint->op==RTREE_MATCH || pConstraint->op==RTREE_QUERY );
  138600. assert( nCoord==2 || nCoord==4 || nCoord==6 || nCoord==8 || nCoord==10 );
  138601. if( pConstraint->op==RTREE_QUERY && pSearch->iLevel==1 ){
  138602. pInfo->iRowid = readInt64(pCellData);
  138603. }
  138604. pCellData += 8;
  138605. for(i=0; i<nCoord; i++, pCellData += 4){
  138606. RTREE_DECODE_COORD(eInt, pCellData, aCoord[i]);
  138607. }
  138608. if( pConstraint->op==RTREE_MATCH ){
  138609. rc = pConstraint->u.xGeom((sqlite3_rtree_geometry*)pInfo,
  138610. nCoord, aCoord, &i);
  138611. if( i==0 ) *peWithin = NOT_WITHIN;
  138612. *prScore = RTREE_ZERO;
  138613. }else{
  138614. pInfo->aCoord = aCoord;
  138615. pInfo->iLevel = pSearch->iLevel - 1;
  138616. pInfo->rScore = pInfo->rParentScore = pSearch->rScore;
  138617. pInfo->eWithin = pInfo->eParentWithin = pSearch->eWithin;
  138618. rc = pConstraint->u.xQueryFunc(pInfo);
  138619. if( pInfo->eWithin<*peWithin ) *peWithin = pInfo->eWithin;
  138620. if( pInfo->rScore<*prScore || *prScore<RTREE_ZERO ){
  138621. *prScore = pInfo->rScore;
  138622. }
  138623. }
  138624. return rc;
  138625. }
  138626. /*
  138627. ** Check the internal RTree node given by pCellData against constraint p.
  138628. ** If this constraint cannot be satisfied by any child within the node,
  138629. ** set *peWithin to NOT_WITHIN.
  138630. */
  138631. static void rtreeNonleafConstraint(
  138632. RtreeConstraint *p, /* The constraint to test */
  138633. int eInt, /* True if RTree holds integer coordinates */
  138634. u8 *pCellData, /* Raw cell content as appears on disk */
  138635. int *peWithin /* Adjust downward, as appropriate */
  138636. ){
  138637. sqlite3_rtree_dbl val; /* Coordinate value convert to a double */
  138638. /* p->iCoord might point to either a lower or upper bound coordinate
  138639. ** in a coordinate pair. But make pCellData point to the lower bound.
  138640. */
  138641. pCellData += 8 + 4*(p->iCoord&0xfe);
  138642. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  138643. || p->op==RTREE_GT || p->op==RTREE_EQ );
  138644. switch( p->op ){
  138645. case RTREE_LE:
  138646. case RTREE_LT:
  138647. case RTREE_EQ:
  138648. RTREE_DECODE_COORD(eInt, pCellData, val);
  138649. /* val now holds the lower bound of the coordinate pair */
  138650. if( p->u.rValue>=val ) return;
  138651. if( p->op!=RTREE_EQ ) break; /* RTREE_LE and RTREE_LT end here */
  138652. /* Fall through for the RTREE_EQ case */
  138653. default: /* RTREE_GT or RTREE_GE, or fallthrough of RTREE_EQ */
  138654. pCellData += 4;
  138655. RTREE_DECODE_COORD(eInt, pCellData, val);
  138656. /* val now holds the upper bound of the coordinate pair */
  138657. if( p->u.rValue<=val ) return;
  138658. }
  138659. *peWithin = NOT_WITHIN;
  138660. }
  138661. /*
  138662. ** Check the leaf RTree cell given by pCellData against constraint p.
  138663. ** If this constraint is not satisfied, set *peWithin to NOT_WITHIN.
  138664. ** If the constraint is satisfied, leave *peWithin unchanged.
  138665. **
  138666. ** The constraint is of the form: xN op $val
  138667. **
  138668. ** The op is given by p->op. The xN is p->iCoord-th coordinate in
  138669. ** pCellData. $val is given by p->u.rValue.
  138670. */
  138671. static void rtreeLeafConstraint(
  138672. RtreeConstraint *p, /* The constraint to test */
  138673. int eInt, /* True if RTree holds integer coordinates */
  138674. u8 *pCellData, /* Raw cell content as appears on disk */
  138675. int *peWithin /* Adjust downward, as appropriate */
  138676. ){
  138677. RtreeDValue xN; /* Coordinate value converted to a double */
  138678. assert(p->op==RTREE_LE || p->op==RTREE_LT || p->op==RTREE_GE
  138679. || p->op==RTREE_GT || p->op==RTREE_EQ );
  138680. pCellData += 8 + p->iCoord*4;
  138681. RTREE_DECODE_COORD(eInt, pCellData, xN);
  138682. switch( p->op ){
  138683. case RTREE_LE: if( xN <= p->u.rValue ) return; break;
  138684. case RTREE_LT: if( xN < p->u.rValue ) return; break;
  138685. case RTREE_GE: if( xN >= p->u.rValue ) return; break;
  138686. case RTREE_GT: if( xN > p->u.rValue ) return; break;
  138687. default: if( xN == p->u.rValue ) return; break;
  138688. }
  138689. *peWithin = NOT_WITHIN;
  138690. }
  138691. /*
  138692. ** One of the cells in node pNode is guaranteed to have a 64-bit
  138693. ** integer value equal to iRowid. Return the index of this cell.
  138694. */
  138695. static int nodeRowidIndex(
  138696. Rtree *pRtree,
  138697. RtreeNode *pNode,
  138698. i64 iRowid,
  138699. int *piIndex
  138700. ){
  138701. int ii;
  138702. int nCell = NCELL(pNode);
  138703. assert( nCell<200 );
  138704. for(ii=0; ii<nCell; ii++){
  138705. if( nodeGetRowid(pRtree, pNode, ii)==iRowid ){
  138706. *piIndex = ii;
  138707. return SQLITE_OK;
  138708. }
  138709. }
  138710. return SQLITE_CORRUPT_VTAB;
  138711. }
  138712. /*
  138713. ** Return the index of the cell containing a pointer to node pNode
  138714. ** in its parent. If pNode is the root node, return -1.
  138715. */
  138716. static int nodeParentIndex(Rtree *pRtree, RtreeNode *pNode, int *piIndex){
  138717. RtreeNode *pParent = pNode->pParent;
  138718. if( pParent ){
  138719. return nodeRowidIndex(pRtree, pParent, pNode->iNode, piIndex);
  138720. }
  138721. *piIndex = -1;
  138722. return SQLITE_OK;
  138723. }
  138724. /*
  138725. ** Compare two search points. Return negative, zero, or positive if the first
  138726. ** is less than, equal to, or greater than the second.
  138727. **
  138728. ** The rScore is the primary key. Smaller rScore values come first.
  138729. ** If the rScore is a tie, then use iLevel as the tie breaker with smaller
  138730. ** iLevel values coming first. In this way, if rScore is the same for all
  138731. ** SearchPoints, then iLevel becomes the deciding factor and the result
  138732. ** is a depth-first search, which is the desired default behavior.
  138733. */
  138734. static int rtreeSearchPointCompare(
  138735. const RtreeSearchPoint *pA,
  138736. const RtreeSearchPoint *pB
  138737. ){
  138738. if( pA->rScore<pB->rScore ) return -1;
  138739. if( pA->rScore>pB->rScore ) return +1;
  138740. if( pA->iLevel<pB->iLevel ) return -1;
  138741. if( pA->iLevel>pB->iLevel ) return +1;
  138742. return 0;
  138743. }
  138744. /*
  138745. ** Interchange to search points in a cursor.
  138746. */
  138747. static void rtreeSearchPointSwap(RtreeCursor *p, int i, int j){
  138748. RtreeSearchPoint t = p->aPoint[i];
  138749. assert( i<j );
  138750. p->aPoint[i] = p->aPoint[j];
  138751. p->aPoint[j] = t;
  138752. i++; j++;
  138753. if( i<RTREE_CACHE_SZ ){
  138754. if( j>=RTREE_CACHE_SZ ){
  138755. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  138756. p->aNode[i] = 0;
  138757. }else{
  138758. RtreeNode *pTemp = p->aNode[i];
  138759. p->aNode[i] = p->aNode[j];
  138760. p->aNode[j] = pTemp;
  138761. }
  138762. }
  138763. }
  138764. /*
  138765. ** Return the search point with the lowest current score.
  138766. */
  138767. static RtreeSearchPoint *rtreeSearchPointFirst(RtreeCursor *pCur){
  138768. return pCur->bPoint ? &pCur->sPoint : pCur->nPoint ? pCur->aPoint : 0;
  138769. }
  138770. /*
  138771. ** Get the RtreeNode for the search point with the lowest score.
  138772. */
  138773. static RtreeNode *rtreeNodeOfFirstSearchPoint(RtreeCursor *pCur, int *pRC){
  138774. sqlite3_int64 id;
  138775. int ii = 1 - pCur->bPoint;
  138776. assert( ii==0 || ii==1 );
  138777. assert( pCur->bPoint || pCur->nPoint );
  138778. if( pCur->aNode[ii]==0 ){
  138779. assert( pRC!=0 );
  138780. id = ii ? pCur->aPoint[0].id : pCur->sPoint.id;
  138781. *pRC = nodeAcquire(RTREE_OF_CURSOR(pCur), id, 0, &pCur->aNode[ii]);
  138782. }
  138783. return pCur->aNode[ii];
  138784. }
  138785. /*
  138786. ** Push a new element onto the priority queue
  138787. */
  138788. static RtreeSearchPoint *rtreeEnqueue(
  138789. RtreeCursor *pCur, /* The cursor */
  138790. RtreeDValue rScore, /* Score for the new search point */
  138791. u8 iLevel /* Level for the new search point */
  138792. ){
  138793. int i, j;
  138794. RtreeSearchPoint *pNew;
  138795. if( pCur->nPoint>=pCur->nPointAlloc ){
  138796. int nNew = pCur->nPointAlloc*2 + 8;
  138797. pNew = sqlite3_realloc(pCur->aPoint, nNew*sizeof(pCur->aPoint[0]));
  138798. if( pNew==0 ) return 0;
  138799. pCur->aPoint = pNew;
  138800. pCur->nPointAlloc = nNew;
  138801. }
  138802. i = pCur->nPoint++;
  138803. pNew = pCur->aPoint + i;
  138804. pNew->rScore = rScore;
  138805. pNew->iLevel = iLevel;
  138806. assert( iLevel>=0 && iLevel<=RTREE_MAX_DEPTH );
  138807. while( i>0 ){
  138808. RtreeSearchPoint *pParent;
  138809. j = (i-1)/2;
  138810. pParent = pCur->aPoint + j;
  138811. if( rtreeSearchPointCompare(pNew, pParent)>=0 ) break;
  138812. rtreeSearchPointSwap(pCur, j, i);
  138813. i = j;
  138814. pNew = pParent;
  138815. }
  138816. return pNew;
  138817. }
  138818. /*
  138819. ** Allocate a new RtreeSearchPoint and return a pointer to it. Return
  138820. ** NULL if malloc fails.
  138821. */
  138822. static RtreeSearchPoint *rtreeSearchPointNew(
  138823. RtreeCursor *pCur, /* The cursor */
  138824. RtreeDValue rScore, /* Score for the new search point */
  138825. u8 iLevel /* Level for the new search point */
  138826. ){
  138827. RtreeSearchPoint *pNew, *pFirst;
  138828. pFirst = rtreeSearchPointFirst(pCur);
  138829. pCur->anQueue[iLevel]++;
  138830. if( pFirst==0
  138831. || pFirst->rScore>rScore
  138832. || (pFirst->rScore==rScore && pFirst->iLevel>iLevel)
  138833. ){
  138834. if( pCur->bPoint ){
  138835. int ii;
  138836. pNew = rtreeEnqueue(pCur, rScore, iLevel);
  138837. if( pNew==0 ) return 0;
  138838. ii = (int)(pNew - pCur->aPoint) + 1;
  138839. if( ii<RTREE_CACHE_SZ ){
  138840. assert( pCur->aNode[ii]==0 );
  138841. pCur->aNode[ii] = pCur->aNode[0];
  138842. }else{
  138843. nodeRelease(RTREE_OF_CURSOR(pCur), pCur->aNode[0]);
  138844. }
  138845. pCur->aNode[0] = 0;
  138846. *pNew = pCur->sPoint;
  138847. }
  138848. pCur->sPoint.rScore = rScore;
  138849. pCur->sPoint.iLevel = iLevel;
  138850. pCur->bPoint = 1;
  138851. return &pCur->sPoint;
  138852. }else{
  138853. return rtreeEnqueue(pCur, rScore, iLevel);
  138854. }
  138855. }
  138856. #if 0
  138857. /* Tracing routines for the RtreeSearchPoint queue */
  138858. static void tracePoint(RtreeSearchPoint *p, int idx, RtreeCursor *pCur){
  138859. if( idx<0 ){ printf(" s"); }else{ printf("%2d", idx); }
  138860. printf(" %d.%05lld.%02d %g %d",
  138861. p->iLevel, p->id, p->iCell, p->rScore, p->eWithin
  138862. );
  138863. idx++;
  138864. if( idx<RTREE_CACHE_SZ ){
  138865. printf(" %p\n", pCur->aNode[idx]);
  138866. }else{
  138867. printf("\n");
  138868. }
  138869. }
  138870. static void traceQueue(RtreeCursor *pCur, const char *zPrefix){
  138871. int ii;
  138872. printf("=== %9s ", zPrefix);
  138873. if( pCur->bPoint ){
  138874. tracePoint(&pCur->sPoint, -1, pCur);
  138875. }
  138876. for(ii=0; ii<pCur->nPoint; ii++){
  138877. if( ii>0 || pCur->bPoint ) printf(" ");
  138878. tracePoint(&pCur->aPoint[ii], ii, pCur);
  138879. }
  138880. }
  138881. # define RTREE_QUEUE_TRACE(A,B) traceQueue(A,B)
  138882. #else
  138883. # define RTREE_QUEUE_TRACE(A,B) /* no-op */
  138884. #endif
  138885. /* Remove the search point with the lowest current score.
  138886. */
  138887. static void rtreeSearchPointPop(RtreeCursor *p){
  138888. int i, j, k, n;
  138889. i = 1 - p->bPoint;
  138890. assert( i==0 || i==1 );
  138891. if( p->aNode[i] ){
  138892. nodeRelease(RTREE_OF_CURSOR(p), p->aNode[i]);
  138893. p->aNode[i] = 0;
  138894. }
  138895. if( p->bPoint ){
  138896. p->anQueue[p->sPoint.iLevel]--;
  138897. p->bPoint = 0;
  138898. }else if( p->nPoint ){
  138899. p->anQueue[p->aPoint[0].iLevel]--;
  138900. n = --p->nPoint;
  138901. p->aPoint[0] = p->aPoint[n];
  138902. if( n<RTREE_CACHE_SZ-1 ){
  138903. p->aNode[1] = p->aNode[n+1];
  138904. p->aNode[n+1] = 0;
  138905. }
  138906. i = 0;
  138907. while( (j = i*2+1)<n ){
  138908. k = j+1;
  138909. if( k<n && rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[j])<0 ){
  138910. if( rtreeSearchPointCompare(&p->aPoint[k], &p->aPoint[i])<0 ){
  138911. rtreeSearchPointSwap(p, i, k);
  138912. i = k;
  138913. }else{
  138914. break;
  138915. }
  138916. }else{
  138917. if( rtreeSearchPointCompare(&p->aPoint[j], &p->aPoint[i])<0 ){
  138918. rtreeSearchPointSwap(p, i, j);
  138919. i = j;
  138920. }else{
  138921. break;
  138922. }
  138923. }
  138924. }
  138925. }
  138926. }
  138927. /*
  138928. ** Continue the search on cursor pCur until the front of the queue
  138929. ** contains an entry suitable for returning as a result-set row,
  138930. ** or until the RtreeSearchPoint queue is empty, indicating that the
  138931. ** query has completed.
  138932. */
  138933. static int rtreeStepToLeaf(RtreeCursor *pCur){
  138934. RtreeSearchPoint *p;
  138935. Rtree *pRtree = RTREE_OF_CURSOR(pCur);
  138936. RtreeNode *pNode;
  138937. int eWithin;
  138938. int rc = SQLITE_OK;
  138939. int nCell;
  138940. int nConstraint = pCur->nConstraint;
  138941. int ii;
  138942. int eInt;
  138943. RtreeSearchPoint x;
  138944. eInt = pRtree->eCoordType==RTREE_COORD_INT32;
  138945. while( (p = rtreeSearchPointFirst(pCur))!=0 && p->iLevel>0 ){
  138946. pNode = rtreeNodeOfFirstSearchPoint(pCur, &rc);
  138947. if( rc ) return rc;
  138948. nCell = NCELL(pNode);
  138949. assert( nCell<200 );
  138950. while( p->iCell<nCell ){
  138951. sqlite3_rtree_dbl rScore = (sqlite3_rtree_dbl)-1;
  138952. u8 *pCellData = pNode->zData + (4+pRtree->nBytesPerCell*p->iCell);
  138953. eWithin = FULLY_WITHIN;
  138954. for(ii=0; ii<nConstraint; ii++){
  138955. RtreeConstraint *pConstraint = pCur->aConstraint + ii;
  138956. if( pConstraint->op>=RTREE_MATCH ){
  138957. rc = rtreeCallbackConstraint(pConstraint, eInt, pCellData, p,
  138958. &rScore, &eWithin);
  138959. if( rc ) return rc;
  138960. }else if( p->iLevel==1 ){
  138961. rtreeLeafConstraint(pConstraint, eInt, pCellData, &eWithin);
  138962. }else{
  138963. rtreeNonleafConstraint(pConstraint, eInt, pCellData, &eWithin);
  138964. }
  138965. if( eWithin==NOT_WITHIN ) break;
  138966. }
  138967. p->iCell++;
  138968. if( eWithin==NOT_WITHIN ) continue;
  138969. x.iLevel = p->iLevel - 1;
  138970. if( x.iLevel ){
  138971. x.id = readInt64(pCellData);
  138972. x.iCell = 0;
  138973. }else{
  138974. x.id = p->id;
  138975. x.iCell = p->iCell - 1;
  138976. }
  138977. if( p->iCell>=nCell ){
  138978. RTREE_QUEUE_TRACE(pCur, "POP-S:");
  138979. rtreeSearchPointPop(pCur);
  138980. }
  138981. if( rScore<RTREE_ZERO ) rScore = RTREE_ZERO;
  138982. p = rtreeSearchPointNew(pCur, rScore, x.iLevel);
  138983. if( p==0 ) return SQLITE_NOMEM;
  138984. p->eWithin = eWithin;
  138985. p->id = x.id;
  138986. p->iCell = x.iCell;
  138987. RTREE_QUEUE_TRACE(pCur, "PUSH-S:");
  138988. break;
  138989. }
  138990. if( p->iCell>=nCell ){
  138991. RTREE_QUEUE_TRACE(pCur, "POP-Se:");
  138992. rtreeSearchPointPop(pCur);
  138993. }
  138994. }
  138995. pCur->atEOF = p==0;
  138996. return SQLITE_OK;
  138997. }
  138998. /*
  138999. ** Rtree virtual table module xNext method.
  139000. */
  139001. static int rtreeNext(sqlite3_vtab_cursor *pVtabCursor){
  139002. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  139003. int rc = SQLITE_OK;
  139004. /* Move to the next entry that matches the configured constraints. */
  139005. RTREE_QUEUE_TRACE(pCsr, "POP-Nx:");
  139006. rtreeSearchPointPop(pCsr);
  139007. rc = rtreeStepToLeaf(pCsr);
  139008. return rc;
  139009. }
  139010. /*
  139011. ** Rtree virtual table module xRowid method.
  139012. */
  139013. static int rtreeRowid(sqlite3_vtab_cursor *pVtabCursor, sqlite_int64 *pRowid){
  139014. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  139015. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  139016. int rc = SQLITE_OK;
  139017. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  139018. if( rc==SQLITE_OK && p ){
  139019. *pRowid = nodeGetRowid(RTREE_OF_CURSOR(pCsr), pNode, p->iCell);
  139020. }
  139021. return rc;
  139022. }
  139023. /*
  139024. ** Rtree virtual table module xColumn method.
  139025. */
  139026. static int rtreeColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
  139027. Rtree *pRtree = (Rtree *)cur->pVtab;
  139028. RtreeCursor *pCsr = (RtreeCursor *)cur;
  139029. RtreeSearchPoint *p = rtreeSearchPointFirst(pCsr);
  139030. RtreeCoord c;
  139031. int rc = SQLITE_OK;
  139032. RtreeNode *pNode = rtreeNodeOfFirstSearchPoint(pCsr, &rc);
  139033. if( rc ) return rc;
  139034. if( p==0 ) return SQLITE_OK;
  139035. if( i==0 ){
  139036. sqlite3_result_int64(ctx, nodeGetRowid(pRtree, pNode, p->iCell));
  139037. }else{
  139038. if( rc ) return rc;
  139039. nodeGetCoord(pRtree, pNode, p->iCell, i-1, &c);
  139040. #ifndef SQLITE_RTREE_INT_ONLY
  139041. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  139042. sqlite3_result_double(ctx, c.f);
  139043. }else
  139044. #endif
  139045. {
  139046. assert( pRtree->eCoordType==RTREE_COORD_INT32 );
  139047. sqlite3_result_int(ctx, c.i);
  139048. }
  139049. }
  139050. return SQLITE_OK;
  139051. }
  139052. /*
  139053. ** Use nodeAcquire() to obtain the leaf node containing the record with
  139054. ** rowid iRowid. If successful, set *ppLeaf to point to the node and
  139055. ** return SQLITE_OK. If there is no such record in the table, set
  139056. ** *ppLeaf to 0 and return SQLITE_OK. If an error occurs, set *ppLeaf
  139057. ** to zero and return an SQLite error code.
  139058. */
  139059. static int findLeafNode(
  139060. Rtree *pRtree, /* RTree to search */
  139061. i64 iRowid, /* The rowid searching for */
  139062. RtreeNode **ppLeaf, /* Write the node here */
  139063. sqlite3_int64 *piNode /* Write the node-id here */
  139064. ){
  139065. int rc;
  139066. *ppLeaf = 0;
  139067. sqlite3_bind_int64(pRtree->pReadRowid, 1, iRowid);
  139068. if( sqlite3_step(pRtree->pReadRowid)==SQLITE_ROW ){
  139069. i64 iNode = sqlite3_column_int64(pRtree->pReadRowid, 0);
  139070. if( piNode ) *piNode = iNode;
  139071. rc = nodeAcquire(pRtree, iNode, 0, ppLeaf);
  139072. sqlite3_reset(pRtree->pReadRowid);
  139073. }else{
  139074. rc = sqlite3_reset(pRtree->pReadRowid);
  139075. }
  139076. return rc;
  139077. }
  139078. /*
  139079. ** This function is called to configure the RtreeConstraint object passed
  139080. ** as the second argument for a MATCH constraint. The value passed as the
  139081. ** first argument to this function is the right-hand operand to the MATCH
  139082. ** operator.
  139083. */
  139084. static int deserializeGeometry(sqlite3_value *pValue, RtreeConstraint *pCons){
  139085. RtreeMatchArg *pBlob; /* BLOB returned by geometry function */
  139086. sqlite3_rtree_query_info *pInfo; /* Callback information */
  139087. int nBlob; /* Size of the geometry function blob */
  139088. int nExpected; /* Expected size of the BLOB */
  139089. /* Check that value is actually a blob. */
  139090. if( sqlite3_value_type(pValue)!=SQLITE_BLOB ) return SQLITE_ERROR;
  139091. /* Check that the blob is roughly the right size. */
  139092. nBlob = sqlite3_value_bytes(pValue);
  139093. if( nBlob<(int)sizeof(RtreeMatchArg)
  139094. || ((nBlob-sizeof(RtreeMatchArg))%sizeof(RtreeDValue))!=0
  139095. ){
  139096. return SQLITE_ERROR;
  139097. }
  139098. pInfo = (sqlite3_rtree_query_info*)sqlite3_malloc( sizeof(*pInfo)+nBlob );
  139099. if( !pInfo ) return SQLITE_NOMEM;
  139100. memset(pInfo, 0, sizeof(*pInfo));
  139101. pBlob = (RtreeMatchArg*)&pInfo[1];
  139102. memcpy(pBlob, sqlite3_value_blob(pValue), nBlob);
  139103. nExpected = (int)(sizeof(RtreeMatchArg) +
  139104. (pBlob->nParam-1)*sizeof(RtreeDValue));
  139105. if( pBlob->magic!=RTREE_GEOMETRY_MAGIC || nBlob!=nExpected ){
  139106. sqlite3_free(pInfo);
  139107. return SQLITE_ERROR;
  139108. }
  139109. pInfo->pContext = pBlob->cb.pContext;
  139110. pInfo->nParam = pBlob->nParam;
  139111. pInfo->aParam = pBlob->aParam;
  139112. if( pBlob->cb.xGeom ){
  139113. pCons->u.xGeom = pBlob->cb.xGeom;
  139114. }else{
  139115. pCons->op = RTREE_QUERY;
  139116. pCons->u.xQueryFunc = pBlob->cb.xQueryFunc;
  139117. }
  139118. pCons->pInfo = pInfo;
  139119. return SQLITE_OK;
  139120. }
  139121. /*
  139122. ** Rtree virtual table module xFilter method.
  139123. */
  139124. static int rtreeFilter(
  139125. sqlite3_vtab_cursor *pVtabCursor,
  139126. int idxNum, const char *idxStr,
  139127. int argc, sqlite3_value **argv
  139128. ){
  139129. Rtree *pRtree = (Rtree *)pVtabCursor->pVtab;
  139130. RtreeCursor *pCsr = (RtreeCursor *)pVtabCursor;
  139131. RtreeNode *pRoot = 0;
  139132. int ii;
  139133. int rc = SQLITE_OK;
  139134. int iCell = 0;
  139135. rtreeReference(pRtree);
  139136. /* Reset the cursor to the same state as rtreeOpen() leaves it in. */
  139137. freeCursorConstraints(pCsr);
  139138. sqlite3_free(pCsr->aPoint);
  139139. memset(pCsr, 0, sizeof(RtreeCursor));
  139140. pCsr->base.pVtab = (sqlite3_vtab*)pRtree;
  139141. pCsr->iStrategy = idxNum;
  139142. if( idxNum==1 ){
  139143. /* Special case - lookup by rowid. */
  139144. RtreeNode *pLeaf; /* Leaf on which the required cell resides */
  139145. RtreeSearchPoint *p; /* Search point for the the leaf */
  139146. i64 iRowid = sqlite3_value_int64(argv[0]);
  139147. i64 iNode = 0;
  139148. rc = findLeafNode(pRtree, iRowid, &pLeaf, &iNode);
  139149. if( rc==SQLITE_OK && pLeaf!=0 ){
  139150. p = rtreeSearchPointNew(pCsr, RTREE_ZERO, 0);
  139151. assert( p!=0 ); /* Always returns pCsr->sPoint */
  139152. pCsr->aNode[0] = pLeaf;
  139153. p->id = iNode;
  139154. p->eWithin = PARTLY_WITHIN;
  139155. rc = nodeRowidIndex(pRtree, pLeaf, iRowid, &iCell);
  139156. p->iCell = iCell;
  139157. RTREE_QUEUE_TRACE(pCsr, "PUSH-F1:");
  139158. }else{
  139159. pCsr->atEOF = 1;
  139160. }
  139161. }else{
  139162. /* Normal case - r-tree scan. Set up the RtreeCursor.aConstraint array
  139163. ** with the configured constraints.
  139164. */
  139165. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  139166. if( rc==SQLITE_OK && argc>0 ){
  139167. pCsr->aConstraint = sqlite3_malloc(sizeof(RtreeConstraint)*argc);
  139168. pCsr->nConstraint = argc;
  139169. if( !pCsr->aConstraint ){
  139170. rc = SQLITE_NOMEM;
  139171. }else{
  139172. memset(pCsr->aConstraint, 0, sizeof(RtreeConstraint)*argc);
  139173. memset(pCsr->anQueue, 0, sizeof(u32)*(pRtree->iDepth + 1));
  139174. assert( (idxStr==0 && argc==0)
  139175. || (idxStr && (int)strlen(idxStr)==argc*2) );
  139176. for(ii=0; ii<argc; ii++){
  139177. RtreeConstraint *p = &pCsr->aConstraint[ii];
  139178. p->op = idxStr[ii*2];
  139179. p->iCoord = idxStr[ii*2+1]-'0';
  139180. if( p->op>=RTREE_MATCH ){
  139181. /* A MATCH operator. The right-hand-side must be a blob that
  139182. ** can be cast into an RtreeMatchArg object. One created using
  139183. ** an sqlite3_rtree_geometry_callback() SQL user function.
  139184. */
  139185. rc = deserializeGeometry(argv[ii], p);
  139186. if( rc!=SQLITE_OK ){
  139187. break;
  139188. }
  139189. p->pInfo->nCoord = pRtree->nDim*2;
  139190. p->pInfo->anQueue = pCsr->anQueue;
  139191. p->pInfo->mxLevel = pRtree->iDepth + 1;
  139192. }else{
  139193. #ifdef SQLITE_RTREE_INT_ONLY
  139194. p->u.rValue = sqlite3_value_int64(argv[ii]);
  139195. #else
  139196. p->u.rValue = sqlite3_value_double(argv[ii]);
  139197. #endif
  139198. }
  139199. }
  139200. }
  139201. }
  139202. if( rc==SQLITE_OK ){
  139203. RtreeSearchPoint *pNew;
  139204. pNew = rtreeSearchPointNew(pCsr, RTREE_ZERO, pRtree->iDepth+1);
  139205. if( pNew==0 ) return SQLITE_NOMEM;
  139206. pNew->id = 1;
  139207. pNew->iCell = 0;
  139208. pNew->eWithin = PARTLY_WITHIN;
  139209. assert( pCsr->bPoint==1 );
  139210. pCsr->aNode[0] = pRoot;
  139211. pRoot = 0;
  139212. RTREE_QUEUE_TRACE(pCsr, "PUSH-Fm:");
  139213. rc = rtreeStepToLeaf(pCsr);
  139214. }
  139215. }
  139216. nodeRelease(pRtree, pRoot);
  139217. rtreeRelease(pRtree);
  139218. return rc;
  139219. }
  139220. /*
  139221. ** Set the pIdxInfo->estimatedRows variable to nRow. Unless this
  139222. ** extension is currently being used by a version of SQLite too old to
  139223. ** support estimatedRows. In that case this function is a no-op.
  139224. */
  139225. static void setEstimatedRows(sqlite3_index_info *pIdxInfo, i64 nRow){
  139226. #if SQLITE_VERSION_NUMBER>=3008002
  139227. if( sqlite3_libversion_number()>=3008002 ){
  139228. pIdxInfo->estimatedRows = nRow;
  139229. }
  139230. #endif
  139231. }
  139232. /*
  139233. ** Rtree virtual table module xBestIndex method. There are three
  139234. ** table scan strategies to choose from (in order from most to
  139235. ** least desirable):
  139236. **
  139237. ** idxNum idxStr Strategy
  139238. ** ------------------------------------------------
  139239. ** 1 Unused Direct lookup by rowid.
  139240. ** 2 See below R-tree query or full-table scan.
  139241. ** ------------------------------------------------
  139242. **
  139243. ** If strategy 1 is used, then idxStr is not meaningful. If strategy
  139244. ** 2 is used, idxStr is formatted to contain 2 bytes for each
  139245. ** constraint used. The first two bytes of idxStr correspond to
  139246. ** the constraint in sqlite3_index_info.aConstraintUsage[] with
  139247. ** (argvIndex==1) etc.
  139248. **
  139249. ** The first of each pair of bytes in idxStr identifies the constraint
  139250. ** operator as follows:
  139251. **
  139252. ** Operator Byte Value
  139253. ** ----------------------
  139254. ** = 0x41 ('A')
  139255. ** <= 0x42 ('B')
  139256. ** < 0x43 ('C')
  139257. ** >= 0x44 ('D')
  139258. ** > 0x45 ('E')
  139259. ** MATCH 0x46 ('F')
  139260. ** ----------------------
  139261. **
  139262. ** The second of each pair of bytes identifies the coordinate column
  139263. ** to which the constraint applies. The leftmost coordinate column
  139264. ** is 'a', the second from the left 'b' etc.
  139265. */
  139266. static int rtreeBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo){
  139267. Rtree *pRtree = (Rtree*)tab;
  139268. int rc = SQLITE_OK;
  139269. int ii;
  139270. i64 nRow; /* Estimated rows returned by this scan */
  139271. int iIdx = 0;
  139272. char zIdxStr[RTREE_MAX_DIMENSIONS*8+1];
  139273. memset(zIdxStr, 0, sizeof(zIdxStr));
  139274. assert( pIdxInfo->idxStr==0 );
  139275. for(ii=0; ii<pIdxInfo->nConstraint && iIdx<(int)(sizeof(zIdxStr)-1); ii++){
  139276. struct sqlite3_index_constraint *p = &pIdxInfo->aConstraint[ii];
  139277. if( p->usable && p->iColumn==0 && p->op==SQLITE_INDEX_CONSTRAINT_EQ ){
  139278. /* We have an equality constraint on the rowid. Use strategy 1. */
  139279. int jj;
  139280. for(jj=0; jj<ii; jj++){
  139281. pIdxInfo->aConstraintUsage[jj].argvIndex = 0;
  139282. pIdxInfo->aConstraintUsage[jj].omit = 0;
  139283. }
  139284. pIdxInfo->idxNum = 1;
  139285. pIdxInfo->aConstraintUsage[ii].argvIndex = 1;
  139286. pIdxInfo->aConstraintUsage[jj].omit = 1;
  139287. /* This strategy involves a two rowid lookups on an B-Tree structures
  139288. ** and then a linear search of an R-Tree node. This should be
  139289. ** considered almost as quick as a direct rowid lookup (for which
  139290. ** sqlite uses an internal cost of 0.0). It is expected to return
  139291. ** a single row.
  139292. */
  139293. pIdxInfo->estimatedCost = 30.0;
  139294. setEstimatedRows(pIdxInfo, 1);
  139295. return SQLITE_OK;
  139296. }
  139297. if( p->usable && (p->iColumn>0 || p->op==SQLITE_INDEX_CONSTRAINT_MATCH) ){
  139298. u8 op;
  139299. switch( p->op ){
  139300. case SQLITE_INDEX_CONSTRAINT_EQ: op = RTREE_EQ; break;
  139301. case SQLITE_INDEX_CONSTRAINT_GT: op = RTREE_GT; break;
  139302. case SQLITE_INDEX_CONSTRAINT_LE: op = RTREE_LE; break;
  139303. case SQLITE_INDEX_CONSTRAINT_LT: op = RTREE_LT; break;
  139304. case SQLITE_INDEX_CONSTRAINT_GE: op = RTREE_GE; break;
  139305. default:
  139306. assert( p->op==SQLITE_INDEX_CONSTRAINT_MATCH );
  139307. op = RTREE_MATCH;
  139308. break;
  139309. }
  139310. zIdxStr[iIdx++] = op;
  139311. zIdxStr[iIdx++] = p->iColumn - 1 + '0';
  139312. pIdxInfo->aConstraintUsage[ii].argvIndex = (iIdx/2);
  139313. pIdxInfo->aConstraintUsage[ii].omit = 1;
  139314. }
  139315. }
  139316. pIdxInfo->idxNum = 2;
  139317. pIdxInfo->needToFreeIdxStr = 1;
  139318. if( iIdx>0 && 0==(pIdxInfo->idxStr = sqlite3_mprintf("%s", zIdxStr)) ){
  139319. return SQLITE_NOMEM;
  139320. }
  139321. nRow = pRtree->nRowEst / (iIdx + 1);
  139322. pIdxInfo->estimatedCost = (double)6.0 * (double)nRow;
  139323. setEstimatedRows(pIdxInfo, nRow);
  139324. return rc;
  139325. }
  139326. /*
  139327. ** Return the N-dimensional volumn of the cell stored in *p.
  139328. */
  139329. static RtreeDValue cellArea(Rtree *pRtree, RtreeCell *p){
  139330. RtreeDValue area = (RtreeDValue)1;
  139331. int ii;
  139332. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139333. area = (area * (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii])));
  139334. }
  139335. return area;
  139336. }
  139337. /*
  139338. ** Return the margin length of cell p. The margin length is the sum
  139339. ** of the objects size in each dimension.
  139340. */
  139341. static RtreeDValue cellMargin(Rtree *pRtree, RtreeCell *p){
  139342. RtreeDValue margin = (RtreeDValue)0;
  139343. int ii;
  139344. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139345. margin += (DCOORD(p->aCoord[ii+1]) - DCOORD(p->aCoord[ii]));
  139346. }
  139347. return margin;
  139348. }
  139349. /*
  139350. ** Store the union of cells p1 and p2 in p1.
  139351. */
  139352. static void cellUnion(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  139353. int ii;
  139354. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  139355. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139356. p1->aCoord[ii].f = MIN(p1->aCoord[ii].f, p2->aCoord[ii].f);
  139357. p1->aCoord[ii+1].f = MAX(p1->aCoord[ii+1].f, p2->aCoord[ii+1].f);
  139358. }
  139359. }else{
  139360. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139361. p1->aCoord[ii].i = MIN(p1->aCoord[ii].i, p2->aCoord[ii].i);
  139362. p1->aCoord[ii+1].i = MAX(p1->aCoord[ii+1].i, p2->aCoord[ii+1].i);
  139363. }
  139364. }
  139365. }
  139366. /*
  139367. ** Return true if the area covered by p2 is a subset of the area covered
  139368. ** by p1. False otherwise.
  139369. */
  139370. static int cellContains(Rtree *pRtree, RtreeCell *p1, RtreeCell *p2){
  139371. int ii;
  139372. int isInt = (pRtree->eCoordType==RTREE_COORD_INT32);
  139373. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  139374. RtreeCoord *a1 = &p1->aCoord[ii];
  139375. RtreeCoord *a2 = &p2->aCoord[ii];
  139376. if( (!isInt && (a2[0].f<a1[0].f || a2[1].f>a1[1].f))
  139377. || ( isInt && (a2[0].i<a1[0].i || a2[1].i>a1[1].i))
  139378. ){
  139379. return 0;
  139380. }
  139381. }
  139382. return 1;
  139383. }
  139384. /*
  139385. ** Return the amount cell p would grow by if it were unioned with pCell.
  139386. */
  139387. static RtreeDValue cellGrowth(Rtree *pRtree, RtreeCell *p, RtreeCell *pCell){
  139388. RtreeDValue area;
  139389. RtreeCell cell;
  139390. memcpy(&cell, p, sizeof(RtreeCell));
  139391. area = cellArea(pRtree, &cell);
  139392. cellUnion(pRtree, &cell, pCell);
  139393. return (cellArea(pRtree, &cell)-area);
  139394. }
  139395. static RtreeDValue cellOverlap(
  139396. Rtree *pRtree,
  139397. RtreeCell *p,
  139398. RtreeCell *aCell,
  139399. int nCell
  139400. ){
  139401. int ii;
  139402. RtreeDValue overlap = RTREE_ZERO;
  139403. for(ii=0; ii<nCell; ii++){
  139404. int jj;
  139405. RtreeDValue o = (RtreeDValue)1;
  139406. for(jj=0; jj<(pRtree->nDim*2); jj+=2){
  139407. RtreeDValue x1, x2;
  139408. x1 = MAX(DCOORD(p->aCoord[jj]), DCOORD(aCell[ii].aCoord[jj]));
  139409. x2 = MIN(DCOORD(p->aCoord[jj+1]), DCOORD(aCell[ii].aCoord[jj+1]));
  139410. if( x2<x1 ){
  139411. o = (RtreeDValue)0;
  139412. break;
  139413. }else{
  139414. o = o * (x2-x1);
  139415. }
  139416. }
  139417. overlap += o;
  139418. }
  139419. return overlap;
  139420. }
  139421. /*
  139422. ** This function implements the ChooseLeaf algorithm from Gutman[84].
  139423. ** ChooseSubTree in r*tree terminology.
  139424. */
  139425. static int ChooseLeaf(
  139426. Rtree *pRtree, /* Rtree table */
  139427. RtreeCell *pCell, /* Cell to insert into rtree */
  139428. int iHeight, /* Height of sub-tree rooted at pCell */
  139429. RtreeNode **ppLeaf /* OUT: Selected leaf page */
  139430. ){
  139431. int rc;
  139432. int ii;
  139433. RtreeNode *pNode;
  139434. rc = nodeAcquire(pRtree, 1, 0, &pNode);
  139435. for(ii=0; rc==SQLITE_OK && ii<(pRtree->iDepth-iHeight); ii++){
  139436. int iCell;
  139437. sqlite3_int64 iBest = 0;
  139438. RtreeDValue fMinGrowth = RTREE_ZERO;
  139439. RtreeDValue fMinArea = RTREE_ZERO;
  139440. int nCell = NCELL(pNode);
  139441. RtreeCell cell;
  139442. RtreeNode *pChild;
  139443. RtreeCell *aCell = 0;
  139444. /* Select the child node which will be enlarged the least if pCell
  139445. ** is inserted into it. Resolve ties by choosing the entry with
  139446. ** the smallest area.
  139447. */
  139448. for(iCell=0; iCell<nCell; iCell++){
  139449. int bBest = 0;
  139450. RtreeDValue growth;
  139451. RtreeDValue area;
  139452. nodeGetCell(pRtree, pNode, iCell, &cell);
  139453. growth = cellGrowth(pRtree, &cell, pCell);
  139454. area = cellArea(pRtree, &cell);
  139455. if( iCell==0||growth<fMinGrowth||(growth==fMinGrowth && area<fMinArea) ){
  139456. bBest = 1;
  139457. }
  139458. if( bBest ){
  139459. fMinGrowth = growth;
  139460. fMinArea = area;
  139461. iBest = cell.iRowid;
  139462. }
  139463. }
  139464. sqlite3_free(aCell);
  139465. rc = nodeAcquire(pRtree, iBest, pNode, &pChild);
  139466. nodeRelease(pRtree, pNode);
  139467. pNode = pChild;
  139468. }
  139469. *ppLeaf = pNode;
  139470. return rc;
  139471. }
  139472. /*
  139473. ** A cell with the same content as pCell has just been inserted into
  139474. ** the node pNode. This function updates the bounding box cells in
  139475. ** all ancestor elements.
  139476. */
  139477. static int AdjustTree(
  139478. Rtree *pRtree, /* Rtree table */
  139479. RtreeNode *pNode, /* Adjust ancestry of this node. */
  139480. RtreeCell *pCell /* This cell was just inserted */
  139481. ){
  139482. RtreeNode *p = pNode;
  139483. while( p->pParent ){
  139484. RtreeNode *pParent = p->pParent;
  139485. RtreeCell cell;
  139486. int iCell;
  139487. if( nodeParentIndex(pRtree, p, &iCell) ){
  139488. return SQLITE_CORRUPT_VTAB;
  139489. }
  139490. nodeGetCell(pRtree, pParent, iCell, &cell);
  139491. if( !cellContains(pRtree, &cell, pCell) ){
  139492. cellUnion(pRtree, &cell, pCell);
  139493. nodeOverwriteCell(pRtree, pParent, &cell, iCell);
  139494. }
  139495. p = pParent;
  139496. }
  139497. return SQLITE_OK;
  139498. }
  139499. /*
  139500. ** Write mapping (iRowid->iNode) to the <rtree>_rowid table.
  139501. */
  139502. static int rowidWrite(Rtree *pRtree, sqlite3_int64 iRowid, sqlite3_int64 iNode){
  139503. sqlite3_bind_int64(pRtree->pWriteRowid, 1, iRowid);
  139504. sqlite3_bind_int64(pRtree->pWriteRowid, 2, iNode);
  139505. sqlite3_step(pRtree->pWriteRowid);
  139506. return sqlite3_reset(pRtree->pWriteRowid);
  139507. }
  139508. /*
  139509. ** Write mapping (iNode->iPar) to the <rtree>_parent table.
  139510. */
  139511. static int parentWrite(Rtree *pRtree, sqlite3_int64 iNode, sqlite3_int64 iPar){
  139512. sqlite3_bind_int64(pRtree->pWriteParent, 1, iNode);
  139513. sqlite3_bind_int64(pRtree->pWriteParent, 2, iPar);
  139514. sqlite3_step(pRtree->pWriteParent);
  139515. return sqlite3_reset(pRtree->pWriteParent);
  139516. }
  139517. static int rtreeInsertCell(Rtree *, RtreeNode *, RtreeCell *, int);
  139518. /*
  139519. ** Arguments aIdx, aDistance and aSpare all point to arrays of size
  139520. ** nIdx. The aIdx array contains the set of integers from 0 to
  139521. ** (nIdx-1) in no particular order. This function sorts the values
  139522. ** in aIdx according to the indexed values in aDistance. For
  139523. ** example, assuming the inputs:
  139524. **
  139525. ** aIdx = { 0, 1, 2, 3 }
  139526. ** aDistance = { 5.0, 2.0, 7.0, 6.0 }
  139527. **
  139528. ** this function sets the aIdx array to contain:
  139529. **
  139530. ** aIdx = { 0, 1, 2, 3 }
  139531. **
  139532. ** The aSpare array is used as temporary working space by the
  139533. ** sorting algorithm.
  139534. */
  139535. static void SortByDistance(
  139536. int *aIdx,
  139537. int nIdx,
  139538. RtreeDValue *aDistance,
  139539. int *aSpare
  139540. ){
  139541. if( nIdx>1 ){
  139542. int iLeft = 0;
  139543. int iRight = 0;
  139544. int nLeft = nIdx/2;
  139545. int nRight = nIdx-nLeft;
  139546. int *aLeft = aIdx;
  139547. int *aRight = &aIdx[nLeft];
  139548. SortByDistance(aLeft, nLeft, aDistance, aSpare);
  139549. SortByDistance(aRight, nRight, aDistance, aSpare);
  139550. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  139551. aLeft = aSpare;
  139552. while( iLeft<nLeft || iRight<nRight ){
  139553. if( iLeft==nLeft ){
  139554. aIdx[iLeft+iRight] = aRight[iRight];
  139555. iRight++;
  139556. }else if( iRight==nRight ){
  139557. aIdx[iLeft+iRight] = aLeft[iLeft];
  139558. iLeft++;
  139559. }else{
  139560. RtreeDValue fLeft = aDistance[aLeft[iLeft]];
  139561. RtreeDValue fRight = aDistance[aRight[iRight]];
  139562. if( fLeft<fRight ){
  139563. aIdx[iLeft+iRight] = aLeft[iLeft];
  139564. iLeft++;
  139565. }else{
  139566. aIdx[iLeft+iRight] = aRight[iRight];
  139567. iRight++;
  139568. }
  139569. }
  139570. }
  139571. #if 0
  139572. /* Check that the sort worked */
  139573. {
  139574. int jj;
  139575. for(jj=1; jj<nIdx; jj++){
  139576. RtreeDValue left = aDistance[aIdx[jj-1]];
  139577. RtreeDValue right = aDistance[aIdx[jj]];
  139578. assert( left<=right );
  139579. }
  139580. }
  139581. #endif
  139582. }
  139583. }
  139584. /*
  139585. ** Arguments aIdx, aCell and aSpare all point to arrays of size
  139586. ** nIdx. The aIdx array contains the set of integers from 0 to
  139587. ** (nIdx-1) in no particular order. This function sorts the values
  139588. ** in aIdx according to dimension iDim of the cells in aCell. The
  139589. ** minimum value of dimension iDim is considered first, the
  139590. ** maximum used to break ties.
  139591. **
  139592. ** The aSpare array is used as temporary working space by the
  139593. ** sorting algorithm.
  139594. */
  139595. static void SortByDimension(
  139596. Rtree *pRtree,
  139597. int *aIdx,
  139598. int nIdx,
  139599. int iDim,
  139600. RtreeCell *aCell,
  139601. int *aSpare
  139602. ){
  139603. if( nIdx>1 ){
  139604. int iLeft = 0;
  139605. int iRight = 0;
  139606. int nLeft = nIdx/2;
  139607. int nRight = nIdx-nLeft;
  139608. int *aLeft = aIdx;
  139609. int *aRight = &aIdx[nLeft];
  139610. SortByDimension(pRtree, aLeft, nLeft, iDim, aCell, aSpare);
  139611. SortByDimension(pRtree, aRight, nRight, iDim, aCell, aSpare);
  139612. memcpy(aSpare, aLeft, sizeof(int)*nLeft);
  139613. aLeft = aSpare;
  139614. while( iLeft<nLeft || iRight<nRight ){
  139615. RtreeDValue xleft1 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2]);
  139616. RtreeDValue xleft2 = DCOORD(aCell[aLeft[iLeft]].aCoord[iDim*2+1]);
  139617. RtreeDValue xright1 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2]);
  139618. RtreeDValue xright2 = DCOORD(aCell[aRight[iRight]].aCoord[iDim*2+1]);
  139619. if( (iLeft!=nLeft) && ((iRight==nRight)
  139620. || (xleft1<xright1)
  139621. || (xleft1==xright1 && xleft2<xright2)
  139622. )){
  139623. aIdx[iLeft+iRight] = aLeft[iLeft];
  139624. iLeft++;
  139625. }else{
  139626. aIdx[iLeft+iRight] = aRight[iRight];
  139627. iRight++;
  139628. }
  139629. }
  139630. #if 0
  139631. /* Check that the sort worked */
  139632. {
  139633. int jj;
  139634. for(jj=1; jj<nIdx; jj++){
  139635. RtreeDValue xleft1 = aCell[aIdx[jj-1]].aCoord[iDim*2];
  139636. RtreeDValue xleft2 = aCell[aIdx[jj-1]].aCoord[iDim*2+1];
  139637. RtreeDValue xright1 = aCell[aIdx[jj]].aCoord[iDim*2];
  139638. RtreeDValue xright2 = aCell[aIdx[jj]].aCoord[iDim*2+1];
  139639. assert( xleft1<=xright1 && (xleft1<xright1 || xleft2<=xright2) );
  139640. }
  139641. }
  139642. #endif
  139643. }
  139644. }
  139645. /*
  139646. ** Implementation of the R*-tree variant of SplitNode from Beckman[1990].
  139647. */
  139648. static int splitNodeStartree(
  139649. Rtree *pRtree,
  139650. RtreeCell *aCell,
  139651. int nCell,
  139652. RtreeNode *pLeft,
  139653. RtreeNode *pRight,
  139654. RtreeCell *pBboxLeft,
  139655. RtreeCell *pBboxRight
  139656. ){
  139657. int **aaSorted;
  139658. int *aSpare;
  139659. int ii;
  139660. int iBestDim = 0;
  139661. int iBestSplit = 0;
  139662. RtreeDValue fBestMargin = RTREE_ZERO;
  139663. int nByte = (pRtree->nDim+1)*(sizeof(int*)+nCell*sizeof(int));
  139664. aaSorted = (int **)sqlite3_malloc(nByte);
  139665. if( !aaSorted ){
  139666. return SQLITE_NOMEM;
  139667. }
  139668. aSpare = &((int *)&aaSorted[pRtree->nDim])[pRtree->nDim*nCell];
  139669. memset(aaSorted, 0, nByte);
  139670. for(ii=0; ii<pRtree->nDim; ii++){
  139671. int jj;
  139672. aaSorted[ii] = &((int *)&aaSorted[pRtree->nDim])[ii*nCell];
  139673. for(jj=0; jj<nCell; jj++){
  139674. aaSorted[ii][jj] = jj;
  139675. }
  139676. SortByDimension(pRtree, aaSorted[ii], nCell, ii, aCell, aSpare);
  139677. }
  139678. for(ii=0; ii<pRtree->nDim; ii++){
  139679. RtreeDValue margin = RTREE_ZERO;
  139680. RtreeDValue fBestOverlap = RTREE_ZERO;
  139681. RtreeDValue fBestArea = RTREE_ZERO;
  139682. int iBestLeft = 0;
  139683. int nLeft;
  139684. for(
  139685. nLeft=RTREE_MINCELLS(pRtree);
  139686. nLeft<=(nCell-RTREE_MINCELLS(pRtree));
  139687. nLeft++
  139688. ){
  139689. RtreeCell left;
  139690. RtreeCell right;
  139691. int kk;
  139692. RtreeDValue overlap;
  139693. RtreeDValue area;
  139694. memcpy(&left, &aCell[aaSorted[ii][0]], sizeof(RtreeCell));
  139695. memcpy(&right, &aCell[aaSorted[ii][nCell-1]], sizeof(RtreeCell));
  139696. for(kk=1; kk<(nCell-1); kk++){
  139697. if( kk<nLeft ){
  139698. cellUnion(pRtree, &left, &aCell[aaSorted[ii][kk]]);
  139699. }else{
  139700. cellUnion(pRtree, &right, &aCell[aaSorted[ii][kk]]);
  139701. }
  139702. }
  139703. margin += cellMargin(pRtree, &left);
  139704. margin += cellMargin(pRtree, &right);
  139705. overlap = cellOverlap(pRtree, &left, &right, 1);
  139706. area = cellArea(pRtree, &left) + cellArea(pRtree, &right);
  139707. if( (nLeft==RTREE_MINCELLS(pRtree))
  139708. || (overlap<fBestOverlap)
  139709. || (overlap==fBestOverlap && area<fBestArea)
  139710. ){
  139711. iBestLeft = nLeft;
  139712. fBestOverlap = overlap;
  139713. fBestArea = area;
  139714. }
  139715. }
  139716. if( ii==0 || margin<fBestMargin ){
  139717. iBestDim = ii;
  139718. fBestMargin = margin;
  139719. iBestSplit = iBestLeft;
  139720. }
  139721. }
  139722. memcpy(pBboxLeft, &aCell[aaSorted[iBestDim][0]], sizeof(RtreeCell));
  139723. memcpy(pBboxRight, &aCell[aaSorted[iBestDim][iBestSplit]], sizeof(RtreeCell));
  139724. for(ii=0; ii<nCell; ii++){
  139725. RtreeNode *pTarget = (ii<iBestSplit)?pLeft:pRight;
  139726. RtreeCell *pBbox = (ii<iBestSplit)?pBboxLeft:pBboxRight;
  139727. RtreeCell *pCell = &aCell[aaSorted[iBestDim][ii]];
  139728. nodeInsertCell(pRtree, pTarget, pCell);
  139729. cellUnion(pRtree, pBbox, pCell);
  139730. }
  139731. sqlite3_free(aaSorted);
  139732. return SQLITE_OK;
  139733. }
  139734. static int updateMapping(
  139735. Rtree *pRtree,
  139736. i64 iRowid,
  139737. RtreeNode *pNode,
  139738. int iHeight
  139739. ){
  139740. int (*xSetMapping)(Rtree *, sqlite3_int64, sqlite3_int64);
  139741. xSetMapping = ((iHeight==0)?rowidWrite:parentWrite);
  139742. if( iHeight>0 ){
  139743. RtreeNode *pChild = nodeHashLookup(pRtree, iRowid);
  139744. if( pChild ){
  139745. nodeRelease(pRtree, pChild->pParent);
  139746. nodeReference(pNode);
  139747. pChild->pParent = pNode;
  139748. }
  139749. }
  139750. return xSetMapping(pRtree, iRowid, pNode->iNode);
  139751. }
  139752. static int SplitNode(
  139753. Rtree *pRtree,
  139754. RtreeNode *pNode,
  139755. RtreeCell *pCell,
  139756. int iHeight
  139757. ){
  139758. int i;
  139759. int newCellIsRight = 0;
  139760. int rc = SQLITE_OK;
  139761. int nCell = NCELL(pNode);
  139762. RtreeCell *aCell;
  139763. int *aiUsed;
  139764. RtreeNode *pLeft = 0;
  139765. RtreeNode *pRight = 0;
  139766. RtreeCell leftbbox;
  139767. RtreeCell rightbbox;
  139768. /* Allocate an array and populate it with a copy of pCell and
  139769. ** all cells from node pLeft. Then zero the original node.
  139770. */
  139771. aCell = sqlite3_malloc((sizeof(RtreeCell)+sizeof(int))*(nCell+1));
  139772. if( !aCell ){
  139773. rc = SQLITE_NOMEM;
  139774. goto splitnode_out;
  139775. }
  139776. aiUsed = (int *)&aCell[nCell+1];
  139777. memset(aiUsed, 0, sizeof(int)*(nCell+1));
  139778. for(i=0; i<nCell; i++){
  139779. nodeGetCell(pRtree, pNode, i, &aCell[i]);
  139780. }
  139781. nodeZero(pRtree, pNode);
  139782. memcpy(&aCell[nCell], pCell, sizeof(RtreeCell));
  139783. nCell++;
  139784. if( pNode->iNode==1 ){
  139785. pRight = nodeNew(pRtree, pNode);
  139786. pLeft = nodeNew(pRtree, pNode);
  139787. pRtree->iDepth++;
  139788. pNode->isDirty = 1;
  139789. writeInt16(pNode->zData, pRtree->iDepth);
  139790. }else{
  139791. pLeft = pNode;
  139792. pRight = nodeNew(pRtree, pLeft->pParent);
  139793. nodeReference(pLeft);
  139794. }
  139795. if( !pLeft || !pRight ){
  139796. rc = SQLITE_NOMEM;
  139797. goto splitnode_out;
  139798. }
  139799. memset(pLeft->zData, 0, pRtree->iNodeSize);
  139800. memset(pRight->zData, 0, pRtree->iNodeSize);
  139801. rc = splitNodeStartree(pRtree, aCell, nCell, pLeft, pRight,
  139802. &leftbbox, &rightbbox);
  139803. if( rc!=SQLITE_OK ){
  139804. goto splitnode_out;
  139805. }
  139806. /* Ensure both child nodes have node numbers assigned to them by calling
  139807. ** nodeWrite(). Node pRight always needs a node number, as it was created
  139808. ** by nodeNew() above. But node pLeft sometimes already has a node number.
  139809. ** In this case avoid the all to nodeWrite().
  139810. */
  139811. if( SQLITE_OK!=(rc = nodeWrite(pRtree, pRight))
  139812. || (0==pLeft->iNode && SQLITE_OK!=(rc = nodeWrite(pRtree, pLeft)))
  139813. ){
  139814. goto splitnode_out;
  139815. }
  139816. rightbbox.iRowid = pRight->iNode;
  139817. leftbbox.iRowid = pLeft->iNode;
  139818. if( pNode->iNode==1 ){
  139819. rc = rtreeInsertCell(pRtree, pLeft->pParent, &leftbbox, iHeight+1);
  139820. if( rc!=SQLITE_OK ){
  139821. goto splitnode_out;
  139822. }
  139823. }else{
  139824. RtreeNode *pParent = pLeft->pParent;
  139825. int iCell;
  139826. rc = nodeParentIndex(pRtree, pLeft, &iCell);
  139827. if( rc==SQLITE_OK ){
  139828. nodeOverwriteCell(pRtree, pParent, &leftbbox, iCell);
  139829. rc = AdjustTree(pRtree, pParent, &leftbbox);
  139830. }
  139831. if( rc!=SQLITE_OK ){
  139832. goto splitnode_out;
  139833. }
  139834. }
  139835. if( (rc = rtreeInsertCell(pRtree, pRight->pParent, &rightbbox, iHeight+1)) ){
  139836. goto splitnode_out;
  139837. }
  139838. for(i=0; i<NCELL(pRight); i++){
  139839. i64 iRowid = nodeGetRowid(pRtree, pRight, i);
  139840. rc = updateMapping(pRtree, iRowid, pRight, iHeight);
  139841. if( iRowid==pCell->iRowid ){
  139842. newCellIsRight = 1;
  139843. }
  139844. if( rc!=SQLITE_OK ){
  139845. goto splitnode_out;
  139846. }
  139847. }
  139848. if( pNode->iNode==1 ){
  139849. for(i=0; i<NCELL(pLeft); i++){
  139850. i64 iRowid = nodeGetRowid(pRtree, pLeft, i);
  139851. rc = updateMapping(pRtree, iRowid, pLeft, iHeight);
  139852. if( rc!=SQLITE_OK ){
  139853. goto splitnode_out;
  139854. }
  139855. }
  139856. }else if( newCellIsRight==0 ){
  139857. rc = updateMapping(pRtree, pCell->iRowid, pLeft, iHeight);
  139858. }
  139859. if( rc==SQLITE_OK ){
  139860. rc = nodeRelease(pRtree, pRight);
  139861. pRight = 0;
  139862. }
  139863. if( rc==SQLITE_OK ){
  139864. rc = nodeRelease(pRtree, pLeft);
  139865. pLeft = 0;
  139866. }
  139867. splitnode_out:
  139868. nodeRelease(pRtree, pRight);
  139869. nodeRelease(pRtree, pLeft);
  139870. sqlite3_free(aCell);
  139871. return rc;
  139872. }
  139873. /*
  139874. ** If node pLeaf is not the root of the r-tree and its pParent pointer is
  139875. ** still NULL, load all ancestor nodes of pLeaf into memory and populate
  139876. ** the pLeaf->pParent chain all the way up to the root node.
  139877. **
  139878. ** This operation is required when a row is deleted (or updated - an update
  139879. ** is implemented as a delete followed by an insert). SQLite provides the
  139880. ** rowid of the row to delete, which can be used to find the leaf on which
  139881. ** the entry resides (argument pLeaf). Once the leaf is located, this
  139882. ** function is called to determine its ancestry.
  139883. */
  139884. static int fixLeafParent(Rtree *pRtree, RtreeNode *pLeaf){
  139885. int rc = SQLITE_OK;
  139886. RtreeNode *pChild = pLeaf;
  139887. while( rc==SQLITE_OK && pChild->iNode!=1 && pChild->pParent==0 ){
  139888. int rc2 = SQLITE_OK; /* sqlite3_reset() return code */
  139889. sqlite3_bind_int64(pRtree->pReadParent, 1, pChild->iNode);
  139890. rc = sqlite3_step(pRtree->pReadParent);
  139891. if( rc==SQLITE_ROW ){
  139892. RtreeNode *pTest; /* Used to test for reference loops */
  139893. i64 iNode; /* Node number of parent node */
  139894. /* Before setting pChild->pParent, test that we are not creating a
  139895. ** loop of references (as we would if, say, pChild==pParent). We don't
  139896. ** want to do this as it leads to a memory leak when trying to delete
  139897. ** the referenced counted node structures.
  139898. */
  139899. iNode = sqlite3_column_int64(pRtree->pReadParent, 0);
  139900. for(pTest=pLeaf; pTest && pTest->iNode!=iNode; pTest=pTest->pParent);
  139901. if( !pTest ){
  139902. rc2 = nodeAcquire(pRtree, iNode, 0, &pChild->pParent);
  139903. }
  139904. }
  139905. rc = sqlite3_reset(pRtree->pReadParent);
  139906. if( rc==SQLITE_OK ) rc = rc2;
  139907. if( rc==SQLITE_OK && !pChild->pParent ) rc = SQLITE_CORRUPT_VTAB;
  139908. pChild = pChild->pParent;
  139909. }
  139910. return rc;
  139911. }
  139912. static int deleteCell(Rtree *, RtreeNode *, int, int);
  139913. static int removeNode(Rtree *pRtree, RtreeNode *pNode, int iHeight){
  139914. int rc;
  139915. int rc2;
  139916. RtreeNode *pParent = 0;
  139917. int iCell;
  139918. assert( pNode->nRef==1 );
  139919. /* Remove the entry in the parent cell. */
  139920. rc = nodeParentIndex(pRtree, pNode, &iCell);
  139921. if( rc==SQLITE_OK ){
  139922. pParent = pNode->pParent;
  139923. pNode->pParent = 0;
  139924. rc = deleteCell(pRtree, pParent, iCell, iHeight+1);
  139925. }
  139926. rc2 = nodeRelease(pRtree, pParent);
  139927. if( rc==SQLITE_OK ){
  139928. rc = rc2;
  139929. }
  139930. if( rc!=SQLITE_OK ){
  139931. return rc;
  139932. }
  139933. /* Remove the xxx_node entry. */
  139934. sqlite3_bind_int64(pRtree->pDeleteNode, 1, pNode->iNode);
  139935. sqlite3_step(pRtree->pDeleteNode);
  139936. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteNode)) ){
  139937. return rc;
  139938. }
  139939. /* Remove the xxx_parent entry. */
  139940. sqlite3_bind_int64(pRtree->pDeleteParent, 1, pNode->iNode);
  139941. sqlite3_step(pRtree->pDeleteParent);
  139942. if( SQLITE_OK!=(rc = sqlite3_reset(pRtree->pDeleteParent)) ){
  139943. return rc;
  139944. }
  139945. /* Remove the node from the in-memory hash table and link it into
  139946. ** the Rtree.pDeleted list. Its contents will be re-inserted later on.
  139947. */
  139948. nodeHashDelete(pRtree, pNode);
  139949. pNode->iNode = iHeight;
  139950. pNode->pNext = pRtree->pDeleted;
  139951. pNode->nRef++;
  139952. pRtree->pDeleted = pNode;
  139953. return SQLITE_OK;
  139954. }
  139955. static int fixBoundingBox(Rtree *pRtree, RtreeNode *pNode){
  139956. RtreeNode *pParent = pNode->pParent;
  139957. int rc = SQLITE_OK;
  139958. if( pParent ){
  139959. int ii;
  139960. int nCell = NCELL(pNode);
  139961. RtreeCell box; /* Bounding box for pNode */
  139962. nodeGetCell(pRtree, pNode, 0, &box);
  139963. for(ii=1; ii<nCell; ii++){
  139964. RtreeCell cell;
  139965. nodeGetCell(pRtree, pNode, ii, &cell);
  139966. cellUnion(pRtree, &box, &cell);
  139967. }
  139968. box.iRowid = pNode->iNode;
  139969. rc = nodeParentIndex(pRtree, pNode, &ii);
  139970. if( rc==SQLITE_OK ){
  139971. nodeOverwriteCell(pRtree, pParent, &box, ii);
  139972. rc = fixBoundingBox(pRtree, pParent);
  139973. }
  139974. }
  139975. return rc;
  139976. }
  139977. /*
  139978. ** Delete the cell at index iCell of node pNode. After removing the
  139979. ** cell, adjust the r-tree data structure if required.
  139980. */
  139981. static int deleteCell(Rtree *pRtree, RtreeNode *pNode, int iCell, int iHeight){
  139982. RtreeNode *pParent;
  139983. int rc;
  139984. if( SQLITE_OK!=(rc = fixLeafParent(pRtree, pNode)) ){
  139985. return rc;
  139986. }
  139987. /* Remove the cell from the node. This call just moves bytes around
  139988. ** the in-memory node image, so it cannot fail.
  139989. */
  139990. nodeDeleteCell(pRtree, pNode, iCell);
  139991. /* If the node is not the tree root and now has less than the minimum
  139992. ** number of cells, remove it from the tree. Otherwise, update the
  139993. ** cell in the parent node so that it tightly contains the updated
  139994. ** node.
  139995. */
  139996. pParent = pNode->pParent;
  139997. assert( pParent || pNode->iNode==1 );
  139998. if( pParent ){
  139999. if( NCELL(pNode)<RTREE_MINCELLS(pRtree) ){
  140000. rc = removeNode(pRtree, pNode, iHeight);
  140001. }else{
  140002. rc = fixBoundingBox(pRtree, pNode);
  140003. }
  140004. }
  140005. return rc;
  140006. }
  140007. static int Reinsert(
  140008. Rtree *pRtree,
  140009. RtreeNode *pNode,
  140010. RtreeCell *pCell,
  140011. int iHeight
  140012. ){
  140013. int *aOrder;
  140014. int *aSpare;
  140015. RtreeCell *aCell;
  140016. RtreeDValue *aDistance;
  140017. int nCell;
  140018. RtreeDValue aCenterCoord[RTREE_MAX_DIMENSIONS];
  140019. int iDim;
  140020. int ii;
  140021. int rc = SQLITE_OK;
  140022. int n;
  140023. memset(aCenterCoord, 0, sizeof(RtreeDValue)*RTREE_MAX_DIMENSIONS);
  140024. nCell = NCELL(pNode)+1;
  140025. n = (nCell+1)&(~1);
  140026. /* Allocate the buffers used by this operation. The allocation is
  140027. ** relinquished before this function returns.
  140028. */
  140029. aCell = (RtreeCell *)sqlite3_malloc(n * (
  140030. sizeof(RtreeCell) + /* aCell array */
  140031. sizeof(int) + /* aOrder array */
  140032. sizeof(int) + /* aSpare array */
  140033. sizeof(RtreeDValue) /* aDistance array */
  140034. ));
  140035. if( !aCell ){
  140036. return SQLITE_NOMEM;
  140037. }
  140038. aOrder = (int *)&aCell[n];
  140039. aSpare = (int *)&aOrder[n];
  140040. aDistance = (RtreeDValue *)&aSpare[n];
  140041. for(ii=0; ii<nCell; ii++){
  140042. if( ii==(nCell-1) ){
  140043. memcpy(&aCell[ii], pCell, sizeof(RtreeCell));
  140044. }else{
  140045. nodeGetCell(pRtree, pNode, ii, &aCell[ii]);
  140046. }
  140047. aOrder[ii] = ii;
  140048. for(iDim=0; iDim<pRtree->nDim; iDim++){
  140049. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2]);
  140050. aCenterCoord[iDim] += DCOORD(aCell[ii].aCoord[iDim*2+1]);
  140051. }
  140052. }
  140053. for(iDim=0; iDim<pRtree->nDim; iDim++){
  140054. aCenterCoord[iDim] = (aCenterCoord[iDim]/(nCell*(RtreeDValue)2));
  140055. }
  140056. for(ii=0; ii<nCell; ii++){
  140057. aDistance[ii] = RTREE_ZERO;
  140058. for(iDim=0; iDim<pRtree->nDim; iDim++){
  140059. RtreeDValue coord = (DCOORD(aCell[ii].aCoord[iDim*2+1]) -
  140060. DCOORD(aCell[ii].aCoord[iDim*2]));
  140061. aDistance[ii] += (coord-aCenterCoord[iDim])*(coord-aCenterCoord[iDim]);
  140062. }
  140063. }
  140064. SortByDistance(aOrder, nCell, aDistance, aSpare);
  140065. nodeZero(pRtree, pNode);
  140066. for(ii=0; rc==SQLITE_OK && ii<(nCell-(RTREE_MINCELLS(pRtree)+1)); ii++){
  140067. RtreeCell *p = &aCell[aOrder[ii]];
  140068. nodeInsertCell(pRtree, pNode, p);
  140069. if( p->iRowid==pCell->iRowid ){
  140070. if( iHeight==0 ){
  140071. rc = rowidWrite(pRtree, p->iRowid, pNode->iNode);
  140072. }else{
  140073. rc = parentWrite(pRtree, p->iRowid, pNode->iNode);
  140074. }
  140075. }
  140076. }
  140077. if( rc==SQLITE_OK ){
  140078. rc = fixBoundingBox(pRtree, pNode);
  140079. }
  140080. for(; rc==SQLITE_OK && ii<nCell; ii++){
  140081. /* Find a node to store this cell in. pNode->iNode currently contains
  140082. ** the height of the sub-tree headed by the cell.
  140083. */
  140084. RtreeNode *pInsert;
  140085. RtreeCell *p = &aCell[aOrder[ii]];
  140086. rc = ChooseLeaf(pRtree, p, iHeight, &pInsert);
  140087. if( rc==SQLITE_OK ){
  140088. int rc2;
  140089. rc = rtreeInsertCell(pRtree, pInsert, p, iHeight);
  140090. rc2 = nodeRelease(pRtree, pInsert);
  140091. if( rc==SQLITE_OK ){
  140092. rc = rc2;
  140093. }
  140094. }
  140095. }
  140096. sqlite3_free(aCell);
  140097. return rc;
  140098. }
  140099. /*
  140100. ** Insert cell pCell into node pNode. Node pNode is the head of a
  140101. ** subtree iHeight high (leaf nodes have iHeight==0).
  140102. */
  140103. static int rtreeInsertCell(
  140104. Rtree *pRtree,
  140105. RtreeNode *pNode,
  140106. RtreeCell *pCell,
  140107. int iHeight
  140108. ){
  140109. int rc = SQLITE_OK;
  140110. if( iHeight>0 ){
  140111. RtreeNode *pChild = nodeHashLookup(pRtree, pCell->iRowid);
  140112. if( pChild ){
  140113. nodeRelease(pRtree, pChild->pParent);
  140114. nodeReference(pNode);
  140115. pChild->pParent = pNode;
  140116. }
  140117. }
  140118. if( nodeInsertCell(pRtree, pNode, pCell) ){
  140119. if( iHeight<=pRtree->iReinsertHeight || pNode->iNode==1){
  140120. rc = SplitNode(pRtree, pNode, pCell, iHeight);
  140121. }else{
  140122. pRtree->iReinsertHeight = iHeight;
  140123. rc = Reinsert(pRtree, pNode, pCell, iHeight);
  140124. }
  140125. }else{
  140126. rc = AdjustTree(pRtree, pNode, pCell);
  140127. if( rc==SQLITE_OK ){
  140128. if( iHeight==0 ){
  140129. rc = rowidWrite(pRtree, pCell->iRowid, pNode->iNode);
  140130. }else{
  140131. rc = parentWrite(pRtree, pCell->iRowid, pNode->iNode);
  140132. }
  140133. }
  140134. }
  140135. return rc;
  140136. }
  140137. static int reinsertNodeContent(Rtree *pRtree, RtreeNode *pNode){
  140138. int ii;
  140139. int rc = SQLITE_OK;
  140140. int nCell = NCELL(pNode);
  140141. for(ii=0; rc==SQLITE_OK && ii<nCell; ii++){
  140142. RtreeNode *pInsert;
  140143. RtreeCell cell;
  140144. nodeGetCell(pRtree, pNode, ii, &cell);
  140145. /* Find a node to store this cell in. pNode->iNode currently contains
  140146. ** the height of the sub-tree headed by the cell.
  140147. */
  140148. rc = ChooseLeaf(pRtree, &cell, (int)pNode->iNode, &pInsert);
  140149. if( rc==SQLITE_OK ){
  140150. int rc2;
  140151. rc = rtreeInsertCell(pRtree, pInsert, &cell, (int)pNode->iNode);
  140152. rc2 = nodeRelease(pRtree, pInsert);
  140153. if( rc==SQLITE_OK ){
  140154. rc = rc2;
  140155. }
  140156. }
  140157. }
  140158. return rc;
  140159. }
  140160. /*
  140161. ** Select a currently unused rowid for a new r-tree record.
  140162. */
  140163. static int newRowid(Rtree *pRtree, i64 *piRowid){
  140164. int rc;
  140165. sqlite3_bind_null(pRtree->pWriteRowid, 1);
  140166. sqlite3_bind_null(pRtree->pWriteRowid, 2);
  140167. sqlite3_step(pRtree->pWriteRowid);
  140168. rc = sqlite3_reset(pRtree->pWriteRowid);
  140169. *piRowid = sqlite3_last_insert_rowid(pRtree->db);
  140170. return rc;
  140171. }
  140172. /*
  140173. ** Remove the entry with rowid=iDelete from the r-tree structure.
  140174. */
  140175. static int rtreeDeleteRowid(Rtree *pRtree, sqlite3_int64 iDelete){
  140176. int rc; /* Return code */
  140177. RtreeNode *pLeaf = 0; /* Leaf node containing record iDelete */
  140178. int iCell; /* Index of iDelete cell in pLeaf */
  140179. RtreeNode *pRoot; /* Root node of rtree structure */
  140180. /* Obtain a reference to the root node to initialize Rtree.iDepth */
  140181. rc = nodeAcquire(pRtree, 1, 0, &pRoot);
  140182. /* Obtain a reference to the leaf node that contains the entry
  140183. ** about to be deleted.
  140184. */
  140185. if( rc==SQLITE_OK ){
  140186. rc = findLeafNode(pRtree, iDelete, &pLeaf, 0);
  140187. }
  140188. /* Delete the cell in question from the leaf node. */
  140189. if( rc==SQLITE_OK ){
  140190. int rc2;
  140191. rc = nodeRowidIndex(pRtree, pLeaf, iDelete, &iCell);
  140192. if( rc==SQLITE_OK ){
  140193. rc = deleteCell(pRtree, pLeaf, iCell, 0);
  140194. }
  140195. rc2 = nodeRelease(pRtree, pLeaf);
  140196. if( rc==SQLITE_OK ){
  140197. rc = rc2;
  140198. }
  140199. }
  140200. /* Delete the corresponding entry in the <rtree>_rowid table. */
  140201. if( rc==SQLITE_OK ){
  140202. sqlite3_bind_int64(pRtree->pDeleteRowid, 1, iDelete);
  140203. sqlite3_step(pRtree->pDeleteRowid);
  140204. rc = sqlite3_reset(pRtree->pDeleteRowid);
  140205. }
  140206. /* Check if the root node now has exactly one child. If so, remove
  140207. ** it, schedule the contents of the child for reinsertion and
  140208. ** reduce the tree height by one.
  140209. **
  140210. ** This is equivalent to copying the contents of the child into
  140211. ** the root node (the operation that Gutman's paper says to perform
  140212. ** in this scenario).
  140213. */
  140214. if( rc==SQLITE_OK && pRtree->iDepth>0 && NCELL(pRoot)==1 ){
  140215. int rc2;
  140216. RtreeNode *pChild;
  140217. i64 iChild = nodeGetRowid(pRtree, pRoot, 0);
  140218. rc = nodeAcquire(pRtree, iChild, pRoot, &pChild);
  140219. if( rc==SQLITE_OK ){
  140220. rc = removeNode(pRtree, pChild, pRtree->iDepth-1);
  140221. }
  140222. rc2 = nodeRelease(pRtree, pChild);
  140223. if( rc==SQLITE_OK ) rc = rc2;
  140224. if( rc==SQLITE_OK ){
  140225. pRtree->iDepth--;
  140226. writeInt16(pRoot->zData, pRtree->iDepth);
  140227. pRoot->isDirty = 1;
  140228. }
  140229. }
  140230. /* Re-insert the contents of any underfull nodes removed from the tree. */
  140231. for(pLeaf=pRtree->pDeleted; pLeaf; pLeaf=pRtree->pDeleted){
  140232. if( rc==SQLITE_OK ){
  140233. rc = reinsertNodeContent(pRtree, pLeaf);
  140234. }
  140235. pRtree->pDeleted = pLeaf->pNext;
  140236. sqlite3_free(pLeaf);
  140237. }
  140238. /* Release the reference to the root node. */
  140239. if( rc==SQLITE_OK ){
  140240. rc = nodeRelease(pRtree, pRoot);
  140241. }else{
  140242. nodeRelease(pRtree, pRoot);
  140243. }
  140244. return rc;
  140245. }
  140246. /*
  140247. ** Rounding constants for float->double conversion.
  140248. */
  140249. #define RNDTOWARDS (1.0 - 1.0/8388608.0) /* Round towards zero */
  140250. #define RNDAWAY (1.0 + 1.0/8388608.0) /* Round away from zero */
  140251. #if !defined(SQLITE_RTREE_INT_ONLY)
  140252. /*
  140253. ** Convert an sqlite3_value into an RtreeValue (presumably a float)
  140254. ** while taking care to round toward negative or positive, respectively.
  140255. */
  140256. static RtreeValue rtreeValueDown(sqlite3_value *v){
  140257. double d = sqlite3_value_double(v);
  140258. float f = (float)d;
  140259. if( f>d ){
  140260. f = (float)(d*(d<0 ? RNDAWAY : RNDTOWARDS));
  140261. }
  140262. return f;
  140263. }
  140264. static RtreeValue rtreeValueUp(sqlite3_value *v){
  140265. double d = sqlite3_value_double(v);
  140266. float f = (float)d;
  140267. if( f<d ){
  140268. f = (float)(d*(d<0 ? RNDTOWARDS : RNDAWAY));
  140269. }
  140270. return f;
  140271. }
  140272. #endif /* !defined(SQLITE_RTREE_INT_ONLY) */
  140273. /*
  140274. ** The xUpdate method for rtree module virtual tables.
  140275. */
  140276. static int rtreeUpdate(
  140277. sqlite3_vtab *pVtab,
  140278. int nData,
  140279. sqlite3_value **azData,
  140280. sqlite_int64 *pRowid
  140281. ){
  140282. Rtree *pRtree = (Rtree *)pVtab;
  140283. int rc = SQLITE_OK;
  140284. RtreeCell cell; /* New cell to insert if nData>1 */
  140285. int bHaveRowid = 0; /* Set to 1 after new rowid is determined */
  140286. rtreeReference(pRtree);
  140287. assert(nData>=1);
  140288. /* Constraint handling. A write operation on an r-tree table may return
  140289. ** SQLITE_CONSTRAINT for two reasons:
  140290. **
  140291. ** 1. A duplicate rowid value, or
  140292. ** 2. The supplied data violates the "x2>=x1" constraint.
  140293. **
  140294. ** In the first case, if the conflict-handling mode is REPLACE, then
  140295. ** the conflicting row can be removed before proceeding. In the second
  140296. ** case, SQLITE_CONSTRAINT must be returned regardless of the
  140297. ** conflict-handling mode specified by the user.
  140298. */
  140299. if( nData>1 ){
  140300. int ii;
  140301. /* Populate the cell.aCoord[] array. The first coordinate is azData[3]. */
  140302. assert( nData==(pRtree->nDim*2 + 3) );
  140303. #ifndef SQLITE_RTREE_INT_ONLY
  140304. if( pRtree->eCoordType==RTREE_COORD_REAL32 ){
  140305. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  140306. cell.aCoord[ii].f = rtreeValueDown(azData[ii+3]);
  140307. cell.aCoord[ii+1].f = rtreeValueUp(azData[ii+4]);
  140308. if( cell.aCoord[ii].f>cell.aCoord[ii+1].f ){
  140309. rc = SQLITE_CONSTRAINT;
  140310. goto constraint;
  140311. }
  140312. }
  140313. }else
  140314. #endif
  140315. {
  140316. for(ii=0; ii<(pRtree->nDim*2); ii+=2){
  140317. cell.aCoord[ii].i = sqlite3_value_int(azData[ii+3]);
  140318. cell.aCoord[ii+1].i = sqlite3_value_int(azData[ii+4]);
  140319. if( cell.aCoord[ii].i>cell.aCoord[ii+1].i ){
  140320. rc = SQLITE_CONSTRAINT;
  140321. goto constraint;
  140322. }
  140323. }
  140324. }
  140325. /* If a rowid value was supplied, check if it is already present in
  140326. ** the table. If so, the constraint has failed. */
  140327. if( sqlite3_value_type(azData[2])!=SQLITE_NULL ){
  140328. cell.iRowid = sqlite3_value_int64(azData[2]);
  140329. if( sqlite3_value_type(azData[0])==SQLITE_NULL
  140330. || sqlite3_value_int64(azData[0])!=cell.iRowid
  140331. ){
  140332. int steprc;
  140333. sqlite3_bind_int64(pRtree->pReadRowid, 1, cell.iRowid);
  140334. steprc = sqlite3_step(pRtree->pReadRowid);
  140335. rc = sqlite3_reset(pRtree->pReadRowid);
  140336. if( SQLITE_ROW==steprc ){
  140337. if( sqlite3_vtab_on_conflict(pRtree->db)==SQLITE_REPLACE ){
  140338. rc = rtreeDeleteRowid(pRtree, cell.iRowid);
  140339. }else{
  140340. rc = SQLITE_CONSTRAINT;
  140341. goto constraint;
  140342. }
  140343. }
  140344. }
  140345. bHaveRowid = 1;
  140346. }
  140347. }
  140348. /* If azData[0] is not an SQL NULL value, it is the rowid of a
  140349. ** record to delete from the r-tree table. The following block does
  140350. ** just that.
  140351. */
  140352. if( sqlite3_value_type(azData[0])!=SQLITE_NULL ){
  140353. rc = rtreeDeleteRowid(pRtree, sqlite3_value_int64(azData[0]));
  140354. }
  140355. /* If the azData[] array contains more than one element, elements
  140356. ** (azData[2]..azData[argc-1]) contain a new record to insert into
  140357. ** the r-tree structure.
  140358. */
  140359. if( rc==SQLITE_OK && nData>1 ){
  140360. /* Insert the new record into the r-tree */
  140361. RtreeNode *pLeaf = 0;
  140362. /* Figure out the rowid of the new row. */
  140363. if( bHaveRowid==0 ){
  140364. rc = newRowid(pRtree, &cell.iRowid);
  140365. }
  140366. *pRowid = cell.iRowid;
  140367. if( rc==SQLITE_OK ){
  140368. rc = ChooseLeaf(pRtree, &cell, 0, &pLeaf);
  140369. }
  140370. if( rc==SQLITE_OK ){
  140371. int rc2;
  140372. pRtree->iReinsertHeight = -1;
  140373. rc = rtreeInsertCell(pRtree, pLeaf, &cell, 0);
  140374. rc2 = nodeRelease(pRtree, pLeaf);
  140375. if( rc==SQLITE_OK ){
  140376. rc = rc2;
  140377. }
  140378. }
  140379. }
  140380. constraint:
  140381. rtreeRelease(pRtree);
  140382. return rc;
  140383. }
  140384. /*
  140385. ** The xRename method for rtree module virtual tables.
  140386. */
  140387. static int rtreeRename(sqlite3_vtab *pVtab, const char *zNewName){
  140388. Rtree *pRtree = (Rtree *)pVtab;
  140389. int rc = SQLITE_NOMEM;
  140390. char *zSql = sqlite3_mprintf(
  140391. "ALTER TABLE %Q.'%q_node' RENAME TO \"%w_node\";"
  140392. "ALTER TABLE %Q.'%q_parent' RENAME TO \"%w_parent\";"
  140393. "ALTER TABLE %Q.'%q_rowid' RENAME TO \"%w_rowid\";"
  140394. , pRtree->zDb, pRtree->zName, zNewName
  140395. , pRtree->zDb, pRtree->zName, zNewName
  140396. , pRtree->zDb, pRtree->zName, zNewName
  140397. );
  140398. if( zSql ){
  140399. rc = sqlite3_exec(pRtree->db, zSql, 0, 0, 0);
  140400. sqlite3_free(zSql);
  140401. }
  140402. return rc;
  140403. }
  140404. /*
  140405. ** This function populates the pRtree->nRowEst variable with an estimate
  140406. ** of the number of rows in the virtual table. If possible, this is based
  140407. ** on sqlite_stat1 data. Otherwise, use RTREE_DEFAULT_ROWEST.
  140408. */
  140409. static int rtreeQueryStat1(sqlite3 *db, Rtree *pRtree){
  140410. const char *zFmt = "SELECT stat FROM %Q.sqlite_stat1 WHERE tbl = '%q_rowid'";
  140411. char *zSql;
  140412. sqlite3_stmt *p;
  140413. int rc;
  140414. i64 nRow = 0;
  140415. zSql = sqlite3_mprintf(zFmt, pRtree->zDb, pRtree->zName);
  140416. if( zSql==0 ){
  140417. rc = SQLITE_NOMEM;
  140418. }else{
  140419. rc = sqlite3_prepare_v2(db, zSql, -1, &p, 0);
  140420. if( rc==SQLITE_OK ){
  140421. if( sqlite3_step(p)==SQLITE_ROW ) nRow = sqlite3_column_int64(p, 0);
  140422. rc = sqlite3_finalize(p);
  140423. }else if( rc!=SQLITE_NOMEM ){
  140424. rc = SQLITE_OK;
  140425. }
  140426. if( rc==SQLITE_OK ){
  140427. if( nRow==0 ){
  140428. pRtree->nRowEst = RTREE_DEFAULT_ROWEST;
  140429. }else{
  140430. pRtree->nRowEst = MAX(nRow, RTREE_MIN_ROWEST);
  140431. }
  140432. }
  140433. sqlite3_free(zSql);
  140434. }
  140435. return rc;
  140436. }
  140437. static sqlite3_module rtreeModule = {
  140438. 0, /* iVersion */
  140439. rtreeCreate, /* xCreate - create a table */
  140440. rtreeConnect, /* xConnect - connect to an existing table */
  140441. rtreeBestIndex, /* xBestIndex - Determine search strategy */
  140442. rtreeDisconnect, /* xDisconnect - Disconnect from a table */
  140443. rtreeDestroy, /* xDestroy - Drop a table */
  140444. rtreeOpen, /* xOpen - open a cursor */
  140445. rtreeClose, /* xClose - close a cursor */
  140446. rtreeFilter, /* xFilter - configure scan constraints */
  140447. rtreeNext, /* xNext - advance a cursor */
  140448. rtreeEof, /* xEof */
  140449. rtreeColumn, /* xColumn - read data */
  140450. rtreeRowid, /* xRowid - read data */
  140451. rtreeUpdate, /* xUpdate - write data */
  140452. 0, /* xBegin - begin transaction */
  140453. 0, /* xSync - sync transaction */
  140454. 0, /* xCommit - commit transaction */
  140455. 0, /* xRollback - rollback transaction */
  140456. 0, /* xFindFunction - function overloading */
  140457. rtreeRename, /* xRename - rename the table */
  140458. 0, /* xSavepoint */
  140459. 0, /* xRelease */
  140460. 0 /* xRollbackTo */
  140461. };
  140462. static int rtreeSqlInit(
  140463. Rtree *pRtree,
  140464. sqlite3 *db,
  140465. const char *zDb,
  140466. const char *zPrefix,
  140467. int isCreate
  140468. ){
  140469. int rc = SQLITE_OK;
  140470. #define N_STATEMENT 9
  140471. static const char *azSql[N_STATEMENT] = {
  140472. /* Read and write the xxx_node table */
  140473. "SELECT data FROM '%q'.'%q_node' WHERE nodeno = :1",
  140474. "INSERT OR REPLACE INTO '%q'.'%q_node' VALUES(:1, :2)",
  140475. "DELETE FROM '%q'.'%q_node' WHERE nodeno = :1",
  140476. /* Read and write the xxx_rowid table */
  140477. "SELECT nodeno FROM '%q'.'%q_rowid' WHERE rowid = :1",
  140478. "INSERT OR REPLACE INTO '%q'.'%q_rowid' VALUES(:1, :2)",
  140479. "DELETE FROM '%q'.'%q_rowid' WHERE rowid = :1",
  140480. /* Read and write the xxx_parent table */
  140481. "SELECT parentnode FROM '%q'.'%q_parent' WHERE nodeno = :1",
  140482. "INSERT OR REPLACE INTO '%q'.'%q_parent' VALUES(:1, :2)",
  140483. "DELETE FROM '%q'.'%q_parent' WHERE nodeno = :1"
  140484. };
  140485. sqlite3_stmt **appStmt[N_STATEMENT];
  140486. int i;
  140487. pRtree->db = db;
  140488. if( isCreate ){
  140489. char *zCreate = sqlite3_mprintf(
  140490. "CREATE TABLE \"%w\".\"%w_node\"(nodeno INTEGER PRIMARY KEY, data BLOB);"
  140491. "CREATE TABLE \"%w\".\"%w_rowid\"(rowid INTEGER PRIMARY KEY, nodeno INTEGER);"
  140492. "CREATE TABLE \"%w\".\"%w_parent\"(nodeno INTEGER PRIMARY KEY,"
  140493. " parentnode INTEGER);"
  140494. "INSERT INTO '%q'.'%q_node' VALUES(1, zeroblob(%d))",
  140495. zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, zDb, zPrefix, pRtree->iNodeSize
  140496. );
  140497. if( !zCreate ){
  140498. return SQLITE_NOMEM;
  140499. }
  140500. rc = sqlite3_exec(db, zCreate, 0, 0, 0);
  140501. sqlite3_free(zCreate);
  140502. if( rc!=SQLITE_OK ){
  140503. return rc;
  140504. }
  140505. }
  140506. appStmt[0] = &pRtree->pReadNode;
  140507. appStmt[1] = &pRtree->pWriteNode;
  140508. appStmt[2] = &pRtree->pDeleteNode;
  140509. appStmt[3] = &pRtree->pReadRowid;
  140510. appStmt[4] = &pRtree->pWriteRowid;
  140511. appStmt[5] = &pRtree->pDeleteRowid;
  140512. appStmt[6] = &pRtree->pReadParent;
  140513. appStmt[7] = &pRtree->pWriteParent;
  140514. appStmt[8] = &pRtree->pDeleteParent;
  140515. rc = rtreeQueryStat1(db, pRtree);
  140516. for(i=0; i<N_STATEMENT && rc==SQLITE_OK; i++){
  140517. char *zSql = sqlite3_mprintf(azSql[i], zDb, zPrefix);
  140518. if( zSql ){
  140519. rc = sqlite3_prepare_v2(db, zSql, -1, appStmt[i], 0);
  140520. }else{
  140521. rc = SQLITE_NOMEM;
  140522. }
  140523. sqlite3_free(zSql);
  140524. }
  140525. return rc;
  140526. }
  140527. /*
  140528. ** The second argument to this function contains the text of an SQL statement
  140529. ** that returns a single integer value. The statement is compiled and executed
  140530. ** using database connection db. If successful, the integer value returned
  140531. ** is written to *piVal and SQLITE_OK returned. Otherwise, an SQLite error
  140532. ** code is returned and the value of *piVal after returning is not defined.
  140533. */
  140534. static int getIntFromStmt(sqlite3 *db, const char *zSql, int *piVal){
  140535. int rc = SQLITE_NOMEM;
  140536. if( zSql ){
  140537. sqlite3_stmt *pStmt = 0;
  140538. rc = sqlite3_prepare_v2(db, zSql, -1, &pStmt, 0);
  140539. if( rc==SQLITE_OK ){
  140540. if( SQLITE_ROW==sqlite3_step(pStmt) ){
  140541. *piVal = sqlite3_column_int(pStmt, 0);
  140542. }
  140543. rc = sqlite3_finalize(pStmt);
  140544. }
  140545. }
  140546. return rc;
  140547. }
  140548. /*
  140549. ** This function is called from within the xConnect() or xCreate() method to
  140550. ** determine the node-size used by the rtree table being created or connected
  140551. ** to. If successful, pRtree->iNodeSize is populated and SQLITE_OK returned.
  140552. ** Otherwise, an SQLite error code is returned.
  140553. **
  140554. ** If this function is being called as part of an xConnect(), then the rtree
  140555. ** table already exists. In this case the node-size is determined by inspecting
  140556. ** the root node of the tree.
  140557. **
  140558. ** Otherwise, for an xCreate(), use 64 bytes less than the database page-size.
  140559. ** This ensures that each node is stored on a single database page. If the
  140560. ** database page-size is so large that more than RTREE_MAXCELLS entries
  140561. ** would fit in a single node, use a smaller node-size.
  140562. */
  140563. static int getNodeSize(
  140564. sqlite3 *db, /* Database handle */
  140565. Rtree *pRtree, /* Rtree handle */
  140566. int isCreate, /* True for xCreate, false for xConnect */
  140567. char **pzErr /* OUT: Error message, if any */
  140568. ){
  140569. int rc;
  140570. char *zSql;
  140571. if( isCreate ){
  140572. int iPageSize = 0;
  140573. zSql = sqlite3_mprintf("PRAGMA %Q.page_size", pRtree->zDb);
  140574. rc = getIntFromStmt(db, zSql, &iPageSize);
  140575. if( rc==SQLITE_OK ){
  140576. pRtree->iNodeSize = iPageSize-64;
  140577. if( (4+pRtree->nBytesPerCell*RTREE_MAXCELLS)<pRtree->iNodeSize ){
  140578. pRtree->iNodeSize = 4+pRtree->nBytesPerCell*RTREE_MAXCELLS;
  140579. }
  140580. }else{
  140581. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  140582. }
  140583. }else{
  140584. zSql = sqlite3_mprintf(
  140585. "SELECT length(data) FROM '%q'.'%q_node' WHERE nodeno = 1",
  140586. pRtree->zDb, pRtree->zName
  140587. );
  140588. rc = getIntFromStmt(db, zSql, &pRtree->iNodeSize);
  140589. if( rc!=SQLITE_OK ){
  140590. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  140591. }
  140592. }
  140593. sqlite3_free(zSql);
  140594. return rc;
  140595. }
  140596. /*
  140597. ** This function is the implementation of both the xConnect and xCreate
  140598. ** methods of the r-tree virtual table.
  140599. **
  140600. ** argv[0] -> module name
  140601. ** argv[1] -> database name
  140602. ** argv[2] -> table name
  140603. ** argv[...] -> column names...
  140604. */
  140605. static int rtreeInit(
  140606. sqlite3 *db, /* Database connection */
  140607. void *pAux, /* One of the RTREE_COORD_* constants */
  140608. int argc, const char *const*argv, /* Parameters to CREATE TABLE statement */
  140609. sqlite3_vtab **ppVtab, /* OUT: New virtual table */
  140610. char **pzErr, /* OUT: Error message, if any */
  140611. int isCreate /* True for xCreate, false for xConnect */
  140612. ){
  140613. int rc = SQLITE_OK;
  140614. Rtree *pRtree;
  140615. int nDb; /* Length of string argv[1] */
  140616. int nName; /* Length of string argv[2] */
  140617. int eCoordType = (pAux ? RTREE_COORD_INT32 : RTREE_COORD_REAL32);
  140618. const char *aErrMsg[] = {
  140619. 0, /* 0 */
  140620. "Wrong number of columns for an rtree table", /* 1 */
  140621. "Too few columns for an rtree table", /* 2 */
  140622. "Too many columns for an rtree table" /* 3 */
  140623. };
  140624. int iErr = (argc<6) ? 2 : argc>(RTREE_MAX_DIMENSIONS*2+4) ? 3 : argc%2;
  140625. if( aErrMsg[iErr] ){
  140626. *pzErr = sqlite3_mprintf("%s", aErrMsg[iErr]);
  140627. return SQLITE_ERROR;
  140628. }
  140629. sqlite3_vtab_config(db, SQLITE_VTAB_CONSTRAINT_SUPPORT, 1);
  140630. /* Allocate the sqlite3_vtab structure */
  140631. nDb = (int)strlen(argv[1]);
  140632. nName = (int)strlen(argv[2]);
  140633. pRtree = (Rtree *)sqlite3_malloc(sizeof(Rtree)+nDb+nName+2);
  140634. if( !pRtree ){
  140635. return SQLITE_NOMEM;
  140636. }
  140637. memset(pRtree, 0, sizeof(Rtree)+nDb+nName+2);
  140638. pRtree->nBusy = 1;
  140639. pRtree->base.pModule = &rtreeModule;
  140640. pRtree->zDb = (char *)&pRtree[1];
  140641. pRtree->zName = &pRtree->zDb[nDb+1];
  140642. pRtree->nDim = (argc-4)/2;
  140643. pRtree->nBytesPerCell = 8 + pRtree->nDim*4*2;
  140644. pRtree->eCoordType = eCoordType;
  140645. memcpy(pRtree->zDb, argv[1], nDb);
  140646. memcpy(pRtree->zName, argv[2], nName);
  140647. /* Figure out the node size to use. */
  140648. rc = getNodeSize(db, pRtree, isCreate, pzErr);
  140649. /* Create/Connect to the underlying relational database schema. If
  140650. ** that is successful, call sqlite3_declare_vtab() to configure
  140651. ** the r-tree table schema.
  140652. */
  140653. if( rc==SQLITE_OK ){
  140654. if( (rc = rtreeSqlInit(pRtree, db, argv[1], argv[2], isCreate)) ){
  140655. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  140656. }else{
  140657. char *zSql = sqlite3_mprintf("CREATE TABLE x(%s", argv[3]);
  140658. char *zTmp;
  140659. int ii;
  140660. for(ii=4; zSql && ii<argc; ii++){
  140661. zTmp = zSql;
  140662. zSql = sqlite3_mprintf("%s, %s", zTmp, argv[ii]);
  140663. sqlite3_free(zTmp);
  140664. }
  140665. if( zSql ){
  140666. zTmp = zSql;
  140667. zSql = sqlite3_mprintf("%s);", zTmp);
  140668. sqlite3_free(zTmp);
  140669. }
  140670. if( !zSql ){
  140671. rc = SQLITE_NOMEM;
  140672. }else if( SQLITE_OK!=(rc = sqlite3_declare_vtab(db, zSql)) ){
  140673. *pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
  140674. }
  140675. sqlite3_free(zSql);
  140676. }
  140677. }
  140678. if( rc==SQLITE_OK ){
  140679. *ppVtab = (sqlite3_vtab *)pRtree;
  140680. }else{
  140681. assert( *ppVtab==0 );
  140682. assert( pRtree->nBusy==1 );
  140683. rtreeRelease(pRtree);
  140684. }
  140685. return rc;
  140686. }
  140687. /*
  140688. ** Implementation of a scalar function that decodes r-tree nodes to
  140689. ** human readable strings. This can be used for debugging and analysis.
  140690. **
  140691. ** The scalar function takes two arguments: (1) the number of dimensions
  140692. ** to the rtree (between 1 and 5, inclusive) and (2) a blob of data containing
  140693. ** an r-tree node. For a two-dimensional r-tree structure called "rt", to
  140694. ** deserialize all nodes, a statement like:
  140695. **
  140696. ** SELECT rtreenode(2, data) FROM rt_node;
  140697. **
  140698. ** The human readable string takes the form of a Tcl list with one
  140699. ** entry for each cell in the r-tree node. Each entry is itself a
  140700. ** list, containing the 8-byte rowid/pageno followed by the
  140701. ** <num-dimension>*2 coordinates.
  140702. */
  140703. static void rtreenode(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  140704. char *zText = 0;
  140705. RtreeNode node;
  140706. Rtree tree;
  140707. int ii;
  140708. UNUSED_PARAMETER(nArg);
  140709. memset(&node, 0, sizeof(RtreeNode));
  140710. memset(&tree, 0, sizeof(Rtree));
  140711. tree.nDim = sqlite3_value_int(apArg[0]);
  140712. tree.nBytesPerCell = 8 + 8 * tree.nDim;
  140713. node.zData = (u8 *)sqlite3_value_blob(apArg[1]);
  140714. for(ii=0; ii<NCELL(&node); ii++){
  140715. char zCell[512];
  140716. int nCell = 0;
  140717. RtreeCell cell;
  140718. int jj;
  140719. nodeGetCell(&tree, &node, ii, &cell);
  140720. sqlite3_snprintf(512-nCell,&zCell[nCell],"%lld", cell.iRowid);
  140721. nCell = (int)strlen(zCell);
  140722. for(jj=0; jj<tree.nDim*2; jj++){
  140723. #ifndef SQLITE_RTREE_INT_ONLY
  140724. sqlite3_snprintf(512-nCell,&zCell[nCell], " %g",
  140725. (double)cell.aCoord[jj].f);
  140726. #else
  140727. sqlite3_snprintf(512-nCell,&zCell[nCell], " %d",
  140728. cell.aCoord[jj].i);
  140729. #endif
  140730. nCell = (int)strlen(zCell);
  140731. }
  140732. if( zText ){
  140733. char *zTextNew = sqlite3_mprintf("%s {%s}", zText, zCell);
  140734. sqlite3_free(zText);
  140735. zText = zTextNew;
  140736. }else{
  140737. zText = sqlite3_mprintf("{%s}", zCell);
  140738. }
  140739. }
  140740. sqlite3_result_text(ctx, zText, -1, sqlite3_free);
  140741. }
  140742. /* This routine implements an SQL function that returns the "depth" parameter
  140743. ** from the front of a blob that is an r-tree node. For example:
  140744. **
  140745. ** SELECT rtreedepth(data) FROM rt_node WHERE nodeno=1;
  140746. **
  140747. ** The depth value is 0 for all nodes other than the root node, and the root
  140748. ** node always has nodeno=1, so the example above is the primary use for this
  140749. ** routine. This routine is intended for testing and analysis only.
  140750. */
  140751. static void rtreedepth(sqlite3_context *ctx, int nArg, sqlite3_value **apArg){
  140752. UNUSED_PARAMETER(nArg);
  140753. if( sqlite3_value_type(apArg[0])!=SQLITE_BLOB
  140754. || sqlite3_value_bytes(apArg[0])<2
  140755. ){
  140756. sqlite3_result_error(ctx, "Invalid argument to rtreedepth()", -1);
  140757. }else{
  140758. u8 *zBlob = (u8 *)sqlite3_value_blob(apArg[0]);
  140759. sqlite3_result_int(ctx, readInt16(zBlob));
  140760. }
  140761. }
  140762. /*
  140763. ** Register the r-tree module with database handle db. This creates the
  140764. ** virtual table module "rtree" and the debugging/analysis scalar
  140765. ** function "rtreenode".
  140766. */
  140767. SQLITE_PRIVATE int sqlite3RtreeInit(sqlite3 *db){
  140768. const int utf8 = SQLITE_UTF8;
  140769. int rc;
  140770. rc = sqlite3_create_function(db, "rtreenode", 2, utf8, 0, rtreenode, 0, 0);
  140771. if( rc==SQLITE_OK ){
  140772. rc = sqlite3_create_function(db, "rtreedepth", 1, utf8, 0,rtreedepth, 0, 0);
  140773. }
  140774. if( rc==SQLITE_OK ){
  140775. #ifdef SQLITE_RTREE_INT_ONLY
  140776. void *c = (void *)RTREE_COORD_INT32;
  140777. #else
  140778. void *c = (void *)RTREE_COORD_REAL32;
  140779. #endif
  140780. rc = sqlite3_create_module_v2(db, "rtree", &rtreeModule, c, 0);
  140781. }
  140782. if( rc==SQLITE_OK ){
  140783. void *c = (void *)RTREE_COORD_INT32;
  140784. rc = sqlite3_create_module_v2(db, "rtree_i32", &rtreeModule, c, 0);
  140785. }
  140786. return rc;
  140787. }
  140788. /*
  140789. ** This routine deletes the RtreeGeomCallback object that was attached
  140790. ** one of the SQL functions create by sqlite3_rtree_geometry_callback()
  140791. ** or sqlite3_rtree_query_callback(). In other words, this routine is the
  140792. ** destructor for an RtreeGeomCallback objecct. This routine is called when
  140793. ** the corresponding SQL function is deleted.
  140794. */
  140795. static void rtreeFreeCallback(void *p){
  140796. RtreeGeomCallback *pInfo = (RtreeGeomCallback*)p;
  140797. if( pInfo->xDestructor ) pInfo->xDestructor(pInfo->pContext);
  140798. sqlite3_free(p);
  140799. }
  140800. /*
  140801. ** Each call to sqlite3_rtree_geometry_callback() or
  140802. ** sqlite3_rtree_query_callback() creates an ordinary SQLite
  140803. ** scalar function that is implemented by this routine.
  140804. **
  140805. ** All this function does is construct an RtreeMatchArg object that
  140806. ** contains the geometry-checking callback routines and a list of
  140807. ** parameters to this function, then return that RtreeMatchArg object
  140808. ** as a BLOB.
  140809. **
  140810. ** The R-Tree MATCH operator will read the returned BLOB, deserialize
  140811. ** the RtreeMatchArg object, and use the RtreeMatchArg object to figure
  140812. ** out which elements of the R-Tree should be returned by the query.
  140813. */
  140814. static void geomCallback(sqlite3_context *ctx, int nArg, sqlite3_value **aArg){
  140815. RtreeGeomCallback *pGeomCtx = (RtreeGeomCallback *)sqlite3_user_data(ctx);
  140816. RtreeMatchArg *pBlob;
  140817. int nBlob;
  140818. nBlob = sizeof(RtreeMatchArg) + (nArg-1)*sizeof(RtreeDValue);
  140819. pBlob = (RtreeMatchArg *)sqlite3_malloc(nBlob);
  140820. if( !pBlob ){
  140821. sqlite3_result_error_nomem(ctx);
  140822. }else{
  140823. int i;
  140824. pBlob->magic = RTREE_GEOMETRY_MAGIC;
  140825. pBlob->cb = pGeomCtx[0];
  140826. pBlob->nParam = nArg;
  140827. for(i=0; i<nArg; i++){
  140828. #ifdef SQLITE_RTREE_INT_ONLY
  140829. pBlob->aParam[i] = sqlite3_value_int64(aArg[i]);
  140830. #else
  140831. pBlob->aParam[i] = sqlite3_value_double(aArg[i]);
  140832. #endif
  140833. }
  140834. sqlite3_result_blob(ctx, pBlob, nBlob, sqlite3_free);
  140835. }
  140836. }
  140837. /*
  140838. ** Register a new geometry function for use with the r-tree MATCH operator.
  140839. */
  140840. SQLITE_API int sqlite3_rtree_geometry_callback(
  140841. sqlite3 *db, /* Register SQL function on this connection */
  140842. const char *zGeom, /* Name of the new SQL function */
  140843. int (*xGeom)(sqlite3_rtree_geometry*,int,RtreeDValue*,int*), /* Callback */
  140844. void *pContext /* Extra data associated with the callback */
  140845. ){
  140846. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  140847. /* Allocate and populate the context object. */
  140848. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  140849. if( !pGeomCtx ) return SQLITE_NOMEM;
  140850. pGeomCtx->xGeom = xGeom;
  140851. pGeomCtx->xQueryFunc = 0;
  140852. pGeomCtx->xDestructor = 0;
  140853. pGeomCtx->pContext = pContext;
  140854. return sqlite3_create_function_v2(db, zGeom, -1, SQLITE_ANY,
  140855. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  140856. );
  140857. }
  140858. /*
  140859. ** Register a new 2nd-generation geometry function for use with the
  140860. ** r-tree MATCH operator.
  140861. */
  140862. SQLITE_API int sqlite3_rtree_query_callback(
  140863. sqlite3 *db, /* Register SQL function on this connection */
  140864. const char *zQueryFunc, /* Name of new SQL function */
  140865. int (*xQueryFunc)(sqlite3_rtree_query_info*), /* Callback */
  140866. void *pContext, /* Extra data passed into the callback */
  140867. void (*xDestructor)(void*) /* Destructor for the extra data */
  140868. ){
  140869. RtreeGeomCallback *pGeomCtx; /* Context object for new user-function */
  140870. /* Allocate and populate the context object. */
  140871. pGeomCtx = (RtreeGeomCallback *)sqlite3_malloc(sizeof(RtreeGeomCallback));
  140872. if( !pGeomCtx ) return SQLITE_NOMEM;
  140873. pGeomCtx->xGeom = 0;
  140874. pGeomCtx->xQueryFunc = xQueryFunc;
  140875. pGeomCtx->xDestructor = xDestructor;
  140876. pGeomCtx->pContext = pContext;
  140877. return sqlite3_create_function_v2(db, zQueryFunc, -1, SQLITE_ANY,
  140878. (void *)pGeomCtx, geomCallback, 0, 0, rtreeFreeCallback
  140879. );
  140880. }
  140881. #if !SQLITE_CORE
  140882. #ifdef _WIN32
  140883. __declspec(dllexport)
  140884. #endif
  140885. SQLITE_API int sqlite3_rtree_init(
  140886. sqlite3 *db,
  140887. char **pzErrMsg,
  140888. const sqlite3_api_routines *pApi
  140889. ){
  140890. SQLITE_EXTENSION_INIT2(pApi)
  140891. return sqlite3RtreeInit(db);
  140892. }
  140893. #endif
  140894. #endif
  140895. /************** End of rtree.c ***********************************************/
  140896. /************** Begin file icu.c *********************************************/
  140897. /*
  140898. ** 2007 May 6
  140899. **
  140900. ** The author disclaims copyright to this source code. In place of
  140901. ** a legal notice, here is a blessing:
  140902. **
  140903. ** May you do good and not evil.
  140904. ** May you find forgiveness for yourself and forgive others.
  140905. ** May you share freely, never taking more than you give.
  140906. **
  140907. *************************************************************************
  140908. ** $Id: icu.c,v 1.7 2007/12/13 21:54:11 drh Exp $
  140909. **
  140910. ** This file implements an integration between the ICU library
  140911. ** ("International Components for Unicode", an open-source library
  140912. ** for handling unicode data) and SQLite. The integration uses
  140913. ** ICU to provide the following to SQLite:
  140914. **
  140915. ** * An implementation of the SQL regexp() function (and hence REGEXP
  140916. ** operator) using the ICU uregex_XX() APIs.
  140917. **
  140918. ** * Implementations of the SQL scalar upper() and lower() functions
  140919. ** for case mapping.
  140920. **
  140921. ** * Integration of ICU and SQLite collation sequences.
  140922. **
  140923. ** * An implementation of the LIKE operator that uses ICU to
  140924. ** provide case-independent matching.
  140925. */
  140926. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_ICU)
  140927. /* Include ICU headers */
  140928. #include <unicode/utypes.h>
  140929. #include <unicode/uregex.h>
  140930. #include <unicode/ustring.h>
  140931. #include <unicode/ucol.h>
  140932. /* #include <assert.h> */
  140933. #ifndef SQLITE_CORE
  140934. SQLITE_EXTENSION_INIT1
  140935. #else
  140936. #endif
  140937. /*
  140938. ** Maximum length (in bytes) of the pattern in a LIKE or GLOB
  140939. ** operator.
  140940. */
  140941. #ifndef SQLITE_MAX_LIKE_PATTERN_LENGTH
  140942. # define SQLITE_MAX_LIKE_PATTERN_LENGTH 50000
  140943. #endif
  140944. /*
  140945. ** Version of sqlite3_free() that is always a function, never a macro.
  140946. */
  140947. static void xFree(void *p){
  140948. sqlite3_free(p);
  140949. }
  140950. /*
  140951. ** Compare two UTF-8 strings for equality where the first string is
  140952. ** a "LIKE" expression. Return true (1) if they are the same and
  140953. ** false (0) if they are different.
  140954. */
  140955. static int icuLikeCompare(
  140956. const uint8_t *zPattern, /* LIKE pattern */
  140957. const uint8_t *zString, /* The UTF-8 string to compare against */
  140958. const UChar32 uEsc /* The escape character */
  140959. ){
  140960. static const int MATCH_ONE = (UChar32)'_';
  140961. static const int MATCH_ALL = (UChar32)'%';
  140962. int iPattern = 0; /* Current byte index in zPattern */
  140963. int iString = 0; /* Current byte index in zString */
  140964. int prevEscape = 0; /* True if the previous character was uEsc */
  140965. while( zPattern[iPattern]!=0 ){
  140966. /* Read (and consume) the next character from the input pattern. */
  140967. UChar32 uPattern;
  140968. U8_NEXT_UNSAFE(zPattern, iPattern, uPattern);
  140969. assert(uPattern!=0);
  140970. /* There are now 4 possibilities:
  140971. **
  140972. ** 1. uPattern is an unescaped match-all character "%",
  140973. ** 2. uPattern is an unescaped match-one character "_",
  140974. ** 3. uPattern is an unescaped escape character, or
  140975. ** 4. uPattern is to be handled as an ordinary character
  140976. */
  140977. if( !prevEscape && uPattern==MATCH_ALL ){
  140978. /* Case 1. */
  140979. uint8_t c;
  140980. /* Skip any MATCH_ALL or MATCH_ONE characters that follow a
  140981. ** MATCH_ALL. For each MATCH_ONE, skip one character in the
  140982. ** test string.
  140983. */
  140984. while( (c=zPattern[iPattern]) == MATCH_ALL || c == MATCH_ONE ){
  140985. if( c==MATCH_ONE ){
  140986. if( zString[iString]==0 ) return 0;
  140987. U8_FWD_1_UNSAFE(zString, iString);
  140988. }
  140989. iPattern++;
  140990. }
  140991. if( zPattern[iPattern]==0 ) return 1;
  140992. while( zString[iString] ){
  140993. if( icuLikeCompare(&zPattern[iPattern], &zString[iString], uEsc) ){
  140994. return 1;
  140995. }
  140996. U8_FWD_1_UNSAFE(zString, iString);
  140997. }
  140998. return 0;
  140999. }else if( !prevEscape && uPattern==MATCH_ONE ){
  141000. /* Case 2. */
  141001. if( zString[iString]==0 ) return 0;
  141002. U8_FWD_1_UNSAFE(zString, iString);
  141003. }else if( !prevEscape && uPattern==uEsc){
  141004. /* Case 3. */
  141005. prevEscape = 1;
  141006. }else{
  141007. /* Case 4. */
  141008. UChar32 uString;
  141009. U8_NEXT_UNSAFE(zString, iString, uString);
  141010. uString = u_foldCase(uString, U_FOLD_CASE_DEFAULT);
  141011. uPattern = u_foldCase(uPattern, U_FOLD_CASE_DEFAULT);
  141012. if( uString!=uPattern ){
  141013. return 0;
  141014. }
  141015. prevEscape = 0;
  141016. }
  141017. }
  141018. return zString[iString]==0;
  141019. }
  141020. /*
  141021. ** Implementation of the like() SQL function. This function implements
  141022. ** the build-in LIKE operator. The first argument to the function is the
  141023. ** pattern and the second argument is the string. So, the SQL statements:
  141024. **
  141025. ** A LIKE B
  141026. **
  141027. ** is implemented as like(B, A). If there is an escape character E,
  141028. **
  141029. ** A LIKE B ESCAPE E
  141030. **
  141031. ** is mapped to like(B, A, E).
  141032. */
  141033. static void icuLikeFunc(
  141034. sqlite3_context *context,
  141035. int argc,
  141036. sqlite3_value **argv
  141037. ){
  141038. const unsigned char *zA = sqlite3_value_text(argv[0]);
  141039. const unsigned char *zB = sqlite3_value_text(argv[1]);
  141040. UChar32 uEsc = 0;
  141041. /* Limit the length of the LIKE or GLOB pattern to avoid problems
  141042. ** of deep recursion and N*N behavior in patternCompare().
  141043. */
  141044. if( sqlite3_value_bytes(argv[0])>SQLITE_MAX_LIKE_PATTERN_LENGTH ){
  141045. sqlite3_result_error(context, "LIKE or GLOB pattern too complex", -1);
  141046. return;
  141047. }
  141048. if( argc==3 ){
  141049. /* The escape character string must consist of a single UTF-8 character.
  141050. ** Otherwise, return an error.
  141051. */
  141052. int nE= sqlite3_value_bytes(argv[2]);
  141053. const unsigned char *zE = sqlite3_value_text(argv[2]);
  141054. int i = 0;
  141055. if( zE==0 ) return;
  141056. U8_NEXT(zE, i, nE, uEsc);
  141057. if( i!=nE){
  141058. sqlite3_result_error(context,
  141059. "ESCAPE expression must be a single character", -1);
  141060. return;
  141061. }
  141062. }
  141063. if( zA && zB ){
  141064. sqlite3_result_int(context, icuLikeCompare(zA, zB, uEsc));
  141065. }
  141066. }
  141067. /*
  141068. ** This function is called when an ICU function called from within
  141069. ** the implementation of an SQL scalar function returns an error.
  141070. **
  141071. ** The scalar function context passed as the first argument is
  141072. ** loaded with an error message based on the following two args.
  141073. */
  141074. static void icuFunctionError(
  141075. sqlite3_context *pCtx, /* SQLite scalar function context */
  141076. const char *zName, /* Name of ICU function that failed */
  141077. UErrorCode e /* Error code returned by ICU function */
  141078. ){
  141079. char zBuf[128];
  141080. sqlite3_snprintf(128, zBuf, "ICU error: %s(): %s", zName, u_errorName(e));
  141081. zBuf[127] = '\0';
  141082. sqlite3_result_error(pCtx, zBuf, -1);
  141083. }
  141084. /*
  141085. ** Function to delete compiled regexp objects. Registered as
  141086. ** a destructor function with sqlite3_set_auxdata().
  141087. */
  141088. static void icuRegexpDelete(void *p){
  141089. URegularExpression *pExpr = (URegularExpression *)p;
  141090. uregex_close(pExpr);
  141091. }
  141092. /*
  141093. ** Implementation of SQLite REGEXP operator. This scalar function takes
  141094. ** two arguments. The first is a regular expression pattern to compile
  141095. ** the second is a string to match against that pattern. If either
  141096. ** argument is an SQL NULL, then NULL Is returned. Otherwise, the result
  141097. ** is 1 if the string matches the pattern, or 0 otherwise.
  141098. **
  141099. ** SQLite maps the regexp() function to the regexp() operator such
  141100. ** that the following two are equivalent:
  141101. **
  141102. ** zString REGEXP zPattern
  141103. ** regexp(zPattern, zString)
  141104. **
  141105. ** Uses the following ICU regexp APIs:
  141106. **
  141107. ** uregex_open()
  141108. ** uregex_matches()
  141109. ** uregex_close()
  141110. */
  141111. static void icuRegexpFunc(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  141112. UErrorCode status = U_ZERO_ERROR;
  141113. URegularExpression *pExpr;
  141114. UBool res;
  141115. const UChar *zString = sqlite3_value_text16(apArg[1]);
  141116. (void)nArg; /* Unused parameter */
  141117. /* If the left hand side of the regexp operator is NULL,
  141118. ** then the result is also NULL.
  141119. */
  141120. if( !zString ){
  141121. return;
  141122. }
  141123. pExpr = sqlite3_get_auxdata(p, 0);
  141124. if( !pExpr ){
  141125. const UChar *zPattern = sqlite3_value_text16(apArg[0]);
  141126. if( !zPattern ){
  141127. return;
  141128. }
  141129. pExpr = uregex_open(zPattern, -1, 0, 0, &status);
  141130. if( U_SUCCESS(status) ){
  141131. sqlite3_set_auxdata(p, 0, pExpr, icuRegexpDelete);
  141132. }else{
  141133. assert(!pExpr);
  141134. icuFunctionError(p, "uregex_open", status);
  141135. return;
  141136. }
  141137. }
  141138. /* Configure the text that the regular expression operates on. */
  141139. uregex_setText(pExpr, zString, -1, &status);
  141140. if( !U_SUCCESS(status) ){
  141141. icuFunctionError(p, "uregex_setText", status);
  141142. return;
  141143. }
  141144. /* Attempt the match */
  141145. res = uregex_matches(pExpr, 0, &status);
  141146. if( !U_SUCCESS(status) ){
  141147. icuFunctionError(p, "uregex_matches", status);
  141148. return;
  141149. }
  141150. /* Set the text that the regular expression operates on to a NULL
  141151. ** pointer. This is not really necessary, but it is tidier than
  141152. ** leaving the regular expression object configured with an invalid
  141153. ** pointer after this function returns.
  141154. */
  141155. uregex_setText(pExpr, 0, 0, &status);
  141156. /* Return 1 or 0. */
  141157. sqlite3_result_int(p, res ? 1 : 0);
  141158. }
  141159. /*
  141160. ** Implementations of scalar functions for case mapping - upper() and
  141161. ** lower(). Function upper() converts its input to upper-case (ABC).
  141162. ** Function lower() converts to lower-case (abc).
  141163. **
  141164. ** ICU provides two types of case mapping, "general" case mapping and
  141165. ** "language specific". Refer to ICU documentation for the differences
  141166. ** between the two.
  141167. **
  141168. ** To utilise "general" case mapping, the upper() or lower() scalar
  141169. ** functions are invoked with one argument:
  141170. **
  141171. ** upper('ABC') -> 'abc'
  141172. ** lower('abc') -> 'ABC'
  141173. **
  141174. ** To access ICU "language specific" case mapping, upper() or lower()
  141175. ** should be invoked with two arguments. The second argument is the name
  141176. ** of the locale to use. Passing an empty string ("") or SQL NULL value
  141177. ** as the second argument is the same as invoking the 1 argument version
  141178. ** of upper() or lower().
  141179. **
  141180. ** lower('I', 'en_us') -> 'i'
  141181. ** lower('I', 'tr_tr') -> 'ı' (small dotless i)
  141182. **
  141183. ** http://www.icu-project.org/userguide/posix.html#case_mappings
  141184. */
  141185. static void icuCaseFunc16(sqlite3_context *p, int nArg, sqlite3_value **apArg){
  141186. const UChar *zInput;
  141187. UChar *zOutput;
  141188. int nInput;
  141189. int nOutput;
  141190. UErrorCode status = U_ZERO_ERROR;
  141191. const char *zLocale = 0;
  141192. assert(nArg==1 || nArg==2);
  141193. if( nArg==2 ){
  141194. zLocale = (const char *)sqlite3_value_text(apArg[1]);
  141195. }
  141196. zInput = sqlite3_value_text16(apArg[0]);
  141197. if( !zInput ){
  141198. return;
  141199. }
  141200. nInput = sqlite3_value_bytes16(apArg[0]);
  141201. nOutput = nInput * 2 + 2;
  141202. zOutput = sqlite3_malloc(nOutput);
  141203. if( !zOutput ){
  141204. return;
  141205. }
  141206. if( sqlite3_user_data(p) ){
  141207. u_strToUpper(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  141208. }else{
  141209. u_strToLower(zOutput, nOutput/2, zInput, nInput/2, zLocale, &status);
  141210. }
  141211. if( !U_SUCCESS(status) ){
  141212. icuFunctionError(p, "u_strToLower()/u_strToUpper", status);
  141213. return;
  141214. }
  141215. sqlite3_result_text16(p, zOutput, -1, xFree);
  141216. }
  141217. /*
  141218. ** Collation sequence destructor function. The pCtx argument points to
  141219. ** a UCollator structure previously allocated using ucol_open().
  141220. */
  141221. static void icuCollationDel(void *pCtx){
  141222. UCollator *p = (UCollator *)pCtx;
  141223. ucol_close(p);
  141224. }
  141225. /*
  141226. ** Collation sequence comparison function. The pCtx argument points to
  141227. ** a UCollator structure previously allocated using ucol_open().
  141228. */
  141229. static int icuCollationColl(
  141230. void *pCtx,
  141231. int nLeft,
  141232. const void *zLeft,
  141233. int nRight,
  141234. const void *zRight
  141235. ){
  141236. UCollationResult res;
  141237. UCollator *p = (UCollator *)pCtx;
  141238. res = ucol_strcoll(p, (UChar *)zLeft, nLeft/2, (UChar *)zRight, nRight/2);
  141239. switch( res ){
  141240. case UCOL_LESS: return -1;
  141241. case UCOL_GREATER: return +1;
  141242. case UCOL_EQUAL: return 0;
  141243. }
  141244. assert(!"Unexpected return value from ucol_strcoll()");
  141245. return 0;
  141246. }
  141247. /*
  141248. ** Implementation of the scalar function icu_load_collation().
  141249. **
  141250. ** This scalar function is used to add ICU collation based collation
  141251. ** types to an SQLite database connection. It is intended to be called
  141252. ** as follows:
  141253. **
  141254. ** SELECT icu_load_collation(<locale>, <collation-name>);
  141255. **
  141256. ** Where <locale> is a string containing an ICU locale identifier (i.e.
  141257. ** "en_AU", "tr_TR" etc.) and <collation-name> is the name of the
  141258. ** collation sequence to create.
  141259. */
  141260. static void icuLoadCollation(
  141261. sqlite3_context *p,
  141262. int nArg,
  141263. sqlite3_value **apArg
  141264. ){
  141265. sqlite3 *db = (sqlite3 *)sqlite3_user_data(p);
  141266. UErrorCode status = U_ZERO_ERROR;
  141267. const char *zLocale; /* Locale identifier - (eg. "jp_JP") */
  141268. const char *zName; /* SQL Collation sequence name (eg. "japanese") */
  141269. UCollator *pUCollator; /* ICU library collation object */
  141270. int rc; /* Return code from sqlite3_create_collation_x() */
  141271. assert(nArg==2);
  141272. zLocale = (const char *)sqlite3_value_text(apArg[0]);
  141273. zName = (const char *)sqlite3_value_text(apArg[1]);
  141274. if( !zLocale || !zName ){
  141275. return;
  141276. }
  141277. pUCollator = ucol_open(zLocale, &status);
  141278. if( !U_SUCCESS(status) ){
  141279. icuFunctionError(p, "ucol_open", status);
  141280. return;
  141281. }
  141282. assert(p);
  141283. rc = sqlite3_create_collation_v2(db, zName, SQLITE_UTF16, (void *)pUCollator,
  141284. icuCollationColl, icuCollationDel
  141285. );
  141286. if( rc!=SQLITE_OK ){
  141287. ucol_close(pUCollator);
  141288. sqlite3_result_error(p, "Error registering collation function", -1);
  141289. }
  141290. }
  141291. /*
  141292. ** Register the ICU extension functions with database db.
  141293. */
  141294. SQLITE_PRIVATE int sqlite3IcuInit(sqlite3 *db){
  141295. struct IcuScalar {
  141296. const char *zName; /* Function name */
  141297. int nArg; /* Number of arguments */
  141298. int enc; /* Optimal text encoding */
  141299. void *pContext; /* sqlite3_user_data() context */
  141300. void (*xFunc)(sqlite3_context*,int,sqlite3_value**);
  141301. } scalars[] = {
  141302. {"regexp", 2, SQLITE_ANY, 0, icuRegexpFunc},
  141303. {"lower", 1, SQLITE_UTF16, 0, icuCaseFunc16},
  141304. {"lower", 2, SQLITE_UTF16, 0, icuCaseFunc16},
  141305. {"upper", 1, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  141306. {"upper", 2, SQLITE_UTF16, (void*)1, icuCaseFunc16},
  141307. {"lower", 1, SQLITE_UTF8, 0, icuCaseFunc16},
  141308. {"lower", 2, SQLITE_UTF8, 0, icuCaseFunc16},
  141309. {"upper", 1, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  141310. {"upper", 2, SQLITE_UTF8, (void*)1, icuCaseFunc16},
  141311. {"like", 2, SQLITE_UTF8, 0, icuLikeFunc},
  141312. {"like", 3, SQLITE_UTF8, 0, icuLikeFunc},
  141313. {"icu_load_collation", 2, SQLITE_UTF8, (void*)db, icuLoadCollation},
  141314. };
  141315. int rc = SQLITE_OK;
  141316. int i;
  141317. for(i=0; rc==SQLITE_OK && i<(int)(sizeof(scalars)/sizeof(scalars[0])); i++){
  141318. struct IcuScalar *p = &scalars[i];
  141319. rc = sqlite3_create_function(
  141320. db, p->zName, p->nArg, p->enc, p->pContext, p->xFunc, 0, 0
  141321. );
  141322. }
  141323. return rc;
  141324. }
  141325. #if !SQLITE_CORE
  141326. #ifdef _WIN32
  141327. __declspec(dllexport)
  141328. #endif
  141329. SQLITE_API int sqlite3_icu_init(
  141330. sqlite3 *db,
  141331. char **pzErrMsg,
  141332. const sqlite3_api_routines *pApi
  141333. ){
  141334. SQLITE_EXTENSION_INIT2(pApi)
  141335. return sqlite3IcuInit(db);
  141336. }
  141337. #endif
  141338. #endif
  141339. /************** End of icu.c *************************************************/
  141340. /************** Begin file fts3_icu.c ****************************************/
  141341. /*
  141342. ** 2007 June 22
  141343. **
  141344. ** The author disclaims copyright to this source code. In place of
  141345. ** a legal notice, here is a blessing:
  141346. **
  141347. ** May you do good and not evil.
  141348. ** May you find forgiveness for yourself and forgive others.
  141349. ** May you share freely, never taking more than you give.
  141350. **
  141351. *************************************************************************
  141352. ** This file implements a tokenizer for fts3 based on the ICU library.
  141353. */
  141354. #if !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3)
  141355. #ifdef SQLITE_ENABLE_ICU
  141356. /* #include <assert.h> */
  141357. /* #include <string.h> */
  141358. #include <unicode/ubrk.h>
  141359. /* #include <unicode/ucol.h> */
  141360. /* #include <unicode/ustring.h> */
  141361. #include <unicode/utf16.h>
  141362. typedef struct IcuTokenizer IcuTokenizer;
  141363. typedef struct IcuCursor IcuCursor;
  141364. struct IcuTokenizer {
  141365. sqlite3_tokenizer base;
  141366. char *zLocale;
  141367. };
  141368. struct IcuCursor {
  141369. sqlite3_tokenizer_cursor base;
  141370. UBreakIterator *pIter; /* ICU break-iterator object */
  141371. int nChar; /* Number of UChar elements in pInput */
  141372. UChar *aChar; /* Copy of input using utf-16 encoding */
  141373. int *aOffset; /* Offsets of each character in utf-8 input */
  141374. int nBuffer;
  141375. char *zBuffer;
  141376. int iToken;
  141377. };
  141378. /*
  141379. ** Create a new tokenizer instance.
  141380. */
  141381. static int icuCreate(
  141382. int argc, /* Number of entries in argv[] */
  141383. const char * const *argv, /* Tokenizer creation arguments */
  141384. sqlite3_tokenizer **ppTokenizer /* OUT: Created tokenizer */
  141385. ){
  141386. IcuTokenizer *p;
  141387. int n = 0;
  141388. if( argc>0 ){
  141389. n = strlen(argv[0])+1;
  141390. }
  141391. p = (IcuTokenizer *)sqlite3_malloc(sizeof(IcuTokenizer)+n);
  141392. if( !p ){
  141393. return SQLITE_NOMEM;
  141394. }
  141395. memset(p, 0, sizeof(IcuTokenizer));
  141396. if( n ){
  141397. p->zLocale = (char *)&p[1];
  141398. memcpy(p->zLocale, argv[0], n);
  141399. }
  141400. *ppTokenizer = (sqlite3_tokenizer *)p;
  141401. return SQLITE_OK;
  141402. }
  141403. /*
  141404. ** Destroy a tokenizer
  141405. */
  141406. static int icuDestroy(sqlite3_tokenizer *pTokenizer){
  141407. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  141408. sqlite3_free(p);
  141409. return SQLITE_OK;
  141410. }
  141411. /*
  141412. ** Prepare to begin tokenizing a particular string. The input
  141413. ** string to be tokenized is pInput[0..nBytes-1]. A cursor
  141414. ** used to incrementally tokenize this string is returned in
  141415. ** *ppCursor.
  141416. */
  141417. static int icuOpen(
  141418. sqlite3_tokenizer *pTokenizer, /* The tokenizer */
  141419. const char *zInput, /* Input string */
  141420. int nInput, /* Length of zInput in bytes */
  141421. sqlite3_tokenizer_cursor **ppCursor /* OUT: Tokenization cursor */
  141422. ){
  141423. IcuTokenizer *p = (IcuTokenizer *)pTokenizer;
  141424. IcuCursor *pCsr;
  141425. const int32_t opt = U_FOLD_CASE_DEFAULT;
  141426. UErrorCode status = U_ZERO_ERROR;
  141427. int nChar;
  141428. UChar32 c;
  141429. int iInput = 0;
  141430. int iOut = 0;
  141431. *ppCursor = 0;
  141432. if( zInput==0 ){
  141433. nInput = 0;
  141434. zInput = "";
  141435. }else if( nInput<0 ){
  141436. nInput = strlen(zInput);
  141437. }
  141438. nChar = nInput+1;
  141439. pCsr = (IcuCursor *)sqlite3_malloc(
  141440. sizeof(IcuCursor) + /* IcuCursor */
  141441. ((nChar+3)&~3) * sizeof(UChar) + /* IcuCursor.aChar[] */
  141442. (nChar+1) * sizeof(int) /* IcuCursor.aOffset[] */
  141443. );
  141444. if( !pCsr ){
  141445. return SQLITE_NOMEM;
  141446. }
  141447. memset(pCsr, 0, sizeof(IcuCursor));
  141448. pCsr->aChar = (UChar *)&pCsr[1];
  141449. pCsr->aOffset = (int *)&pCsr->aChar[(nChar+3)&~3];
  141450. pCsr->aOffset[iOut] = iInput;
  141451. U8_NEXT(zInput, iInput, nInput, c);
  141452. while( c>0 ){
  141453. int isError = 0;
  141454. c = u_foldCase(c, opt);
  141455. U16_APPEND(pCsr->aChar, iOut, nChar, c, isError);
  141456. if( isError ){
  141457. sqlite3_free(pCsr);
  141458. return SQLITE_ERROR;
  141459. }
  141460. pCsr->aOffset[iOut] = iInput;
  141461. if( iInput<nInput ){
  141462. U8_NEXT(zInput, iInput, nInput, c);
  141463. }else{
  141464. c = 0;
  141465. }
  141466. }
  141467. pCsr->pIter = ubrk_open(UBRK_WORD, p->zLocale, pCsr->aChar, iOut, &status);
  141468. if( !U_SUCCESS(status) ){
  141469. sqlite3_free(pCsr);
  141470. return SQLITE_ERROR;
  141471. }
  141472. pCsr->nChar = iOut;
  141473. ubrk_first(pCsr->pIter);
  141474. *ppCursor = (sqlite3_tokenizer_cursor *)pCsr;
  141475. return SQLITE_OK;
  141476. }
  141477. /*
  141478. ** Close a tokenization cursor previously opened by a call to icuOpen().
  141479. */
  141480. static int icuClose(sqlite3_tokenizer_cursor *pCursor){
  141481. IcuCursor *pCsr = (IcuCursor *)pCursor;
  141482. ubrk_close(pCsr->pIter);
  141483. sqlite3_free(pCsr->zBuffer);
  141484. sqlite3_free(pCsr);
  141485. return SQLITE_OK;
  141486. }
  141487. /*
  141488. ** Extract the next token from a tokenization cursor.
  141489. */
  141490. static int icuNext(
  141491. sqlite3_tokenizer_cursor *pCursor, /* Cursor returned by simpleOpen */
  141492. const char **ppToken, /* OUT: *ppToken is the token text */
  141493. int *pnBytes, /* OUT: Number of bytes in token */
  141494. int *piStartOffset, /* OUT: Starting offset of token */
  141495. int *piEndOffset, /* OUT: Ending offset of token */
  141496. int *piPosition /* OUT: Position integer of token */
  141497. ){
  141498. IcuCursor *pCsr = (IcuCursor *)pCursor;
  141499. int iStart = 0;
  141500. int iEnd = 0;
  141501. int nByte = 0;
  141502. while( iStart==iEnd ){
  141503. UChar32 c;
  141504. iStart = ubrk_current(pCsr->pIter);
  141505. iEnd = ubrk_next(pCsr->pIter);
  141506. if( iEnd==UBRK_DONE ){
  141507. return SQLITE_DONE;
  141508. }
  141509. while( iStart<iEnd ){
  141510. int iWhite = iStart;
  141511. U16_NEXT(pCsr->aChar, iWhite, pCsr->nChar, c);
  141512. if( u_isspace(c) ){
  141513. iStart = iWhite;
  141514. }else{
  141515. break;
  141516. }
  141517. }
  141518. assert(iStart<=iEnd);
  141519. }
  141520. do {
  141521. UErrorCode status = U_ZERO_ERROR;
  141522. if( nByte ){
  141523. char *zNew = sqlite3_realloc(pCsr->zBuffer, nByte);
  141524. if( !zNew ){
  141525. return SQLITE_NOMEM;
  141526. }
  141527. pCsr->zBuffer = zNew;
  141528. pCsr->nBuffer = nByte;
  141529. }
  141530. u_strToUTF8(
  141531. pCsr->zBuffer, pCsr->nBuffer, &nByte, /* Output vars */
  141532. &pCsr->aChar[iStart], iEnd-iStart, /* Input vars */
  141533. &status /* Output success/failure */
  141534. );
  141535. } while( nByte>pCsr->nBuffer );
  141536. *ppToken = pCsr->zBuffer;
  141537. *pnBytes = nByte;
  141538. *piStartOffset = pCsr->aOffset[iStart];
  141539. *piEndOffset = pCsr->aOffset[iEnd];
  141540. *piPosition = pCsr->iToken++;
  141541. return SQLITE_OK;
  141542. }
  141543. /*
  141544. ** The set of routines that implement the simple tokenizer
  141545. */
  141546. static const sqlite3_tokenizer_module icuTokenizerModule = {
  141547. 0, /* iVersion */
  141548. icuCreate, /* xCreate */
  141549. icuDestroy, /* xCreate */
  141550. icuOpen, /* xOpen */
  141551. icuClose, /* xClose */
  141552. icuNext, /* xNext */
  141553. };
  141554. /*
  141555. ** Set *ppModule to point at the implementation of the ICU tokenizer.
  141556. */
  141557. SQLITE_PRIVATE void sqlite3Fts3IcuTokenizerModule(
  141558. sqlite3_tokenizer_module const**ppModule
  141559. ){
  141560. *ppModule = &icuTokenizerModule;
  141561. }
  141562. #endif /* defined(SQLITE_ENABLE_ICU) */
  141563. #endif /* !defined(SQLITE_CORE) || defined(SQLITE_ENABLE_FTS3) */
  141564. /************** End of fts3_icu.c ********************************************/